diff --git a/scripts/afp-showmount.nse b/scripts/afp-showmount.nse index f55184ea5..c16611702 100644 --- a/scripts/afp-showmount.nse +++ b/scripts/afp-showmount.nse @@ -45,57 +45,57 @@ portrule = shortport.portnumber(548, "tcp") action = function(host, port) - local status, response, shares - local result = {} - local afpHelper = afp.Helper:new() - local args = nmap.registry.args - local users = nmap.registry.afp or { ['nil'] = 'nil' } + local status, response, shares + local result = {} + local afpHelper = afp.Helper:new() + local args = nmap.registry.args + local users = nmap.registry.afp or { ['nil'] = 'nil' } - if ( args['afp.username'] ) then - users = {} - users[args['afp.username']] = args['afp.password'] - end + if ( args['afp.username'] ) then + users = {} + users[args['afp.username']] = args['afp.password'] + end - for username, password in pairs(users) do + for username, password in pairs(users) do - status, response = afpHelper:OpenSession(host, port) - if ( not status ) then - stdnse.print_debug(response) - return - end + status, response = afpHelper:OpenSession(host, port) + if ( not status ) then + stdnse.print_debug(response) + return + end - -- if we have a username attempt to authenticate as the user - -- Attempt to use No User Authentication? - if ( username ~= 'nil' ) then - status, response = afpHelper:Login(username, password) - else - status, response = afpHelper:Login() - end + -- if we have a username attempt to authenticate as the user + -- Attempt to use No User Authentication? + if ( username ~= 'nil' ) then + status, response = afpHelper:Login(username, password) + else + status, response = afpHelper:Login() + end - if ( not status ) then - stdnse.print_debug("afp-showmount: Login failed", response) - stdnse.print_debug(3, "afp-showmount: Login error: %s", response) - return - end + if ( not status ) then + stdnse.print_debug("afp-showmount: Login failed", response) + stdnse.print_debug(3, "afp-showmount: Login error: %s", response) + return + end - status, shares = afpHelper:ListShares() + status, shares = afpHelper:ListShares() - if status then - for _, vol in ipairs( shares ) do - local status, response = afpHelper:GetSharePermissions( vol ) - if status then - response.name = vol - table.insert(result, response) - end - end - end + if status then + for _, vol in ipairs( shares ) do + local status, response = afpHelper:GetSharePermissions( vol ) + if status then + response.name = vol + table.insert(result, response) + end + end + end - status, response = afpHelper:Logout() - status, response = afpHelper:CloseSession() + status, response = afpHelper:Logout() + status, response = afpHelper:CloseSession() - if ( result ) then - return stdnse.format_output(true, result) - end - end - return + if ( result ) then + return stdnse.format_output(true, result) + end + end + return end diff --git a/scripts/ajp-auth.nse b/scripts/ajp-auth.nse index 846d0ab87..1735fde7a 100644 --- a/scripts/ajp-auth.nse +++ b/scripts/ajp-auth.nse @@ -33,42 +33,42 @@ local arg_path = stdnse.get_script_args(SCRIPT_NAME .. ".path") local function fail(err) return ("\n ERROR: %s"):format(err or "") end action = function(host, port) - local helper = ajp.Helper:new(host, port) + local helper = ajp.Helper:new(host, port) - if ( not(helper:connect()) ) then - return fail("Failed to connect to AJP server") - end + if ( not(helper:connect()) ) then + return fail("Failed to connect to AJP server") + end - local status, answer = helper:get(arg_path or "/") + local status, answer = helper:get(arg_path or "/") - --- check for 401 response code - if ( not(status) or answer.status ~= 401 ) then - return - end + --- check for 401 response code + if ( not(status) or answer.status ~= 401 ) then + return + end - local result = { name = answer["status-line"]:match("^(.*)\r?\n$") } + local result = { name = answer["status-line"]:match("^(.*)\r?\n$") } - local www_authenticate = answer.headers["www-authenticate"] - if not www_authenticate then - table.insert( result, ("Server returned status %d but no WWW-Authenticate header."):format(answer.status) ) - return stdnse.format_output(true, result) - end + local www_authenticate = answer.headers["www-authenticate"] + if not www_authenticate then + table.insert( result, ("Server returned status %d but no WWW-Authenticate header."):format(answer.status) ) + return stdnse.format_output(true, result) + end - local challenges = http.parse_www_authenticate(www_authenticate) - if ( not(challenges) ) then - table.insert( result, ("Server returned status %d but the WWW-Authenticate header could not be parsed."):format(answer.status) ) - table.insert( result, ("WWW-Authenticate: %s"):format(www_authenticate) ) - return stdnse.format_output(true, result) - end + local challenges = http.parse_www_authenticate(www_authenticate) + if ( not(challenges) ) then + table.insert( result, ("Server returned status %d but the WWW-Authenticate header could not be parsed."):format(answer.status) ) + table.insert( result, ("WWW-Authenticate: %s"):format(www_authenticate) ) + return stdnse.format_output(true, result) + end - for _, challenge in ipairs(challenges) do - local line = challenge.scheme - if ( challenge.params ) then - for name, value in pairs(challenge.params) do - line = line .. (" %s=%s"):format(name, value) - end - end - table.insert(result, line) - end - return stdnse.format_output(true, result) + for _, challenge in ipairs(challenges) do + local line = challenge.scheme + if ( challenge.params ) then + for name, value in pairs(challenge.params) do + line = line .. (" %s=%s"):format(name, value) + end + end + table.insert(result, line) + end + return stdnse.format_output(true, result) end diff --git a/scripts/ajp-headers.nse b/scripts/ajp-headers.nse index 06ce63223..caa11370b 100644 --- a/scripts/ajp-headers.nse +++ b/scripts/ajp-headers.nse @@ -34,15 +34,15 @@ local arg_path = stdnse.get_script_args(SCRIPT_NAME .. '.path') or "/" local function fail(err) return ("\n ERROR: %s"):format(err or "") end action = function(host, port) - local method - local helper = ajp.Helper:new(host, port) - helper:connect() + local method + local helper = ajp.Helper:new(host, port) + helper:connect() - local status, response = helper:get(arg_path) - helper:close() + local status, response = helper:get(arg_path) + helper:close() - if ( not(status) ) then - return fail("Failed to retrieve server headers") - end - return stdnse.format_output(true, response.rawheaders) + if ( not(status) ) then + return fail("Failed to retrieve server headers") + end + return stdnse.format_output(true, response.rawheaders) end diff --git a/scripts/ajp-methods.nse b/scripts/ajp-methods.nse index aedc6a8e7..79409352b 100644 --- a/scripts/ajp-methods.nse +++ b/scripts/ajp-methods.nse @@ -42,40 +42,40 @@ local arg_url = stdnse.get_script_args(SCRIPT_NAME .. ".path") or "/" local UNINTERESTING_METHODS = { "GET", "HEAD", "POST", "OPTIONS" } local function filter_out(t, filter) - local result = {} - for _, e in ipairs(t) do - if ( not(stdnse.contains(filter, e)) ) then - result[#result + 1] = e - end - end - return result + local result = {} + for _, e in ipairs(t) do + if ( not(stdnse.contains(filter, e)) ) then + result[#result + 1] = e + end + end + return result end local function fail(err) return ("\n ERROR: %s"):format(err or "") end action = function(host, port) - local helper = ajp.Helper:new(host, port) - if ( not(helper:connect()) ) then - return fail("Failed to connect to server") - end + local helper = ajp.Helper:new(host, port) + if ( not(helper:connect()) ) then + return fail("Failed to connect to server") + end - local status, response = helper:options(arg_url) - helper:close() - if ( not(status) or response.status ~= 200 or - not(response.headers) or not(response.headers['allow']) ) then - return "Failed to get a valid response for the OPTION request" - end + local status, response = helper:options(arg_url) + helper:close() + if ( not(status) or response.status ~= 200 or + not(response.headers) or not(response.headers['allow']) ) then + return "Failed to get a valid response for the OPTION request" + end - local methods = stdnse.strsplit(",%s", response.headers['allow']) + local methods = stdnse.strsplit(",%s", response.headers['allow']) - local output = {} - table.insert(output, ("Supported methods: %s"):format(stdnse.strjoin(" ", methods))) + local output = {} + table.insert(output, ("Supported methods: %s"):format(stdnse.strjoin(" ", methods))) - local interesting = filter_out(methods, UNINTERESTING_METHODS) - if ( #interesting > 0 ) then - table.insert(output, "Potentially risky methods: " .. stdnse.strjoin(" ", interesting)) - table.insert(output, "See http://nmap.org/nsedoc/scripts/ajp-methods.html") - end - return stdnse.format_output(true, output) + local interesting = filter_out(methods, UNINTERESTING_METHODS) + if ( #interesting > 0 ) then + table.insert(output, "Potentially risky methods: " .. stdnse.strjoin(" ", interesting)) + table.insert(output, "See http://nmap.org/nsedoc/scripts/ajp-methods.html") + end + return stdnse.format_output(true, output) end diff --git a/scripts/ajp-request.nse b/scripts/ajp-request.nse index c75b7443e..862985fe8 100644 --- a/scripts/ajp-request.nse +++ b/scripts/ajp-request.nse @@ -56,47 +56,47 @@ local function fail(err) return ("\n ERROR: %s"):format(err or "") end action = function(host, port) - local helper = ajp.Helper:new(host, port) - if ( not(helper:connect()) ) then - return fail("Failed to connect to AJP server") - end + local helper = ajp.Helper:new(host, port) + if ( not(helper:connect()) ) then + return fail("Failed to connect to AJP server") + end - local valid_methods = { - ["GET"] = true, - ["HEAD"] = true, - ["TRACE"] = true, - ["PUT"] = true, - ["DELETE"] = true, - ["OPTIONS"]= true, - } + local valid_methods = { + ["GET"] = true, + ["HEAD"] = true, + ["TRACE"] = true, + ["PUT"] = true, + ["DELETE"] = true, + ["OPTIONS"]= true, + } - local method = arg_method:upper() - if ( not(valid_methods[method]) ) then - return fail(("Method not supported: %s"):format(arg_method)) - end + local method = arg_method:upper() + if ( not(valid_methods[method]) ) then + return fail(("Method not supported: %s"):format(arg_method)) + end - local options = { auth = { username = arg_username, password = arg_password } } - local status, response = helper:request(arg_method, arg_path, nil, nil, options) - if ( not(status) ) then - return fail("Failed to retrieve response for request") - end - helper:close() + local options = { auth = { username = arg_username, password = arg_password } } + local status, response = helper:request(arg_method, arg_path, nil, nil, options) + if ( not(status) ) then + return fail("Failed to retrieve response for request") + end + helper:close() - if ( response ) then - local output = response['status-line'] .. "\n" .. - stdnse.strjoin("\n", response.rawheaders) .. - (response.body and "\n\n" .. response.body or "") - if ( arg_file ) then - local f = io.open(arg_file, "w") - if ( not(f) ) then - return fail(("Failed to open file %s for writing"):format(arg_file)) - end - f:write(output) - f:close() - return ("Response was written to file: %s"):format(arg_file) - else - return "\n" .. output - end - end + if ( response ) then + local output = response['status-line'] .. "\n" .. + stdnse.strjoin("\n", response.rawheaders) .. + (response.body and "\n\n" .. response.body or "") + if ( arg_file ) then + local f = io.open(arg_file, "w") + if ( not(f) ) then + return fail(("Failed to open file %s for writing"):format(arg_file)) + end + f:write(output) + f:close() + return ("Response was written to file: %s"):format(arg_file) + else + return "\n" .. output + end + end end diff --git a/scripts/auth-owners.nse b/scripts/auth-owners.nse index d85d6d2bd..af6c3f951 100644 --- a/scripts/auth-owners.nse +++ b/scripts/auth-owners.nse @@ -32,49 +32,49 @@ license = "Same as Nmap--See http://nmap.org/book/man-legal.html" categories = {"default", "safe"} portrule = function(host, port) - local auth_port = { number=113, protocol="tcp" } - local identd = nmap.get_port_state(host, auth_port) + local auth_port = { number=113, protocol="tcp" } + local identd = nmap.get_port_state(host, auth_port) - return identd ~= nil - and identd.state == "open" - and port.protocol == "tcp" - and port.state == "open" + return identd ~= nil + and identd.state == "open" + and port.protocol == "tcp" + and port.state == "open" end action = function(host, port) - local owner = "" + local owner = "" - local client_ident = nmap.new_socket() - local client_service = nmap.new_socket() + local client_ident = nmap.new_socket() + local client_service = nmap.new_socket() - local catch = function() - client_ident:close() - client_service:close() - end + local catch = function() + client_ident:close() + client_service:close() + end - local try = nmap.new_try(catch) + local try = nmap.new_try(catch) - try(client_ident:connect(host, 113)) - try(client_service:connect(host, port)) + try(client_ident:connect(host, 113)) + try(client_service:connect(host, port)) - local localip, localport, remoteip, remoteport = - try(client_service:get_info()) + local localip, localport, remoteip, remoteport = + try(client_service:get_info()) - local request = port.number .. ", " .. localport .. "\r\n" + local request = port.number .. ", " .. localport .. "\r\n" - try(client_ident:send(request)) + try(client_ident:send(request)) - owner = try(client_ident:receive_lines(1)) + owner = try(client_ident:receive_lines(1)) - if string.match(owner, "ERROR") then - owner = nil - else - owner = string.match(owner, - "%d+%s*,%s*%d+%s*:%s*USERID%s*:%s*.+%s*:%s*(.+)\r?\n") - end + if string.match(owner, "ERROR") then + owner = nil + else + owner = string.match(owner, + "%d+%s*,%s*%d+%s*:%s*USERID%s*:%s*.+%s*:%s*(.+)\r?\n") + end - try(client_ident:close()) - try(client_service:close()) + try(client_ident:close()) + try(client_service:close()) - return owner + return owner end diff --git a/scripts/auth-spoof.nse b/scripts/auth-spoof.nse index 6213423d0..2824d79b4 100644 --- a/scripts/auth-spoof.nse +++ b/scripts/auth-spoof.nse @@ -26,12 +26,12 @@ categories = {"malware", "safe"} portrule = shortport.port_or_service(113, "auth") action = function(host, port) - local status, owner = comm.get_banner(host, port, {lines=1}) + local status, owner = comm.get_banner(host, port, {lines=1}) - if not status then - return - end + if not status then + return + end - return "Spoofed reply: " .. owner + return "Spoofed reply: " .. owner end diff --git a/scripts/bitcoin-getaddr.nse b/scripts/bitcoin-getaddr.nse index 0dd7cfe54..87782bfcf 100644 --- a/scripts/bitcoin-getaddr.nse +++ b/scripts/bitcoin-getaddr.nse @@ -40,35 +40,35 @@ portrule = shortport.port_or_service(8333, "bitcoin", "tcp" ) action = function(host, port) - local bcoin = bitcoin.Helper:new(host, port, { timeout = 20000 }) - local status = bcoin:connect() + local bcoin = bitcoin.Helper:new(host, port, { timeout = 20000 }) + local status = bcoin:connect() - if ( not(status) ) then - return "\n ERROR: Failed to connect to server" - end + if ( not(status) ) then + return "\n ERROR: Failed to connect to server" + end - local status, ver = bcoin:exchVersion() - if ( not(status) ) then - return "\n ERROR: Failed to extract version information" - end + local status, ver = bcoin:exchVersion() + if ( not(status) ) then + return "\n ERROR: Failed to extract version information" + end - local status, nodes = bcoin:getNodes() - if ( not(status) ) then - return "\n ERROR: Failed to extract address information" - end - bcoin:close() + local status, nodes = bcoin:getNodes() + if ( not(status) ) then + return "\n ERROR: Failed to extract address information" + end + bcoin:close() - local response = tab.new(2) - tab.addrow(response, "ip", "timestamp") + local response = tab.new(2) + tab.addrow(response, "ip", "timestamp") - for _, node in ipairs(nodes.addresses or {}) do - if ( target.ALLOW_NEW_TARGETS ) then - target.add(node.address.host) - end - tab.addrow(response, ("%s:%d"):format(node.address.host, node.address.port), os.date("%x %X", node.ts)) - end + for _, node in ipairs(nodes.addresses or {}) do + if ( target.ALLOW_NEW_TARGETS ) then + target.add(node.address.host) + end + tab.addrow(response, ("%s:%d"):format(node.address.host, node.address.port), os.date("%x %X", node.ts)) + end - if ( #response > 1 ) then - return stdnse.format_output(true, tab.dump(response) ) - end + if ( #response > 1 ) then + return stdnse.format_output(true, tab.dump(response) ) + end end diff --git a/scripts/bitcoin-info.nse b/scripts/bitcoin-info.nse index 3ea846937..2ed730f49 100644 --- a/scripts/bitcoin-info.nse +++ b/scripts/bitcoin-info.nse @@ -37,30 +37,30 @@ portrule = shortport.port_or_service(8333, "bitcoin", "tcp" ) action = function(host, port) - local NETWORK = { - [3652501241] = "main", - [3669344250] = "testnet" - } + local NETWORK = { + [3652501241] = "main", + [3669344250] = "testnet" + } - local bcoin = bitcoin.Helper:new(host, port, { timeout = 10000 }) - local status = bcoin:connect() + local bcoin = bitcoin.Helper:new(host, port, { timeout = 10000 }) + local status = bcoin:connect() - if ( not(status) ) then - return "\n ERROR: Failed to connect to server" - end + if ( not(status) ) then + return "\n ERROR: Failed to connect to server" + end - local status, ver = bcoin:exchVersion() - if ( not(status) ) then - return "\n ERROR: Failed to extract version information" - end - bcoin:close() + local status, ver = bcoin:exchVersion() + if ( not(status) ) then + return "\n ERROR: Failed to extract version information" + end + bcoin:close() - local result = {} - table.insert(result, ("Timestamp: %s"):format(stdnse.format_timestamp(ver.timestamp))) - table.insert(result, ("Network: %s"):format(NETWORK[ver.magic])) - table.insert(result, ("Version: %s"):format(ver.ver)) - table.insert(result, ("Node Id: %s"):format(ver.nodeid)) - table.insert(result, ("Lastblock: %s"):format(ver.lastblock)) + local result = {} + table.insert(result, ("Timestamp: %s"):format(stdnse.format_timestamp(ver.timestamp))) + table.insert(result, ("Network: %s"):format(NETWORK[ver.magic])) + table.insert(result, ("Version: %s"):format(ver.ver)) + table.insert(result, ("Node Id: %s"):format(ver.nodeid)) + table.insert(result, ("Lastblock: %s"):format(ver.lastblock)) - return stdnse.format_output(true, result) + return stdnse.format_output(true, result) end diff --git a/scripts/bjnp-discover.nse b/scripts/bjnp-discover.nse index 6a4684372..1e7f31138 100644 --- a/scripts/bjnp-discover.nse +++ b/scripts/bjnp-discover.nse @@ -35,16 +35,16 @@ local stdnse = require("stdnse") portrule = shortport.portnumber({8611, 8612}, "udp") action = function(host, port) - local helper = bjnp.Helper:new(host, port) - if ( not(helper:connect()) ) then - return "\n ERROR: Failed to connect to server" - end - local status, attrs - if ( port.number == 8611 ) then - status, attrs = helper:getPrinterIdentity() - else - status, attrs = helper:getScannerIdentity() - end - helper:close() - return stdnse.format_output(true, attrs) + local helper = bjnp.Helper:new(host, port) + if ( not(helper:connect()) ) then + return "\n ERROR: Failed to connect to server" + end + local status, attrs + if ( port.number == 8611 ) then + status, attrs = helper:getPrinterIdentity() + else + status, attrs = helper:getScannerIdentity() + end + helper:close() + return stdnse.format_output(true, attrs) end diff --git a/scripts/broadcast-avahi-dos.nse b/scripts/broadcast-avahi-dos.nse index fbafc4269..b9e4c1def 100644 --- a/scripts/broadcast-avahi-dos.nse +++ b/scripts/broadcast-avahi-dos.nse @@ -61,11 +61,11 @@ action = function() local output, hosts, tmp = {}, {}, {} for _, hostcfg in pairs(result) do for k, ip in pairs(hostcfg) do - if type(k) == "string" and k == "name" then - if avahi_send_null_udp(ip) then - table.insert(hosts, ip) - tmp[ip] = true - end + if type(k) == "string" and k == "name" then + if avahi_send_null_udp(ip) then + table.insert(hosts, ip) + tmp[ip] = true + end end end end @@ -74,7 +74,7 @@ action = function() hosts.name = "Discovered hosts:" table.insert(output, hosts) table.insert(output, - "After NULL UDP avahi packet DoS (CVE-2011-1002).") + "After NULL UDP avahi packet DoS (CVE-2011-1002).") stdnse.print_debug(3, "sleeping for %d seconds", wtime) stdnse.sleep(wtime) diff --git a/scripts/broadcast-db2-discover.nse b/scripts/broadcast-db2-discover.nse index 939fb1943..153589b0c 100644 --- a/scripts/broadcast-db2-discover.nse +++ b/scripts/broadcast-db2-discover.nse @@ -33,54 +33,54 @@ prerule = function() return true end -- @param server_version string containing the product release -- @return ver string containing the version information local function parseVersion( server_version ) - local pfx = string.sub(server_version,1,3) + local pfx = string.sub(server_version,1,3) - if pfx == "SQL" then - local major_version = string.sub(server_version,4,5) + if pfx == "SQL" then + local major_version = string.sub(server_version,4,5) - -- strip the leading 0 from the major version, for consistency with - -- nmap-service-probes results - if string.sub(major_version,1,1) == "0" then - major_version = string.sub(major_version,2) - end - local minor_version = string.sub(server_version,6,7) - local hotfix = string.sub(server_version,8) - server_version = major_version .. "." .. minor_version .. "." .. hotfix - else - return "Unknown version" - end + -- strip the leading 0 from the major version, for consistency with + -- nmap-service-probes results + if string.sub(major_version,1,1) == "0" then + major_version = string.sub(major_version,2) + end + local minor_version = string.sub(server_version,6,7) + local hotfix = string.sub(server_version,8) + server_version = major_version .. "." .. minor_version .. "." .. hotfix + else + return "Unknown version" + end - return ("IBM DB2 v%s"):format(server_version) + return ("IBM DB2 v%s"):format(server_version) end action = function() - local DB2GETADDR = "DB2GETADDR\0SQL09010\0" - local socket = nmap.new_socket("udp") - local result = {} - local host, port = "255.255.255.255", 523 + local DB2GETADDR = "DB2GETADDR\0SQL09010\0" + local socket = nmap.new_socket("udp") + local result = {} + local host, port = "255.255.255.255", 523 - socket:set_timeout(5000) - local status = socket:sendto( host, port, DB2GETADDR ) - if ( not(status) ) then return end + socket:set_timeout(5000) + local status = socket:sendto( host, port, DB2GETADDR ) + if ( not(status) ) then return end - while(true) do - local data - status, data = socket:receive() - if( not(status) ) then break end + while(true) do + local data + status, data = socket:receive() + if( not(status) ) then break end - local version, srvname = data:match("DB2RETADDR.(SQL%d+).(.-)\0") - local _, ip - status, _, _, ip, _ = socket:get_info() - if ( not(status) ) then return end + local version, srvname = data:match("DB2RETADDR.(SQL%d+).(.-)\0") + local _, ip + status, _, _, ip, _ = socket:get_info() + if ( not(status) ) then return end - if target.ALLOW_NEW_TARGETS then target.add(ip) end + if target.ALLOW_NEW_TARGETS then target.add(ip) end - if ( status ) then - table.insert( result, ("%s - Host: %s; Version: %s"):format(ip, srvname, parseVersion( version ) ) ) - end - end - socket:close() + if ( status ) then + table.insert( result, ("%s - Host: %s; Version: %s"):format(ip, srvname, parseVersion( version ) ) ) + end + end + socket:close() - return stdnse.format_output( true, result ) + return stdnse.format_output( true, result ) end diff --git a/scripts/broadcast-dns-service-discovery.nse b/scripts/broadcast-dns-service-discovery.nse index f7973fc0c..f19648342 100644 --- a/scripts/broadcast-dns-service-discovery.nse +++ b/scripts/broadcast-dns-service-discovery.nse @@ -47,11 +47,11 @@ categories = {"broadcast", "safe"} prerule = function() return true end action = function() - local helper = dnssd.Helper:new( ) - helper:setMulticast(true) + local helper = dnssd.Helper:new( ) + helper:setMulticast(true) - local status, result = helper:queryServices() - if ( status ) then - return stdnse.format_output(true, result) - end + local status, result = helper:queryServices() + if ( status ) then + return stdnse.format_output(true, result) + end end diff --git a/scripts/broadcast-netbios-master-browser.nse b/scripts/broadcast-netbios-master-browser.nse index 11d4e116f..117be68db 100644 --- a/scripts/broadcast-netbios-master-browser.nse +++ b/scripts/broadcast-netbios-master-browser.nse @@ -32,37 +32,37 @@ local function isGroup(flags) return ( bit.band(flags, 0x8000) == 0x8000 ) end action = function() - -- NBNS only works over ipv4 - if ( nmap.address_family() == "inet6") then return end + -- NBNS only works over ipv4 + if ( nmap.address_family() == "inet6") then return end - local MASTER_BROWSER_DOMAIN = 0x1D - local STD_WORKSTATION_SERVICE = 0x00 - local NBNAME = "\1\2__MSBROWSE__\2\1" - local BROADCAST_ADDR = "255.255.255.255" + local MASTER_BROWSER_DOMAIN = 0x1D + local STD_WORKSTATION_SERVICE = 0x00 + local NBNAME = "\1\2__MSBROWSE__\2\1" + local BROADCAST_ADDR = "255.255.255.255" - local status, result = netbios.nbquery( { ip = BROADCAST_ADDR }, NBNAME, { multiple = true }) - if ( not(status) ) then return end + local status, result = netbios.nbquery( { ip = BROADCAST_ADDR }, NBNAME, { multiple = true }) + if ( not(status) ) then return end - local outtab = tab.new(3) - tab.addrow(outtab, 'ip', 'server', 'domain') + local outtab = tab.new(3) + tab.addrow(outtab, 'ip', 'server', 'domain') - for _, v in ipairs(result) do - local status, names, _ = netbios.do_nbstat(v.peer) - local srv_name, domain_name - if (status) then - for _, item in ipairs(names) do - if ( item.suffix == MASTER_BROWSER_DOMAIN and not(isGroup(item.flags)) ) then - domain_name = item.name - elseif ( item.suffix == STD_WORKSTATION_SERVICE and not(isGroup(item.flags)) ) then - srv_name = item.name - end - end - if ( srv_name and domain_name ) then - tab.addrow(outtab, v.peer, srv_name, domain_name) - else - stdnse.print_debug(3, "No server name or domain name was found") - end - end - end - return "\n" .. tab.dump(outtab) + for _, v in ipairs(result) do + local status, names, _ = netbios.do_nbstat(v.peer) + local srv_name, domain_name + if (status) then + for _, item in ipairs(names) do + if ( item.suffix == MASTER_BROWSER_DOMAIN and not(isGroup(item.flags)) ) then + domain_name = item.name + elseif ( item.suffix == STD_WORKSTATION_SERVICE and not(isGroup(item.flags)) ) then + srv_name = item.name + end + end + if ( srv_name and domain_name ) then + tab.addrow(outtab, v.peer, srv_name, domain_name) + else + stdnse.print_debug(3, "No server name or domain name was found") + end + end + end + return "\n" .. tab.dump(outtab) end diff --git a/scripts/broadcast-networker-discover.nse b/scripts/broadcast-networker-discover.nse index 9c570e7cf..7d031d204 100644 --- a/scripts/broadcast-networker-discover.nse +++ b/scripts/broadcast-networker-discover.nse @@ -26,69 +26,69 @@ prerule = function() return true end local function Callit( host, port, program, protocol ) - local results = {} - local portmap, comm = rpc.Portmap:new(), rpc.Comm:new('rpcbind', 2) + local results = {} + local portmap, comm = rpc.Portmap:new(), rpc.Comm:new('rpcbind', 2) - local status, result = comm:Connect(host, port) - if (not(status)) then - return false, result - end + local status, result = comm:Connect(host, port) + if (not(status)) then + return false, result + end - comm.socket:set_timeout(10000) - status, result = portmap:Callit(comm, program, protocol, 2 ) - if ( not(status) ) then - return false, result - end + comm.socket:set_timeout(10000) + status, result = portmap:Callit(comm, program, protocol, 2 ) + if ( not(status) ) then + return false, result + end - while ( status ) do - local _, rhost - status, _, _, rhost, _ = comm:GetSocketInfo() - if (not(status)) then - return false, "Failed to get socket information" - end + while ( status ) do + local _, rhost + status, _, _, rhost, _ = comm:GetSocketInfo() + if (not(status)) then + return false, "Failed to get socket information" + end - if ( status ) then - table.insert(results, rhost) - end + if ( status ) then + table.insert(results, rhost) + end - status, result = comm:ReceivePacket() - end + status, result = comm:ReceivePacket() + end - comm:Disconnect() - return true, results + comm:Disconnect() + return true, results end local function fail(err) return ("\n ERROR: %s"):format(err or "") end action = function() - local results = {} - local ip = ( nmap.address_family() == "inet" ) and "255.255.255.255" or "ff02::202" - local iface = nmap.get_interface() + local results = {} + local ip = ( nmap.address_family() == "inet" ) and "255.255.255.255" or "ff02::202" + local iface = nmap.get_interface() - -- handle problematic sends on OS X requiring the interface to be - -- supplied as part of IPv6 - if ( iface and nmap.address_family() == "inet6" ) then - ip = ip .. "%" .. iface - end + -- handle problematic sends on OS X requiring the interface to be + -- supplied as part of IPv6 + if ( iface and nmap.address_family() == "inet6" ) then + ip = ip .. "%" .. iface + end - for _, port in ipairs({7938,111}) do - local host, port = { ip = ip }, { number = port, protocol = "udp" } - local status - status, results = Callit( host, port, "nsrstat", "udp" ) + for _, port in ipairs({7938,111}) do + local host, port = { ip = ip }, { number = port, protocol = "udp" } + local status + status, results = Callit( host, port, "nsrstat", "udp" ) - -- warn about problematic sends on OS X requiring the interface to be - -- supplied as part of IPv6 - if ( not(status) and results == "Portmap.Callit: Failed to send data" ) then - return fail("Failed sending data, try supplying the correct interface using -e") - end + -- warn about problematic sends on OS X requiring the interface to be + -- supplied as part of IPv6 + if ( not(status) and results == "Portmap.Callit: Failed to send data" ) then + return fail("Failed sending data, try supplying the correct interface using -e") + end - if ( status ) then - break - end - end + if ( status ) then + break + end + end - if ( "table" == type(results) and 0 < #results ) then - return stdnse.format_output(true, results) - end + if ( "table" == type(results) and 0 < #results ) then + return stdnse.format_output(true, results) + end end diff --git a/scripts/broadcast-novell-locate.nse b/scripts/broadcast-novell-locate.nse index 568ef6a15..0285a95bb 100644 --- a/scripts/broadcast-novell-locate.nse +++ b/scripts/broadcast-novell-locate.nse @@ -32,48 +32,48 @@ prerule = function() return true end function action() - local helper = srvloc.Helper:new() + local helper = srvloc.Helper:new() - local status, bindery = helper:ServiceRequest("bindery.novell", "DEFAULT") - if ( not(status) or not(bindery) ) then - helper:close() - return - end - bindery = bindery[1] - local srvname = bindery:match("%/%/%/(.*)$") + local status, bindery = helper:ServiceRequest("bindery.novell", "DEFAULT") + if ( not(status) or not(bindery) ) then + helper:close() + return + end + bindery = bindery[1] + local srvname = bindery:match("%/%/%/(.*)$") - local status, attrib = helper:AttributeRequest(bindery, "DEFAULT", "svcaddr-ws") - helper:close() - attrib = attrib:match("^%(svcaddr%-ws=(.*)%)$") - if ( not(attrib) ) then return end + local status, attrib = helper:AttributeRequest(bindery, "DEFAULT", "svcaddr-ws") + helper:close() + attrib = attrib:match("^%(svcaddr%-ws=(.*)%)$") + if ( not(attrib) ) then return end - local attribs = stdnse.strsplit(",", attrib) - if ( not(attribs) ) then return end + local attribs = stdnse.strsplit(",", attrib) + if ( not(attribs) ) then return end - local addrs = { name = "Addresses"} - local ips = {} - for _, attr in ipairs(attribs) do - local addr = attr:match("^%d*%-%d*%-%d*%-(........)") - if ( addr ) then - local pos, dw_addr = bin.unpack( " timeout ) - socket:close() + repeat + local status, data = socket:receive() + if ( status ) then + local srvname = data:match("^NR([^_]*)_*AHM_3___\0$") + if ( srvname ) then + local status, _, _, rhost, _ = socket:get_info() + if ( not(status) ) then + socket:close() + return false, "Failed to get socket information" + end + -- avoid duplicates + responses[rhost] = srvname + end + end + until( os.time() - stime > timeout ) + socket:close() - local result = {} - for ip, name in pairs(responses) do - table.insert(result, ("%s - %s"):format(ip,name)) - end - return stdnse.format_output(true, result) + local result = {} + for ip, name in pairs(responses) do + table.insert(result, ("%s - %s"):format(ip,name)) + end + return stdnse.format_output(true, result) end diff --git a/scripts/broadcast-tellstick-discover.nse b/scripts/broadcast-tellstick-discover.nse index 033f158f3..3ccfed57b 100644 --- a/scripts/broadcast-tellstick-discover.nse +++ b/scripts/broadcast-tellstick-discover.nse @@ -30,42 +30,42 @@ prerule = function() return ( nmap.address_family() == 'inet' ) end local function fail(err) return ("\n ERROR: %s"):format(err or "") end action = function() - local socket = nmap.new_socket("udp") - local host, port = { ip = "255.255.255.255" }, { number = 30303, protocol = "udp" } + local socket = nmap.new_socket("udp") + local host, port = { ip = "255.255.255.255" }, { number = 30303, protocol = "udp" } - socket:set_timeout(5000) - if ( not(socket:sendto(host, port, "D")) ) then - return fail("Failed to send discovery request to server") - end + socket:set_timeout(5000) + if ( not(socket:sendto(host, port, "D")) ) then + return fail("Failed to send discovery request to server") + end - local output = {} + local output = {} - while( true ) do - local status, response = socket:receive() - if ( not(status) ) then - break - end + while( true ) do + local status, response = socket:receive() + if ( not(status) ) then + break + end - local status, _, _, ip = socket:get_info() - if ( not(status) ) then - stdnse.print_debug(2, "Failed to get socket information") - break - end + local status, _, _, ip = socket:get_info() + if ( not(status) ) then + stdnse.print_debug(2, "Failed to get socket information") + break + end - local prod, mac, activation, version = response:match("^([^:]*):([^:]*):([^:]*):([^:]*)$") - if ( prod and mac and activation and version ) then - local output_part = { - name = ip, - ("Product: %s"):format(prod), - ("MAC: %s"):format(mac), - ("Activation code: %s"):format(activation), - ("Version: %s"):format(version) - } - table.insert(output, output_part) - end - end + local prod, mac, activation, version = response:match("^([^:]*):([^:]*):([^:]*):([^:]*)$") + if ( prod and mac and activation and version ) then + local output_part = { + name = ip, + ("Product: %s"):format(prod), + ("MAC: %s"):format(mac), + ("Activation code: %s"):format(activation), + ("Version: %s"):format(version) + } + table.insert(output, output_part) + end + end - if ( 0 < #output ) then - return stdnse.format_output(true, output) - end + if ( 0 < #output ) then + return stdnse.format_output(true, output) + end end diff --git a/scripts/broadcast-upnp-info.nse b/scripts/broadcast-upnp-info.nse index 8edaca0c4..8a084db9a 100644 --- a/scripts/broadcast-upnp-info.nse +++ b/scripts/broadcast-upnp-info.nse @@ -40,12 +40,12 @@ prerule = function() return true end -- Sends UPnP discovery packet to host, -- and extracts service information from results action = function() - local helper = upnp.Helper:new() - helper:setMulticast(true) - local status, result = helper:queryServices() + local helper = upnp.Helper:new() + helper:setMulticast(true) + local status, result = helper:queryServices() - if ( status ) then - return stdnse.format_output(true, result) - end + if ( status ) then + return stdnse.format_output(true, result) + end end diff --git a/scripts/broadcast-versant-locate.nse b/scripts/broadcast-versant-locate.nse index 537d0a41a..75f34fac1 100644 --- a/scripts/broadcast-versant-locate.nse +++ b/scripts/broadcast-versant-locate.nse @@ -25,14 +25,14 @@ categories = {"broadcast", "safe"} prerule = function() return true end action = function() - local helper = srvloc.Helper:new() - local status, result = helper:ServiceRequest("service:odbms.versant:vod", "default") - helper:close() + local helper = srvloc.Helper:new() + local status, result = helper:ServiceRequest("service:odbms.versant:vod", "default") + helper:close() - if ( not(status) ) then return end - local output = {} - for _, v in ipairs(result) do - table.insert(output, v:match("^service:odbms.versant:vod://(.*)$")) - end - return stdnse.format_output(true, output) + if ( not(status) ) then return end + local output = {} + for _, v in ipairs(result) do + table.insert(output, v:match("^service:odbms.versant:vod://(.*)$")) + end + return stdnse.format_output(true, output) end diff --git a/scripts/broadcast-wake-on-lan.nse b/scripts/broadcast-wake-on-lan.nse index 212e346c3..a2687e694 100644 --- a/scripts/broadcast-wake-on-lan.nse +++ b/scripts/broadcast-wake-on-lan.nse @@ -27,45 +27,45 @@ local MAC = stdnse.get_script_args("broadcast-wake-on-lan.MAC") local address = stdnse.get_script_args("broadcast-wake-on-lan.address") prerule = function() - -- only run if we are ipv4 and have a MAC - return (MAC ~= nil and nmap.address_family() == "inet") + -- only run if we are ipv4 and have a MAC + return (MAC ~= nil and nmap.address_family() == "inet") end -- Creates the WoL packet based on the remote MAC -- @param mac string containing the MAC without delimiters -- @return packet string containing the raw packet local function createWOLPacket(mac) - local packet = bin.pack("H", "FFFFFFFFFFFF") - for i=1, 16 do - packet = packet .. bin.pack("H", mac) - end - return packet + local packet = bin.pack("H", "FFFFFFFFFFFF") + for i=1, 16 do + packet = packet .. bin.pack("H", mac) + end + return packet end action = function() - local MAC_hex - if ( MAC:match("%x%x:%x%x:%x%x:%x%x:%x%x:%x%x") ) then - MAC_hex = MAC:gsub(":", "") - elseif( MAC:match("%x%x%-%x%x%-%x%x%-%x%x%-%x%x%-%x%x") ) then - MAC_hex = MAC:gsub("-", "") - else - return "\n ERROR: Failed to process MAC address" - end + local MAC_hex + if ( MAC:match("%x%x:%x%x:%x%x:%x%x:%x%x:%x%x") ) then + MAC_hex = MAC:gsub(":", "") + elseif( MAC:match("%x%x%-%x%x%-%x%x%-%x%x%-%x%x%-%x%x") ) then + MAC_hex = MAC:gsub("-", "") + else + return "\n ERROR: Failed to process MAC address" + end - local host = { ip = address or "255.255.255.255" } - local port = { number = 9, protocol = "udp" } - local socket = nmap.new_socket("udp") + local host = { ip = address or "255.255.255.255" } + local port = { number = 9, protocol = "udp" } + local socket = nmap.new_socket("udp") - -- send two packets, just in case - for i=1,2 do - local packet = createWOLPacket(MAC_hex) - local status, err = socket:sendto(host, port, packet) - if ( not(status) ) then - return "\n ERROR: Failed to send packet" - end - end - return stdnse.format_output(true, ("Sent WOL packet to: %s"):format(MAC)) + -- send two packets, just in case + for i=1,2 do + local packet = createWOLPacket(MAC_hex) + local status, err = socket:sendto(host, port, packet) + if ( not(status) ) then + return "\n ERROR: Failed to send packet" + end + end + return stdnse.format_output(true, ("Sent WOL packet to: %s"):format(MAC)) end diff --git a/scripts/broadcast-wsdd-discover.nse b/scripts/broadcast-wsdd-discover.nse index bd4a2ddef..680dd1f0e 100644 --- a/scripts/broadcast-wsdd-discover.nse +++ b/scripts/broadcast-wsdd-discover.nse @@ -54,49 +54,49 @@ prerule = function() return true end -- the name should be one of the discovery functions in wsdd.Helper -- @param result table into which the results are stored discoverThread = function( funcname, results ) - -- calculates a timeout based on the timing template (default: 5s) - local timeout = ( 20000 / ( nmap.timing_level() + 1 ) ) - local condvar = nmap.condvar( results ) - local helper = wsdd.Helper:new() - helper:setMulticast(true) - helper:setTimeout(timeout) + -- calculates a timeout based on the timing template (default: 5s) + local timeout = ( 20000 / ( nmap.timing_level() + 1 ) ) + local condvar = nmap.condvar( results ) + local helper = wsdd.Helper:new() + helper:setMulticast(true) + helper:setTimeout(timeout) - local status, result = helper[funcname](helper) - if ( status ) then table.insert(results, result) end - condvar("broadcast") + local status, result = helper[funcname](helper) + if ( status ) then table.insert(results, result) end + condvar("broadcast") end local function sortfunc(a,b) - if ( a and b and a.name and b.name ) and ( a.name < b.name ) then - return true - end - return false + if ( a and b and a.name and b.name ) and ( a.name < b.name ) then + return true + end + return false end action = function() - local threads, results = {}, {} - local condvar = nmap.condvar( results ) + local threads, results = {}, {} + local condvar = nmap.condvar( results ) - -- Attempt to discover both devices and WCF web services - for _, f in ipairs( {"discoverDevices", "discoverWCFServices"} ) do - threads[stdnse.new_thread( discoverThread, f, results )] = true - end + -- Attempt to discover both devices and WCF web services + for _, f in ipairs( {"discoverDevices", "discoverWCFServices"} ) do + threads[stdnse.new_thread( discoverThread, f, results )] = true + end - local done - -- wait for all threads to finish - while( not(done) ) do - done = true - for thread in pairs(threads) do - if (coroutine.status(thread) ~= "dead") then done = false end - end - if ( not(done) ) then - condvar("wait") - end - end + local done + -- wait for all threads to finish + while( not(done) ) do + done = true + for thread in pairs(threads) do + if (coroutine.status(thread) ~= "dead") then done = false end + end + if ( not(done) ) then + condvar("wait") + end + end - if ( results ) then - table.sort( results, sortfunc ) - return stdnse.format_output(true, results) - end + if ( results ) then + table.sort( results, sortfunc ) + return stdnse.format_output(true, results) + end end diff --git a/scripts/broadcast-xdmcp-discover.nse b/scripts/broadcast-xdmcp-discover.nse index d0a0c2def..c19b0a50b 100644 --- a/scripts/broadcast-xdmcp-discover.nse +++ b/scripts/broadcast-xdmcp-discover.nse @@ -31,43 +31,43 @@ local arg_timeout = stdnse.parse_timespec(stdnse.get_script_args(SCRIPT_NAME .. action = function() - local host, port = { ip = "255.255.255.255" }, { number = 177, protocol = "udp" } - local options = { timeout = 1 } - local helper = xdmcp.Helper:new(host, port, options) - local status = helper:connect() + local host, port = { ip = "255.255.255.255" }, { number = 177, protocol = "udp" } + local options = { timeout = 1 } + local helper = xdmcp.Helper:new(host, port, options) + local status = helper:connect() - local req = xdmcp.Packet[xdmcp.OpCode.BCAST_QUERY]:new(nil) - local status, err = helper:send(req) - if ( not(status) ) then - return false, err - end + local req = xdmcp.Packet[xdmcp.OpCode.BCAST_QUERY]:new(nil) + local status, err = helper:send(req) + if ( not(status) ) then + return false, err + end - local timeout = arg_timeout or 5 - local start = os.time() - local result = {} - repeat + local timeout = arg_timeout or 5 + local start = os.time() + local result = {} + repeat - local status, response = helper:recv() - if ( not(status) and response ~= "TIMEOUT" ) then - break - elseif ( status ) then - local status, _, _, rhost = helper.socket:get_info() - if ( response.header.opcode == xdmcp.OpCode.WILLING ) then - result[rhost] = true - else - result[rhost] = false - end - end + local status, response = helper:recv() + if ( not(status) and response ~= "TIMEOUT" ) then + break + elseif ( status ) then + local status, _, _, rhost = helper.socket:get_info() + if ( response.header.opcode == xdmcp.OpCode.WILLING ) then + result[rhost] = true + else + result[rhost] = false + end + end - until( os.time() - start > timeout ) + until( os.time() - start > timeout ) - local output = {} - for ip, res in pairs(result) do - if ( res ) then - table.insert(output, ("%s - Willing"):format(ip)) - else - table.insert(output, ("%s - Unwilling"):format(ip)) - end - end - return stdnse.format_output(true, output) + local output = {} + for ip, res in pairs(result) do + if ( res ) then + table.insert(output, ("%s - Willing"):format(ip)) + else + table.insert(output, ("%s - Unwilling"):format(ip)) + end + end + return stdnse.format_output(true, output) end diff --git a/scripts/cassandra-info.nse b/scripts/cassandra-info.nse index b0c1f21b3..bdcf77e7a 100644 --- a/scripts/cassandra-info.nse +++ b/scripts/cassandra-info.nse @@ -40,55 +40,55 @@ portrule = shortport.port_or_service({9160}, {"cassandra"}) function action(host,port) - local socket = nmap.new_socket() - local cassinc = 2 -- cmd/resp starts at 2 + local socket = nmap.new_socket() + local cassinc = 2 -- cmd/resp starts at 2 - -- set a reasonable timeout value - socket:set_timeout(10000) - -- do some exception / cleanup - local catch = function() - socket:close() - end + -- set a reasonable timeout value + socket:set_timeout(10000) + -- do some exception / cleanup + local catch = function() + socket:close() + end - local try = nmap.new_try(catch) + local try = nmap.new_try(catch) - try( socket:connect(host, port) ) + try( socket:connect(host, port) ) - local results = {} + local results = {} - -- uglyness to allow creds.cassandra to work, as the port is not recognized - -- as cassandra even when service scan was run, taken from mongodb - local ps = port.service - port.service = 'cassandra' - local c = creds.Credentials:new(creds.ALL_DATA, host, port) - for cred in c:getCredentials(creds.State.VALID + creds.State.PARAM) do - local status, err = cassandra.login(socket, cred.user, cred.pass) - table.insert(results, ("Using credentials: %s"):format(cred.user.."/"..cred.pass)) - if ( not(status) ) then - return err - end - end - port.service = ps + -- uglyness to allow creds.cassandra to work, as the port is not recognized + -- as cassandra even when service scan was run, taken from mongodb + local ps = port.service + port.service = 'cassandra' + local c = creds.Credentials:new(creds.ALL_DATA, host, port) + for cred in c:getCredentials(creds.State.VALID + creds.State.PARAM) do + local status, err = cassandra.login(socket, cred.user, cred.pass) + table.insert(results, ("Using credentials: %s"):format(cred.user.."/"..cred.pass)) + if ( not(status) ) then + return err + end + end + port.service = ps - local status, val = cassandra.describe_cluster_name(socket,cassinc) - if (not(status)) then - return "Error getting cluster name: " .. val - end - cassinc = cassinc + 1 - port.version.name ='cassandra' - port.version.product='Cassandra' - port.version.name_confidence = 10 - nmap.set_port_version(host,port) - table.insert(results, ("Cluster name: %s"):format(val)) + local status, val = cassandra.describe_cluster_name(socket,cassinc) + if (not(status)) then + return "Error getting cluster name: " .. val + end + cassinc = cassinc + 1 + port.version.name ='cassandra' + port.version.product='Cassandra' + port.version.name_confidence = 10 + nmap.set_port_version(host,port) + table.insert(results, ("Cluster name: %s"):format(val)) - local status, val = cassandra.describe_version(socket,cassinc) - if (not(status)) then - return "Error getting version: " .. val - end - cassinc = cassinc + 1 - port.version.product='Cassandra ('..val..')' - nmap.set_port_version(host,port) - table.insert(results, ("Version: %s"):format(val)) + local status, val = cassandra.describe_version(socket,cassinc) + if (not(status)) then + return "Error getting version: " .. val + end + cassinc = cassinc + 1 + port.version.product='Cassandra ('..val..')' + nmap.set_port_version(host,port) + table.insert(results, ("Version: %s"):format(val)) - return stdnse.format_output(true, results) + return stdnse.format_output(true, results) end diff --git a/scripts/cccam-version.nse b/scripts/cccam-version.nse index a0f5fe69a..2f5ca3158 100644 --- a/scripts/cccam-version.nse +++ b/scripts/cccam-version.nse @@ -23,43 +23,43 @@ author = "David Fifield" local NUM_TRIALS = 2 local function trial(host, port) - local status, data, s + local status, data, s - s = nmap.new_socket() - status, data = s:connect(host, port) - if not status then - return - end + s = nmap.new_socket() + status, data = s:connect(host, port) + if not status then + return + end - status, data = s:receive_bytes(0) - if not status then - s:close() - return - end - s:close() + status, data = s:receive_bytes(0) + if not status then + s:close() + return + end + s:close() - return data + return data end portrule = shortport.version_port_or_service({10000, 10001, 12000, 12001, 16000, 16001}, "cccam") function action(host, port) - local seen = {} + local seen = {} - -- Try a couple of times to see that the response isn't constant. (But - -- more trials also increase the chance that we will reject a legitimate - -- cccam service.) - for i = 1, NUM_TRIALS do - local data + -- Try a couple of times to see that the response isn't constant. (But + -- more trials also increase the chance that we will reject a legitimate + -- cccam service.) + for i = 1, NUM_TRIALS do + local data - data = trial(host, port) - if not data or seen[data] or #data ~= 16 or not formulas.looksRandom(data) then - return - end - seen[data] = true - end + data = trial(host, port) + if not data or seen[data] or #data ~= 16 or not formulas.looksRandom(data) then + return + end + seen[data] = true + end - port.version.name = "cccam" - port.version.version = "CCcam DVR card sharing system" - nmap.set_port_version(host, port) + port.version.name = "cccam" + port.version.version = "CCcam DVR card sharing system" + nmap.set_port_version(host, port) end diff --git a/scripts/citrix-enum-servers-xml.nse b/scripts/citrix-enum-servers-xml.nse index 349f70956..98bb16a88 100644 --- a/scripts/citrix-enum-servers-xml.nse +++ b/scripts/citrix-enum-servers-xml.nse @@ -34,14 +34,14 @@ portrule = shortport.portnumber({8080,80,443}, "tcp") action = function(host, port) - local xmldata = citrixxml.request_server_data(host.ip, port.number) - local servers = citrixxml.parse_server_data_response(xmldata) - local response = {} + local xmldata = citrixxml.request_server_data(host.ip, port.number) + local servers = citrixxml.parse_server_data_response(xmldata) + local response = {} - for _, srv in ipairs(servers) do - table.insert(response, srv) - end + for _, srv in ipairs(servers) do + table.insert(response, srv) + end - return stdnse.format_output(true, response) + return stdnse.format_output(true, response) end diff --git a/scripts/couchdb-databases.nse b/scripts/couchdb-databases.nse index e7a6612d3..700d49173 100644 --- a/scripts/couchdb-databases.nse +++ b/scripts/couchdb-databases.nse @@ -39,7 +39,7 @@ categories = {"discovery", "safe"} portrule = shortport.port_or_service({5984}) -- Some lazy shortcuts local function dbg(str,...) - stdnse.print_debug("couchdb-get-tables:"..str, ...) + stdnse.print_debug("couchdb-get-tables:"..str, ...) end local DISCARD = {} @@ -49,51 +49,51 @@ local DISCARD = {} -- @param data a table containg data --@return another table containing data, with some keys removed local function queryResultToTable(data) - local result = {} - for k,v in pairs(data) do - dbg("(%s,%s)",k,tostring(v)) - if DISCARD[k] ~= 1 then - if type(v) == 'table' then - table.insert(result,k) - table.insert(result,queryResultToTable(v)) - else - table.insert(result,(("%s = %s"):format(tostring(k), tostring(v)))) - end - end - end - return result + local result = {} + for k,v in pairs(data) do + dbg("(%s,%s)",k,tostring(v)) + if DISCARD[k] ~= 1 then + if type(v) == 'table' then + table.insert(result,k) + table.insert(result,queryResultToTable(v)) + else + table.insert(result,(("%s = %s"):format(tostring(k), tostring(v)))) + end + end + end + return result end action = function(host, port) - local data, result, err - dbg("Requesting all databases") - data = http.get( host, port, '/_all_dbs' ) + local data, result, err + dbg("Requesting all databases") + data = http.get( host, port, '/_all_dbs' ) - -- check that body was received - if not data.body or data.body == "" then - local msg = ("%s did not respond with any data."):format(host.targetname or host.ip ) - dbg( msg ) - return msg - end + -- check that body was received + if not data.body or data.body == "" then + local msg = ("%s did not respond with any data."):format(host.targetname or host.ip ) + dbg( msg ) + return msg + end - -- The html body should look like this : - -- ["somedatabase", "anotherdatabase"] + -- The html body should look like this : + -- ["somedatabase", "anotherdatabase"] - local status, result = json.parse(data.body) - if not status then - dbg(result) - return result - end + local status, result = json.parse(data.body) + if not status then + dbg(result) + return result + end - -- Here we know it is a couchdb - port.version.name ='httpd' - port.version.product='Apache CouchDB' - nmap.set_port_version(host,port) + -- Here we know it is a couchdb + port.version.name ='httpd' + port.version.product='Apache CouchDB' + nmap.set_port_version(host,port) - -- We have a valid table in result containing the parsed json - -- now, get all the interesting bits + -- We have a valid table in result containing the parsed json + -- now, get all the interesting bits - result = queryResultToTable(result) + result = queryResultToTable(result) - return stdnse.format_output(true, result ) + return stdnse.format_output(true, result ) end diff --git a/scripts/creds-summary.nse b/scripts/creds-summary.nse index 0de397e8f..da91b853e 100644 --- a/scripts/creds-summary.nse +++ b/scripts/creds-summary.nse @@ -30,12 +30,12 @@ categories = {"auth", "default", "safe"} postrule = function() - local all = creds.Credentials:new(creds.ALL_DATA) - local tab = all:getTable() - if ( tab and #tab > 0 ) then return true end + local all = creds.Credentials:new(creds.ALL_DATA) + local tab = all:getTable() + if ( tab and #tab > 0 ) then return true end end action = function() - local all = creds.Credentials:new(creds.ALL_DATA) - return (all and tostring(all) or nil) + local all = creds.Credentials:new(creds.ALL_DATA) + return (all and tostring(all) or nil) end diff --git a/scripts/cups-info.nse b/scripts/cups-info.nse index 61df99623..1873b301f 100644 --- a/scripts/cups-info.nse +++ b/scripts/cups-info.nse @@ -47,35 +47,35 @@ local function fail(err) return ("\n ERROR: %s"):format(err or "") end action = function(host, port) - local helper = ipp.Helper:new(host, port) - if ( not(helper:connect()) ) then - return fail("Failed to connect to server") - end + local helper = ipp.Helper:new(host, port) + if ( not(helper:connect()) ) then + return fail("Failed to connect to server") + end - local status, printers = helper:getPrinters() - if ( not(status) ) then - return - end + local status, printers = helper:getPrinters() + if ( not(status) ) then + return + end - local output = {} - for _, printer in ipairs(printers) do - local states = { - [ipp.IPP.PrinterState.IPP_PRINTER_IDLE] = "Idle", - [ipp.IPP.PrinterState.IPP_PRINTER_PROCESSING] = "Processing", - [ipp.IPP.PrinterState.IPP_PRINTER_STOPPED] = "Stopped", - } - local pos, state = bin.unpack(">I", printer.state) - table.insert(output, { - name = printer.name, - ("DNS-SD Name: %s"):format(printer.dns_sd_name or ""), - ("Location: %s"):format(printer.location or ""), - ("Model: %s"):format(printer.model or ""), - ("State: %s"):format(states[state] or ""), - ("Queue: %s print jobs"):format(tonumber(printer.queue_count) or 0), - } ) - end + local output = {} + for _, printer in ipairs(printers) do + local states = { + [ipp.IPP.PrinterState.IPP_PRINTER_IDLE] = "Idle", + [ipp.IPP.PrinterState.IPP_PRINTER_PROCESSING] = "Processing", + [ipp.IPP.PrinterState.IPP_PRINTER_STOPPED] = "Stopped", + } + local pos, state = bin.unpack(">I", printer.state) + table.insert(output, { + name = printer.name, + ("DNS-SD Name: %s"):format(printer.dns_sd_name or ""), + ("Location: %s"):format(printer.location or ""), + ("Model: %s"):format(printer.model or ""), + ("State: %s"):format(states[state] or ""), + ("Queue: %s print jobs"):format(tonumber(printer.queue_count) or 0), + } ) + end - if ( 0 ~= #output ) then - return stdnse.format_output(true, output) - end + if ( 0 ~= #output ) then + return stdnse.format_output(true, output) + end end diff --git a/scripts/cups-queue-info.nse b/scripts/cups-queue-info.nse index 875625b97..495a40a0f 100644 --- a/scripts/cups-queue-info.nse +++ b/scripts/cups-queue-info.nse @@ -37,13 +37,13 @@ portrule = shortport.port_or_service(631, "ipp", "tcp", "open") local function fail(err) return ("\n ERROR: %s"):format(err or "") end action = function(host, port) - local helper = ipp.Helper:new(host, port) - if ( not(helper:connect()) ) then - return fail("Failed to connect to server") - end + local helper = ipp.Helper:new(host, port) + if ( not(helper:connect()) ) then + return fail("Failed to connect to server") + end - local output = helper:getQueueInfo() - if ( output ) then - return stdnse.format_output(true, output) - end + local output = helper:getQueueInfo() + if ( output ) then + return stdnse.format_output(true, output) + end end diff --git a/scripts/cvs-brute.nse b/scripts/cvs-brute.nse index e49f6a321..cd0396ff1 100644 --- a/scripts/cvs-brute.nse +++ b/scripts/cvs-brute.nse @@ -43,65 +43,65 @@ portrule = shortport.port_or_service(2401, "cvspserver") Driver = { - new = function(self, host, port, repo) - local o = { repo = repo, helper = cvs.Helper:new(host, port) } - setmetatable(o, self) - self.__index = self - return o - end, + new = function(self, host, port, repo) + local o = { repo = repo, helper = cvs.Helper:new(host, port) } + setmetatable(o, self) + self.__index = self + return o + end, - connect = function( self ) - self.helper:connect() - return true - end, + connect = function( self ) + self.helper:connect() + return true + end, - login = function( self, username, password ) - local status, err = self.helper:login( self.repo, username, password ) - if ( status ) then - return true, brute.Account:new(username, password, creds.State.VALID) - end + login = function( self, username, password ) + local status, err = self.helper:login( self.repo, username, password ) + if ( status ) then + return true, brute.Account:new(username, password, creds.State.VALID) + end - -- This error seems to indicate tha the user does not exist - if ( err:match("E PAM start error%: Critical error %- immediate abort\0$") ) then - stdnse.print_debug(2, "%s: The user %s does not exist", SCRIPT_NAME, username) - local err = brute.Error:new("Account invalid") - err:setInvalidAccount(username) - return false, err - end - return false, brute.Error:new( "Incorrect password" ) - end, + -- This error seems to indicate tha the user does not exist + if ( err:match("E PAM start error%: Critical error %- immediate abort\0$") ) then + stdnse.print_debug(2, "%s: The user %s does not exist", SCRIPT_NAME, username) + local err = brute.Error:new("Account invalid") + err:setInvalidAccount(username) + return false, err + end + return false, brute.Error:new( "Incorrect password" ) + end, - disconnect = function( self ) - self.helper:close() - end, + disconnect = function( self ) + self.helper:close() + end, } local function getDiscoveredRepos(host) - if ( not(host.registry.cvs_repos)) then - return - end + if ( not(host.registry.cvs_repos)) then + return + end - return host.registry.cvs_repos + return host.registry.cvs_repos end action = function(host, port) - local repo = stdnse.get_script_args("cvs-brute.repo") and - { stdnse.get_script_args("cvs-brute.repo") } or - getDiscoveredRepos(host) - if ( not(repo) ) then return "\n ERROR: No CVS repository specified (see cvs-brute.repo)" end + local repo = stdnse.get_script_args("cvs-brute.repo") and + { stdnse.get_script_args("cvs-brute.repo") } or + getDiscoveredRepos(host) + if ( not(repo) ) then return "\n ERROR: No CVS repository specified (see cvs-brute.repo)" end - local status, result + local status, result - -- If repositories were discovered and not overridden by argument - -- only attempt to brute force the first one. - local engine = brute.Engine:new(Driver, host, port, repo[1]) + -- If repositories were discovered and not overridden by argument + -- only attempt to brute force the first one. + local engine = brute.Engine:new(Driver, host, port, repo[1]) - engine.options.script_name = SCRIPT_NAME - status, result = engine:start() + engine.options.script_name = SCRIPT_NAME + status, result = engine:start() - return result + return result end diff --git a/scripts/daytime.nse b/scripts/daytime.nse index 773f69c8a..171a85181 100644 --- a/scripts/daytime.nse +++ b/scripts/daytime.nse @@ -21,9 +21,9 @@ categories = {"discovery", "safe"} portrule = shortport.port_or_service(13, "daytime", {"tcp", "udp"}) action = function(host, port) - local status, result = comm.exchange(host, port, "dummy", {lines=1, proto=port.protocol}) + local status, result = comm.exchange(host, port, "dummy", {lines=1, proto=port.protocol}) - if status then - return result - end + if status then + return result + end end diff --git a/scripts/db2-discover.nse b/scripts/db2-discover.nse index c6a702806..a2a067bc5 100644 --- a/scripts/db2-discover.nse +++ b/scripts/db2-discover.nse @@ -31,64 +31,64 @@ categories = {"discovery", "safe", "default"} portrule = shortport.version_port_or_service(523, "ibm-db2", "udp", - {"open", "open|filtered"}) + {"open", "open|filtered"}) --- Converts the prodrel server string to a version string -- -- @param server_version string containing the product release -- @return ver string containing the version information local function parseVersion( server_version ) - local pfx = string.sub(server_version,1,3) + local pfx = string.sub(server_version,1,3) - if pfx == "SQL" then - local major_version = string.sub(server_version,4,5) + if pfx == "SQL" then + local major_version = string.sub(server_version,4,5) - -- strip the leading 0 from the major version, for consistency with - -- nmap-service-probes results - if string.sub(major_version,1,1) == "0" then - major_version = string.sub(major_version,2) - end - local minor_version = string.sub(server_version,6,7) - local hotfix = string.sub(server_version,8) - server_version = major_version .. "." .. minor_version .. "." .. hotfix - else - return "Unknown version" - end + -- strip the leading 0 from the major version, for consistency with + -- nmap-service-probes results + if string.sub(major_version,1,1) == "0" then + major_version = string.sub(major_version,2) + end + local minor_version = string.sub(server_version,6,7) + local hotfix = string.sub(server_version,8) + server_version = major_version .. "." .. minor_version .. "." .. hotfix + else + return "Unknown version" + end - return ("IBM DB2 v%s"):format(server_version) + return ("IBM DB2 v%s"):format(server_version) end action = function(host, port) - local DB2GETADDR = "DB2GETADDR\0SQL09010\0" - local socket = nmap.new_socket() - local result = {} + local DB2GETADDR = "DB2GETADDR\0SQL09010\0" + local socket = nmap.new_socket() + local result = {} - socket:set_timeout(5000) + socket:set_timeout(5000) - local status, err = socket:connect( host, port, "udp") - if ( not(status) ) then return end + local status, err = socket:connect( host, port, "udp") + if ( not(status) ) then return end - status, err = socket:send( DB2GETADDR ) - if ( not(status) ) then return end + status, err = socket:send( DB2GETADDR ) + if ( not(status) ) then return end - local data - status, data = socket:receive() - if( not(status) ) then - socket:close() - return - end + local data + status, data = socket:receive() + if( not(status) ) then + socket:close() + return + end - local version, srvname = data:match("DB2RETADDR.(SQL%d+).(.-)\0") + local version, srvname = data:match("DB2RETADDR.(SQL%d+).(.-)\0") - if ( status ) then - table.insert( result, ("Host: %s"):format(srvname) ) - table.insert( result, ("Version: %s"):format(parseVersion(version)) ) - end + if ( status ) then + table.insert( result, ("Host: %s"):format(srvname) ) + table.insert( result, ("Version: %s"):format(parseVersion(version)) ) + end - socket:close() - -- set port to open - nmap.set_port_state(host, port, "open") + socket:close() + -- set port to open + nmap.set_port_state(host, port, "open") - return stdnse.format_output( true, result ) + return stdnse.format_output( true, result ) end diff --git a/scripts/dict-info.nse b/scripts/dict-info.nse index 3a0d026f1..2bd59541a 100644 --- a/scripts/dict-info.nse +++ b/scripts/dict-info.nse @@ -40,39 +40,39 @@ portrule = shortport.port_or_service(2628, "dict", "tcp") local function fail(err) return ("\n ERROR: %s"):format(err or "") end action = function(host, port) - local socket = nmap.new_socket() - if ( not(socket:connect(host, port)) ) then - return fail("Failed to connect to dictd server") - end + local socket = nmap.new_socket() + if ( not(socket:connect(host, port)) ) then + return fail("Failed to connect to dictd server") + end - local probes = { - 'client "dict 1.12.0/rf on Linux 3.0.0-12-generic"', - 'show server', - 'quit', - } + local probes = { + 'client "dict 1.12.0/rf on Linux 3.0.0-12-generic"', + 'show server', + 'quit', + } - if ( not(socket:send(stdnse.strjoin("\r\n", probes) .. "\r\n")) ) then - return fail("Failed to send request to server") - end + if ( not(socket:send(stdnse.strjoin("\r\n", probes) .. "\r\n")) ) then + return fail("Failed to send request to server") + end - local srvinfo + local srvinfo - repeat - local status, data = socket:receive_buf("\r\n", false) - if ( not(status) ) then - return fail("Failed to read response from server") - elseif ( data:match("^5") ) then - return fail(data) - elseif ( data:match("^114") ) then - srvinfo = {} - elseif ( srvinfo and not(data:match("^%.$")) ) then - table.insert(srvinfo, data) - end - until(not(status) or data:match("^221") or data:match("^%.$")) - socket:close() + repeat + local status, data = socket:receive_buf("\r\n", false) + if ( not(status) ) then + return fail("Failed to read response from server") + elseif ( data:match("^5") ) then + return fail(data) + elseif ( data:match("^114") ) then + srvinfo = {} + elseif ( srvinfo and not(data:match("^%.$")) ) then + table.insert(srvinfo, data) + end + until(not(status) or data:match("^221") or data:match("^%.$")) + socket:close() - -- if last item is an empty string remove it, to avoid trailing line feed - srvinfo[#srvinfo] = ( srvinfo[#srvinfo] ~= "" and srvinfo[#srvinfo] or nil ) + -- if last item is an empty string remove it, to avoid trailing line feed + srvinfo[#srvinfo] = ( srvinfo[#srvinfo] ~= "" and srvinfo[#srvinfo] or nil ) - return stdnse.format_output(true, srvinfo) + return stdnse.format_output(true, srvinfo) end diff --git a/scripts/distcc-cve2004-2687.nse b/scripts/distcc-cve2004-2687.nse index d43d06098..0e24e1810 100644 --- a/scripts/distcc-cve2004-2687.nse +++ b/scripts/distcc-cve2004-2687.nse @@ -53,56 +53,56 @@ local function fail(err) return ("\n ERROR: %s"):format(err or "") end action = function(host, port) - local distcc_vuln = { - title = "distcc Daemon Command Execution", - IDS = {CVE = 'CVE-2004-2687'}, - risk_factor = "High", - scores = { - CVSSv2 = "9.3 (HIGH) (AV:N/AC:M/Au:N/C:C/I:C/A:C)", - }, - description = [[ + local distcc_vuln = { + title = "distcc Daemon Command Execution", + IDS = {CVE = 'CVE-2004-2687'}, + risk_factor = "High", + scores = { + CVSSv2 = "9.3 (HIGH) (AV:N/AC:M/Au:N/C:C/I:C/A:C)", + }, + description = [[ Allows executing of arbitrary commands on systems running distccd 3.1 and earlier. The vulnerability is the consequence of weak service configuration. ]], - references = { - 'http://http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2004-2687', - 'http://http://www.osvdb.org/13378', - 'http://distcc.googlecode.com/svn/trunk/doc/web/security.html', - }, - dates = { disclosure = {year = '2002', month = '02', day = '01'}, }, - exploit_results = {}, - } + references = { + 'http://http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2004-2687', + 'http://http://www.osvdb.org/13378', + 'http://distcc.googlecode.com/svn/trunk/doc/web/security.html', + }, + dates = { disclosure = {year = '2002', month = '02', day = '01'}, }, + exploit_results = {}, + } - local report = vulns.Report:new(SCRIPT_NAME, host, port) - distcc_vuln.state = vulns.STATE.NOT_VULN + local report = vulns.Report:new(SCRIPT_NAME, host, port) + distcc_vuln.state = vulns.STATE.NOT_VULN - local socket = nmap.new_socket() - if ( not(socket:connect(host, port)) ) then - return fail("Failed to connect to distcc server") - end + local socket = nmap.new_socket() + if ( not(socket:connect(host, port)) ) then + return fail("Failed to connect to distcc server") + end - local cmds = { - "DIST00000001", - ("ARGC00000008ARGV00000002shARGV00000002-cARGV%08.8xsh -c " .. - "'(%s)'ARGV00000001#ARGV00000002-cARGV00000006main.cARGV00000002" .. - "-oARGV00000006main.o"):format(10 + #arg_cmd, arg_cmd), - "DOTI00000001A\n", - } + local cmds = { + "DIST00000001", + ("ARGC00000008ARGV00000002shARGV00000002-cARGV%08.8xsh -c " .. + "'(%s)'ARGV00000001#ARGV00000002-cARGV00000006main.cARGV00000002" .. + "-oARGV00000006main.o"):format(10 + #arg_cmd, arg_cmd), + "DOTI00000001A\n", + } - for _, cmd in ipairs(cmds) do - if ( not(socket:send(cmd)) ) then - return fail("Failed to send data to distcc server") - end - end + for _, cmd in ipairs(cmds) do + if ( not(socket:send(cmd)) ) then + return fail("Failed to send data to distcc server") + end + end - local status, data = socket:receive_buf("DOTO00000000", false) + local status, data = socket:receive_buf("DOTO00000000", false) - if ( status ) then - local output = data:match("SOUT%w%w%w%w%w%w%w%w(.*)") - if (output and #output > 0) then - distcc_vuln.extra_info = stdnse.format_output(true, output) - distcc_vuln.state = vulns.STATE.EXPLOIT - return report:make_output(distcc_vuln) - end - end + if ( status ) then + local output = data:match("SOUT%w%w%w%w%w%w%w%w(.*)") + if (output and #output > 0) then + distcc_vuln.extra_info = stdnse.format_output(true, output) + distcc_vuln.state = vulns.STATE.EXPLOIT + return report:make_output(distcc_vuln) + end + end end diff --git a/scripts/dns-service-discovery.nse b/scripts/dns-service-discovery.nse index aec82924a..c7e4c8a30 100644 --- a/scripts/dns-service-discovery.nse +++ b/scripts/dns-service-discovery.nse @@ -55,13 +55,13 @@ categories = {"default", "discovery", "safe"} portrule = shortport.portnumber(5353, "udp") action = function(host, port) - local helper = dnssd.Helper:new( host, port ) - local status, result = helper:queryServices() + local helper = dnssd.Helper:new( host, port ) + local status, result = helper:queryServices() - if ( status ) then - -- set port to open - nmap.set_port_state(host, port, "open") - return stdnse.format_output(true, result) - end + if ( status ) then + -- set port to open + nmap.set_port_state(host, port, "open") + return stdnse.format_output(true, result) + end end diff --git a/scripts/dns-update.nse b/scripts/dns-update.nse index cfe714213..b01c19ab8 100644 --- a/scripts/dns-update.nse +++ b/scripts/dns-update.nse @@ -50,55 +50,55 @@ portrule = shortport.port_or_service( 53, "dns", "udp", {"open", "open|filtered" local function test(host, port) - local status, err = dns.update( "www.cqure.net", { host=host, port=port, dtype="A", data="10.10.10.10" } ) - if ( status ) then stdnse.print_debug("SUCCESS") else stdnse.print_debug("FAIL: " .. (err or "")) end - status, err = dns.update( "www2", { zone="cqure.net", host=host, port=port, dtype="A", data="10.10.10.10" } ) - if ( status ) then stdnse.print_debug("SUCCESS") else stdnse.print_debug("FAIL: " .. (err or "")) end - status, err = dns.update( "alias.cqure.net", { host=host, port=port, dtype="CNAME", data="www.cqure.net" } ) - if ( status ) then stdnse.print_debug("SUCCESS") else stdnse.print_debug("FAIL: " .. (err or "")) end - status, err = dns.update( "cqure.net", { host=host, port=port, dtype="MX", data={ pref=10, mx="mail.cqure.net"} }) - if ( status ) then stdnse.print_debug("SUCCESS") else stdnse.print_debug("FAIL: " .. (err or "")) end - status, err = dns.update( "_ldap._tcp.cqure.net", { host=host, port=port, dtype="SRV", data={ prio=0, weight=100, port=389, target="ldap.cqure.net" } } ) - if ( status ) then stdnse.print_debug("SUCCESS") else stdnse.print_debug("FAIL: " .. (err or "")) end + local status, err = dns.update( "www.cqure.net", { host=host, port=port, dtype="A", data="10.10.10.10" } ) + if ( status ) then stdnse.print_debug("SUCCESS") else stdnse.print_debug("FAIL: " .. (err or "")) end + status, err = dns.update( "www2", { zone="cqure.net", host=host, port=port, dtype="A", data="10.10.10.10" } ) + if ( status ) then stdnse.print_debug("SUCCESS") else stdnse.print_debug("FAIL: " .. (err or "")) end + status, err = dns.update( "alias.cqure.net", { host=host, port=port, dtype="CNAME", data="www.cqure.net" } ) + if ( status ) then stdnse.print_debug("SUCCESS") else stdnse.print_debug("FAIL: " .. (err or "")) end + status, err = dns.update( "cqure.net", { host=host, port=port, dtype="MX", data={ pref=10, mx="mail.cqure.net"} }) + if ( status ) then stdnse.print_debug("SUCCESS") else stdnse.print_debug("FAIL: " .. (err or "")) end + status, err = dns.update( "_ldap._tcp.cqure.net", { host=host, port=port, dtype="SRV", data={ prio=0, weight=100, port=389, target="ldap.cqure.net" } } ) + if ( status ) then stdnse.print_debug("SUCCESS") else stdnse.print_debug("FAIL: " .. (err or "")) end - status, err = dns.update( "www.cqure.net", { host=host, port=port, dtype="A", data="", ttl=0 } ) - if ( status ) then stdnse.print_debug("SUCCESS") else stdnse.print_debug("FAIL: " .. (err or "")) end - status, err = dns.update( "www2.cqure.net", { host=host, port=port, dtype="A", data="", ttl=0 } ) - if ( status ) then stdnse.print_debug("SUCCESS") else stdnse.print_debug("FAIL: " .. (err or "")) end - status, err = dns.update( "alias.cqure.net", { host=host, port=port, dtype="CNAME", data="", ttl=0 } ) - if ( status ) then stdnse.print_debug("SUCCESS") else stdnse.print_debug("FAIL: " .. (err or "")) end - status, err = dns.update( "cqure.net", { host=host, port=port, dtype="MX", data="", ttl=0 } ) - if ( status ) then stdnse.print_debug("SUCCESS") else stdnse.print_debug("FAIL: " .. (err or "")) end - status, err = dns.update( "_ldap._tcp.cqure.net", { host=host, port=port, dtype="SRV", data="", ttl=0 } ) - if ( status ) then stdnse.print_debug("SUCCESS") else stdnse.print_debug("FAIL: " .. (err or "")) end + status, err = dns.update( "www.cqure.net", { host=host, port=port, dtype="A", data="", ttl=0 } ) + if ( status ) then stdnse.print_debug("SUCCESS") else stdnse.print_debug("FAIL: " .. (err or "")) end + status, err = dns.update( "www2.cqure.net", { host=host, port=port, dtype="A", data="", ttl=0 } ) + if ( status ) then stdnse.print_debug("SUCCESS") else stdnse.print_debug("FAIL: " .. (err or "")) end + status, err = dns.update( "alias.cqure.net", { host=host, port=port, dtype="CNAME", data="", ttl=0 } ) + if ( status ) then stdnse.print_debug("SUCCESS") else stdnse.print_debug("FAIL: " .. (err or "")) end + status, err = dns.update( "cqure.net", { host=host, port=port, dtype="MX", data="", ttl=0 } ) + if ( status ) then stdnse.print_debug("SUCCESS") else stdnse.print_debug("FAIL: " .. (err or "")) end + status, err = dns.update( "_ldap._tcp.cqure.net", { host=host, port=port, dtype="SRV", data="", ttl=0 } ) + if ( status ) then stdnse.print_debug("SUCCESS") else stdnse.print_debug("FAIL: " .. (err or "")) end end action = function(host, port) - local t = stdnse.get_script_args('dns-update.test') - local name, ip = stdnse.get_script_args('dns-update.hostname', 'dns-update.ip') + local t = stdnse.get_script_args('dns-update.test') + local name, ip = stdnse.get_script_args('dns-update.hostname', 'dns-update.ip') - if ( t ) then return test(host, port) end - if ( not(name) or not(ip) ) then return end + if ( t ) then return test(host, port) end + if ( not(name) or not(ip) ) then return end - -- we really need an ip or name to continue - -- we could attempt a random name, but we need to know at least the name of the zone - local status, err = dns.update( name, { host=host, port=port, dtype="A", data=ip } ) + -- we really need an ip or name to continue + -- we could attempt a random name, but we need to know at least the name of the zone + local status, err = dns.update( name, { host=host, port=port, dtype="A", data=ip } ) - if ( status ) then - local result = {} - table.insert(result, ("Successfully added the record \"%s\""):format(name)) - local status = dns.update( name, { host=host, port=port, dtype="A", data="", ttl=0 } ) - if ( status ) then - table.insert(result, ("Successfully deleted the record \"%s\""):format(name)) - else - table.insert(result, ("Failed to delete the record \"%s\""):format(name)) - end - nmap.set_port_state(host, port, "open") - return stdnse.format_output(true, result) - elseif ( err ) then - return "\n ERROR: " .. err - end + if ( status ) then + local result = {} + table.insert(result, ("Successfully added the record \"%s\""):format(name)) + local status = dns.update( name, { host=host, port=port, dtype="A", data="", ttl=0 } ) + if ( status ) then + table.insert(result, ("Successfully deleted the record \"%s\""):format(name)) + else + table.insert(result, ("Failed to delete the record \"%s\""):format(name)) + end + nmap.set_port_state(host, port, "open") + return stdnse.format_output(true, result) + elseif ( err ) then + return "\n ERROR: " .. err + end end diff --git a/scripts/dns-zeustracker.nse b/scripts/dns-zeustracker.nse index 7861b78f6..3a4298e56 100644 --- a/scripts/dns-zeustracker.nse +++ b/scripts/dns-zeustracker.nse @@ -30,31 +30,31 @@ hostrule = function(host) return not(ipOps.isPrivate(host.ip)) end action = function(host) - local levels = { - "Bulletproof hosted", - "Hacked webserver", - "Free hosting service", - "Unknown", - "Hosted on a FastFlux botnet" - } - local dname = dns.reverse(host.ip) - dname = dname:gsub ("%.in%-addr%.arpa",".ipbl.zeustracker.abuse.ch") - local status, result = dns.query(dname, {dtype='TXT', retAll=true} ) + local levels = { + "Bulletproof hosted", + "Hacked webserver", + "Free hosting service", + "Unknown", + "Hosted on a FastFlux botnet" + } + local dname = dns.reverse(host.ip) + dname = dname:gsub ("%.in%-addr%.arpa",".ipbl.zeustracker.abuse.ch") + local status, result = dns.query(dname, {dtype='TXT', retAll=true} ) - if ( not(status) and result == "No Such Name" ) then - return - elseif ( not(status) ) then - return stdnse.format_output(false, "DNS Query failed") - end + if ( not(status) and result == "No Such Name" ) then + return + elseif ( not(status) ) then + return stdnse.format_output(false, "DNS Query failed") + end - local output = tab.new(9) - tab.addrow(output, "Name", "IP", "SBL", "ASN", "Country", "Status", "Level", - "Files Online", "Date added") - for _, record in ipairs(result) do - local name, ip, sbl, asn, country, status, level, files_online, - dateadded = table.unpack(stdnse.strsplit("| ", record)) - level = levels[tonumber(level)] or "Unknown" - tab.addrow(output, name, ip, sbl, asn, country, status, level, files_online, dateadded) - end - return stdnse.format_output(true, tab.dump(output)) + local output = tab.new(9) + tab.addrow(output, "Name", "IP", "SBL", "ASN", "Country", "Status", "Level", + "Files Online", "Date added") + for _, record in ipairs(result) do + local name, ip, sbl, asn, country, status, level, files_online, + dateadded = table.unpack(stdnse.strsplit("| ", record)) + level = levels[tonumber(level)] or "Unknown" + tab.addrow(output, name, ip, sbl, asn, country, status, level, files_online, dateadded) + end + return stdnse.format_output(true, tab.dump(output)) end diff --git a/scripts/epmd-info.nse b/scripts/epmd-info.nse index 490d55040..4289641bd 100644 --- a/scripts/epmd-info.nse +++ b/scripts/epmd-info.nse @@ -30,28 +30,28 @@ portrule = shortport.port_or_service (4369, "epmd") local NAMESREQ = 110 action = function(host, port) - local socket = nmap.new_socket() - local status, err = socket:connect(host.ip, port.number) - if not status then - return {} - end - local payload = bin.pack("C", NAMESREQ) - local probe = bin.pack(">SA", #payload, payload) - socket:send(probe) - local status = true - local data = "" - local tmp = "" - while status do - data = data .. tmp - status, tmp = socket:receive() - end - local pos, realport = bin.unpack(">I", data) - local nodestring = string.sub(data, pos, -2) - local nodes = stdnse.strsplit("\n", nodestring) - local response = {} - table.insert(response, 'epmd running on port ' .. realport) - for _, node in ipairs(nodes) do - table.insert(response, node) - end - return stdnse.format_output(true, response) + local socket = nmap.new_socket() + local status, err = socket:connect(host.ip, port.number) + if not status then + return {} + end + local payload = bin.pack("C", NAMESREQ) + local probe = bin.pack(">SA", #payload, payload) + socket:send(probe) + local status = true + local data = "" + local tmp = "" + while status do + data = data .. tmp + status, tmp = socket:receive() + end + local pos, realport = bin.unpack(">I", data) + local nodestring = string.sub(data, pos, -2) + local nodes = stdnse.strsplit("\n", nodestring) + local response = {} + table.insert(response, 'epmd running on port ' .. realport) + for _, node in ipairs(nodes) do + table.insert(response, node) + end + return stdnse.format_output(true, response) end diff --git a/scripts/eppc-enum-processes.nse b/scripts/eppc-enum-processes.nse index 7e790df26..fb057ac71 100644 --- a/scripts/eppc-enum-processes.nse +++ b/scripts/eppc-enum-processes.nse @@ -40,64 +40,64 @@ portrule = shortport.port_or_service(3031, "eppc", "tcp", "open") action = function( host, port ) - local socket = nmap.new_socket() - socket:set_timeout(5000) + local socket = nmap.new_socket() + socket:set_timeout(5000) - local try = nmap.new_try( - function() - stdnse.print_debug("%s: failed", SCRIPT_NAME) - socket:close() - end - ) + local try = nmap.new_try( + function() + stdnse.print_debug("%s: failed", SCRIPT_NAME) + socket:close() + end + ) - -- a list of application that may or may not be running on the target - local apps = { - "Address Book", - "App Store", - "Facetime", - "Finder", - "Firefox", - "Google Chrome", - "iChat", - "iPhoto", - "Keychain Access", - "iTunes", - "Photo booth", - "QuickTime Player", - "Remote Buddy", - "Safari", - "Spotify", - "Terminal", - "TextMate", - "Transmission", - "VLC", - "VLC media player", - } + -- a list of application that may or may not be running on the target + local apps = { + "Address Book", + "App Store", + "Facetime", + "Finder", + "Firefox", + "Google Chrome", + "iChat", + "iPhoto", + "Keychain Access", + "iTunes", + "Photo booth", + "QuickTime Player", + "Remote Buddy", + "Safari", + "Spotify", + "Terminal", + "TextMate", + "Transmission", + "VLC", + "VLC media player", + } - local results = tab.new(3) - tab.addrow( results, "application", "uid", "pid" ) + local results = tab.new(3) + tab.addrow( results, "application", "uid", "pid" ) - for _, app in ipairs(apps) do - try( socket:connect(host, port, "tcp") ) - local data + for _, app in ipairs(apps) do + try( socket:connect(host, port, "tcp") ) + local data - local packets = { - "PPCT\0\0\0\1\0\0\0\1", - -- unfortunately I've found no packet specifications, so this has to do - bin.pack("HCpH", "e44c50525401e101", 225 + #app, app, "dfdbe302013ddfdfdfdfd500") - } + local packets = { + "PPCT\0\0\0\1\0\0\0\1", + -- unfortunately I've found no packet specifications, so this has to do + bin.pack("HCpH", "e44c50525401e101", 225 + #app, app, "dfdbe302013ddfdfdfdfd500") + } - for _, v in ipairs(packets) do - try( socket:send(v) ) - data = try( socket:receive() ) - end + for _, v in ipairs(packets) do + try( socket:send(v) ) + data = try( socket:receive() ) + end - local uid, pid = data:match("uid=(%d+)&pid=(%d+)") - if ( uid and pid ) then tab.addrow( results, app, uid, pid ) end + local uid, pid = data:match("uid=(%d+)&pid=(%d+)") + if ( uid and pid ) then tab.addrow( results, app, uid, pid ) end - try( socket:close() ) - end + try( socket:close() ) + end - return "\n" .. tab.dump(results) + return "\n" .. tab.dump(results) end diff --git a/scripts/finger.nse b/scripts/finger.nse index bd5c2b597..b40135ea7 100644 --- a/scripts/finger.nse +++ b/scripts/finger.nse @@ -30,8 +30,8 @@ categories = {"default", "discovery", "safe"} portrule = shortport.port_or_service(79, "finger") action = function(host, port) - local try = nmap.new_try() + local try = nmap.new_try() - return try(comm.exchange(host, port, "\r\n", - {lines=100, proto=port.protocol, timeout=5000})) + return try(comm.exchange(host, port, "\r\n", + {lines=100, proto=port.protocol, timeout=5000})) end diff --git a/scripts/freelancer-info.nse b/scripts/freelancer-info.nse index 09ffa8cd7..a6059c20a 100644 --- a/scripts/freelancer-info.nse +++ b/scripts/freelancer-info.nse @@ -48,57 +48,57 @@ categories = { "default", "discovery", "safe", "version" } portrule = shortport.version_port_or_service({2302}, "freelancer", "udp") action = function(host, port) - local status, data = comm.exchange(host, port.number, - "\x00\x02\xf1\x26\x01\x26\xf0\x90\xa6\xf0\x26\x57\x4e\xac\xa0\xec\xf8\x68\xe4\x8d\x21", - { proto = "udp", timeout = 3000 }) - if not status then - return - end + local status, data = comm.exchange(host, port.number, + "\x00\x02\xf1\x26\x01\x26\xf0\x90\xa6\xf0\x26\x57\x4e\xac\xa0\xec\xf8\x68\xe4\x8d\x21", + { proto = "udp", timeout = 3000 }) + if not status then + return + end - -- port is open - nmap.set_port_state(host, port, "open") + -- port is open + nmap.set_port_state(host, port, "open") - local passwordbyte, maxplayers, numplayers, name, pvpallow, newplayersallow, description = - string.match(data, "^\x00\x03\xf1\x26............(.)...(.)...(.)...................................................................(.*)\0\0(.):(.):.*:.*:.*:(.*)\0\0$") - if not passwordbyte then - return - end + local passwordbyte, maxplayers, numplayers, name, pvpallow, newplayersallow, description = + string.match(data, "^\x00\x03\xf1\x26............(.)...(.)...(.)...................................................................(.*)\0\0(.):(.):.*:.*:.*:(.*)\0\0$") + if not passwordbyte then + return + end - local o = stdnse.output_table() + local o = stdnse.output_table() - o["server name"] = string.gsub(name, "[^%g%s]", "") - o["server description"] = string.gsub(description, "[^%g%s]", "") - o["players"] = numplayers:byte(1) - 1 - o["max. players"] = maxplayers:byte(1) - 1 + o["server name"] = string.gsub(name, "[^%g%s]", "") + o["server description"] = string.gsub(description, "[^%g%s]", "") + o["players"] = numplayers:byte(1) - 1 + o["max. players"] = maxplayers:byte(1) - 1 - passwordbyte = passwordbyte:byte(1) - if bit.band(passwordbyte, 128) ~= 0 then - o["password"] = "yes" - else - o["password"] = "no" - end + passwordbyte = passwordbyte:byte(1) + if bit.band(passwordbyte, 128) ~= 0 then + o["password"] = "yes" + else + o["password"] = "no" + end - o["allow players to harm other players"] = "n/a" - if pvpallow == "1" then - o["allow players to harm other players"] = "yes" - elseif pvpallow == "0" then - o["allow players to harm other players"] = "no" - end + o["allow players to harm other players"] = "n/a" + if pvpallow == "1" then + o["allow players to harm other players"] = "yes" + elseif pvpallow == "0" then + o["allow players to harm other players"] = "no" + end - o["allow new players"] = "n/a" - if newplayersallow == "1" then - o["allow new players"] = "yes" - elseif newplayersallow == "0" then - o["allow new players"] = "no" - end + o["allow new players"] = "n/a" + if newplayersallow == "1" then + o["allow new players"] = "yes" + elseif newplayersallow == "0" then + o["allow new players"] = "no" + end - port.version.name = "freelancer" - port.version.name_confidence = 10 - port.version.product = "Freelancer" - port.version.extrainfo = "name: " .. o["server name"] .. "; players: " .. - o["players"] .. "/" .. o["max. players"] .. "; password: " .. o["password"] + port.version.name = "freelancer" + port.version.name_confidence = 10 + port.version.product = "Freelancer" + port.version.extrainfo = "name: " .. o["server name"] .. "; players: " .. + o["players"] .. "/" .. o["max. players"] .. "; password: " .. o["password"] - nmap.set_port_version(host, port, "hardmatched") + nmap.set_port_version(host, port, "hardmatched") - return o + return o end diff --git a/scripts/ftp-libopie.nse b/scripts/ftp-libopie.nse index 99f7f0fad..1ec36dcc0 100644 --- a/scripts/ftp-libopie.nse +++ b/scripts/ftp-libopie.nse @@ -41,61 +41,61 @@ categories = {"vuln","intrusive"} portrule = shortport.port_or_service(21, "ftp") action = function(host, port) - local opie_vuln = { - title = "OPIE off-by-one stack overflow", - IDS = {CVE = 'CVE-2010-1938', OSVDB = '64949'}, - risk_factor = "High", - scores = { - CVSSv2 = "9.3 (HIGH) (AV:N/AC:M/Au:N/C:C/I:C/A:C)", - }, - description = [[ + local opie_vuln = { + title = "OPIE off-by-one stack overflow", + IDS = {CVE = 'CVE-2010-1938', OSVDB = '64949'}, + risk_factor = "High", + scores = { + CVSSv2 = "9.3 (HIGH) (AV:N/AC:M/Au:N/C:C/I:C/A:C)", + }, + description = [[ An off-by-one error in OPIE library 2.4.1-test1 and earlier, allows remote attackers to cause a denial of service or possibly execute arbitrary code via a long username.]], - references = { -'http://security.freebsd.org/advisories/FreeBSD-SA-10:05.opie.asc', -'http://site.pi3.com.pl/adv/libopie-adv.txt', - }, - dates = { - disclosure = {year = '2010', month = '05', day = '27'}, - }, - } + references = { + 'http://security.freebsd.org/advisories/FreeBSD-SA-10:05.opie.asc', + 'http://site.pi3.com.pl/adv/libopie-adv.txt', + }, + dates = { + disclosure = {year = '2010', month = '05', day = '27'}, + }, + } - local report = vulns.Report:new(SCRIPT_NAME, host, port) + local report = vulns.Report:new(SCRIPT_NAME, host, port) - local socket = nmap.new_socket() - local result - -- If we use more that 31 chars for username, ftpd will crash (quoted from the advisory). - local user_account = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" - local status = true + local socket = nmap.new_socket() + local result + -- If we use more that 31 chars for username, ftpd will crash (quoted from the advisory). + local user_account = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + local status = true - local err_catch = function() - socket:close() - end + local err_catch = function() + socket:close() + end - local try = nmap.new_try(err_catch) + local try = nmap.new_try(err_catch) - socket:set_timeout(10000) - try(socket:connect(host, port)) + socket:set_timeout(10000) + try(socket:connect(host, port)) - -- First, try a safe User so that we are sure that everything is ok - local payload = "USER opie\r\n" - try(socket:send(payload)) + -- First, try a safe User so that we are sure that everything is ok + local payload = "USER opie\r\n" + try(socket:send(payload)) - status, result = socket:receive_lines(1); - if status and not (string.match(result,"^421")) then + status, result = socket:receive_lines(1); + if status and not (string.match(result,"^421")) then - -- Second, try the vulnerable user account - local payload = "USER " .. user_account .. "\r\n" - try(socket:send(payload)) + -- Second, try the vulnerable user account + local payload = "USER " .. user_account .. "\r\n" + try(socket:send(payload)) - status, result = socket:receive_lines(1); - if status then - opie_vuln.state = vulns.STATE.NOT_VULN - else - -- if the server does not answer anymore we may have reached a stack overflow condition - opie_vuln.state = vulns.STATE.LIKELY_VULN - end - end - return report:make_output(opie_vuln) + status, result = socket:receive_lines(1); + if status then + opie_vuln.state = vulns.STATE.NOT_VULN + else + -- if the server does not answer anymore we may have reached a stack overflow condition + opie_vuln.state = vulns.STATE.LIKELY_VULN + end + end + return report:make_output(opie_vuln) end diff --git a/scripts/giop-info.nse b/scripts/giop-info.nse index 269e9803c..5406d4494 100644 --- a/scripts/giop-info.nse +++ b/scripts/giop-info.nse @@ -30,32 +30,32 @@ portrule = shortport.port_or_service( {2809,1050,1049} , "giop", "tcp", "open") action = function(host, port) - local helper = giop.Helper:new( host, port ) - local ctx, objs, status, err - local result = {} + local helper = giop.Helper:new( host, port ) + local ctx, objs, status, err + local result = {} - status, err = helper:Connect() - if ( not(status) ) then return err end + status, err = helper:Connect() + if ( not(status) ) then return err end - status, ctx = helper:GetNamingContext() - if ( not(status) ) then return " \n ERROR: " .. ctx end + status, ctx = helper:GetNamingContext() + if ( not(status) ) then return " \n ERROR: " .. ctx end - status, objs = helper:ListObjects(ctx) - if ( not(status) ) then return " \n ERROR: " .. objs end + status, objs = helper:ListObjects(ctx) + if ( not(status) ) then return " \n ERROR: " .. objs end - for _, obj in ipairs( objs ) do - local tmp = "" + for _, obj in ipairs( objs ) do + local tmp = "" - if ( obj.enum == 0 ) then - tmp = "Object: " - elseif( obj.enum == 1 ) then - tmp = "Context: " - else - tmp = "Unknown: " - end + if ( obj.enum == 0 ) then + tmp = "Object: " + elseif( obj.enum == 1 ) then + tmp = "Context: " + else + tmp = "Unknown: " + end - table.insert(result, tmp .. obj.id ) - end + table.insert(result, tmp .. obj.id ) + end - return stdnse.format_output(true, result) + return stdnse.format_output(true, result) end diff --git a/scripts/gopher-ls.nse b/scripts/gopher-ls.nse index 8fe887f96..582a508a2 100644 --- a/scripts/gopher-ls.nse +++ b/scripts/gopher-ls.nse @@ -32,60 +32,60 @@ categories = {"default", "discovery", "safe"} portrule = shortport.port_or_service (70, "gopher", {"tcp"}) local function typelabel(gtype) - if gtype == "0" then - return "[txt]" - end - if gtype == "1" then - return "[dir]" - end - return string.format("[%s]", gtype) + if gtype == "0" then + return "[txt]" + end + if gtype == "1" then + return "[dir]" + end + return string.format("[%s]", gtype) end action = function( host, port ) - local INFO = "i" - local maxfiles = stdnse.get_script_args(SCRIPT_NAME..".maxfiles") - if not maxfiles then - maxfiles = 10 - else - maxfiles = tonumber(maxfiles) - end - if maxfiles < 1 then - maxfiles = nil - end + local INFO = "i" + local maxfiles = stdnse.get_script_args(SCRIPT_NAME..".maxfiles") + if not maxfiles then + maxfiles = 10 + else + maxfiles = tonumber(maxfiles) + end + if maxfiles < 1 then + maxfiles = nil + end - local socket = nmap.new_socket() - local status, err = socket:connect(host.ip, port.number) - if not status then - return - end + local socket = nmap.new_socket() + local status, err = socket:connect(host.ip, port.number) + if not status then + return + end - socket:send("\r\n") + socket:send("\r\n") - local buffer, _ = stdnse.make_buffer(socket, "\r\n") - local line = buffer() - local files = {} + local buffer, _ = stdnse.make_buffer(socket, "\r\n") + local line = buffer() + local files = {} - while line ~= nil do - if #line > 1 then - local gtype = string.sub(line, 1, 1) - local fields = stdnse.strsplit("\t", string.sub(line, 2)) - if #fields > 1 then - local label = fields[1] - local filename = fields[2] - if gtype ~= INFO then - if maxfiles and #files >= maxfiles then - table.insert(files, string.format('Only %d shown. Use --script-args %s.maxfiles=-1 to see all.', maxfiles, SCRIPT_NAME)) - break - else - table.insert(files, string.format('%s %s "%s"', typelabel(gtype), filename, label)) - end - end - end - end - line = buffer() - end - return "\n" .. stdnse.strjoin("\n", files) + while line ~= nil do + if #line > 1 then + local gtype = string.sub(line, 1, 1) + local fields = stdnse.strsplit("\t", string.sub(line, 2)) + if #fields > 1 then + local label = fields[1] + local filename = fields[2] + if gtype ~= INFO then + if maxfiles and #files >= maxfiles then + table.insert(files, string.format('Only %d shown. Use --script-args %s.maxfiles=-1 to see all.', maxfiles, SCRIPT_NAME)) + break + else + table.insert(files, string.format('%s %s "%s"', typelabel(gtype), filename, label)) + end + end + end + end + line = buffer() + end + return "\n" .. stdnse.strjoin("\n", files) end diff --git a/scripts/gpsd-info.nse b/scripts/gpsd-info.nse index 28fdb9687..577b79d6f 100644 --- a/scripts/gpsd-info.nse +++ b/scripts/gpsd-info.nse @@ -34,70 +34,70 @@ local arg_timeout = stdnse.parse_timespec(stdnse.get_script_args(SCRIPT_NAME .. arg_timeout = arg_timeout or 10 local function updateData(gpsinfo, entry) - for k, v in pairs(gpsinfo) do - if ( entry[k] and 0 < #tostring(entry[k]) ) then - gpsinfo[k] = entry[k] - end - end + for k, v in pairs(gpsinfo) do + if ( entry[k] and 0 < #tostring(entry[k]) ) then + gpsinfo[k] = entry[k] + end + end end local function hasAllData(gpsinfo) - for k, v in pairs(gpsinfo) do - if ( k ~= "speed" and v == '-' ) then - return false - end - end - return true + for k, v in pairs(gpsinfo) do + if ( k ~= "speed" and v == '-' ) then + return false + end + end + return true end local function fail(err) return ("\n ERROR: %s"):format(err or "") end action = function(host, port) - local gpsinfo = { - longitude = "-", - latitude = "-", - speed = "-", - time = "-", - date = "-", - } + local gpsinfo = { + longitude = "-", + latitude = "-", + speed = "-", + time = "-", + date = "-", + } - local socket = nmap.new_socket() - socket:set_timeout(1000) + local socket = nmap.new_socket() + socket:set_timeout(1000) - local status = socket:connect(host, port) + local status = socket:connect(host, port) - if ( not(status) ) then - return fail("Failed to connect to server") - end + if ( not(status) ) then + return fail("Failed to connect to server") + end - -- get the banner - local status, line = socket:receive_lines(1) - socket:send('?WATCH={"enable":true,"nmea":true}\r\n') + -- get the banner + local status, line = socket:receive_lines(1) + socket:send('?WATCH={"enable":true,"nmea":true}\r\n') - local start_time = os.time() + local start_time = os.time() - repeat - local entry - status, line = socket:receive_buf("\r\n", false) - if ( status ) then - status, entry = gps.NMEA.parse(line) - if ( status ) then - updateData(gpsinfo, entry) - end - end - until( os.time() - start_time > arg_timeout or hasAllData(gpsinfo) ) + repeat + local entry + status, line = socket:receive_buf("\r\n", false) + if ( status ) then + status, entry = gps.NMEA.parse(line) + if ( status ) then + updateData(gpsinfo, entry) + end + end + until( os.time() - start_time > arg_timeout or hasAllData(gpsinfo) ) - socket:send('?WATCH={"enable":false}\r\n') + socket:send('?WATCH={"enable":false}\r\n') - if ( not(hasAllData(gpsinfo)) ) then - return - end + if ( not(hasAllData(gpsinfo)) ) then + return + end - local output = { - ("Time of fix: %s"):format(stdnse.format_timestamp(gps.Util.convertTime(gpsinfo.date, gpsinfo.time))), - ("Coordinates: %.4f,%.4f"):format(tonumber(gpsinfo.latitude), tonumber(gpsinfo.longitude)), - ("Speed: %s knots"):format(gpsinfo.speed) - } - return stdnse.format_output(true, output) + local output = { + ("Time of fix: %s"):format(stdnse.format_timestamp(gps.Util.convertTime(gpsinfo.date, gpsinfo.time))), + ("Coordinates: %.4f,%.4f"):format(tonumber(gpsinfo.latitude), tonumber(gpsinfo.longitude)), + ("Speed: %s knots"):format(gpsinfo.speed) + } + return stdnse.format_output(true, output) end diff --git a/scripts/hadoop-datanode-info.nse b/scripts/hadoop-datanode-info.nse index 30864a499..8d97c8e46 100644 --- a/scripts/hadoop-datanode-info.nse +++ b/scripts/hadoop-datanode-info.nse @@ -34,30 +34,30 @@ categories = {"default", "discovery", "safe"} portrule = function(host, port) - -- Run for the special port number, or for any HTTP-like service that is - -- not on a usual HTTP port. - return shortport.port_or_service({50075}, "hadoop-datanode")(host, port) - or (shortport.service(shortport.LIKELY_HTTP_SERVICES)(host, port) and not shortport.portnumber(shortport.LIKELY_HTTP_PORTS)(host, port)) + -- Run for the special port number, or for any HTTP-like service that is + -- not on a usual HTTP port. + return shortport.port_or_service({50075}, "hadoop-datanode")(host, port) + or (shortport.service(shortport.LIKELY_HTTP_SERVICES)(host, port) and not shortport.portnumber(shortport.LIKELY_HTTP_PORTS)(host, port)) end action = function( host, port ) - local result = {} - local uri = "/browseDirectory.jsp" - stdnse.print_debug(1, ("%s:HTTP GET %s:%s%s"):format(SCRIPT_NAME, host.targetname or host.ip, port.number, uri)) - local response = http.get( host, port, uri ) - stdnse.print_debug(1, ("%s: Status %s"):format(SCRIPT_NAME,response['status-line'] or "No Response")) - if response['status-line'] and response['status-line']:match("200%s+OK") and response['body'] then - local body = response['body']:gsub("%%","%%%%") - stdnse.print_debug(2, ("%s: Body %s\n"):format(SCRIPT_NAME,body)) - if body:match("([^][\"]+)\">Log") then - port.version.name = "hadoop-datanode" - port.version.product = "Apache Hadoop" - nmap.set_port_version(host, port) - local logs = body:match("([^][\"]+)\">Log") - stdnse.print_debug(1, ("%s: Logs %s"):format(SCRIPT_NAME,logs)) - table.insert(result, ("Logs: %s"):format(logs)) - end - return stdnse.format_output(true, result) - end + local result = {} + local uri = "/browseDirectory.jsp" + stdnse.print_debug(1, ("%s:HTTP GET %s:%s%s"):format(SCRIPT_NAME, host.targetname or host.ip, port.number, uri)) + local response = http.get( host, port, uri ) + stdnse.print_debug(1, ("%s: Status %s"):format(SCRIPT_NAME,response['status-line'] or "No Response")) + if response['status-line'] and response['status-line']:match("200%s+OK") and response['body'] then + local body = response['body']:gsub("%%","%%%%") + stdnse.print_debug(2, ("%s: Body %s\n"):format(SCRIPT_NAME,body)) + if body:match("([^][\"]+)\">Log") then + port.version.name = "hadoop-datanode" + port.version.product = "Apache Hadoop" + nmap.set_port_version(host, port) + local logs = body:match("([^][\"]+)\">Log") + stdnse.print_debug(1, ("%s: Logs %s"):format(SCRIPT_NAME,logs)) + table.insert(result, ("Logs: %s"):format(logs)) + end + return stdnse.format_output(true, result) + end end diff --git a/scripts/hadoop-tasktracker-info.nse b/scripts/hadoop-tasktracker-info.nse index 342b65183..a41e36175 100644 --- a/scripts/hadoop-tasktracker-info.nse +++ b/scripts/hadoop-tasktracker-info.nse @@ -38,45 +38,45 @@ categories = {"default", "discovery", "safe"} portrule = function(host, port) - -- Run for the special port number, or for any HTTP-like service that is - -- not on a usual HTTP port. - return shortport.port_or_service ({50060}, "hadoop-tasktracker")(host, port) - or (shortport.service(shortport.LIKELY_HTTP_SERVICES)(host, port) and not shortport.portnumber(shortport.LIKELY_HTTP_PORTS)(host, port)) + -- Run for the special port number, or for any HTTP-like service that is + -- not on a usual HTTP port. + return shortport.port_or_service ({50060}, "hadoop-tasktracker")(host, port) + or (shortport.service(shortport.LIKELY_HTTP_SERVICES)(host, port) and not shortport.portnumber(shortport.LIKELY_HTTP_PORTS)(host, port)) end action = function( host, port ) - local result = {} - local uri = "/tasktracker.jsp" - stdnse.print_debug(1, ("%s:HTTP GET %s:%s%s"):format(SCRIPT_NAME, host.targetname or host.ip, port.number, uri)) - local response = http.get( host, port, uri ) - stdnse.print_debug(1, ("%s: Status %s"):format(SCRIPT_NAME,response['status-line'] or "No Response")) - if response['status-line'] and response['status-line']:match("200%s+OK") and response['body'] then - local body = response['body']:gsub("%%","%%%%") - stdnse.print_debug(2, ("%s: Body %s\n"):format(SCRIPT_NAME,body)) - if response['body']:match("Version:%s*([^][<]+)") then - local version = response['body']:match("Version:%s*([^][<]+)") - local versionNo = version:match("([^][,]+)") - local versionHash = version:match("[^][,]+%s+(%w+)") - stdnse.print_debug(1, ("%s: Version %s (%s)"):format(SCRIPT_NAME,versionNo,versionHash)) - table.insert(result, ("Version: %s (%s)"):format(versionNo,versionHash)) - port.version.version = version - end - if response['body']:match("Compiled:%s*([^][<]+)") then - local compiled = response['body']:match("Compiled:%s*([^][<]+)"):gsub("%s+", " ") - stdnse.print_debug(1, ("%s: Compiled %s"):format(SCRIPT_NAME,compiled)) - table.insert(result, ("Compiled: %s"):format(compiled)) - end - if body:match("([^][\"]+)\">Log") then - local logs = body:match("([^][\"]+)\">Log") - stdnse.print_debug(1, ("%s: Logs %s"):format(SCRIPT_NAME,logs)) - table.insert(result, ("Logs: %s"):format(logs)) - end - if #result > 0 then - port.version.name = "hadoop-tasktracker" - port.version.product = "Apache Hadoop" - nmap.set_port_version(host, port) - end - return stdnse.format_output(true, result) - end + local result = {} + local uri = "/tasktracker.jsp" + stdnse.print_debug(1, ("%s:HTTP GET %s:%s%s"):format(SCRIPT_NAME, host.targetname or host.ip, port.number, uri)) + local response = http.get( host, port, uri ) + stdnse.print_debug(1, ("%s: Status %s"):format(SCRIPT_NAME,response['status-line'] or "No Response")) + if response['status-line'] and response['status-line']:match("200%s+OK") and response['body'] then + local body = response['body']:gsub("%%","%%%%") + stdnse.print_debug(2, ("%s: Body %s\n"):format(SCRIPT_NAME,body)) + if response['body']:match("Version:%s*([^][<]+)") then + local version = response['body']:match("Version:%s*([^][<]+)") + local versionNo = version:match("([^][,]+)") + local versionHash = version:match("[^][,]+%s+(%w+)") + stdnse.print_debug(1, ("%s: Version %s (%s)"):format(SCRIPT_NAME,versionNo,versionHash)) + table.insert(result, ("Version: %s (%s)"):format(versionNo,versionHash)) + port.version.version = version + end + if response['body']:match("Compiled:%s*([^][<]+)") then + local compiled = response['body']:match("Compiled:%s*([^][<]+)"):gsub("%s+", " ") + stdnse.print_debug(1, ("%s: Compiled %s"):format(SCRIPT_NAME,compiled)) + table.insert(result, ("Compiled: %s"):format(compiled)) + end + if body:match("([^][\"]+)\">Log") then + local logs = body:match("([^][\"]+)\">Log") + stdnse.print_debug(1, ("%s: Logs %s"):format(SCRIPT_NAME,logs)) + table.insert(result, ("Logs: %s"):format(logs)) + end + if #result > 0 then + port.version.name = "hadoop-tasktracker" + port.version.product = "Apache Hadoop" + nmap.set_port_version(host, port) + end + return stdnse.format_output(true, result) + end end diff --git a/scripts/hbase-region-info.nse b/scripts/hbase-region-info.nse index 490c51e77..b01de653a 100644 --- a/scripts/hbase-region-info.nse +++ b/scripts/hbase-region-info.nse @@ -43,58 +43,58 @@ categories = {"default", "discovery", "safe"} portrule = function(host, port) - -- Run for the special port number, or for any HTTP-like service that is - -- not on a usual HTTP port. - return shortport.port_or_service ({60030}, "hbase-region")(host, port) - or (shortport.service(shortport.LIKELY_HTTP_SERVICES)(host, port) and not shortport.portnumber(shortport.LIKELY_HTTP_PORTS)(host, port)) + -- Run for the special port number, or for any HTTP-like service that is + -- not on a usual HTTP port. + return shortport.port_or_service ({60030}, "hbase-region")(host, port) + or (shortport.service(shortport.LIKELY_HTTP_SERVICES)(host, port) and not shortport.portnumber(shortport.LIKELY_HTTP_PORTS)(host, port)) end action = function( host, port ) - local result = {} - local region_servers = {} - -- uri was previously "/regionserver.jsp". See - -- http://seclists.org/nmap-dev/2012/q3/903. - local uri = "/rs-status" - stdnse.print_debug(1, ("%s:HTTP GET %s:%s%s"):format(SCRIPT_NAME, host.targetname or host.ip, port.number, uri)) - local response = http.get( host, port, uri ) - stdnse.print_debug(1, ("%s: Status %s"):format(SCRIPT_NAME,response['status-line'] or "No Response")) - if response['status-line'] and response['status-line']:match("200%s+OK") and response['body'] then - local body = response['body']:gsub("%%","%%%%") - stdnse.print_debug(2, ("%s: Body %s\n"):format(SCRIPT_NAME,body)) - if body:match("HBase%s+Version([^][<]+)") then - local version = body:match("HBase%s+Version([^][<]+)"):gsub("%s+", " ") - stdnse.print_debug(1, ("%s:Hbase Version %s"):format(SCRIPT_NAME,version)) - table.insert(result, ("Hbase Version: %s"):format(version)) - port.version.version = version - end - if body:match("HBase%s+Compiled([^][<]+)") then - local compiled = body:match("HBase%s+Compiled([^][<]+)"):gsub("%s+", " ") - stdnse.print_debug(1, ("%s: Hbase Compiled %s"):format(SCRIPT_NAME,compiled)) - table.insert(result, ("Hbase Compiled: %s"):format(compiled)) - end - if body:match("Metrics([^][<]+)") then - local metrics = body:match("Metrics([^][<]+)"):gsub("%s+", " ") - stdnse.print_debug(1, ("%s: Metrics %s"):format(SCRIPT_NAME,metrics)) - table.insert(result, ("Metrics %s"):format(metrics)) - end - if body:match("Quorum([^][<]+)") then - local quorum = body:match("Quorum([^][<]+)"):gsub("%s+", " ") - stdnse.print_debug(1, ("%s: Zookeeper Quorum %s"):format(SCRIPT_NAME,quorum)) - table.insert(result, ("Zookeeper Quorum: %s"):format(quorum)) - if target.ALLOW_NEW_TARGETS then - if quorum:match("([%w%.]+)") then - local newtarget = quorum:match("([%w%.]+)") - stdnse.print_debug(1, ("%s: Added target: %s"):format(SCRIPT_NAME, newtarget)) - local status,err = target.add(newtarget) - end - end - end - if #result > 0 then - port.version.name = "hbase-region" - port.version.product = "Apache Hadoop Hbase" - nmap.set_port_version(host, port) - end - return stdnse.format_output(true, result) - end + local result = {} + local region_servers = {} + -- uri was previously "/regionserver.jsp". See + -- http://seclists.org/nmap-dev/2012/q3/903. + local uri = "/rs-status" + stdnse.print_debug(1, ("%s:HTTP GET %s:%s%s"):format(SCRIPT_NAME, host.targetname or host.ip, port.number, uri)) + local response = http.get( host, port, uri ) + stdnse.print_debug(1, ("%s: Status %s"):format(SCRIPT_NAME,response['status-line'] or "No Response")) + if response['status-line'] and response['status-line']:match("200%s+OK") and response['body'] then + local body = response['body']:gsub("%%","%%%%") + stdnse.print_debug(2, ("%s: Body %s\n"):format(SCRIPT_NAME,body)) + if body:match("HBase%s+Version([^][<]+)") then + local version = body:match("HBase%s+Version([^][<]+)"):gsub("%s+", " ") + stdnse.print_debug(1, ("%s:Hbase Version %s"):format(SCRIPT_NAME,version)) + table.insert(result, ("Hbase Version: %s"):format(version)) + port.version.version = version + end + if body:match("HBase%s+Compiled([^][<]+)") then + local compiled = body:match("HBase%s+Compiled([^][<]+)"):gsub("%s+", " ") + stdnse.print_debug(1, ("%s: Hbase Compiled %s"):format(SCRIPT_NAME,compiled)) + table.insert(result, ("Hbase Compiled: %s"):format(compiled)) + end + if body:match("Metrics([^][<]+)") then + local metrics = body:match("Metrics([^][<]+)"):gsub("%s+", " ") + stdnse.print_debug(1, ("%s: Metrics %s"):format(SCRIPT_NAME,metrics)) + table.insert(result, ("Metrics %s"):format(metrics)) + end + if body:match("Quorum([^][<]+)") then + local quorum = body:match("Quorum([^][<]+)"):gsub("%s+", " ") + stdnse.print_debug(1, ("%s: Zookeeper Quorum %s"):format(SCRIPT_NAME,quorum)) + table.insert(result, ("Zookeeper Quorum: %s"):format(quorum)) + if target.ALLOW_NEW_TARGETS then + if quorum:match("([%w%.]+)") then + local newtarget = quorum:match("([%w%.]+)") + stdnse.print_debug(1, ("%s: Added target: %s"):format(SCRIPT_NAME, newtarget)) + local status,err = target.add(newtarget) + end + end + end + if #result > 0 then + port.version.name = "hbase-region" + port.version.product = "Apache Hadoop Hbase" + nmap.set_port_version(host, port) + end + return stdnse.format_output(true, result) + end end diff --git a/scripts/hddtemp-info.nse b/scripts/hddtemp-info.nse index 9a1eeb48d..071716409 100644 --- a/scripts/hddtemp-info.nse +++ b/scripts/hddtemp-info.nse @@ -25,23 +25,23 @@ categories = {"default", "discovery", "safe"} portrule = shortport.port_or_service (7634, "hddtemp", {"tcp"}) action = function( host, port ) - -- 5000B should be enough for 100 disks - local status, data = comm.get_banner(host, port, {bytes=5000}) - if not status then - return - end - local separator = string.sub(data, 1, 1) - local fields = stdnse.strsplit(separator, data) - local info = {} - local disks = math.floor((# fields) / 5) - for i = 0, (disks - 1) do - local start = i * 5 - local device = fields[start + 2] - local label = fields[start + 3] - local temperature = fields[start + 4] - local unit = fields[start + 5] - local formatted = string.format("%s: %s: %s %s", device, label, temperature, unit) - table.insert(info, formatted) - end - return stdnse.format_output(true, info) + -- 5000B should be enough for 100 disks + local status, data = comm.get_banner(host, port, {bytes=5000}) + if not status then + return + end + local separator = string.sub(data, 1, 1) + local fields = stdnse.strsplit(separator, data) + local info = {} + local disks = math.floor((# fields) / 5) + for i = 0, (disks - 1) do + local start = i * 5 + local device = fields[start + 2] + local label = fields[start + 3] + local temperature = fields[start + 4] + local unit = fields[start + 5] + local formatted = string.format("%s: %s: %s %s", device, label, temperature, unit) + table.insert(info, formatted) + end + return stdnse.format_output(true, info) end diff --git a/scripts/http-apache-negotiation.nse b/scripts/http-apache-negotiation.nse index 985d3bf41..dfef62e62 100644 --- a/scripts/http-apache-negotiation.nse +++ b/scripts/http-apache-negotiation.nse @@ -43,24 +43,24 @@ portrule = shortport.http action = function(host, port) - local root = stdnse.get_script_args("http-apache-negotiation.root") or "/" + local root = stdnse.get_script_args("http-apache-negotiation.root") or "/" - -- Common default file names. Could add a couple more. - local files = { - 'robots', - 'index', - 'home', - 'blog' - } + -- Common default file names. Could add a couple more. + local files = { + 'robots', + 'index', + 'home', + 'blog' + } - for _, file in ipairs(files) do - local header = http.get(host, port, root .. file).header + for _, file in ipairs(files) do + local header = http.get(host, port, root .. file).header - -- Matching file. in content-location header - -- or negotiate in vary header. - if header["content-location"] and string.find(header["content-location"], file ..".") - or header["vary"] and string.find(header["vary"], "negotiate") then - return "mod_negotiation enabled." - end + -- Matching file. in content-location header + -- or negotiate in vary header. + if header["content-location"] and string.find(header["content-location"], file ..".") + or header["vary"] and string.find(header["vary"], "negotiate") then + return "mod_negotiation enabled." end + end end diff --git a/scripts/http-cakephp-version.nse b/scripts/http-cakephp-version.nse index 7218b3198..1963c0aa2 100644 --- a/scripts/http-cakephp-version.nse +++ b/scripts/http-cakephp-version.nse @@ -42,66 +42,66 @@ local VENDORS_QUERY = "/js/vendors.php" -- Cakephp's stylesheets hashes local CAKEPHP_STYLESHEET_HASHES = { - ["aaf0340c16415585554a7aefde2778c4"] = {"1.1.12"}, - ["8f8a877d924aa26ccd66c84ff8f8c8fe"] = {"1.1.14"}, - ["02a661c167affd9deda2a45f4341297e"] = {"1.1.17", "1.1.20"}, - ["1776a7c1b3255b07c6b9f43b9f50f05e"] = {"1.2.0 - 1.2.5", "1.3.0 Alpha"}, - ["1ffc970c5eae684bebc0e0133c4e1f01"] = {"1.2.6"}, - ["2e7f5372931a7f6f86786e95871ac947"] = {"1.2.7 - 1.2.9"}, - ["3422eded2fcceb3c89cabb5156b5d4e2"] = {"1.3.0 beta"}, - ["3c31e4674f42a49108b5300f8e73be26"] = {"1.3.0 RC1 - 1.3.7"} + ["aaf0340c16415585554a7aefde2778c4"] = {"1.1.12"}, + ["8f8a877d924aa26ccd66c84ff8f8c8fe"] = {"1.1.14"}, + ["02a661c167affd9deda2a45f4341297e"] = {"1.1.17", "1.1.20"}, + ["1776a7c1b3255b07c6b9f43b9f50f05e"] = {"1.2.0 - 1.2.5", "1.3.0 Alpha"}, + ["1ffc970c5eae684bebc0e0133c4e1f01"] = {"1.2.6"}, + ["2e7f5372931a7f6f86786e95871ac947"] = {"1.2.7 - 1.2.9"}, + ["3422eded2fcceb3c89cabb5156b5d4e2"] = {"1.3.0 beta"}, + ["3c31e4674f42a49108b5300f8e73be26"] = {"1.3.0 RC1 - 1.3.7"} } action = function(host, port) - local response, png_icon_response, gif_icon_response - local icon_versions, stylesheet_versions - local icon_hash, stylesheet_hash - local output_lines - local installation_version + local response, png_icon_response, gif_icon_response + local icon_versions, stylesheet_versions + local icon_hash, stylesheet_hash + local output_lines + local installation_version - -- Identify servers that answer 200 to invalid HTTP requests and exit as these would invalidate the tests - local _, http_status, _ = http.identify_404(host,port) - if ( http_status == 200 ) then - stdnse.print_debug(1, "%s: Exiting due to ambiguous response from web server on %s:%s. All URIs return status 200.", SCRIPT_NAME, host.ip, port.number) - return false - end + -- Identify servers that answer 200 to invalid HTTP requests and exit as these would invalidate the tests + local _, http_status, _ = http.identify_404(host,port) + if ( http_status == 200 ) then + stdnse.print_debug(1, "%s: Exiting due to ambiguous response from web server on %s:%s. All URIs return status 200.", SCRIPT_NAME, host.ip, port.number) + return false + end - -- Are the default icons there? - png_icon_response = http.get(host, port, PNG_ICON_QUERY) - gif_icon_response = http.get(host, port, GIF_ICON_QUERY) - if png_icon_response.body and png_icon_response.status == 200 then - icon_versions = {"1.3.x"} - elseif gif_icon_response.body and gif_icon_response.status == 200 then - icon_versions = {"1.2.x"} - end + -- Are the default icons there? + png_icon_response = http.get(host, port, PNG_ICON_QUERY) + gif_icon_response = http.get(host, port, GIF_ICON_QUERY) + if png_icon_response.body and png_icon_response.status == 200 then + icon_versions = {"1.3.x"} + elseif gif_icon_response.body and gif_icon_response.status == 200 then + icon_versions = {"1.2.x"} + end - -- Download cake.generic.css and fingerprint - response = http.get(host, port, STYLESHEET_QUERY) - if response.body and response.status == 200 then - stylesheet_hash = stdnse.tohex(openssl.md5(response.body)) - stylesheet_versions = CAKEPHP_STYLESHEET_HASHES[stylesheet_hash] - end - -- Is /js/vendors.php there? - response = http.get(host, port, VENDORS_QUERY) - if response.body and response.status == 200 then - installation_version = {"1.1.x","1.2.x"} - elseif response.status ~= 200 and (icon_versions or stylesheet_versions) then - installation_version = {"1.3.x"} - end - -- Prepare output - output_lines = {} - if installation_version then - output_lines[#output_lines + 1] = "Version of codebase: " .. stdnse.strjoin(", ", installation_version) - end - if icon_versions then - output_lines[#output_lines + 1] = "Version of icons: " .. stdnse.strjoin(", ", icon_versions) - end - if stylesheet_versions then - output_lines[#output_lines + 1] = "Version of stylesheet: " .. stdnse.strjoin(", ", stylesheet_versions) - elseif stylesheet_hash and nmap.verbosity() >= 2 then - output_lines[#output_lines + 1] = "Default stylesheet has an unknown hash: " .. stylesheet_hash - end - if #output_lines > 0 then - return stdnse.strjoin("\n", output_lines) - end + -- Download cake.generic.css and fingerprint + response = http.get(host, port, STYLESHEET_QUERY) + if response.body and response.status == 200 then + stylesheet_hash = stdnse.tohex(openssl.md5(response.body)) + stylesheet_versions = CAKEPHP_STYLESHEET_HASHES[stylesheet_hash] + end + -- Is /js/vendors.php there? + response = http.get(host, port, VENDORS_QUERY) + if response.body and response.status == 200 then + installation_version = {"1.1.x","1.2.x"} + elseif response.status ~= 200 and (icon_versions or stylesheet_versions) then + installation_version = {"1.3.x"} + end + -- Prepare output + output_lines = {} + if installation_version then + output_lines[#output_lines + 1] = "Version of codebase: " .. stdnse.strjoin(", ", installation_version) + end + if icon_versions then + output_lines[#output_lines + 1] = "Version of icons: " .. stdnse.strjoin(", ", icon_versions) + end + if stylesheet_versions then + output_lines[#output_lines + 1] = "Version of stylesheet: " .. stdnse.strjoin(", ", stylesheet_versions) + elseif stylesheet_hash and nmap.verbosity() >= 2 then + output_lines[#output_lines + 1] = "Default stylesheet has an unknown hash: " .. stylesheet_hash + end + if #output_lines > 0 then + return stdnse.strjoin("\n", output_lines) + end end diff --git a/scripts/http-cors.nse b/scripts/http-cors.nse index 88cb617b9..9c1c6fd23 100644 --- a/scripts/http-cors.nse +++ b/scripts/http-cors.nse @@ -39,62 +39,62 @@ portrule = shortport.http local methods = {"HEAD", "GET", "POST", "PUT", "DELETE", "TRACE", "OPTIONS", "CONNECT", "PATCH"} local function origin_ok(raw, origin) - if not raw then - return false - end - if raw == "*" then - return true - end - if raw == "null" then - return false - end - local allowed = stdnse.strsplit(" ", raw) - for _, ao in ipairs(allowed) do - if origin == ao then - return true - end - end - return false + if not raw then + return false + end + if raw == "*" then + return true + end + if raw == "null" then + return false + end + local allowed = stdnse.strsplit(" ", raw) + for _, ao in ipairs(allowed) do + if origin == ao then + return true + end + end + return false end local function method_ok(raw, method) - if not raw then - return false - end - local stuff = stdnse.strsplit(" ", raw) - local nospace = stdnse.strjoin("", stuff) - local allowed = stdnse.strsplit(",", nospace) - for _, am in ipairs(allowed) do - if method == am then - return true - end - end - return false + if not raw then + return false + end + local stuff = stdnse.strsplit(" ", raw) + local nospace = stdnse.strjoin("", stuff) + local allowed = stdnse.strsplit(",", nospace) + for _, am in ipairs(allowed) do + if method == am then + return true + end + end + return false end local function test(host, port, method, origin) - local header = { - ["Origin"] = origin, - ["Access-Control-Request-Method"] = method, - } - local response = http.generic_request(host, port, "OPTIONS", "/", {header = header}) - local aorigins = response.header["access-control-allow-origin"] - local amethods = response.header["access-control-allow-methods"] - local ook = origin_ok(aorigins, response) - local mok = method_ok(amethods, method) - return ook and mok + local header = { + ["Origin"] = origin, + ["Access-Control-Request-Method"] = method, + } + local response = http.generic_request(host, port, "OPTIONS", "/", {header = header}) + local aorigins = response.header["access-control-allow-origin"] + local amethods = response.header["access-control-allow-methods"] + local ook = origin_ok(aorigins, response) + local mok = method_ok(amethods, method) + return ook and mok end action = function(host, port) - local path = nmap.registry.args["http-cors.path"] or "/" - local origin = nmap.registry.args["http-cors.origin"] or "example.com" - local allowed = {} - for _, method in ipairs(methods) do - if test(host, port, method, origin) then - table.insert(allowed, method) - end - end - if #allowed > 0 then - return stdnse.strjoin(" ", allowed) - end + local path = nmap.registry.args["http-cors.path"] or "/" + local origin = nmap.registry.args["http-cors.origin"] or "example.com" + local allowed = {} + for _, method in ipairs(methods) do + if test(host, port, method, origin) then + table.insert(allowed, method) + end + end + if #allowed > 0 then + return stdnse.strjoin(" ", allowed) + end end diff --git a/scripts/http-date.nse b/scripts/http-date.nse index ab7320cf4..8889d0bd4 100644 --- a/scripts/http-date.nse +++ b/scripts/http-date.nse @@ -31,24 +31,24 @@ categories = {"discovery", "safe"} portrule = shortport.http action = function(host, port) - local request_time = os.time() - local response = http.get(host, port, "/") - if not response.status or not response.header["date"] then - return - end + local request_time = os.time() + local response = http.get(host, port, "/") + if not response.status or not response.header["date"] then + return + end - local response_date = http.parse_date(response.header["date"]) - if not response_date then - return - end - local response_time = stdnse.date_to_timestamp(response_date) + local response_date = http.parse_date(response.header["date"]) + if not response_date then + return + end + local response_time = stdnse.date_to_timestamp(response_date) - local output_tab = stdnse.output_table() - output_tab.date = stdnse.format_timestamp(response_time, 0) - output_tab.delta = os.difftime(response_time, request_time) + local output_tab = stdnse.output_table() + output_tab.date = stdnse.format_timestamp(response_time, 0) + output_tab.delta = os.difftime(response_time, request_time) - local output_str = string.format("%s; %s from local time.", - response.header["date"], stdnse.format_difftime(os.date("!*t", response_time), os.date("!*t", request_time))) + local output_str = string.format("%s; %s from local time.", + response.header["date"], stdnse.format_difftime(os.date("!*t", response_time), os.date("!*t", request_time))) - return output_tab, output_str + return output_tab, output_str end diff --git a/scripts/http-dlink-backdoor.nse b/scripts/http-dlink-backdoor.nse index 4943d552e..e0859492f 100644 --- a/scripts/http-dlink-backdoor.nse +++ b/scripts/http-dlink-backdoor.nse @@ -44,28 +44,28 @@ local vulns = require "vulns" portrule = shortport.http action = function(host, port) - local response = http.get(host, port, "/", { redirect_ok = false, no_cache = true }) - local server = response.header and response.header['server'] or "" - local vuln_table = { - title = "Firmware backdoor in some models of D-Link routers allow for admin password bypass", - state = vulns.STATE.NOT_VULN, - risk_factor = "High", - description = [[ + local response = http.get(host, port, "/", { redirect_ok = false, no_cache = true }) + local server = response.header and response.header['server'] or "" + local vuln_table = { + title = "Firmware backdoor in some models of D-Link routers allow for admin password bypass", + state = vulns.STATE.NOT_VULN, + risk_factor = "High", + description = [[ D-Link routers have been found with a firmware backdoor allowing for admin password bypass using a "secret" User-Agent string. ]], - references = { - 'http://www.devttys0.com/2013/10/reverse-engineering-a-d-link-backdoor/', - } - } - if ( response.status == 401 and server:match("^thttpd%-alphanetworks") ) or - ( response.status == 302 and server:match("^Alpha_webserv") ) then - response = http.get(host, port, "/", { header = { ["User-Agent"] = "xmlset_roodkcableoj28840ybtide" } }) + references = { + 'http://www.devttys0.com/2013/10/reverse-engineering-a-d-link-backdoor/', + } + } + if ( response.status == 401 and server:match("^thttpd%-alphanetworks") ) or + ( response.status == 302 and server:match("^Alpha_webserv") ) then + response = http.get(host, port, "/", { header = { ["User-Agent"] = "xmlset_roodkcableoj28840ybtide" } }) - if ( response.status == 200 ) then - vuln_table.state = vulns.STATE.VULN - local report = vulns.Report:new(SCRIPT_NAME, host, port) - return report:make_output(vuln_table) - end - end - return + if ( response.status == 200 ) then + vuln_table.state = vulns.STATE.VULN + local report = vulns.Report:new(SCRIPT_NAME, host, port) + return report:make_output(vuln_table) + end + end + return end diff --git a/scripts/http-drupal-enum-users.nse b/scripts/http-drupal-enum-users.nse index 369f42fb5..61a117c8e 100644 --- a/scripts/http-drupal-enum-users.nse +++ b/scripts/http-drupal-enum-users.nse @@ -45,7 +45,7 @@ action = function(host, port) -- ensure that root ends with a trailing slash if ( not(root:match(".*/$")) ) then - root = root .. "/" + root = root .. "/" end -- characters that usernames may begin with diff --git a/scripts/http-email-harvest.nse b/scripts/http-email-harvest.nse index ea6a09b72..e2e225560 100644 --- a/scripts/http-email-harvest.nse +++ b/scripts/http-email-harvest.nse @@ -41,48 +41,48 @@ categories = {"discovery", "safe"} portrule = shortport.http function action(host, port) - local EMAIL_PATTERN = "[A-Za-z0-9%.%%%+%-]+@[A-Za-z0-9%.%%%+%-]+%.%w%w%w?%w?" + local EMAIL_PATTERN = "[A-Za-z0-9%.%%%+%-]+@[A-Za-z0-9%.%%%+%-]+%.%w%w%w?%w?" - local crawler = httpspider.Crawler:new(host, port, nil, { - scriptname = SCRIPT_NAME - } - ) + local crawler = httpspider.Crawler:new(host, port, nil, { + scriptname = SCRIPT_NAME + } + ) - if ( not(crawler) ) then - return - end - crawler:set_timeout(10000) + if ( not(crawler) ) then + return + end + crawler:set_timeout(10000) - local emails = {} - while(true) do - local status, r = crawler:crawl() - -- if the crawler fails it can be due to a number of different reasons - -- most of them are "legitimate" and should not be reason to abort - if ( not(status) ) then - if ( r.err ) then - return stdnse.format_output(true, ("ERROR: %s"):format(r.reason)) - else - break - end - end + local emails = {} + while(true) do + local status, r = crawler:crawl() + -- if the crawler fails it can be due to a number of different reasons + -- most of them are "legitimate" and should not be reason to abort + if ( not(status) ) then + if ( r.err ) then + return stdnse.format_output(true, ("ERROR: %s"):format(r.reason)) + else + break + end + end - -- Collect each e-mail address and build a unique index of them + -- Collect each e-mail address and build a unique index of them if r.response.body then for email in r.response.body:gmatch(EMAIL_PATTERN) do emails[email] = true end end - end + end - -- if no email addresses were collected abort - if ( not(emails) ) then return end + -- if no email addresses were collected abort + if ( not(emails) ) then return end - local results = {} - for email, _ in pairs(emails) do - table.insert(results, email) - end + local results = {} + for email, _ in pairs(emails) do + table.insert(results, email) + end - results.name = crawler:getLimitations() + results.name = crawler:getLimitations() - return stdnse.format_output(true, results) + return stdnse.format_output(true, results) end diff --git a/scripts/http-frontpage-login.nse b/scripts/http-frontpage-login.nse index 06a187df1..ed594882b 100644 --- a/scripts/http-frontpage-login.nse +++ b/scripts/http-frontpage-login.nse @@ -43,47 +43,47 @@ categories = {"vuln", "safe"} portrule = shortport.http action = function(host, port) - local path = stdnse.get_script_args('http-frontpage-login.path') or "/" - local data - local frontpage_vuln = { - title = "Frontpage extension anonymous login", + local path = stdnse.get_script_args('http-frontpage-login.path') or "/" + local data + local frontpage_vuln = { + title = "Frontpage extension anonymous login", - description = [[ + description = [[ Default installations of older versions of frontpage extensions allow anonymous logins which can lead to server compromise. ]], - references = { - 'http://insecure.org/sploits/Microsoft.frontpage.insecurities.html', - }, - exploit_results = {}, - }; + references = { + 'http://insecure.org/sploits/Microsoft.frontpage.insecurities.html', + }, + exploit_results = {}, + }; - local report = vulns.Report:new(SCRIPT_NAME, host, port); - frontpage_vuln.state = vulns.STATE.NOT_VULN; + local report = vulns.Report:new(SCRIPT_NAME, host, port); + frontpage_vuln.state = vulns.STATE.NOT_VULN; - data = http.get( host, port, path .. "/_vti_inf.html" ) + data = http.get( host, port, path .. "/_vti_inf.html" ) - if data and data.status and data.status == 200 then - --server does support frontpage extensions - local fp_version = string.match(data.body,"FPVersion=\"[%d%.]*\"") - if fp_version then - -- do post request http://msdn.microsoft.com/en-us/library/ms446353 - local postdata = "method=open+service:".. fp_version .."&service_name=/" - data = http.post(host,port,path .. "/_vti_bin/_vti_aut/author.dll",nil,nil,postdata) - if data and data.status then - if data.status == 200 then - stdnse.print_debug("Frontpage returned 200 OK, server vulnerable.") - frontpage_vuln.state = vulns.STATE.VULN; - return report:make_output(frontpage_vuln); - elseif data.status == 401 then - stdnse.print_debug("Frontpage returned 401, password protected.") - return false - else - stdnse.print_debug("Frontpage returned unknown response.") - return false - end - end - end - end - stdnse.print_debug("Frontpage probably not installed.") - return false + if data and data.status and data.status == 200 then + --server does support frontpage extensions + local fp_version = string.match(data.body,"FPVersion=\"[%d%.]*\"") + if fp_version then + -- do post request http://msdn.microsoft.com/en-us/library/ms446353 + local postdata = "method=open+service:".. fp_version .."&service_name=/" + data = http.post(host,port,path .. "/_vti_bin/_vti_aut/author.dll",nil,nil,postdata) + if data and data.status then + if data.status == 200 then + stdnse.print_debug("Frontpage returned 200 OK, server vulnerable.") + frontpage_vuln.state = vulns.STATE.VULN; + return report:make_output(frontpage_vuln); + elseif data.status == 401 then + stdnse.print_debug("Frontpage returned 401, password protected.") + return false + else + stdnse.print_debug("Frontpage returned unknown response.") + return false + end + end + end + end + stdnse.print_debug("Frontpage probably not installed.") + return false end diff --git a/scripts/http-gitweb-projects-enum.nse b/scripts/http-gitweb-projects-enum.nse index 7d2cd17b4..1ec39ca80 100644 --- a/scripts/http-gitweb-projects-enum.nse +++ b/scripts/http-gitweb-projects-enum.nse @@ -40,68 +40,68 @@ portrule = shortport.http -- @return author name filtred from html entities --- get_owner = function(res) - local result=res - local _ - if ( res:match(']*%>(.-)%)') do - local regx=']*href="(.-)">(.-)(.-)title="(.-)"(.-)(.-)' - for _, project, _, desc, _, owner in tr_code:gmatch(regx) do + for tr_code in html:gmatch('(%]*%>(.-)%)') do + local regx=']*href="(.-)">(.-)(.-)title="(.-)"(.-)(.-)' + for _, project, _, desc, _, owner in tr_code:gmatch(regx) do - --if desc result return default text of gitweb replace it by no description - if(string.find(desc,'Unnamed repository')) then - desc='no description' - end + --if desc result return default text of gitweb replace it by no description + if(string.find(desc,'Unnamed repository')) then + desc='no description' + end - tab.addrow(repo, project, get_owner(owner), desc) + tab.addrow(repo, project, get_owner(owner), desc) -- Protect from parsing errors or long owners -- just an arbitrary value - if owner:len() < 128 and not owners[owner] then - owners[owner] = true - owners_counter = owners_counter + 1 - end + if owner:len() < 128 and not owners[owner] then + owners[owner] = true + owners_counter = owners_counter + 1 + end - projects_counter = projects_counter + 1 - end - end + projects_counter = projects_counter + 1 + end + end - table.insert(result,tab.dump(repo)) - table.insert(result, "") - table.insert(result, - string.format("Number of projects: %d", projects_counter)) - if (owners_counter > 0 ) then - table.insert(result, - string.format("Number of owners: %d", owners_counter)) - end + table.insert(result,tab.dump(repo)) + table.insert(result, "") + table.insert(result, + string.format("Number of projects: %d", projects_counter)) + if (owners_counter > 0 ) then + table.insert(result, + string.format("Number of owners: %d", owners_counter)) + end - end - return stdnse.format_output(true,result) + end + return stdnse.format_output(true,result) end diff --git a/scripts/http-google-malware.nse b/scripts/http-google-malware.nse index 0060c9e31..23f24d0df 100644 --- a/scripts/http-google-malware.nse +++ b/scripts/http-google-malware.nse @@ -77,9 +77,9 @@ action = function(host, port) local req = http.get_url(qry) stdnse.print_debug(2, "%s", qry) - if ( req.status > 400 ) then - return "[ERROR] Request failed (invalid API key?)" - end + if ( req.status > 400 ) then + return "[ERROR] Request failed (invalid API key?)" + end --The Safe Lookup API responds with a type when site is on the lists if req.body then diff --git a/scripts/http-headers.nse b/scripts/http-headers.nse index 58ca6c58a..c3926cf38 100644 --- a/scripts/http-headers.nse +++ b/scripts/http-headers.nse @@ -34,42 +34,42 @@ categories = {"discovery", "safe"} portrule = shortport.http action = function(host, port) - local path = stdnse.get_script_args(SCRIPT_NAME..".path") or "/" - local useget = stdnse.get_script_args(SCRIPT_NAME..".useget") - local request_type = "HEAD" - local status = false - local result + local path = stdnse.get_script_args(SCRIPT_NAME..".path") or "/" + local useget = stdnse.get_script_args(SCRIPT_NAME..".useget") + local request_type = "HEAD" + local status = false + local result - -- Check if the user didn't want HEAD to be used - if(useget == nil) then - -- Try using HEAD first - status, result = http.can_use_head(host, port, nil, path) - end + -- Check if the user didn't want HEAD to be used + if(useget == nil) then + -- Try using HEAD first + status, result = http.can_use_head(host, port, nil, path) + end - -- If head failed, try using GET - if(status == false) then - stdnse.print_debug(1, "http-headers.nse: HEAD request failed, falling back to GET") - result = http.get(host, port, path) - request_type = "GET" - end + -- If head failed, try using GET + if(status == false) then + stdnse.print_debug(1, "http-headers.nse: HEAD request failed, falling back to GET") + result = http.get(host, port, path) + request_type = "GET" + end - if(result == nil) then - if(nmap.debugging() > 0) then - return "ERROR: Header request failed" - else - return nil - end - end + if(result == nil) then + if(nmap.debugging() > 0) then + return "ERROR: Header request failed" + else + return nil + end + end - if(result.rawheader == nil) then - if(nmap.debugging() > 0) then - return "ERROR: Header request didn't return a proper header" - else - return nil - end - end + if(result.rawheader == nil) then + if(nmap.debugging() > 0) then + return "ERROR: Header request didn't return a proper header" + else + return nil + end + end - table.insert(result.rawheader, "(Request type: " .. request_type .. ")") + table.insert(result.rawheader, "(Request type: " .. request_type .. ")") - return stdnse.format_output(true, result.rawheader) + return stdnse.format_output(true, result.rawheader) end diff --git a/scripts/http-icloud-findmyiphone.nse b/scripts/http-icloud-findmyiphone.nse index d17af3c34..df2086b45 100644 --- a/scripts/http-icloud-findmyiphone.nse +++ b/scripts/http-icloud-findmyiphone.nse @@ -42,46 +42,46 @@ prerule = function() return true end -- This function decodes the single quote as a start and should really -- be replaced with a proper UTF-8 decoder in the future local function decodeString(str) - return str:gsub("\226\128\153", "'") + return str:gsub("\226\128\153", "'") end local function fail(err) return ("\n ERROR: %s"):format(err or "") end action = function() - if ( not(arg_username) or not(arg_password) ) then - return fail("No username or password was supplied") - end + if ( not(arg_username) or not(arg_password) ) then + return fail("No username or password was supplied") + end - local mobileme = mobileme.Helper:new(arg_username, arg_password) - local status, response = mobileme:getLocation() + local mobileme = mobileme.Helper:new(arg_username, arg_password) + local status, response = mobileme:getLocation() - if ( not(status) ) then - stdnse.print_debug(2, "%s: %s", SCRIPT_NAME, response) - return fail("Failed to retrieve location information") - end + if ( not(status) ) then + stdnse.print_debug(2, "%s: %s", SCRIPT_NAME, response) + return fail("Failed to retrieve location information") + end - local output = tab.new(4) - tab.addrow(output, "name", "location", "accuracy", "date", "type") - for name, info in pairs(response) do - local loc - if ( info.latitude and info.longitude ) then - loc = ("%.3f,%.3f"):format( - tonumber(info.latitude) or "-", - tonumber(info.longitude) or "-") - else - loc = "-,-" - end - local ts - if ( info.timestamp and 1000 < info.timestamp ) then - ts = os.date("%x %X", info.timestamp/1000) - else - ts = "-" - end - tab.addrow(output, decodeString(name), loc, info.accuracy or "-", ts, info.postype or "-") - end + local output = tab.new(4) + tab.addrow(output, "name", "location", "accuracy", "date", "type") + for name, info in pairs(response) do + local loc + if ( info.latitude and info.longitude ) then + loc = ("%.3f,%.3f"):format( + tonumber(info.latitude) or "-", + tonumber(info.longitude) or "-") + else + loc = "-,-" + end + local ts + if ( info.timestamp and 1000 < info.timestamp ) then + ts = os.date("%x %X", info.timestamp/1000) + else + ts = "-" + end + tab.addrow(output, decodeString(name), loc, info.accuracy or "-", ts, info.postype or "-") + end - if ( 1 < #output ) then - return stdnse.format_output(true, tab.dump(output)) - end + if ( 1 < #output ) then + return stdnse.format_output(true, tab.dump(output)) + end end diff --git a/scripts/http-malware-host.nse b/scripts/http-malware-host.nse index 47fb0398c..5018ef22c 100644 --- a/scripts/http-malware-host.nse +++ b/scripts/http-malware-host.nse @@ -38,44 +38,44 @@ categories = {"malware", "safe"} portrule = shortport.http action = function(host, port) - -- Check what response we get for a 404 - local result, result_404, known_404 = http.identify_404(host, port) - if(result == false) then - return stdnse.format_output(false, "Couldn't identify 404 message: " .. result_404) - end + -- Check what response we get for a 404 + local result, result_404, known_404 = http.identify_404(host, port) + if(result == false) then + return stdnse.format_output(false, "Couldn't identify 404 message: " .. result_404) + end - -- If the 404 result is a 302, we're going to have trouble - if(result_404 == 302) then - return stdnse.format_output(false, "Unknown pages return a 302 response; unable to check") - end + -- If the 404 result is a 302, we're going to have trouble + if(result_404 == 302) then + return stdnse.format_output(false, "Unknown pages return a 302 response; unable to check") + end - -- Identify servers that answer 200 to invalid HTTP requests and exit as these would invalidate the test - if ( result_404 == 200 ) then - stdnse.print_debug(1, "%s: Exiting due to ambiguous response from web server on %s:%s. All URIs return status 200.", SCRIPT_NAME, host.ip, port.number) - return false - end + -- Identify servers that answer 200 to invalid HTTP requests and exit as these would invalidate the test + if ( result_404 == 200 ) then + stdnse.print_debug(1, "%s: Exiting due to ambiguous response from web server on %s:%s. All URIs return status 200.", SCRIPT_NAME, host.ip, port.number) + return false + end - -- Perform a GET request on the file - result = http.get_url("http://" .. host.ip .. ":" .. port.number .. "/ts/in.cgi?open2") - if(not(result)) then - return stdnse.format_output(false, "Couldn't perform GET request") - end + -- Perform a GET request on the file + result = http.get_url("http://" .. host.ip .. ":" .. port.number .. "/ts/in.cgi?open2") + if(not(result)) then + return stdnse.format_output(false, "Couldn't perform GET request") + end - if(result.status == 302) then - local response = {} - if(result.header.location) then - table.insert(response, string.format("Host appears to be infected (/ts/in.cgi?open2 redirects to %s)", result.header.location)) - else - table.insert(response, "Host appears to be infected (/ts/in.cgi?open2 return a redirect") - end - table.insert(response, "See: http://blog.unmaskparasites.com/2009/09/11/dynamic-dns-and-botnet-of-zombie-web-servers/") - return stdnse.format_output(true, response) - end + if(result.status == 302) then + local response = {} + if(result.header.location) then + table.insert(response, string.format("Host appears to be infected (/ts/in.cgi?open2 redirects to %s)", result.header.location)) + else + table.insert(response, "Host appears to be infected (/ts/in.cgi?open2 return a redirect") + end + table.insert(response, "See: http://blog.unmaskparasites.com/2009/09/11/dynamic-dns-and-botnet-of-zombie-web-servers/") + return stdnse.format_output(true, response) + end - -- Not infected - if(nmap.verbosity() > 0) then - return "Host appears to be clean" - else - return nil - end + -- Not infected + if(nmap.verbosity() > 0) then + return "Host appears to be clean" + else + return nil + end end diff --git a/scripts/http-put.nse b/scripts/http-put.nse index fe1b479ab..5d206194c 100644 --- a/scripts/http-put.nse +++ b/scripts/http-put.nse @@ -37,23 +37,23 @@ portrule = shortport.port_or_service( {80, 443}, {"http", "https"}, "tcp", "open action = function( host, port ) - local fname, url = stdnse.get_script_args('http-put.file', 'http-put.url') - if ( not(fname) or not(url) ) then - return - end + local fname, url = stdnse.get_script_args('http-put.file', 'http-put.url') + if ( not(fname) or not(url) ) then + return + end - local f = io.open(fname, "r") - if ( not(f) ) then - return stdnse.format_output(true, ("ERROR: Failed to open file: %s"):format(fname)) - end - local content = f:read("*all") - f:close() + local f = io.open(fname, "r") + if ( not(f) ) then + return stdnse.format_output(true, ("ERROR: Failed to open file: %s"):format(fname)) + end + local content = f:read("*all") + f:close() - local response = http.put(host, port, url, nil, content) + local response = http.put(host, port, url, nil, content) - if ( response.status == 200 or response.status == 204 ) then - return stdnse.format_output(true, ("%s was successfully created"):format(url)) - end + if ( response.status == 200 or response.status == 204 ) then + return stdnse.format_output(true, ("%s was successfully created"):format(url)) + end - return stdnse.format_output(true, ("ERROR: %s could not be created"):format(url)) + return stdnse.format_output(true, ("ERROR: %s could not be created"):format(url)) end diff --git a/scripts/http-referer-checker.nse b/scripts/http-referer-checker.nse index e9af5bd9a..f42dc6edb 100644 --- a/scripts/http-referer-checker.nse +++ b/scripts/http-referer-checker.nse @@ -35,57 +35,57 @@ portrule = shortport.port_or_service( {80, 443}, {"http", "https"}, "tcp", "open action = function(host, port) - local crawler = httpspider.Crawler:new(host, port, '/', { scriptname = SCRIPT_NAME, - maxpagecount = 30, - maxdepth = -1, - withinhost = 0, - withindomain = 0 - }) + local crawler = httpspider.Crawler:new(host, port, '/', { scriptname = SCRIPT_NAME, + maxpagecount = 30, + maxdepth = -1, + withinhost = 0, + withindomain = 0 + }) - crawler.options.doscraping = function(url) - if crawler:iswithinhost(url) - and not crawler:isresource(url, "js") - and not crawler:isresource(url, "css") then - return true - end + crawler.options.doscraping = function(url) + if crawler:iswithinhost(url) + and not crawler:isresource(url, "js") + and not crawler:isresource(url, "css") then + return true + end + end + + crawler:set_timeout(10000) + + if (not(crawler)) then + return + end + + local scripts = {} + + while(true) do + + local status, r = crawler:crawl() + if (not(status)) then + if (r.err) then + return stdnse.format_output(true, ("ERROR: %s"):format(r.reason)) + else + break + end end - crawler:set_timeout(10000) - - if (not(crawler)) then - return + if crawler:isresource(r.url, "js") and not crawler:iswithinhost(r.url) then + scripts[tostring(r.url)] = true end - local scripts = {} + end - while(true) do + if next(scripts) == nil then + return "Couldn't find any cross-domain scripts." + end - local status, r = crawler:crawl() - if (not(status)) then - if (r.err) then - return stdnse.format_output(true, ("ERROR: %s"):format(r.reason)) - else - break - end - end + local results = {} + for s, _ in pairs(scripts) do + table.insert(results, s) + end - if crawler:isresource(r.url, "js") and not crawler:iswithinhost(r.url) then - scripts[tostring(r.url)] = true - end + results.name = crawler:getLimitations() - end - - if next(scripts) == nil then - return "Couldn't find any cross-domain scripts." - end - - local results = {} - for s, _ in pairs(scripts) do - table.insert(results, s) - end - - results.name = crawler:getLimitations() - - return stdnse.format_output(true, results) + return stdnse.format_output(true, results) end diff --git a/scripts/http-robtex-reverse-ip.nse b/scripts/http-robtex-reverse-ip.nse index 44d477aee..3c28d7f51 100644 --- a/scripts/http-robtex-reverse-ip.nse +++ b/scripts/http-robtex-reverse-ip.nse @@ -46,28 +46,28 @@ categories = {"discovery", "safe", "external"} -- @param data string containing the retrieved web page -- @return table containing the resolved host names function parse_robtex_response(data) - local data = string.gsub(data,"\r?\n","") - local result = {} - for href, link in string.gmatch(data,"
  • ([^\"^']-)
  • ") do - table.insert(result, link) - end - return result + local data = string.gsub(data,"\r?\n","") + local result = {} + for href, link in string.gmatch(data,"
  • ([^\"^']-)
  • ") do + table.insert(result, link) + end + return result end prerule = function() return stdnse.get_script_args("http-robtex-reverse-ip.host") ~= nil end action = function(host, port) - local target = stdnse.get_script_args("http-robtex-reverse-ip.host") - local ip = ipOps.ip_to_str(target) - if ( not(ip) or #ip ~= 4 ) then - return stdnse.format_output(false, "The argument \"http-robtex-reverse-ip.host\" did not contain a valid IPv4 address") - end + local target = stdnse.get_script_args("http-robtex-reverse-ip.host") + local ip = ipOps.ip_to_str(target) + if ( not(ip) or #ip ~= 4 ) then + return stdnse.format_output(false, "The argument \"http-robtex-reverse-ip.host\" did not contain a valid IPv4 address") + end - local link = "https://www.robtex.com/ip/"..target..".html" - local htmldata = http.get_url(link) - local domains = parse_robtex_response(htmldata.body) - if ( #domains > 0 ) then - return stdnse.format_output(true, domains) - end + local link = "https://www.robtex.com/ip/"..target..".html" + local htmldata = http.get_url(link) + local domains = parse_robtex_response(htmldata.body) + if ( #domains > 0 ) then + return stdnse.format_output(true, domains) + end end diff --git a/scripts/http-robtex-shared-ns.nse b/scripts/http-robtex-shared-ns.nse index c6bbeca65..358a6ab83 100644 --- a/scripts/http-robtex-shared-ns.nse +++ b/scripts/http-robtex-shared-ns.nse @@ -43,56 +43,56 @@ end function parse_robtex_response(data) local result = {} - if ( not(data) ) then - return - end + if ( not(data) ) then + return + end - -- cut out the section we're interested in - data = data:match(".-(.-)") + -- cut out the section we're interested in + data = data:match(".-(.-)") - -- process each html list item - for li in data:gmatch("
  • (.-)
  • ") do - local domain = li:match("(.*)") - if ( domain ) then - table.insert(result, domain) - end - end + -- process each html list item + for li in data:gmatch("
  • (.-)
  • ") do + local domain = li:match("(.*)") + if ( domain ) then + table.insert(result, domain) + end + end return result end local function lookup_dns_server(data) - return data:match("The primary name server is (.-).") + return data:match("The primary name server is (.-).") end local function fetch_robtex_data(url) - local htmldata = http.get("www.robtex.com", 443, url) - if ( not(htmldata) or not(htmldata.body) ) then - return - end + local htmldata = http.get("www.robtex.com", 443, url) + if ( not(htmldata) or not(htmldata.body) ) then + return + end - -- fixup hex encodings - return unescape(htmldata.body) + -- fixup hex encodings + return unescape(htmldata.body) end hostrule = function (host) return host.targetname end action = function(host) - local base_url = "/dns/" .. host.targetname .. ".html" - local data = fetch_robtex_data(base_url) - local domains = parse_robtex_response(data) + local base_url = "/dns/" .. host.targetname .. ".html" + local data = fetch_robtex_data(base_url) + local domains = parse_robtex_response(data) - if ( not(domains) ) then - local server = lookup_dns_server(data) - if ( not(server) ) then - return - end - local url = base_url:format(server) - stdnse.print_debug(2, "%s: Querying URL: %s", SCRIPT_NAME, url) - data = fetch_robtex_data(url) + if ( not(domains) ) then + local server = lookup_dns_server(data) + if ( not(server) ) then + return + end + local url = base_url:format(server) + stdnse.print_debug(2, "%s: Querying URL: %s", SCRIPT_NAME, url) + data = fetch_robtex_data(url) - domains = parse_robtex_response(data) - end + domains = parse_robtex_response(data) + end if (domains and #domains > 0) then return stdnse.format_output(true, domains) diff --git a/scripts/http-vlcstreamer-ls.nse b/scripts/http-vlcstreamer-ls.nse index 11a925956..53004db5c 100644 --- a/scripts/http-vlcstreamer-ls.nse +++ b/scripts/http-vlcstreamer-ls.nse @@ -58,29 +58,29 @@ local function fail(err) return ("\n ERROR: %s"):format(err or "") end action = function(host, port) - local response = http.get(host, port, ("/secure?command=browse&dir=%s"):format(arg_dir)) + local response = http.get(host, port, ("/secure?command=browse&dir=%s"):format(arg_dir)) - if ( response.status ~= 200 or not(response.body) or 0 == #response.body ) then - if ( response.status == 401 ) then - return fail("Server requires authentication") - else - return - end - end + if ( response.status ~= 200 or not(response.body) or 0 == #response.body ) then + if ( response.status == 401 ) then + return fail("Server requires authentication") + else + return + end + end - local status, parsed = json.parse(response.body) - if ( not(status) ) then - return fail("Failed to parse response") - end + local status, parsed = json.parse(response.body) + if ( not(status) ) then + return fail("Failed to parse response") + end - if ( parsed.errorMessage ) then - return fail(parsed.errorMessage) - end + if ( parsed.errorMessage ) then + return fail(parsed.errorMessage) + end - local output = {} - for _, entry in pairs(parsed.files or {}) do - table.insert(output,entry.path) - end - table.sort(output, function(a,b) return aCL",0x4c,cmdID) -- 0x4c is object type tag - -- invoke run method - local result - status, result = jdwp.invokeObjectMethod(socket,0,injectedClass.instance,injectedClass.thread,injectedClass.id,runMethodID,1,runArgs) - if not status then - stdnse.print_debug(1, "%s: Couldn't invoke run method", SCRIPT_NAME) - return stdnse.format_output(false, result) - end - -- get the result string - local _,_,stringID = bin.unpack(">CL",result) - status,result = jdwp.readString(socket,0,stringID) - return stdnse.format_output(status,result) + if runMethodID == nil then + stdnse.print_debug(1, "%s: Couldn't find run method", SCRIPT_NAME) + return stdnse.format_output(false, "Couldn't find run method.") + end + -- set run() method argument + local cmd = stdnse.get_script_args(SCRIPT_NAME .. '.cmd') + if cmd == nil then + return stdnse.format_output(false, "This script requires a cmd argument to be specified.") + end + local cmdID + status,cmdID = jdwp.createString(socket,0,cmd) + if not status then + stdnse.print_debug(1, "%s: Couldn't create string", SCRIPT_NAME) + return stdnse.format_output(false, cmdID) + end + local runArgs = bin.pack(">CL",0x4c,cmdID) -- 0x4c is object type tag + -- invoke run method + local result + status, result = jdwp.invokeObjectMethod(socket,0,injectedClass.instance,injectedClass.thread,injectedClass.id,runMethodID,1,runArgs) + if not status then + stdnse.print_debug(1, "%s: Couldn't invoke run method", SCRIPT_NAME) + return stdnse.format_output(false, result) + end + -- get the result string + local _,_,stringID = bin.unpack(">CL",result) + status,result = jdwp.readString(socket,0,stringID) + return stdnse.format_output(status,result) end diff --git a/scripts/jdwp-info.nse b/scripts/jdwp-info.nse index 52e9bf5a8..30f07cbb8 100644 --- a/scripts/jdwp-info.nse +++ b/scripts/jdwp-info.nse @@ -44,51 +44,51 @@ categories = {"default","safe","discovery"} -- |_ System time: Sat Aug 11 15:21:44 CEST 2012 portrule = function(host, port) - -- JDWP will close the port if there is no valid handshake within 2 - -- seconds, Service detection's NULL probe detects it as tcpwrapped. - return port.service == "tcpwrapped" - and port.protocol == "tcp" and port.state == "open" - and not(shortport.port_is_excluded(port.number,port.protocol)) + -- JDWP will close the port if there is no valid handshake within 2 + -- seconds, Service detection's NULL probe detects it as tcpwrapped. + return port.service == "tcpwrapped" + and port.protocol == "tcp" and port.state == "open" + and not(shortport.port_is_excluded(port.number,port.protocol)) end action = function(host, port) - stdnse.sleep(5) -- let the remote socket recover from connect() scan - local status,socket = jdwp.connect(host,port) -- initialize the connection - if not status then - stdnse.print_debug("error, %s",socket) - return nil - end + stdnse.sleep(5) -- let the remote socket recover from connect() scan + local status,socket = jdwp.connect(host,port) -- initialize the connection + if not status then + stdnse.print_debug("error, %s",socket) + return nil + end - -- read .class file - local file = io.open(nmap.fetchfile("nselib/data/jdwp-class/JDWPSystemInfo.class"), "rb") - local class_bytes = file:read("*all") + -- read .class file + local file = io.open(nmap.fetchfile("nselib/data/jdwp-class/JDWPSystemInfo.class"), "rb") + local class_bytes = file:read("*all") - -- inject the class - local injectedClass - status,injectedClass = jdwp.injectClass(socket,class_bytes) - if not status then - stdnse.print_debug(1, "%s: Failed to inject class", SCRIPT_NAME) - return stdnse.format_output(false, "Failed to inject class") - end - -- find injected class method - local runMethodID = jdwp.findMethod(socket,injectedClass.id,"run",false) + -- inject the class + local injectedClass + status,injectedClass = jdwp.injectClass(socket,class_bytes) + if not status then + stdnse.print_debug(1, "%s: Failed to inject class", SCRIPT_NAME) + return stdnse.format_output(false, "Failed to inject class") + end + -- find injected class method + local runMethodID = jdwp.findMethod(socket,injectedClass.id,"run",false) - if runMethodID == nil then - stdnse.print_debug(1, "%s: Couldn't find run method", SCRIPT_NAME) - return stdnse.format_output(false, "Couldn't find run method.") - end + if runMethodID == nil then + stdnse.print_debug(1, "%s: Couldn't find run method", SCRIPT_NAME) + return stdnse.format_output(false, "Couldn't find run method.") + end - -- invoke run method - local result - status, result = jdwp.invokeObjectMethod(socket,0,injectedClass.instance,injectedClass.thread,injectedClass.id,runMethodID,0,nil) - if not status then - stdnse.print_debug(1, "%s: Couldn't invoke run method", SCRIPT_NAME) - return stdnse.format_output(false, result) - end - -- get the result string - local _,_,stringID = bin.unpack(">CL",result) - status,result = jdwp.readString(socket,0,stringID) - -- parse results - return stdnse.format_output(status,result) + -- invoke run method + local result + status, result = jdwp.invokeObjectMethod(socket,0,injectedClass.instance,injectedClass.thread,injectedClass.id,runMethodID,0,nil) + if not status then + stdnse.print_debug(1, "%s: Couldn't invoke run method", SCRIPT_NAME) + return stdnse.format_output(false, result) + end + -- get the result string + local _,_,stringID = bin.unpack(">CL",result) + status,result = jdwp.readString(socket,0,stringID) + -- parse results + return stdnse.format_output(status,result) end diff --git a/scripts/jdwp-inject.nse b/scripts/jdwp-inject.nse index 5997203cc..7a10c0835 100644 --- a/scripts/jdwp-inject.nse +++ b/scripts/jdwp-inject.nse @@ -31,55 +31,55 @@ license = "Same as Nmap--See http://nmap.org/book/man-legal.html" categories = {"exploit","intrusive"} portrule = function(host, port) - -- JDWP will close the port if there is no valid handshake within 2 - -- seconds, Service detection's NULL probe detects it as tcpwrapped. - return port.service == "tcpwrapped" - and port.protocol == "tcp" and port.state == "open" - and not(shortport.port_is_excluded(port.number,port.protocol)) + -- JDWP will close the port if there is no valid handshake within 2 + -- seconds, Service detection's NULL probe detects it as tcpwrapped. + return port.service == "tcpwrapped" + and port.protocol == "tcp" and port.state == "open" + and not(shortport.port_is_excluded(port.number,port.protocol)) end action = function(host, port) - stdnse.sleep(5) -- let the remote socket recover from connect() scan - local status,socket = jdwp.connect(host,port) -- initialize the connection - if not status then - stdnse.print_debug("error, %s",socket) - return nil - end + stdnse.sleep(5) -- let the remote socket recover from connect() scan + local status,socket = jdwp.connect(host,port) -- initialize the connection + if not status then + stdnse.print_debug("error, %s",socket) + return nil + end - -- read .class file - local filename = stdnse.get_script_args(SCRIPT_NAME .. '.filename') - if filename == nil then - return stdnse.format_output(false, "This script requires a .class file to inject.") - end - local file = io.open(nmap.fetchfile(filename) or filename, "rb") - local class_bytes = file:read("*all") + -- read .class file + local filename = stdnse.get_script_args(SCRIPT_NAME .. '.filename') + if filename == nil then + return stdnse.format_output(false, "This script requires a .class file to inject.") + end + local file = io.open(nmap.fetchfile(filename) or filename, "rb") + local class_bytes = file:read("*all") - -- inject the class - local injectedClass - status,injectedClass = jdwp.injectClass(socket,class_bytes) - if not status then - stdnse.print_debug(1, "%s: Failed to inject class", SCRIPT_NAME) - return stdnse.format_output(false, "Failed to inject class") - end - -- find injected class method - local runMethodID = jdwp.findMethod(socket,injectedClass.id,"run",false) + -- inject the class + local injectedClass + status,injectedClass = jdwp.injectClass(socket,class_bytes) + if not status then + stdnse.print_debug(1, "%s: Failed to inject class", SCRIPT_NAME) + return stdnse.format_output(false, "Failed to inject class") + end + -- find injected class method + local runMethodID = jdwp.findMethod(socket,injectedClass.id,"run",false) - if runMethodID == nil then - stdnse.print_debug(1, "%s: Couldn't find run method", SCRIPT_NAME) - return stdnse.format_output(false, "Couldn't find run method.") - end + if runMethodID == nil then + stdnse.print_debug(1, "%s: Couldn't find run method", SCRIPT_NAME) + return stdnse.format_output(false, "Couldn't find run method.") + end - -- invoke run method - local result - status, result = jdwp.invokeObjectMethod(socket,0,injectedClass.instance,injectedClass.thread,injectedClass.id,runMethodID,0,nil) - if not status then - stdnse.print_debug(1, "%s: Couldn't invoke run method", SCRIPT_NAME) - return stdnse.format_output(false, result) - end - -- get the result string - local _,_,stringID = bin.unpack(">CL",result) - status,result = jdwp.readString(socket,0,stringID) - -- parse results - return stdnse.format_output(status,result) + -- invoke run method + local result + status, result = jdwp.invokeObjectMethod(socket,0,injectedClass.instance,injectedClass.thread,injectedClass.id,runMethodID,0,nil) + if not status then + stdnse.print_debug(1, "%s: Couldn't invoke run method", SCRIPT_NAME) + return stdnse.format_output(false, result) + end + -- get the result string + local _,_,stringID = bin.unpack(">CL",result) + status,result = jdwp.readString(socket,0,stringID) + -- parse results + return stdnse.format_output(status,result) end diff --git a/scripts/jdwp-version.nse b/scripts/jdwp-version.nse index e697076be..b630f789c 100644 --- a/scripts/jdwp-version.nse +++ b/scripts/jdwp-version.nse @@ -23,36 +23,36 @@ categories = {"version"} portrule = function(host, port) - -- JDWP will close the port if there is no valid handshake within 2 - -- seconds, Service detection's NULL probe detects it as tcpwrapped. - return port.service == "tcpwrapped" - and port.protocol == "tcp" and port.state == "open" - and not(shortport.port_is_excluded(port.number,port.protocol)) + -- JDWP will close the port if there is no valid handshake within 2 + -- seconds, Service detection's NULL probe detects it as tcpwrapped. + return port.service == "tcpwrapped" + and port.protocol == "tcp" and port.state == "open" + and not(shortport.port_is_excluded(port.number,port.protocol)) end action = function(host, port) - -- make sure we get at least one more packet after the JDWP-Handshake - -- response even if there is some delay; the handshake response has 14 - -- bytes, so wait for 18 bytes here. - local status, result = comm.exchange(host, port, "JDWP-Handshake\0\0\0\11\0\0\0\1\0\1\1", {proto="tcp", bytes=18}) - if (not status) then - return - end - -- match jdwp m|JDWP-Handshake| p/$1/ v/$3/ i/$2\n$4/ - local match = {string.match(result, "^JDWP%-Handshake\0\0..\0\0\0\1\128\0\0\0\0..([^\0\n]*)\n([^\0]*)\0\0..\0\0..\0\0..([0-9._]+)\0\0..([^\0]*)")} - if match == nil or #match == 0 then - -- if we have one \128 (reply marker), it is at least not echo because the request did not contain \128 - if (string.match(result,"^JDWP%-Handshake\0.*\128") ~= nil) then - port.version.name="jdwp" - port.version.product="unknown" - nmap.set_port_version(host, port) - end - return - end - port.version.name="jdwp" - port.version.product = match[1] - port.version.version = match[3] - -- port.version.extrainfo = match[2] .. "\n" .. match[4] - nmap.set_port_version(host, port) - return + -- make sure we get at least one more packet after the JDWP-Handshake + -- response even if there is some delay; the handshake response has 14 + -- bytes, so wait for 18 bytes here. + local status, result = comm.exchange(host, port, "JDWP-Handshake\0\0\0\11\0\0\0\1\0\1\1", {proto="tcp", bytes=18}) + if (not status) then + return + end + -- match jdwp m|JDWP-Handshake| p/$1/ v/$3/ i/$2\n$4/ + local match = {string.match(result, "^JDWP%-Handshake\0\0..\0\0\0\1\128\0\0\0\0..([^\0\n]*)\n([^\0]*)\0\0..\0\0..\0\0..([0-9._]+)\0\0..([^\0]*)")} + if match == nil or #match == 0 then + -- if we have one \128 (reply marker), it is at least not echo because the request did not contain \128 + if (string.match(result,"^JDWP%-Handshake\0.*\128") ~= nil) then + port.version.name="jdwp" + port.version.product="unknown" + nmap.set_port_version(host, port) + end + return + end + port.version.name="jdwp" + port.version.product = match[1] + port.version.version = match[3] + -- port.version.extrainfo = match[2] .. "\n" .. match[4] + nmap.set_port_version(host, port) + return end diff --git a/scripts/lexmark-config.nse b/scripts/lexmark-config.nse index 95528128e..1ee573b07 100644 --- a/scripts/lexmark-config.nse +++ b/scripts/lexmark-config.nse @@ -55,32 +55,32 @@ portrule = shortport.portnumber({5353,9100}, "udp") action = function( host, port ) - local result = {} - local status, response = dns.query( "", { port = port.number, host = host.ip, dtype="PTR", retPkt=true} ) - if ( not(status) ) then - return - end - local status, txtrecords = dns.findNiceAnswer( dns.types.TXT, response, true ) - if ( not(status) ) then - return - end + local result = {} + local status, response = dns.query( "", { port = port.number, host = host.ip, dtype="PTR", retPkt=true} ) + if ( not(status) ) then + return + end + local status, txtrecords = dns.findNiceAnswer( dns.types.TXT, response, true ) + if ( not(status) ) then + return + end - for _, v in ipairs( txtrecords ) do - if ( v:len() > 0 ) then - if v:find("PRINTERVIDPID") then - port.version.name="hbn3" - end - if not v:find("product=") then - v = v:gsub(" ", ": ", 1) - end - table.insert( result, v ) - end - end + for _, v in ipairs( txtrecords ) do + if ( v:len() > 0 ) then + if v:find("PRINTERVIDPID") then + port.version.name="hbn3" + end + if not v:find("product=") then + v = v:gsub(" ", ": ", 1) + end + table.insert( result, v ) + end + end - -- set port to open - nmap.set_port_state(host, port, "open") - nmap.set_port_version(host, port) + -- set port to open + nmap.set_port_state(host, port, "open") + nmap.set_port_version(host, port) - return stdnse.format_output(true, result) + return stdnse.format_output(true, result) end diff --git a/scripts/metasploit-xmlrpc-brute.nse b/scripts/metasploit-xmlrpc-brute.nse index 21584793d..233a0a2d2 100644 --- a/scripts/metasploit-xmlrpc-brute.nse +++ b/scripts/metasploit-xmlrpc-brute.nse @@ -35,65 +35,65 @@ portrule = shortport.port_or_service(55553, "metasploit-xmlrpc", "tcp") Driver = { - new = function (self, host, port, opts) - local o = { host = host, port = port, opts = opts } - setmetatable (o,self) - self.__index = self - return o - end, + new = function (self, host, port, opts) + local o = { host = host, port = port, opts = opts } + setmetatable (o,self) + self.__index = self + return o + end, - connect = function ( self ) - self.socket = nmap.new_socket() - if ( not(self.socket:connect(self.host, self.port, self.opts)) ) then - return false - end - return true - end, + connect = function ( self ) + self.socket = nmap.new_socket() + if ( not(self.socket:connect(self.host, self.port, self.opts)) ) then + return false + end + return true + end, - login = function( self, username, password ) - local xmlreq='auth.login'..username..''..password.."\n"..string.char(0) - local status, err = self.socket:send(xmlreq) + login = function( self, username, password ) + local xmlreq='auth.login'..username..''..password.."\n"..string.char(0) + local status, err = self.socket:send(xmlreq) - if ( not ( status ) ) then - local err = brute.Error:new( "Unable to send handshake" ) - err:setAbort(true) - return false, err - end + if ( not ( status ) ) then + local err = brute.Error:new( "Unable to send handshake" ) + err:setAbort(true) + return false, err + end - -- Create a buffer and receive the first line - local response - status, response = self.socket:receive_buf("\r?\n", false) + -- Create a buffer and receive the first line + local response + status, response = self.socket:receive_buf("\r?\n", false) - if (response == nil or string.match(response,"faultStringauthentication error")) then - stdnse.print_debug(2, "metasploit-xmlrpc-brute: Bad login: %s/%s", username, password) - return false, brute.Error:new( "Bad login" ) - elseif (string.match(response,"resultsuccess")) then + if (response == nil or string.match(response,"faultStringauthentication error")) then + stdnse.print_debug(2, "metasploit-xmlrpc-brute: Bad login: %s/%s", username, password) + return false, brute.Error:new( "Bad login" ) + elseif (string.match(response,"resultsuccess")) then - stdnse.print_debug(1, "metasploit-xmlrpc-brute: Good login: %s/%s", username, password) - return true, brute.Account:new(username, password, creds.State.VALID) - end - stdnse.print_debug(1, "metasploit-xmlrpc-brute: WARNING: Unhandled response: %s", response) - return false, brute.Error:new( "unhandled response" ) - end, + stdnse.print_debug(1, "metasploit-xmlrpc-brute: Good login: %s/%s", username, password) + return true, brute.Account:new(username, password, creds.State.VALID) + end + stdnse.print_debug(1, "metasploit-xmlrpc-brute: WARNING: Unhandled response: %s", response) + return false, brute.Error:new( "unhandled response" ) + end, - disconnect = function( self ) - self.socket:close() - end, + disconnect = function( self ) + self.socket:close() + end, } action = function(host, port) - -- first determine whether we need SSL or not - local xmlreq='core.version\n'..string.char(0) - local socket, _, opts = comm.tryssl(host, port, xmlreq, { recv_first = false } ) - if ( not(socket) ) then - return "\n ERROR: Failed to determine whether SSL was needed or not" - end + -- first determine whether we need SSL or not + local xmlreq='core.version\n'..string.char(0) + local socket, _, opts = comm.tryssl(host, port, xmlreq, { recv_first = false } ) + if ( not(socket) ) then + return "\n ERROR: Failed to determine whether SSL was needed or not" + end - local engine = brute.Engine:new(Driver, host, port, opts) - engine.options.script_name = SCRIPT_NAME - engine.options.firstonly = true - local status, result = engine:start() - return result + local engine = brute.Engine:new(Driver, host, port, opts) + engine.options.script_name = SCRIPT_NAME + engine.options.firstonly = true + local status, result = engine:start() + return result end diff --git a/scripts/mongodb-brute.nse b/scripts/mongodb-brute.nse index dea4b2ebe..2f5438270 100644 --- a/scripts/mongodb-brute.nse +++ b/scripts/mongodb-brute.nse @@ -35,72 +35,72 @@ portrule = shortport.port_or_service({27017}, {"mongodb"}) Driver = { - new = function(self, host, port, options) - local o = { host = host, port = port, sock = nmap.new_socket() } - setmetatable(o, self) - self.__index = self - return o - end, + new = function(self, host, port, options) + local o = { host = host, port = port, sock = nmap.new_socket() } + setmetatable(o, self) + self.__index = self + return o + end, - connect = function(self) - return self.sock:connect(self.host, self.port) - end, + connect = function(self) + return self.sock:connect(self.host, self.port) + end, - login = function(self, username, password) - local status, resp = mongodb.login(self.sock, arg_db, username, password) - if ( status ) then - return true, brute.Account:new(username, password, creds.State.VALID) - elseif ( resp ~= "Authentication failed" ) then - local err = brute.Error:new( resp ) - err:setRetry( true ) - return false, err - end - return false, brute.Error:new( "Incorrect password" ) - end, + login = function(self, username, password) + local status, resp = mongodb.login(self.sock, arg_db, username, password) + if ( status ) then + return true, brute.Account:new(username, password, creds.State.VALID) + elseif ( resp ~= "Authentication failed" ) then + local err = brute.Error:new( resp ) + err:setRetry( true ) + return false, err + end + return false, brute.Error:new( "Incorrect password" ) + end, - disconnect = function(self) - return self.sock:close() - end, + disconnect = function(self) + return self.sock:close() + end, } local function needsAuth(host, port) - local socket = nmap.new_socket() - local status, result = socket:connect(host, port) - if ( not(status) ) then - return false, "Failed to connect to server" - end + local socket = nmap.new_socket() + local status, result = socket:connect(host, port) + if ( not(status) ) then + return false, "Failed to connect to server" + end - local packet - status, packet = mongodb.listDbQuery() - if ( not(status) ) then - return false, result - end + local packet + status, packet = mongodb.listDbQuery() + if ( not(status) ) then + return false, result + end - --- Send packet - status, result = mongodb.query(socket, packet) - if ( not(status) ) then - return false, result - end + --- Send packet + status, result = mongodb.query(socket, packet) + if ( not(status) ) then + return false, result + end - socket:close() - if ( status and result.errmsg ) then - return true - end - return false + socket:close() + if ( status and result.errmsg ) then + return true + end + return false end action = function(host, port) - if ( not(needsAuth(host, port)) ) then - return "No authentication needed" - end + if ( not(needsAuth(host, port)) ) then + return "No authentication needed" + end - local engine = brute.Engine:new(Driver, host, port ) + local engine = brute.Engine:new(Driver, host, port ) - engine.options.script_name = SCRIPT_NAME - engine.options.firstonly = true - local status, result = engine:start() + engine.options.script_name = SCRIPT_NAME + engine.options.firstonly = true + local status, result = engine:start() - return result + return result end diff --git a/scripts/mongodb-databases.nse b/scripts/mongodb-databases.nse index 1cdde1281..b3fd6b078 100644 --- a/scripts/mongodb-databases.nse +++ b/scripts/mongodb-databases.nse @@ -51,50 +51,50 @@ portrule = shortport.port_or_service({27017}, {"mongodb"}) function action(host,port) - local socket = nmap.new_socket() + local socket = nmap.new_socket() - -- set a reasonable timeout value - socket:set_timeout(10000) - -- do some exception / cleanup - local catch = function() - socket:close() - end + -- set a reasonable timeout value + socket:set_timeout(10000) + -- do some exception / cleanup + local catch = function() + socket:close() + end - local try = nmap.new_try(catch) + local try = nmap.new_try(catch) - try( socket:connect(host, port) ) + try( socket:connect(host, port) ) - -- uglyness to allow creds.mongodb to work, as the port is not recognized - -- as mongodb, unless a service scan was run - local ps = port.service - port.service = 'mongodb' - local c = creds.Credentials:new(creds.ALL_DATA, host, port) - for cred in c:getCredentials(creds.State.VALID + creds.State.PARAM) do - local status, err = mongodb.login(socket, "admin", cred.user, cred.pass) - if ( not(status) ) then - return err - end - end - port.service = ps + -- uglyness to allow creds.mongodb to work, as the port is not recognized + -- as mongodb, unless a service scan was run + local ps = port.service + port.service = 'mongodb' + local c = creds.Credentials:new(creds.ALL_DATA, host, port) + for cred in c:getCredentials(creds.State.VALID + creds.State.PARAM) do + local status, err = mongodb.login(socket, "admin", cred.user, cred.pass) + if ( not(status) ) then + return err + end + end + port.service = ps - local req, result, packet, err, status - --Build packet - status, packet = mongodb.listDbQuery() - if not status then return result end-- Error message + local req, result, packet, err, status + --Build packet + status, packet = mongodb.listDbQuery() + if not status then return result end-- Error message - --- Send packet - status, result = mongodb.query(socket, packet) - if not status then return result end-- Error message + --- Send packet + status, result = mongodb.query(socket, packet) + if not status then return result end-- Error message - port.version.name ='mongodb' - port.version.product='MongoDB' - nmap.set_port_version(host,port) + port.version.name ='mongodb' + port.version.product='MongoDB' + nmap.set_port_version(host,port) - local output = mongodb.queryResultToTable(result) - if err ~= nil then - stdnse.log_error(err) - end - if result ~= nil then - return stdnse.format_output(true, output ) - end + local output = mongodb.queryResultToTable(result) + if err ~= nil then + stdnse.log_error(err) + end + if result ~= nil then + return stdnse.format_output(true, output ) + end end diff --git a/scripts/ms-sql-dac.nse b/scripts/ms-sql-dac.nse index d853bf937..87ba6d150 100644 --- a/scripts/ms-sql-dac.nse +++ b/scripts/ms-sql-dac.nse @@ -37,69 +37,69 @@ license = "Same as Nmap--See http://nmap.org/book/man-legal.html" categories = {"discovery", "safe"} hostrule = function(host) - if ( mssql.Helper.WasDiscoveryPerformed( host ) ) then - return mssql.Helper.GetDiscoveredInstances( host ) ~= nil - else - local sqlBrowserPort = nmap.get_port_state( host, {number = 1434, protocol = "udp"} ) - if ( (stdnse.get_script_args( {"mssql.instance-all", "mssql.instance-name", "mssql.instance-port"} ) ~= nil) or - (sqlBrowserPort and (sqlBrowserPort.state == "open" or sqlBrowserPort.state == "open|filtered")) ) then - return true - end - end + if ( mssql.Helper.WasDiscoveryPerformed( host ) ) then + return mssql.Helper.GetDiscoveredInstances( host ) ~= nil + else + local sqlBrowserPort = nmap.get_port_state( host, {number = 1434, protocol = "udp"} ) + if ( (stdnse.get_script_args( {"mssql.instance-all", "mssql.instance-name", "mssql.instance-port"} ) ~= nil) or + (sqlBrowserPort and (sqlBrowserPort.state == "open" or sqlBrowserPort.state == "open|filtered")) ) then + return true + end + end end local function checkPort(host, port) - local s = nmap.new_socket() - s:set_timeout(5000) - local status = s:connect(host, port, "tcp") - s:close() - return status + local s = nmap.new_socket() + s:set_timeout(5000) + local status = s:connect(host, port, "tcp") + s:close() + return status end local function discoverDAC(host, name, result) - local condvar = nmap.condvar(result) - stdnse.print_debug(2, "Discovering DAC port on instance: %s", name) - local port = mssql.Helper.DiscoverDACPort( host, name ) - if ( port ) then - if ( checkPort(host, port) ) then - table.insert(result, ("Instance: %s; DAC port: %s"):format(name, port)) - else - table.insert(result, ("Instance: %s; DAC port: %s (connection failed)"):format(name, port)) - end - end - condvar "signal" + local condvar = nmap.condvar(result) + stdnse.print_debug(2, "Discovering DAC port on instance: %s", name) + local port = mssql.Helper.DiscoverDACPort( host, name ) + if ( port ) then + if ( checkPort(host, port) ) then + table.insert(result, ("Instance: %s; DAC port: %s"):format(name, port)) + else + table.insert(result, ("Instance: %s; DAC port: %s (connection failed)"):format(name, port)) + end + end + condvar "signal" end action = function( host ) - local result, threads = {}, {} - local condvar = nmap.condvar(result) + local result, threads = {}, {} + local condvar = nmap.condvar(result) - local status, instanceList = mssql.Helper.GetTargetInstances( host ) - -- if no instances were targeted, then display info on all - if ( not status ) then - if ( not mssql.Helper.WasDiscoveryPerformed( host ) ) then - mssql.Helper.Discover( host ) - end - instanceList = mssql.Helper.GetDiscoveredInstances( host ) - end + local status, instanceList = mssql.Helper.GetTargetInstances( host ) + -- if no instances were targeted, then display info on all + if ( not status ) then + if ( not mssql.Helper.WasDiscoveryPerformed( host ) ) then + mssql.Helper.Discover( host ) + end + instanceList = mssql.Helper.GetDiscoveredInstances( host ) + end - for _, instance in ipairs(instanceList or {}) do - local name = instance:GetName():match("^[^\\]*\\(.*)$") - if ( name ) then - local co = stdnse.new_thread(discoverDAC, host, name, result) - threads[co] = true - end - end + for _, instance in ipairs(instanceList or {}) do + local name = instance:GetName():match("^[^\\]*\\(.*)$") + if ( name ) then + local co = stdnse.new_thread(discoverDAC, host, name, result) + threads[co] = true + end + end - while(next(threads)) do - for t in pairs(threads) do - threads[t] = ( coroutine.status(t) ~= "dead" ) and true or nil - end - if ( next(threads) ) then - condvar "wait" - end - end + while(next(threads)) do + for t in pairs(threads) do + threads[t] = ( coroutine.status(t) ~= "dead" ) and true or nil + end + if ( next(threads) ) then + condvar "wait" + end + end - return stdnse.format_output( true, result ) + return stdnse.format_output( true, result ) end diff --git a/scripts/mysql-brute.nse b/scripts/mysql-brute.nse index 656e57a8f..9044ae1b3 100644 --- a/scripts/mysql-brute.nse +++ b/scripts/mysql-brute.nse @@ -41,57 +41,57 @@ arg_timeout = (arg_timeout or 5) * 1000 Driver = { - new = function(self, host, port) - local o = {} - setmetatable(o, self) - self.__index = self - o.host = host - o.port = port - return o - end, + new = function(self, host, port) + local o = {} + setmetatable(o, self) + self.__index = self + o.host = host + o.port = port + return o + end, - connect = function( self ) - self.socket = nmap.new_socket() - local status, err = self.socket:connect(self.host, self.port) - self.socket:set_timeout(arg_timeout) - if(not(status)) then - return false, brute.Error:new( "Couldn't connect to host: " .. err ) - end - return true - end, + connect = function( self ) + self.socket = nmap.new_socket() + local status, err = self.socket:connect(self.host, self.port) + self.socket:set_timeout(arg_timeout) + if(not(status)) then + return false, brute.Error:new( "Couldn't connect to host: " .. err ) + end + return true + end, - login = function (self, user, pass) - local status, response = mysql.receiveGreeting(self.socket) - if(not(status)) then - return false,brute.Error:new(response) - end - stdnse.print_debug( "Trying %s/%s ...", user, pass ) - status, response = mysql.loginRequest( self.socket, { authversion = "post41", charset = response.charset }, user, pass, response.salt ) - if status then - -- Add credentials for other mysql scripts to use - if nmap.registry.mysqlusers == nil then - nmap.registry.mysqlusers = {} - end - nmap.registry.mysqlusers[user]=pass - return true, brute.Account:new( user, pass, creds.State.VALID) - end - return false,brute.Error:new( "Incorrect password" ) - end, + login = function (self, user, pass) + local status, response = mysql.receiveGreeting(self.socket) + if(not(status)) then + return false,brute.Error:new(response) + end + stdnse.print_debug( "Trying %s/%s ...", user, pass ) + status, response = mysql.loginRequest( self.socket, { authversion = "post41", charset = response.charset }, user, pass, response.salt ) + if status then + -- Add credentials for other mysql scripts to use + if nmap.registry.mysqlusers == nil then + nmap.registry.mysqlusers = {} + end + nmap.registry.mysqlusers[user]=pass + return true, brute.Account:new( user, pass, creds.State.VALID) + end + return false,brute.Error:new( "Incorrect password" ) + end, - disconnect = function( self ) - self.socket:close() - return true - end + disconnect = function( self ) + self.socket:close() + return true + end } action = function( host, port ) - local status, result - local engine = brute.Engine:new(Driver, host, port) - engine.options.script_name = SCRIPT_NAME + local status, result + local engine = brute.Engine:new(Driver, host, port) + engine.options.script_name = SCRIPT_NAME - status, result = engine:start() + status, result = engine:start() - return result + return result end diff --git a/scripts/mysql-databases.nse b/scripts/mysql-databases.nse index ad58f21e3..722e524b1 100644 --- a/scripts/mysql-databases.nse +++ b/scripts/mysql-databases.nse @@ -41,58 +41,58 @@ portrule = shortport.port_or_service(3306, "mysql") action = function( host, port ) - local socket = nmap.new_socket() - local catch = function() socket:close() end - local try = nmap.new_try(catch) - local result, response, dbs = {}, nil, {} - local users = {} - local nmap_args = nmap.registry.args - local status, rows + local socket = nmap.new_socket() + local catch = function() socket:close() end + local try = nmap.new_try(catch) + local result, response, dbs = {}, nil, {} + local users = {} + local nmap_args = nmap.registry.args + local status, rows - -- set a reasonable timeout value - socket:set_timeout(5000) + -- set a reasonable timeout value + socket:set_timeout(5000) - -- first, let's see if the script has any credentials as arguments? - if nmap_args.mysqluser then - users[nmap_args.mysqluser] = nmap_args.mysqlpass or "" - -- next, let's see if mysql-brute or mysql-empty-password brought us anything - elseif nmap.registry.mysqlusers then - -- do we have root credentials? - if nmap.registry.mysqlusers['root'] then - users['root'] = nmap.registry.mysqlusers['root'] - else - -- we didn't have root, so let's make sure we loop over them all - users = nmap.registry.mysqlusers - end - -- last, no dice, we don't have any credentials at all - else - stdnse.print_debug("No credentials supplied, aborting ...") - return - end + -- first, let's see if the script has any credentials as arguments? + if nmap_args.mysqluser then + users[nmap_args.mysqluser] = nmap_args.mysqlpass or "" + -- next, let's see if mysql-brute or mysql-empty-password brought us anything + elseif nmap.registry.mysqlusers then + -- do we have root credentials? + if nmap.registry.mysqlusers['root'] then + users['root'] = nmap.registry.mysqlusers['root'] + else + -- we didn't have root, so let's make sure we loop over them all + users = nmap.registry.mysqlusers + end + -- last, no dice, we don't have any credentials at all + else + stdnse.print_debug("No credentials supplied, aborting ...") + return + end - -- - -- Iterates over credentials, breaks once it successfully recieves results - -- - for username, password in pairs(users) do + -- + -- Iterates over credentials, breaks once it successfully recieves results + -- + for username, password in pairs(users) do - try( socket:connect(host, port) ) + try( socket:connect(host, port) ) - response = try( mysql.receiveGreeting( socket ) ) - status, response = mysql.loginRequest( socket, { authversion = "post41", charset = response.charset }, username, password, response.salt ) + response = try( mysql.receiveGreeting( socket ) ) + status, response = mysql.loginRequest( socket, { authversion = "post41", charset = response.charset }, username, password, response.salt ) - if status and response.errorcode == 0 then - local status, rs = mysql.sqlQuery( socket, "show databases" ) - if status then - result = mysql.formatResultset(rs, { noheaders = true }) + if status and response.errorcode == 0 then + local status, rs = mysql.sqlQuery( socket, "show databases" ) + if status then + result = mysql.formatResultset(rs, { noheaders = true }) - -- if we got here as root, we've got them all - -- if we're here as someone else, we cant be sure - if username == 'root' then - break - end - end - end - socket:close() - end - return stdnse.format_output(true, result) + -- if we got here as root, we've got them all + -- if we're here as someone else, we cant be sure + if username == 'root' then + break + end + end + end + socket:close() + end + return stdnse.format_output(true, result) end diff --git a/scripts/mysql-dump-hashes.nse b/scripts/mysql-dump-hashes.nse index 30c0e901d..a6af1006e 100644 --- a/scripts/mysql-dump-hashes.nse +++ b/scripts/mysql-dump-hashes.nse @@ -43,60 +43,60 @@ local arg_password = stdnse.get_script_args(SCRIPT_NAME .. ".password") or "" local function fail(err) return ("\n ERROR: %s"):format(err or "") end local function getCredentials() - -- first, let's see if the script has any credentials as arguments? - if ( arg_username ) then - return { [arg_username] = arg_password } - -- next, let's see if mysql-brute or mysql-empty-password brought us anything - elseif nmap.registry.mysqlusers then - -- do we have root credentials? - if nmap.registry.mysqlusers['root'] then - return { ['root'] = nmap.registry.mysqlusers['root'] } - else - -- we didn't have root, so let's make sure we loop over them all - return nmap.registry.mysqlusers - end - -- last, no dice, we don't have any credentials at all - end + -- first, let's see if the script has any credentials as arguments? + if ( arg_username ) then + return { [arg_username] = arg_password } + -- next, let's see if mysql-brute or mysql-empty-password brought us anything + elseif nmap.registry.mysqlusers then + -- do we have root credentials? + if nmap.registry.mysqlusers['root'] then + return { ['root'] = nmap.registry.mysqlusers['root'] } + else + -- we didn't have root, so let's make sure we loop over them all + return nmap.registry.mysqlusers + end + -- last, no dice, we don't have any credentials at all + end end local function mysqlLogin(socket, username, password) - local status, response = mysql.receiveGreeting( socket ) - if ( not(status) ) then - return response - end - return mysql.loginRequest( socket, { authversion = "post41", charset = response.charset }, username, password, response.salt ) + local status, response = mysql.receiveGreeting( socket ) + if ( not(status) ) then + return response + end + return mysql.loginRequest( socket, { authversion = "post41", charset = response.charset }, username, password, response.salt ) end action = function(host, port) - local creds = getCredentials() - if ( not(creds) ) then - stdnse.print_debug(2, "No credentials were supplied, aborting ...") - return - end + local creds = getCredentials() + if ( not(creds) ) then + stdnse.print_debug(2, "No credentials were supplied, aborting ...") + return + end - local result = {} - for username, password in pairs(creds) do - local socket = nmap.new_socket() - if ( not(socket:connect(host, port)) ) then - return fail("Failed to connect to server") - end + local result = {} + for username, password in pairs(creds) do + local socket = nmap.new_socket() + if ( not(socket:connect(host, port)) ) then + return fail("Failed to connect to server") + end - local status, response = mysqlLogin(socket, username, password) - if ( status ) then - local query = "SELECT DISTINCT CONCAT(user, ':', password) FROM mysql.user WHERE password <> ''" - local status, rows = mysql.sqlQuery( socket, query ) - socket:close() - if ( status ) then - result = mysql.formatResultset(rows, { noheaders = true }) - break - end - else - socket:close() - end - end + local status, response = mysqlLogin(socket, username, password) + if ( status ) then + local query = "SELECT DISTINCT CONCAT(user, ':', password) FROM mysql.user WHERE password <> ''" + local status, rows = mysql.sqlQuery( socket, query ) + socket:close() + if ( status ) then + result = mysql.formatResultset(rows, { noheaders = true }) + break + end + else + socket:close() + end + end - if ( result ) then - return stdnse.format_output(true, result) - end + if ( result ) then + return stdnse.format_output(true, result) + end end diff --git a/scripts/mysql-empty-password.nse b/scripts/mysql-empty-password.nse index 39aa037dc..1d6914483 100644 --- a/scripts/mysql-empty-password.nse +++ b/scripts/mysql-empty-password.nse @@ -31,35 +31,35 @@ portrule = shortport.port_or_service(3306, "mysql") action = function( host, port ) - local socket = nmap.new_socket() - local result = {} - local users = {"", "root"} + local socket = nmap.new_socket() + local result = {} + local users = {"", "root"} - -- set a reasonable timeout value - socket:set_timeout(5000) + -- set a reasonable timeout value + socket:set_timeout(5000) - for _, v in ipairs( users ) do - local status, response = socket:connect(host, port) - if( not(status) ) then return " \n ERROR: Failed to connect to mysql server" end + for _, v in ipairs( users ) do + local status, response = socket:connect(host, port) + if( not(status) ) then return " \n ERROR: Failed to connect to mysql server" end - status, response = mysql.receiveGreeting( socket ) - if ( not(status) ) then - stdnse.print_debug(3, SCRIPT_NAME) - socket:close() - return response - end + status, response = mysql.receiveGreeting( socket ) + if ( not(status) ) then + stdnse.print_debug(3, SCRIPT_NAME) + socket:close() + return response + end - status, response = mysql.loginRequest( socket, { authversion = "post41", charset = response.charset }, v, nil, response.salt ) - if response.errorcode == 0 then - table.insert(result, string.format("%s account has empty password", ( v=="" and "anonymous" or v ) ) ) - if nmap.registry.mysqlusers == nil then - nmap.registry.mysqlusers = {} - end - nmap.registry.mysqlusers[v=="" and "anonymous" or v] = "" - end - socket:close() - end + status, response = mysql.loginRequest( socket, { authversion = "post41", charset = response.charset }, v, nil, response.salt ) + if response.errorcode == 0 then + table.insert(result, string.format("%s account has empty password", ( v=="" and "anonymous" or v ) ) ) + if nmap.registry.mysqlusers == nil then + nmap.registry.mysqlusers = {} + end + nmap.registry.mysqlusers[v=="" and "anonymous" or v] = "" + end + socket:close() + end - return stdnse.format_output(true, result) + return stdnse.format_output(true, result) end diff --git a/scripts/mysql-users.nse b/scripts/mysql-users.nse index 28e6e678b..0863cb173 100644 --- a/scripts/mysql-users.nse +++ b/scripts/mysql-users.nse @@ -44,54 +44,54 @@ portrule = shortport.port_or_service(3306, "mysql") action = function( host, port ) - local socket = nmap.new_socket() - local catch = function() socket:close() end - local try = nmap.new_try(catch) - local result, response = {}, nil - local users = {} - local nmap_args = nmap.registry.args - local status, rows + local socket = nmap.new_socket() + local catch = function() socket:close() end + local try = nmap.new_try(catch) + local result, response = {}, nil + local users = {} + local nmap_args = nmap.registry.args + local status, rows - -- set a reasonable timeout value - socket:set_timeout(5000) + -- set a reasonable timeout value + socket:set_timeout(5000) - -- first, let's see if the script has any credentials as arguments? - if nmap_args.mysqluser then - users[nmap_args.mysqluser] = nmap_args.mysqlpass or "" - -- next, let's see if mysql-brute or mysql-empty-password brought us anything - elseif nmap.registry.mysqlusers then - -- do we have root credentials? - if nmap.registry.mysqlusers['root'] then - users['root'] = nmap.registry.mysqlusers['root'] - else - -- we didn't have root, so let's make sure we loop over them all - users = nmap.registry.mysqlusers - end - -- last, no dice, we don't have any credentials at all - else - stdnse.print_debug("No credentials supplied, aborting ...") - return - end + -- first, let's see if the script has any credentials as arguments? + if nmap_args.mysqluser then + users[nmap_args.mysqluser] = nmap_args.mysqlpass or "" + -- next, let's see if mysql-brute or mysql-empty-password brought us anything + elseif nmap.registry.mysqlusers then + -- do we have root credentials? + if nmap.registry.mysqlusers['root'] then + users['root'] = nmap.registry.mysqlusers['root'] + else + -- we didn't have root, so let's make sure we loop over them all + users = nmap.registry.mysqlusers + end + -- last, no dice, we don't have any credentials at all + else + stdnse.print_debug("No credentials supplied, aborting ...") + return + end - -- - -- Iterates over credentials, breaks once it successfully recieves results - -- - for username, password in pairs(users) do + -- + -- Iterates over credentials, breaks once it successfully recieves results + -- + for username, password in pairs(users) do - try( socket:connect(host, port) ) + try( socket:connect(host, port) ) - response = try( mysql.receiveGreeting( socket ) ) - status, response = mysql.loginRequest( socket, { authversion = "post41", charset = response.charset }, username, password, response.salt ) + response = try( mysql.receiveGreeting( socket ) ) + status, response = mysql.loginRequest( socket, { authversion = "post41", charset = response.charset }, username, password, response.salt ) - if status and response.errorcode == 0 then - status, rows = mysql.sqlQuery( socket, "SELECT DISTINCT user FROM mysql.user" ) - if status then - result = mysql.formatResultset(rows, { noheaders = true }) - end - end - socket:close() - end + if status and response.errorcode == 0 then + status, rows = mysql.sqlQuery( socket, "SELECT DISTINCT user FROM mysql.user" ) + if status then + result = mysql.formatResultset(rows, { noheaders = true }) + end + end + socket:close() + end - return stdnse.format_output(true, result) + return stdnse.format_output(true, result) end diff --git a/scripts/nat-pmp-info.nse b/scripts/nat-pmp-info.nse index 693d0dda6..4c22f001f 100644 --- a/scripts/nat-pmp-info.nse +++ b/scripts/nat-pmp-info.nse @@ -25,14 +25,14 @@ categories = {"default", "discovery", "safe"} portrule = shortport.port_or_service(5351, "nat-pmp", {"udp"} ) action = function(host, port) - local helper = natpmp.Helper:new(host, port) - local status, response = helper:getWANIP() + local helper = natpmp.Helper:new(host, port) + local status, response = helper:getWANIP() - if ( status ) then - nmap.set_port_state(host, port, "open") - port.version.name = "nat-pmp" - nmap.set_port_version(host, port) + if ( status ) then + nmap.set_port_state(host, port, "open") + port.version.name = "nat-pmp" + nmap.set_port_version(host, port) - return stdnse.format_output(true, ("WAN IP: %s"):format(response.ip)) - end + return stdnse.format_output(true, ("WAN IP: %s"):format(response.ip)) + end end diff --git a/scripts/ncp-enum-users.nse b/scripts/ncp-enum-users.nse index 9d535f741..d84f87b98 100644 --- a/scripts/ncp-enum-users.nse +++ b/scripts/ncp-enum-users.nse @@ -35,20 +35,20 @@ categories = {"auth", "safe"} portrule = shortport.port_or_service(524, "ncp", "tcp") action = function(host, port) - local helper = ncp.Helper:new(host,port) + local helper = ncp.Helper:new(host,port) - local status, resp = helper:connect() - if ( not(status) ) then return stdnse.format_output(false, resp) end + local status, resp = helper:connect() + if ( not(status) ) then return stdnse.format_output(false, resp) end - status, resp = helper:search("[Root]", "User", "*") - if ( not(status) ) then return stdnse.format_output(false, resp) end + status, resp = helper:search("[Root]", "User", "*") + if ( not(status) ) then return stdnse.format_output(false, resp) end - local output = {} + local output = {} - for _, entry in ipairs(resp) do - table.insert(output, entry.name) - end + for _, entry in ipairs(resp) do + table.insert(output, entry.name) + end - return stdnse.format_output(true, output) + return stdnse.format_output(true, output) end diff --git a/scripts/ncp-serverinfo.nse b/scripts/ncp-serverinfo.nse index fe5811db3..e811914ac 100644 --- a/scripts/ncp-serverinfo.nse +++ b/scripts/ncp-serverinfo.nse @@ -37,15 +37,15 @@ categories = {"default", "discovery", "safe"} portrule = shortport.port_or_service(524, "ncp", "tcp") action = function(host, port) - local helper = ncp.Helper:new(host,port) + local helper = ncp.Helper:new(host,port) - local status, resp = helper:connect() - if ( not(status) ) then return stdnse.format_output(false, resp) end + local status, resp = helper:connect() + if ( not(status) ) then return stdnse.format_output(false, resp) end - status, resp = helper:getServerInfo() - if ( not(status) ) then return stdnse.format_output(false, resp) end + status, resp = helper:getServerInfo() + if ( not(status) ) then return stdnse.format_output(false, resp) end - helper:close() + helper:close() - return stdnse.format_output(true, resp) + return stdnse.format_output(true, resp) end diff --git a/scripts/ndmp-fs-info.nse b/scripts/ndmp-fs-info.nse index c1abc08e8..689367b0b 100644 --- a/scripts/ndmp-fs-info.nse +++ b/scripts/ndmp-fs-info.nse @@ -47,24 +47,24 @@ local function fail(err) return ("\n ERROR: %s"):format(err or "") end action = function(host, port) - local helper = ndmp.Helper:new(host, port) - local status, msg = helper:connect() - if ( not(status) ) then return fail("Failed to connect to server") end + local helper = ndmp.Helper:new(host, port) + local status, msg = helper:connect() + if ( not(status) ) then return fail("Failed to connect to server") end - status, msg = helper:getFsInfo() - if ( not(status) ) then return fail("Failed to get filesystem information from server") end - helper:close() + status, msg = helper:getFsInfo() + if ( not(status) ) then return fail("Failed to get filesystem information from server") end + helper:close() - local result = tab.new(3) - tab.addrow(result, "FS", "Logical device", "Physical device") + local result = tab.new(3) + tab.addrow(result, "FS", "Logical device", "Physical device") - for _, item in ipairs(msg.fsinfo) do - if ( item.fs_logical_device and #item.fs_logical_device ~= 0 ) then - if ( item and item.fs_type and item.fs_logical_device and item.fs_physical_device ) then - tab.addrow(result, item.fs_type, item.fs_logical_device:gsub("?", " "), item.fs_physical_device) - end - end - end + for _, item in ipairs(msg.fsinfo) do + if ( item.fs_logical_device and #item.fs_logical_device ~= 0 ) then + if ( item and item.fs_type and item.fs_logical_device and item.fs_physical_device ) then + tab.addrow(result, item.fs_type, item.fs_logical_device:gsub("?", " "), item.fs_physical_device) + end + end + end - return "\n" .. tab.dump(result) + return "\n" .. tab.dump(result) end diff --git a/scripts/ndmp-version.nse b/scripts/ndmp-version.nse index 2dd8d5ea0..00448292f 100644 --- a/scripts/ndmp-version.nse +++ b/scripts/ndmp-version.nse @@ -29,35 +29,35 @@ portrule = shortport.version_port_or_service(10000, "ndmp", "tcp") local function fail(err) return ("\n ERROR: %s"):format(err or "") end local function vendorLookup(vendor) - if ( vendor:match("VERITAS") ) then - return "Symantec/Veritas Backup Exec ndmp" - else - return vendor - end + if ( vendor:match("VERITAS") ) then + return "Symantec/Veritas Backup Exec ndmp" + else + return vendor + end end action = function(host, port) - local helper = ndmp.Helper:new(host, port) - local status, err = helper:connect() - if ( not(status) ) then return fail("Failed to connect to server") end + local helper = ndmp.Helper:new(host, port) + local status, err = helper:connect() + if ( not(status) ) then return fail("Failed to connect to server") end - local hi, si - status, hi = helper:getHostInfo() - if ( not(status) ) then return fail("Failed to get host information from server") end + local hi, si + status, hi = helper:getHostInfo() + if ( not(status) ) then return fail("Failed to get host information from server") end - status, si = helper:getServerInfo() - if ( not(status) ) then return fail("Failed to get server information from server") end - helper:close() + status, si = helper:getServerInfo() + if ( not(status) ) then return fail("Failed to get server information from server") end + helper:close() - local major, minor, build, smajor, sminor = hi.hostinfo.osver:match("Major Version=(%d+) Minor Version=(%d+) Build Number=(%d+) ServicePack Major=(%d+) ServicePack Minor=(%d+)") - port.version.name = "ndmp" - port.version.product = vendorLookup(si.serverinfo.vendor) - port.version.ostype = hi.hostinfo.ostype - if ( hi.hostinfo.hostname ) then - port.version.extrainfo = ("Name: %s; "):format(hi.hostinfo.hostname) - end - if ( major and minor and build and smajor and sminor ) then - port.version.extrainfo = port.version.extrainfo .. ("OS ver: %d.%d; OS Build: %d; OS Service Pack: %d"):format(major, minor, build, smajor) - end - nmap.set_port_version(host, port) + local major, minor, build, smajor, sminor = hi.hostinfo.osver:match("Major Version=(%d+) Minor Version=(%d+) Build Number=(%d+) ServicePack Major=(%d+) ServicePack Minor=(%d+)") + port.version.name = "ndmp" + port.version.product = vendorLookup(si.serverinfo.vendor) + port.version.ostype = hi.hostinfo.ostype + if ( hi.hostinfo.hostname ) then + port.version.extrainfo = ("Name: %s; "):format(hi.hostinfo.hostname) + end + if ( major and minor and build and smajor and sminor ) then + port.version.extrainfo = port.version.extrainfo .. ("OS ver: %d.%d; OS Build: %d; OS Service Pack: %d"):format(major, minor, build, smajor) + end + nmap.set_port_version(host, port) end diff --git a/scripts/netbus-auth-bypass.nse b/scripts/netbus-auth-bypass.nse index f5955dd0d..d456ead37 100644 --- a/scripts/netbus-auth-bypass.nse +++ b/scripts/netbus-auth-bypass.nse @@ -31,28 +31,28 @@ portrule = shortport.port_or_service (12345, "netbus", {"tcp"}) action = function( host, port ) - local socket = nmap.new_socket() - local status, err = socket:connect(host.ip, port.number) - if not status then - return - end - local buffer, _ = stdnse.make_buffer(socket, "\r") - buffer() --discard banner + local socket = nmap.new_socket() + local status, err = socket:connect(host.ip, port.number) + if not status then + return + end + local buffer, _ = stdnse.make_buffer(socket, "\r") + buffer() --discard banner - -- The first argument of Password is the super-login bit. - -- On vulnerable servers any password will do as long as - -- we send the super-login bit. Regular NetBus has only - -- one password. Thus, if we can login with two different - -- passwords using super-login, the server is vulnerable. + -- The first argument of Password is the super-login bit. + -- On vulnerable servers any password will do as long as + -- we send the super-login bit. Regular NetBus has only + -- one password. Thus, if we can login with two different + -- passwords using super-login, the server is vulnerable. - socket:send("Password;1;\r") --password: empty - if buffer() ~= "Access;1" then - return - end - socket:send("Password;1; \r") --password: space - if buffer() == "Access;1" then - return "Vulnerable" - end - return "Not vulnerable, but password is empty" + socket:send("Password;1;\r") --password: empty + if buffer() ~= "Access;1" then + return + end + socket:send("Password;1; \r") --password: space + if buffer() == "Access;1" then + return "Vulnerable" + end + return "Not vulnerable, but password is empty" end diff --git a/scripts/netbus-brute.nse b/scripts/netbus-brute.nse index 2ab1d0c77..045f04d66 100644 --- a/scripts/netbus-brute.nse +++ b/scripts/netbus-brute.nse @@ -26,33 +26,33 @@ dependencies = {"netbus-version"} portrule = shortport.port_or_service (12345, "netbus", {"tcp"}) action = function( host, port ) - local try = nmap.new_try() - local passwords = try(unpwdb.passwords()) - local socket = nmap.new_socket() - local status, err = socket:connect(host.ip, port.number) - if not status then - return - end - local buffer, err = stdnse.make_buffer(socket, "\r") - local _ = buffer() --skip the banner - for password in passwords do - local foo = string.format("Password;0;%s\r", password) - socket:send(foo) - local login = buffer() - if login == "Access;1" then - -- Store the password for other netbus scripts - local key = string.format("%s:%d", host.ip, port.number) - if not nmap.registry.netbuspasswords then - nmap.registry.netbuspasswords = {} - end - nmap.registry.netbuspasswords[key] = password - if password == "" then - return "" - end - return string.format("%s", password) - end - end - socket:close() + local try = nmap.new_try() + local passwords = try(unpwdb.passwords()) + local socket = nmap.new_socket() + local status, err = socket:connect(host.ip, port.number) + if not status then + return + end + local buffer, err = stdnse.make_buffer(socket, "\r") + local _ = buffer() --skip the banner + for password in passwords do + local foo = string.format("Password;0;%s\r", password) + socket:send(foo) + local login = buffer() + if login == "Access;1" then + -- Store the password for other netbus scripts + local key = string.format("%s:%d", host.ip, port.number) + if not nmap.registry.netbuspasswords then + nmap.registry.netbuspasswords = {} + end + nmap.registry.netbuspasswords[key] = password + if password == "" then + return "" + end + return string.format("%s", password) + end + end + socket:close() end diff --git a/scripts/netbus-version.nse b/scripts/netbus-version.nse index 35862d1d8..945d72c18 100644 --- a/scripts/netbus-version.nse +++ b/scripts/netbus-version.nse @@ -23,28 +23,28 @@ portrule = shortport.version_port_or_service ({}, "netbus", {"tcp"}) action = function( host, port ) - local socket = nmap.new_socket() - socket:set_timeout(5000) - local status, err = socket:connect(host.ip, port.number) - if not status then - return - end - local buffer, _ = stdnse.make_buffer(socket, "\r") - buffer() --discard banner - socket:send("Password;0;\r") + local socket = nmap.new_socket() + socket:set_timeout(5000) + local status, err = socket:connect(host.ip, port.number) + if not status then + return + end + local buffer, _ = stdnse.make_buffer(socket, "\r") + buffer() --discard banner + socket:send("Password;0;\r") - --NetBus answers to auth - if buffer() ~= nil then - return - end + --NetBus answers to auth + if buffer() ~= nil then + return + end - --NetBuster does not - port.version.name = "netbus" - port.version.product = "NetBuster" - port.version.extrainfo = "honeypot" - port.version.version = nil - nmap.set_port_version(host, port) - return + --NetBuster does not + port.version.name = "netbus" + port.version.product = "NetBuster" + port.version.extrainfo = "honeypot" + port.version.version = nil + nmap.set_port_version(host, port) + return end diff --git a/scripts/nexpose-brute.nse b/scripts/nexpose-brute.nse index 9af2ab0f8..851335d24 100644 --- a/scripts/nexpose-brute.nse +++ b/scripts/nexpose-brute.nse @@ -39,43 +39,43 @@ portrule = shortport.port_or_service(3780, "nexpose", "tcp") Driver = { - new = function (self, host, port) - local o = { host = host, port = port } - setmetatable (o,self) - self.__index = self - return o - end, + new = function (self, host, port) + local o = { host = host, port = port } + setmetatable (o,self) + self.__index = self + return o + end, - connect = function ( self ) return true end, + connect = function ( self ) return true end, - login = function( self, username, password ) - local postdata='' - local response = http.post( self.host, self.port, '/api/1.1/xml', { no_cache = true, header = { ["Content-Type"] = "text/xml" } }, nil, postdata ) + login = function( self, username, password ) + local postdata='' + local response = http.post( self.host, self.port, '/api/1.1/xml', { no_cache = true, header = { ["Content-Type"] = "text/xml" } }, nil, postdata ) - if (not(response)) then - local err = brute.Error:new( "Couldn't send/receive HTTPS request" ) - err:setRetry( true ) - return false, err - end + if (not(response)) then + local err = brute.Error:new( "Couldn't send/receive HTTPS request" ) + err:setRetry( true ) + return false, err + end - if (response.body == nil or response.body:match('Python: OVSAgentServer Document") then - set_port_version(host, port, "2.2", response.header["server"]) - return - end + response = http.get(host, port, "/") + if response.status == 200 and string.match(response.body, + "Python: OVSAgentServer Document") then + set_port_version(host, port, "2.2", response.header["server"]) + return + end - -- So much for version 2.2. If the response to GET was 501, then we may - -- have a version 3.0 or 3.0.1. - if not (response.status == 501) then - return - end + -- So much for version 2.2. If the response to GET was 501, then we may + -- have a version 3.0 or 3.0.1. + if not (response.status == 501) then + return + end - response = http.post(host, port, "/", - {header = {["Content-Type"] = "text/xml"}}, nil, - "system.listMethods") - if response.status == 403 and string.match(response.body, - "Message: Unauthorized HTTP Access Attempt from %('[%d.]+', %d+%)!%.") then - set_port_version(host, port, "3.0", response.header["server"]) - return - elseif response.status == 403 and string.match(response.body, - "Message: Unauthorized access attempt from %('[%d.]+', %d+%)!%.") then - set_port_version(host, port, "3.0.1", response.header["server"]) - return - end + response = http.post(host, port, "/", + {header = {["Content-Type"] = "text/xml"}}, nil, + "system.listMethods") + if response.status == 403 and string.match(response.body, + "Message: Unauthorized HTTP Access Attempt from %('[%d.]+', %d+%)!%.") then + set_port_version(host, port, "3.0", response.header["server"]) + return + elseif response.status == 403 and string.match(response.body, + "Message: Unauthorized access attempt from %('[%d.]+', %d+%)!%.") then + set_port_version(host, port, "3.0.1", response.header["server"]) + return + end end diff --git a/scripts/pjl-ready-message.nse b/scripts/pjl-ready-message.nse index 22da18491..b947dd2fa 100644 --- a/scripts/pjl-ready-message.nse +++ b/scripts/pjl-ready-message.nse @@ -27,79 +27,79 @@ categories = {"intrusive"} portrule = shortport.port_or_service(9100, "jetdirect") local function parse_response(response) - local msg - local line + local msg + local line - for line in response:gmatch(".-\n") do - msg = line:match("^DISPLAY=\"(.*)\"") - if msg then - return msg - end - end + for line in response:gmatch(".-\n") do + msg = line:match("^DISPLAY=\"(.*)\"") + if msg then + return msg + end + end end action = function(host, port) - local status --to be used to grab the existing status of the display screen before changing it. - local newstatus --used to repoll the printer after setting the display to check that the probe worked. - local statusmsg --stores the PJL command to get the printer's status - local response --stores the response sent over the network from the printer by the PJL status command + local status --to be used to grab the existing status of the display screen before changing it. + local newstatus --used to repoll the printer after setting the display to check that the probe worked. + local statusmsg --stores the PJL command to get the printer's status + local response --stores the response sent over the network from the printer by the PJL status command - statusmsg="@PJL INFO STATUS\n" + statusmsg="@PJL INFO STATUS\n" - local rdymsg="" --string containing text to send to the printer. - local rdymsgarg="" --will contain the argument from the command line if one exists + local rdymsg="" --string containing text to send to the printer. + local rdymsgarg="" --will contain the argument from the command line if one exists - local socket = nmap.new_socket() - socket:set_timeout(15000) - local try = nmap.new_try(function() socket:close() end) - try(socket:connect(host, port)) - try(socket:send(statusmsg)) --this block gets the current display status - local data - response,data=socket:receive() - if not response then --send an initial probe. If no response, send nothing further. - socket:close() - if nmap.verbosity() > 0 then - return "No response from printer: "..data - else - return nil - end - end + local socket = nmap.new_socket() + socket:set_timeout(15000) + local try = nmap.new_try(function() socket:close() end) + try(socket:connect(host, port)) + try(socket:send(statusmsg)) --this block gets the current display status + local data + response,data=socket:receive() + if not response then --send an initial probe. If no response, send nothing further. + socket:close() + if nmap.verbosity() > 0 then + return "No response from printer: "..data + else + return nil + end + end - status = parse_response(data) - if not status then - if nmap.verbosity() > 0 then - return "Error reading printer response: "..data - else - return nil - end - end + status = parse_response(data) + if not status then + if nmap.verbosity() > 0 then + return "Error reading printer response: "..data + else + return nil + end + end - rdymsgarg = nmap.registry.args.pjl_ready_message - if not rdymsgarg then - if status then - return "\""..status.."\"" - else - return nil - end - end + rdymsgarg = nmap.registry.args.pjl_ready_message + if not rdymsgarg then + if status then + return "\""..status.."\"" + else + return nil + end + end - rdymsg="@PJL RDYMSG DISPLAY = \""..rdymsgarg.."\"\r\n" - try(socket:send(rdymsg)) --actually set the display message here. + rdymsg="@PJL RDYMSG DISPLAY = \""..rdymsgarg.."\"\r\n" + try(socket:send(rdymsg)) --actually set the display message here. - try(socket:send(statusmsg)) --this block gets the status again for comparison - response,data=socket:receive() - if not response then - socket:close() - return "\""..status.."\"" - end - newstatus=parse_response(data) - if not newstatus then - socket:close() - return "\""..status.."\"" - end + try(socket:send(statusmsg)) --this block gets the status again for comparison + response,data=socket:receive() + if not response then + socket:close() + return "\""..status.."\"" + end + newstatus=parse_response(data) + if not newstatus then + socket:close() + return "\""..status.."\"" + end - socket:close() + socket:close() - return "\""..status.."\" changed to \""..newstatus.."\"" + return "\""..status.."\" changed to \""..newstatus.."\"" end diff --git a/scripts/pop3-capabilities.nse b/scripts/pop3-capabilities.nse index ed9ad516e..4b6ba5ff9 100644 --- a/scripts/pop3-capabilities.nse +++ b/scripts/pop3-capabilities.nse @@ -27,22 +27,22 @@ categories = {"default","discovery","safe"} portrule = shortport.port_or_service({110,995},{"pop3","pop3s"}) action = function(host, port) - local capa, err = pop3.capabilities(host, port) - if type(capa) == "table" then - -- Convert the capabilities table into an array of strings. - local capstrings = {} - for cap, args in pairs(capa) do - if ( #args > 0 ) then - table.insert(capstrings, ("%s(%s)"):format(cap, stdnse.strjoin(" ", args))) - else - table.insert(capstrings, cap) - end - end - return stdnse.strjoin(" ", capstrings) - elseif type(err) == "string" then - stdnse.print_debug(1, "%s: '%s' for %s", SCRIPT_NAME, err, host.ip) - return - else - return "server doesn't support CAPA" - end + local capa, err = pop3.capabilities(host, port) + if type(capa) == "table" then + -- Convert the capabilities table into an array of strings. + local capstrings = {} + for cap, args in pairs(capa) do + if ( #args > 0 ) then + table.insert(capstrings, ("%s(%s)"):format(cap, stdnse.strjoin(" ", args))) + else + table.insert(capstrings, cap) + end + end + return stdnse.strjoin(" ", capstrings) + elseif type(err) == "string" then + stdnse.print_debug(1, "%s: '%s' for %s", SCRIPT_NAME, err, host.ip) + return + else + return "server doesn't support CAPA" + end end diff --git a/scripts/pptp-version.nse b/scripts/pptp-version.nse index 55b6cf64e..b74296421 100644 --- a/scripts/pptp-version.nse +++ b/scripts/pptp-version.nse @@ -24,68 +24,68 @@ categories = {"version"} portrule = shortport.version_port_or_service(1723) action = function(host, port) - -- build a PPTP Start-Control-Connection-Request packet - -- copied from packet capture of pptp exchange - -- for details of packet structure, see http://www.ietf.org/rfc/rfc2637.txt - local payload = "\000\156\000\001\026\043\060\077" .. -- length=156, Message type=control, cookie - "\000\001\000\000\001\000\000\000" .. -- Control type=Start-Control-Connection-Request, Reserved, Protocol=1.0, Reserverd - "\000\000\000\001\000\000\000\001" .. -- Framing Capabilities, Bearer Capabilities - "\255\255\000\001" .. "none" .. -- Maximum channels, firmware version, hostname - "\000\000\000\000\000\000\000\000" .. -- padding for hostname - "\000\000\000\000\000\000\000\000" .. -- padding for hostname - "\000\000\000\000\000\000\000\000" .. -- padding for hostname - "\000\000\000\000\000\000\000\000" .. -- padding for hostname - "\000\000\000\000\000\000\000\000" .. -- padding for hostname - "\000\000\000\000\000\000\000\000" .. -- padding for hostname - "\000\000\000\000\000\000\000\000" .. -- padding for hostname - "\000\000\000\000" .. "nmap" .. -- padding for hostname, vendor name - "\000\000\000\000\000\000\000\000" .. -- padding for vendor name - "\000\000\000\000\000\000\000\000" .. -- padding for vendor name - "\000\000\000\000\000\000\000\000" .. -- padding for vendor name - "\000\000\000\000\000\000\000\000" .. -- padding for vendor name - "\000\000\000\000\000\000\000\000" .. -- padding for vendor name - "\000\000\000\000\000\000\000\000" .. -- padding for vendor name - "\000\000\000\000\000\000\000\000" .. -- padding for vendor name - "\000\000\000\000"; -- padding for vendor name + -- build a PPTP Start-Control-Connection-Request packet + -- copied from packet capture of pptp exchange + -- for details of packet structure, see http://www.ietf.org/rfc/rfc2637.txt + local payload = "\000\156\000\001\026\043\060\077" .. -- length=156, Message type=control, cookie + "\000\001\000\000\001\000\000\000" .. -- Control type=Start-Control-Connection-Request, Reserved, Protocol=1.0, Reserverd + "\000\000\000\001\000\000\000\001" .. -- Framing Capabilities, Bearer Capabilities + "\255\255\000\001" .. "none" .. -- Maximum channels, firmware version, hostname + "\000\000\000\000\000\000\000\000" .. -- padding for hostname + "\000\000\000\000\000\000\000\000" .. -- padding for hostname + "\000\000\000\000\000\000\000\000" .. -- padding for hostname + "\000\000\000\000\000\000\000\000" .. -- padding for hostname + "\000\000\000\000\000\000\000\000" .. -- padding for hostname + "\000\000\000\000\000\000\000\000" .. -- padding for hostname + "\000\000\000\000\000\000\000\000" .. -- padding for hostname + "\000\000\000\000" .. "nmap" .. -- padding for hostname, vendor name + "\000\000\000\000\000\000\000\000" .. -- padding for vendor name + "\000\000\000\000\000\000\000\000" .. -- padding for vendor name + "\000\000\000\000\000\000\000\000" .. -- padding for vendor name + "\000\000\000\000\000\000\000\000" .. -- padding for vendor name + "\000\000\000\000\000\000\000\000" .. -- padding for vendor name + "\000\000\000\000\000\000\000\000" .. -- padding for vendor name + "\000\000\000\000\000\000\000\000" .. -- padding for vendor name + "\000\000\000\000"; -- padding for vendor name - local try = nmap.new_try() - local response = try(comm.exchange(host, port, payload, {timeout=5000})) + local try = nmap.new_try() + local response = try(comm.exchange(host, port, payload, {timeout=5000})) - local result + local result - -- check to see if the packet we got back matches the beginning of a PPTP Start-Control-Connection-Reply packet - result = string.match(response, "\0\156\0\001\026\043(.*)") - local output + -- check to see if the packet we got back matches the beginning of a PPTP Start-Control-Connection-Reply packet + result = string.match(response, "\0\156\0\001\026\043(.*)") + local output - if result ~= nil then - local firmware - local hostname - local vendor + if result ~= nil then + local firmware + local hostname + local vendor - -- get the firmware version (2 octets) - local s1,s2 - s1,s2 = string.byte(result, 22, 23) - firmware = s1 * 256 + s2 + -- get the firmware version (2 octets) + local s1,s2 + s1,s2 = string.byte(result, 22, 23) + firmware = s1 * 256 + s2 - -- get the hostname (64 octets) - local s3 - s3 = string.sub(result, 24, 87) - hostname = string.match(s3, "(.-)\0") + -- get the hostname (64 octets) + local s3 + s3 = string.sub(result, 24, 87) + hostname = string.match(s3, "(.-)\0") - -- get the vendor (should be 64 octets, but capture to end of the string to be safe) - local s4, length - length = #result - s4 = string.sub(result, 88, length) - vendor = string.match(s4, "(.-)\0") + -- get the vendor (should be 64 octets, but capture to end of the string to be safe) + local s4, length + length = #result + s4 = string.sub(result, 88, length) + vendor = string.match(s4, "(.-)\0") - port.version.name = "pptp" - port.version.name_confidence = 10 - if vendor ~= nil then port.version.product = vendor end - if firmware ~= 0 then port.version.version = "(Firmware: " .. firmware .. ")" end - if hostname ~= nil then port.version.hostname = hostname end + port.version.name = "pptp" + port.version.name_confidence = 10 + if vendor ~= nil then port.version.product = vendor end + if firmware ~= 0 then port.version.version = "(Firmware: " .. firmware .. ")" end + if hostname ~= nil then port.version.hostname = hostname end - port.version.service_tunnel = "none" - nmap.set_port_version(host, port) - end + port.version.service_tunnel = "none" + nmap.set_port_version(host, port) + end end diff --git a/scripts/realvnc-auth-bypass.nse b/scripts/realvnc-auth-bypass.nse index ce6187a40..f49ec087e 100644 --- a/scripts/realvnc-auth-bypass.nse +++ b/scripts/realvnc-auth-bypass.nse @@ -20,36 +20,36 @@ categories = {"auth", "default", "safe"} portrule = shortport.port_or_service(5900, "vnc") action = function(host, port) - local socket = nmap.new_socket() - local result - local status = true + local socket = nmap.new_socket() + local result + local status = true - socket:connect(host, port) + socket:connect(host, port) - status, result = socket:receive_lines(1) + status, result = socket:receive_lines(1) - if (not status) then - socket:close() - return - end + if (not status) then + socket:close() + return + end - socket:send("RFB 003.008\n") - status, result = socket:receive_bytes(2) + socket:send("RFB 003.008\n") + status, result = socket:receive_bytes(2) - if (not status or result ~= "\001\002") then - socket:close() - return - end + if (not status or result ~= "\001\002") then + socket:close() + return + end - socket:send("\001") - status, result = socket:receive_bytes(4) + socket:send("\001") + status, result = socket:receive_bytes(4) - if (not status or result ~= "\000\000\000\000") then - socket:close() - return - end + if (not status or result ~= "\000\000\000\000") then + socket:close() + return + end - socket:close() + socket:close() - return "Vulnerable" + return "Vulnerable" end diff --git a/scripts/resolveall.nse b/scripts/resolveall.nse index 386c8e3fa..d570f3b4b 100644 --- a/scripts/resolveall.nse +++ b/scripts/resolveall.nse @@ -45,46 +45,46 @@ prerule = function() end local addtargets = function(list) - local sum = 0 + local sum = 0 - for _, t in ipairs(list) do - local st, err = target.add(t) - if st then - sum = sum + 1 - else - stdnse.print_debug("Couldn't add target " .. t .. ": " .. err) - end - end + for _, t in ipairs(list) do + local st, err = target.add(t) + if st then + sum = sum + 1 + else + stdnse.print_debug("Couldn't add target " .. t .. ": " .. err) + end + end - return sum + return sum end action = function() - local hosts = stdnse.get_script_args("resolveall.hosts") + local hosts = stdnse.get_script_args("resolveall.hosts") - if type(hosts) ~= "table" then - hosts = {hosts} - end + if type(hosts) ~= "table" then + hosts = {hosts} + end - local sum, output = 0, {} - for _, host in ipairs(hosts) do - local status, list = nmap.resolve(host, nmap.address_family()) - if status and #list > 0 then - if target.ALLOW_NEW_TARGETS then - sum = sum + addtargets(list) - end - table.insert(output, - string.format("Host '%s' resolves to:", host)) - table.insert(output, list) - end - end + local sum, output = 0, {} + for _, host in ipairs(hosts) do + local status, list = nmap.resolve(host, nmap.address_family()) + if status and #list > 0 then + if target.ALLOW_NEW_TARGETS then + sum = sum + addtargets(list) + end + table.insert(output, + string.format("Host '%s' resolves to:", host)) + table.insert(output, list) + end + end - if sum > 0 then - table.insert(output, - string.format("Successfully added %d new targets", - tostring(sum))) - else - table.insert(output, "Use the 'newtargets' script-arg to add the results as targets") - end - return stdnse.format_output(true, output) + if sum > 0 then + table.insert(output, + string.format("Successfully added %d new targets", + tostring(sum))) + else + table.insert(output, "Use the 'newtargets' script-arg to add the results as targets") + end + return stdnse.format_output(true, output) end diff --git a/scripts/rexec-brute.nse b/scripts/rexec-brute.nse index e269ad0c8..b1678dff9 100644 --- a/scripts/rexec-brute.nse +++ b/scripts/rexec-brute.nse @@ -36,51 +36,51 @@ portrule = shortport.port_or_service(512, "exec", "tcp") Driver = { - -- creates a new Driver instance - -- @param host table as received by the action function - -- @param port table as received by the action function - -- @return o instance of Driver - new = function(self, host, port, options) - local o = { host = host, port = port, timeout = options.timeout } - setmetatable(o, self) - self.__index = self - return o - end, + -- creates a new Driver instance + -- @param host table as received by the action function + -- @param port table as received by the action function + -- @return o instance of Driver + new = function(self, host, port, options) + local o = { host = host, port = port, timeout = options.timeout } + setmetatable(o, self) + self.__index = self + return o + end, - connect = function(self) - self.socket = nmap.new_socket() - self.socket:set_timeout(self.timeout) - local status, err = self.socket:connect(self.host, self.port) - if ( not(status) ) then - local err = brute.Error:new("Connection failed") - err:setRetry( true ) - return false, err - end - return true - end, + connect = function(self) + self.socket = nmap.new_socket() + self.socket:set_timeout(self.timeout) + local status, err = self.socket:connect(self.host, self.port) + if ( not(status) ) then + local err = brute.Error:new("Connection failed") + err:setRetry( true ) + return false, err + end + return true + end, - login = function(self, username, password) - local cmd = "id" - local data = ("\0%s\0%s\0%s\0"):format(username, password, cmd) + login = function(self, username, password) + local cmd = "id" + local data = ("\0%s\0%s\0%s\0"):format(username, password, cmd) - local status, err = self.socket:send(data) - if ( not(status) ) then - local err = brute.Error:new("Send failed") - err:setRetry( true ) - return false, err - end + local status, err = self.socket:send(data) + if ( not(status) ) then + local err = brute.Error:new("Send failed") + err:setRetry( true ) + return false, err + end - local response - status, response = self.socket:receive() - if ( status ) then - return true, brute.Account:new(username, password, creds.State.VALID) - end - return false, brute.Error:new( "Incorrect password" ) - end, + local response + status, response = self.socket:receive() + if ( status ) then + return true, brute.Account:new(username, password, creds.State.VALID) + end + return false, brute.Error:new( "Incorrect password" ) + end, - disconnect = function(self) - self.socket:close() - end, + disconnect = function(self) + self.socket:close() + end, } @@ -89,12 +89,12 @@ local arg_timeout = stdnse.parse_timespec(stdnse.get_script_args(SCRIPT_NAME .. arg_timeout = (arg_timeout or 10) * 1000 action = function(host, port) - local options = { - timeout = arg_timeout - } + local options = { + timeout = arg_timeout + } - local engine = brute.Engine:new(Driver, host, port, options) - engine.options.script_name = SCRIPT_NAME - local status, result = engine:start() - return result + local engine = brute.Engine:new(Driver, host, port, options) + engine.options.script_name = SCRIPT_NAME + local status, result = engine:start() + return result end diff --git a/scripts/rpcap-brute.nse b/scripts/rpcap-brute.nse index 9b5383ea2..bceb992fc 100644 --- a/scripts/rpcap-brute.nse +++ b/scripts/rpcap-brute.nse @@ -32,63 +32,63 @@ portrule = shortport.port_or_service(2002, "rpcap", "tcp") Driver = { - new = function(self, host, port) - local o = { helper = rpcap.Helper:new(host, port) } - setmetatable(o, self) - self.__index = self - return o - end, + new = function(self, host, port) + local o = { helper = rpcap.Helper:new(host, port) } + setmetatable(o, self) + self.__index = self + return o + end, - connect = function(self) - return self.helper:connect() - end, + connect = function(self) + return self.helper:connect() + end, - login = function(self, username, password) - local status, resp = self.helper:login(username, password) - if ( status ) then - return true, brute.Account:new(username, password, creds.State.VALID) - end - return false, brute.Error:new( "Incorrect password" ) - end, + login = function(self, username, password) + local status, resp = self.helper:login(username, password) + if ( status ) then + return true, brute.Account:new(username, password, creds.State.VALID) + end + return false, brute.Error:new( "Incorrect password" ) + end, - disconnect = function(self) - return self.helper:close() - end, + disconnect = function(self) + return self.helper:close() + end, } local function validateAuth(host, port) - local helper = rpcap.Helper:new(host, port) - local status, result = helper:connect() - if ( not(status) ) then - return false, result - end - status, result = helper:login() - helper:close() + local helper = rpcap.Helper:new(host, port) + local status, result = helper:connect() + if ( not(status) ) then + return false, result + end + status, result = helper:login() + helper:close() - if ( status ) then - return false, "Authentication not required" - elseif ( not(status) and - "Authentication failed; NULL autentication not permitted." == result ) then - return true - end - return status, result + if ( status ) then + return false, "Authentication not required" + elseif ( not(status) and + "Authentication failed; NULL autentication not permitted." == result ) then + return true + end + return status, result end action = function(host, port) - local status, result = validateAuth(host, port) - if ( not(status) ) then - return result - end + local status, result = validateAuth(host, port) + if ( not(status) ) then + return result + end - local engine = brute.Engine:new(Driver, host, port ) + local engine = brute.Engine:new(Driver, host, port ) - engine.options.script_name = SCRIPT_NAME - engine.options.firstonly = true - status, result = engine:start() + engine.options.script_name = SCRIPT_NAME + engine.options.firstonly = true + status, result = engine:start() - return result + return result end diff --git a/scripts/rpcap-info.nse b/scripts/rpcap-info.nse index 846df482f..d181e91f7 100644 --- a/scripts/rpcap-info.nse +++ b/scripts/rpcap-info.nse @@ -44,50 +44,50 @@ local function fail(err) return ("\n ERROR: %s"):format(err or "") end local function getInfo(host, port, username, password) - local helper = rpcap.Helper:new(host, port) - local status, resp = helper:connect() - if ( not(status) ) then - return false, "Failed to connect to server" - end - status, resp = helper:login(username, password) + local helper = rpcap.Helper:new(host, port) + local status, resp = helper:connect() + if ( not(status) ) then + return false, "Failed to connect to server" + end + status, resp = helper:login(username, password) - if ( not(status) ) then - return false, resp - end + if ( not(status) ) then + return false, resp + end - status, resp = helper:findAllInterfaces() - helper:close() - if ( not(status) ) then - return false, resp - end + status, resp = helper:findAllInterfaces() + helper:close() + if ( not(status) ) then + return false, resp + end - port.version.name = "rpcap" - port.version.product = "WinPcap remote packet capture daemon" - nmap.set_port_version(host, port) + port.version.name = "rpcap" + port.version.product = "WinPcap remote packet capture daemon" + nmap.set_port_version(host, port) - return true, resp + return true, resp end action = function(host, port) - -- patch-up the service name, so creds.rpcap will work, ugly but needed as - -- tcp 2002 is registered to the globe service in nmap-services ... - port.service = "rpcap" + -- patch-up the service name, so creds.rpcap will work, ugly but needed as + -- tcp 2002 is registered to the globe service in nmap-services ... + port.service = "rpcap" - local c = creds.Credentials:new(creds.ALL_DATA, host, port) - local states = creds.State.VALID + creds.State.PARAM - local status, resp = getInfo(host, port) + local c = creds.Credentials:new(creds.ALL_DATA, host, port) + local states = creds.State.VALID + creds.State.PARAM + local status, resp = getInfo(host, port) - if ( status ) then - return stdnse.format_output(true, resp) - end + if ( status ) then + return stdnse.format_output(true, resp) + end - for cred in c:getCredentials(states) do - status, resp = getInfo(host, port, cred.user, cred.pass) - if ( status ) then - return stdnse.format_output(true, resp) - end - end + for cred in c:getCredentials(states) do + status, resp = getInfo(host, port, cred.user, cred.pass) + if ( status ) then + return stdnse.format_output(true, resp) + end + end - return fail(resp) + return fail(resp) end diff --git a/scripts/rsync-brute.nse b/scripts/rsync-brute.nse index 59774449b..532b64a21 100644 --- a/scripts/rsync-brute.nse +++ b/scripts/rsync-brute.nse @@ -35,74 +35,74 @@ portrule = shortport.port_or_service(873, "rsync", "tcp") Driver = { - new = function(self, host, port, options) - local o = { host = host, port = port, options = options } - setmetatable(o, self) - self.__index = self - return o - end, + new = function(self, host, port, options) + local o = { host = host, port = port, options = options } + setmetatable(o, self) + self.__index = self + return o + end, - connect = function(self) - self.helper = rsync.Helper:new(self.host, self.port, self.options) - return self.helper:connect() - end, + connect = function(self) + self.helper = rsync.Helper:new(self.host, self.port, self.options) + return self.helper:connect() + end, - login = function(self, username, password) + login = function(self, username, password) - local status, data = self.helper:login(username, password) - -- retry unless we have an authentication failed error - if( not(status) and data ~= "Authentication failed" ) then - local err = brute.Error:new( data ) - err:setRetry( true ) - return false, err - elseif ( not(status) ) then - return false, brute.Error:new( "Login failed" ) - else - return true, brute.Account:new(username, password, creds.State.VALID) - end - end, + local status, data = self.helper:login(username, password) + -- retry unless we have an authentication failed error + if( not(status) and data ~= "Authentication failed" ) then + local err = brute.Error:new( data ) + err:setRetry( true ) + return false, err + elseif ( not(status) ) then + return false, brute.Error:new( "Login failed" ) + else + return true, brute.Account:new(username, password, creds.State.VALID) + end + end, - disconnect = function( self ) - return self.helper:disconnect() - end + disconnect = function( self ) + return self.helper:disconnect() + end } local function isModuleValid(host, port, module) - local helper = rsync.Helper:new(host, port, { module = module }) - if ( not(helper) ) then - return false, "Failed to create helper" - end - local status, data = helper:connect() - if ( not(status) ) then - return false, "Failed to connect to server" - end - status, data = helper:login() - if ( status and data == "No authentication was required" ) then - return false, data - elseif ( not(status) and data == "Authentication required" ) then - return true - elseif ( not(status) and data == ("Unknown module '%s'"):format(module) ) then - return false, data - end - return false, ("Brute pre-check failed for unknown reason: (%s)"):format(data) + local helper = rsync.Helper:new(host, port, { module = module }) + if ( not(helper) ) then + return false, "Failed to create helper" + end + local status, data = helper:connect() + if ( not(status) ) then + return false, "Failed to connect to server" + end + status, data = helper:login() + if ( status and data == "No authentication was required" ) then + return false, data + elseif ( not(status) and data == "Authentication required" ) then + return true + elseif ( not(status) and data == ("Unknown module '%s'"):format(module) ) then + return false, data + end + return false, ("Brute pre-check failed for unknown reason: (%s)"):format(data) end action = function(host, port) - local mod = stdnse.get_script_args(SCRIPT_NAME .. ".module") - if ( not(mod) ) then - return "\n ERROR: rsync-brute.module was not supplied" - end + local mod = stdnse.get_script_args(SCRIPT_NAME .. ".module") + if ( not(mod) ) then + return "\n ERROR: rsync-brute.module was not supplied" + end - local status, err = isModuleValid(host, port, mod) - if ( not(status) ) then - return ("\n ERROR: %s"):format(err) - end + local status, err = isModuleValid(host, port, mod) + if ( not(status) ) then + return ("\n ERROR: %s"):format(err) + end - local engine = brute.Engine:new(Driver, host, port, { module = mod }) - engine.options.script_name = SCRIPT_NAME - local result - status, result = engine:start() - return result + local engine = brute.Engine:new(Driver, host, port, { module = mod }) + engine.options.script_name = SCRIPT_NAME + local result + status, result = engine:start() + return result end diff --git a/scripts/rsync-list-modules.nse b/scripts/rsync-list-modules.nse index be650b7ae..bd38a74e0 100644 --- a/scripts/rsync-list-modules.nse +++ b/scripts/rsync-list-modules.nse @@ -27,20 +27,20 @@ categories = {"discovery", "safe"} portrule = shortport.port_or_service(873, "rsync", "tcp") action = function(host, port) - local helper = rsync.Helper:new(host, port, { module = "" }) - if ( not(helper) ) then - return "\n ERROR: Failed to create rsync.Helper" - end + local helper = rsync.Helper:new(host, port, { module = "" }) + if ( not(helper) ) then + return "\n ERROR: Failed to create rsync.Helper" + end - local status, err = helper:connect() - if ( not(status) ) then - return "\n ERROR: Failed to connect to rsync server" - end + local status, err = helper:connect() + if ( not(status) ) then + return "\n ERROR: Failed to connect to rsync server" + end - local modules = {} - status, modules = helper:listModules() - if ( not(status) ) then - return "\n ERROR: Failed to retrieve a list of modules" - end - return stdnse.format_output(true, modules) + local modules = {} + status, modules = helper:listModules() + if ( not(status) ) then + return "\n ERROR: Failed to retrieve a list of modules" + end + return stdnse.format_output(true, modules) end diff --git a/scripts/rtsp-methods.nse b/scripts/rtsp-methods.nse index a40c82594..4b2fc72f9 100644 --- a/scripts/rtsp-methods.nse +++ b/scripts/rtsp-methods.nse @@ -32,18 +32,18 @@ categories = {"default", "safe"} portrule = shortport.port_or_service(554, "rtsp", "tcp", "open") action = function(host, port) - local path = stdnse.get_script_args('rtsp-methods.path') or '*' - local helper = rtsp.Helper:new(host, port) - local status = helper:connect() - if ( not(status) ) then - stdnse.print_debug(2, "ERROR: Failed to connect to RTSP server") - return - end + local path = stdnse.get_script_args('rtsp-methods.path') or '*' + local helper = rtsp.Helper:new(host, port) + local status = helper:connect() + if ( not(status) ) then + stdnse.print_debug(2, "ERROR: Failed to connect to RTSP server") + return + end - local response - status, response = helper:options(path) - helper:close() - if ( status ) then - return stdnse.format_output(true, response.headers['Public']) - end + local response + status, response = helper:options(path) + helper:close() + if ( status ) then + return stdnse.format_output(true, response.headers['Public']) + end end diff --git a/scripts/sip-methods.nse b/scripts/sip-methods.nse index 10dcdf0e7..5a5b6f54c 100644 --- a/scripts/sip-methods.nse +++ b/scripts/sip-methods.nse @@ -31,24 +31,24 @@ categories = {"default", "safe", "discovery"} portrule = shortport.port_or_service(5060, "sip", {"tcp", "udp"}) action = function(host, port) - local status, session, response - session = sip.Session:new(host, port) - status = session:connect() - if not status then - return "ERROR: Failed to connect to the SIP server." + local status, session, response + session = sip.Session:new(host, port) + status = session:connect() + if not status then + return "ERROR: Failed to connect to the SIP server." + end + + status, response = session:options() + if status then + -- If port state not set to open, set it to open. + if nmap.get_port_state(host, port) ~= "open" then + nmap.set_port_state(host, port, "open") end - status, response = session:options() - if status then - -- If port state not set to open, set it to open. - if nmap.get_port_state(host, port) ~= "open" then - nmap.set_port_state(host, port, "open") - end - - -- Check if allow header exists in response - local allow = response:getHeader("allow") - if allow then - return stdnse.format_output(true, allow) - end + -- Check if allow header exists in response + local allow = response:getHeader("allow") + if allow then + return stdnse.format_output(true, allow) end + end end diff --git a/scripts/smb-enum-groups.nse b/scripts/smb-enum-groups.nse index 3f7a12c5b..1547c63eb 100644 --- a/scripts/smb-enum-groups.nse +++ b/scripts/smb-enum-groups.nse @@ -67,30 +67,30 @@ dependencies = {"smb-brute"} hostrule = function(host) - return smb.get_port(host) ~= nil + return smb.get_port(host) ~= nil end action = function(host) - local status, groups = msrpc.samr_enum_groups(host) - if(not(status)) then - return stdnse.format_output(false, "Couldn't enumerate groups: " .. groups) - end + local status, groups = msrpc.samr_enum_groups(host) + if(not(status)) then + return stdnse.format_output(false, "Couldn't enumerate groups: " .. groups) + end - local response = {} + local response = {} - for domain_name, domain_data in pairs(groups) do + for domain_name, domain_data in pairs(groups) do - for rid, group_data in pairs(domain_data) do - local members = group_data['members'] - if(#members > 0) then - members = stdnse.strjoin(", ", group_data['members']) - else - members = "" - end - table.insert(response, string.format("%s\\%s (RID: %s): %s", domain_name, group_data['name'], rid, members)) - end - end + for rid, group_data in pairs(domain_data) do + local members = group_data['members'] + if(#members > 0) then + members = stdnse.strjoin(", ", group_data['members']) + else + members = "" + end + table.insert(response, string.format("%s\\%s (RID: %s): %s", domain_name, group_data['name'], rid, members)) + end + end - return stdnse.format_output(true, response) + return stdnse.format_output(true, response) end diff --git a/scripts/smb-flood.nse b/scripts/smb-flood.nse index d9c528603..eaa9f1310 100644 --- a/scripts/smb-flood.nse +++ b/scripts/smb-flood.nse @@ -38,21 +38,21 @@ dependencies = {"smb-brute"} hostrule = function(host) - return smb.get_port(host) ~= nil + return smb.get_port(host) ~= nil end action = function(host) - local states = {} - repeat - local status, result = smb.start_ex(host, true, true) - if(status) then - table.insert(states, result) -- Keep the result so it doesn't get garbage cleaned - stdnse.print_debug(1, "smb-flood: Connection successfully opened") - stdnse.sleep(.1) - else - stdnse.print_debug(1, "smb-flood: Connection failed: %s", result) - stdnse.sleep(1) - end - until false + local states = {} + repeat + local status, result = smb.start_ex(host, true, true) + if(status) then + table.insert(states, result) -- Keep the result so it doesn't get garbage cleaned + stdnse.print_debug(1, "smb-flood: Connection successfully opened") + stdnse.sleep(.1) + else + stdnse.print_debug(1, "smb-flood: Connection failed: %s", result) + stdnse.sleep(1) + end + until false end diff --git a/scripts/smb-security-mode.nse b/scripts/smb-security-mode.nse index 4543ba468..cb491f58f 100644 --- a/scripts/smb-security-mode.nse +++ b/scripts/smb-security-mode.nse @@ -40,61 +40,61 @@ dependencies = {"smb-brute"} -- Check whether or not this script should be run. hostrule = function(host) - return smb.get_port(host) ~= nil + return smb.get_port(host) ~= nil end action = function(host) - local state - local status, err - local overrides = {} + local state + local status, err + local overrides = {} - status, state = smb.start(host) - if(status == false) then - return stdnse.format_output(false, state) - end + status, state = smb.start(host) + if(status == false) then + return stdnse.format_output(false, state) + end - status, err = smb.negotiate_protocol(state, overrides) - if(status == false) then - smb.stop(state) - return stdnse.format_output(false, err) - end + status, err = smb.negotiate_protocol(state, overrides) + if(status == false) then + smb.stop(state) + return stdnse.format_output(false, err) + end - local security_mode = state['security_mode'] + local security_mode = state['security_mode'] - local response = {} + local response = {} - local result, username, domain = smb.get_account(host) - if(result ~= false) then - table.insert(response, string.format("Account that was used for smb scripts: %s%s", domain, stdnse.string_or_blank(username, ''))) - end + local result, username, domain = smb.get_account(host) + if(result ~= false) then + table.insert(response, string.format("Account that was used for smb scripts: %s%s", domain, stdnse.string_or_blank(username, ''))) + end - -- User-level authentication or share-level authentication - if(bit.band(security_mode, 1) == 1) then - table.insert(response, "User-level authentication") - else - table.insert(response, "Share-level authentication (dangerous)") - end + -- User-level authentication or share-level authentication + if(bit.band(security_mode, 1) == 1) then + table.insert(response, "User-level authentication") + else + table.insert(response, "Share-level authentication (dangerous)") + end - -- Challenge/response supported? - if(bit.band(security_mode, 2) == 0) then - table.insert(response, "Plaintext passwords required (dangerous)") - else - table.insert(response, "SMB Security: Challenge/response passwords supported") - end + -- Challenge/response supported? + if(bit.band(security_mode, 2) == 0) then + table.insert(response, "Plaintext passwords required (dangerous)") + else + table.insert(response, "SMB Security: Challenge/response passwords supported") + end - -- Message signing supported/required? - if(bit.band(security_mode, 8) == 8) then - table.insert(response, "Message signing required") - elseif(bit.band(security_mode, 4) == 4) then - table.insert(response, "Message signing supported") - else - table.insert(response, "Message signing disabled (dangerous, but default)") - end + -- Message signing supported/required? + if(bit.band(security_mode, 8) == 8) then + table.insert(response, "Message signing required") + elseif(bit.band(security_mode, 4) == 4) then + table.insert(response, "Message signing supported") + else + table.insert(response, "Message signing disabled (dangerous, but default)") + end - smb.stop(state) - return stdnse.format_output(true, response) + smb.stop(state) + return stdnse.format_output(true, response) end diff --git a/scripts/smb-server-stats.nse b/scripts/smb-server-stats.nse index f37f89436..596340ba8 100644 --- a/scripts/smb-server-stats.nse +++ b/scripts/smb-server-stats.nse @@ -40,27 +40,27 @@ dependencies = {"smb-brute"} hostrule = function(host) - return smb.get_port(host) ~= nil + return smb.get_port(host) ~= nil end action = function(host) - local result, stats - local response = {} - local subresponse = {} + local result, stats + local response = {} + local subresponse = {} - result, stats = msrpc.get_server_stats(host) + result, stats = msrpc.get_server_stats(host) - if(result == false) then - return stdnse.format_output(false, response) - end + if(result == false) then + return stdnse.format_output(false, response) + end - table.insert(response, string.format("Server statistics collected since %s (%s):", stats['start_str'], stats['period_str'])) - table.insert(subresponse, string.format("%d bytes (%.2f b/s) sent, %d bytes (%.2f b/s) received", stats['bytessent'], stats['bytessentpersecond'], stats['bytesrcvd'], stats['bytesrcvdpersecond'])) - table.insert(subresponse, string.format("%d failed logins, %d permission errors, %d system errors, %d print jobs, %d files opened", stats['pwerrors'], stats['permerrors'], stats['syserrors'], stats['jobsqueued'], stats['fopens'])) - table.insert(response, subresponse) + table.insert(response, string.format("Server statistics collected since %s (%s):", stats['start_str'], stats['period_str'])) + table.insert(subresponse, string.format("%d bytes (%.2f b/s) sent, %d bytes (%.2f b/s) received", stats['bytessent'], stats['bytessentpersecond'], stats['bytesrcvd'], stats['bytesrcvdpersecond'])) + table.insert(subresponse, string.format("%d failed logins, %d permission errors, %d system errors, %d print jobs, %d files opened", stats['pwerrors'], stats['permerrors'], stats['syserrors'], stats['jobsqueued'], stats['fopens'])) + table.insert(response, subresponse) - return stdnse.format_output(true, response) + return stdnse.format_output(true, response) end diff --git a/scripts/smbv2-enabled.nse b/scripts/smbv2-enabled.nse index d3d77b360..d90479e77 100644 --- a/scripts/smbv2-enabled.nse +++ b/scripts/smbv2-enabled.nse @@ -27,42 +27,42 @@ categories = {"default", "safe"} hostrule = function(host) - return smb.get_port(host) ~= nil + return smb.get_port(host) ~= nil end local function go(host) - local status, smbstate, result - local dialects = { "NT LM 0.12", "SMB 2.002", "SMB 2.???" } - local overrides = {dialects=dialects} + local status, smbstate, result + local dialects = { "NT LM 0.12", "SMB 2.002", "SMB 2.???" } + local overrides = {dialects=dialects} - status, smbstate = smb.start(host) - if(not(status)) then - return false, "Couldn't start SMB session: " .. smbstate - end + status, smbstate = smb.start(host) + if(not(status)) then + return false, "Couldn't start SMB session: " .. smbstate + end - status, result = smb.negotiate_protocol(smbstate, overrides) - if(not(status)) then - if(string.find(result, "SMBv2")) then - return true, "Server supports SMBv2 protocol", true - end - return false, "Couldn't negotiate protocol: " .. result - end + status, result = smb.negotiate_protocol(smbstate, overrides) + if(not(status)) then + if(string.find(result, "SMBv2")) then + return true, "Server supports SMBv2 protocol", true + end + return false, "Couldn't negotiate protocol: " .. result + end - return true, "Server doesn't support SMBv2 protocol", false + return true, "Server doesn't support SMBv2 protocol", false end action = function(host) - local status, result, flag = go(host) + local status, result, flag = go(host) - if(not(status)) then - if(nmap.debugging() > 0) then - return "ERROR: " .. result - else - return nil - end - end + if(not(status)) then + if(nmap.debugging() > 0) then + return "ERROR: " .. result + else + return nil + end + end - return flag, result + return flag, result end diff --git a/scripts/smtp-strangeport.nse b/scripts/smtp-strangeport.nse index 2385a1040..fe62c8218 100644 --- a/scripts/smtp-strangeport.nse +++ b/scripts/smtp-strangeport.nse @@ -17,13 +17,13 @@ license = "Same as Nmap--See http://nmap.org/book/man-legal.html" categories = {"malware", "safe"} portrule = function(host, port) - return port.service == "smtp" and - port.number ~= 25 and port.number ~= 465 and port.number ~= 587 - and port.protocol == "tcp" - and port.state == "open" + return port.service == "smtp" and + port.number ~= 25 and port.number ~= 465 and port.number ~= 587 + and port.protocol == "tcp" + and port.state == "open" end action = function() - return "Mail server on unusual port: possible malware" + return "Mail server on unusual port: possible malware" end diff --git a/scripts/snmp-win32-services.nse b/scripts/snmp-win32-services.nse index 10e52b7a1..f7daf7ec9 100644 --- a/scripts/snmp-win32-services.nse +++ b/scripts/snmp-win32-services.nse @@ -45,40 +45,40 @@ portrule = shortport.portnumber(161, "udp", {"open", "open|filtered"}) -- @return table suitable for stdnse.format_output function process_answer( tbl ) - local new_tab = {} + local new_tab = {} - for _, v in ipairs( tbl ) do - table.insert( new_tab, v.value ) - end + for _, v in ipairs( tbl ) do + table.insert( new_tab, v.value ) + end - table.sort( new_tab ) + table.sort( new_tab ) - return new_tab + return new_tab end action = function(host, port) - local socket = nmap.new_socket() - local catch = function() socket:close() end - local try = nmap.new_try(catch) - local snmpoid = "1.3.6.1.4.1.77.1.2.3.1.1" - local services = {} - local status + local socket = nmap.new_socket() + local catch = function() socket:close() end + local try = nmap.new_try(catch) + local snmpoid = "1.3.6.1.4.1.77.1.2.3.1.1" + local services = {} + local status - socket:set_timeout(5000) - try(socket:connect(host, port)) + socket:set_timeout(5000) + try(socket:connect(host, port)) - status, services = snmp.snmpWalk( socket, snmpoid ) - socket:close() + status, services = snmp.snmpWalk( socket, snmpoid ) + socket:close() - if ( not(status) ) or ( services == nil ) or ( #services == 0 ) then - return - end + if ( not(status) ) or ( services == nil ) or ( #services == 0 ) then + return + end - services = process_answer(services) - nmap.set_port_state(host, port, "open") + services = process_answer(services) + nmap.set_port_state(host, port, "open") - return stdnse.format_output( true, services ) + return stdnse.format_output( true, services ) end diff --git a/scripts/snmp-win32-shares.nse b/scripts/snmp-win32-shares.nse index f9efafa9e..eabd05947 100644 --- a/scripts/snmp-win32-shares.nse +++ b/scripts/snmp-win32-shares.nse @@ -38,13 +38,13 @@ portrule = shortport.portnumber(161, "udp", {"open", "open|filtered"}) -- @return value of relevant type or nil if oid was not found function get_value_from_table( tbl, oid ) - for _, v in ipairs( tbl ) do - if v.oid == oid then - return v.value - end - end + for _, v in ipairs( tbl ) do + if v.oid == oid then + return v.value + end + end - return nil + return nil end --- Processes the table and creates the script output @@ -53,52 +53,52 @@ end -- @return table suitable for stdnse.format_output function process_answer( tbl ) - local share_name = "1.3.6.1.4.1.77.1.2.27.1.1" - local share_path = "1.3.6.1.4.1.77.1.2.27.1.2" - local new_tbl = {} + local share_name = "1.3.6.1.4.1.77.1.2.27.1.1" + local share_path = "1.3.6.1.4.1.77.1.2.27.1.2" + local new_tbl = {} - for _, v in ipairs( tbl ) do + for _, v in ipairs( tbl ) do - if ( v.oid:match("^" .. share_name) ) then - local item = {} - local objid = v.oid:gsub( "^" .. share_name, share_path) - local path = get_value_from_table( tbl, objid ) + if ( v.oid:match("^" .. share_name) ) then + local item = {} + local objid = v.oid:gsub( "^" .. share_name, share_path) + local path = get_value_from_table( tbl, objid ) - item.name = v.value - table.insert( item, path ) - table.insert( new_tbl, item ) - end + item.name = v.value + table.insert( item, path ) + table.insert( new_tbl, item ) + end - end + end - return new_tbl + return new_tbl end action = function(host, port) - local socket = nmap.new_socket() - local catch = function() socket:close() end - local try = nmap.new_try(catch) - local data, snmpoid = nil, "1.3.6.1.4.1.77.1.2.27" - local shares = {} - local status + local socket = nmap.new_socket() + local catch = function() socket:close() end + local try = nmap.new_try(catch) + local data, snmpoid = nil, "1.3.6.1.4.1.77.1.2.27" + local shares = {} + local status - socket:set_timeout(5000) - try(socket:connect(host, port)) + socket:set_timeout(5000) + try(socket:connect(host, port)) - status, shares = snmp.snmpWalk( socket, snmpoid ) - socket:close() + status, shares = snmp.snmpWalk( socket, snmpoid ) + socket:close() - if (not(status)) or ( shares == nil ) or ( #shares == 0 ) then - return shares - end + if (not(status)) or ( shares == nil ) or ( #shares == 0 ) then + return shares + end - shares = process_answer( shares ) + shares = process_answer( shares ) - nmap.set_port_state(host, port, "open") + nmap.set_port_state(host, port, "open") - return stdnse.format_output( true, shares ) + return stdnse.format_output( true, shares ) end diff --git a/scripts/snmp-win32-users.nse b/scripts/snmp-win32-users.nse index bf4d671eb..c8f0b872a 100644 --- a/scripts/snmp-win32-users.nse +++ b/scripts/snmp-win32-users.nse @@ -41,45 +41,45 @@ portrule = shortport.portnumber(161, "udp", {"open", "open|filtered"}) -- @return table suitable for stdnse.format_output function process_answer( tbl ) - local new_tab = {} + local new_tab = {} - for _, v in ipairs( tbl ) do - table.insert( new_tab, v.value ) - end + for _, v in ipairs( tbl ) do + table.insert( new_tab, v.value ) + end - table.sort( new_tab ) + table.sort( new_tab ) - return new_tab + return new_tab end action = function(host, port) - local socket = nmap.new_socket() - local catch = function() socket:close() end - local try = nmap.new_try(catch) - local snmpoid = "1.3.6.1.4.1.77.1.2.25" - local users = {} - local status + local socket = nmap.new_socket() + local catch = function() socket:close() end + local try = nmap.new_try(catch) + local snmpoid = "1.3.6.1.4.1.77.1.2.25" + local users = {} + local status - socket:set_timeout(5000) - try(socket:connect(host, port)) + socket:set_timeout(5000) + try(socket:connect(host, port)) - status, users = snmp.snmpWalk( socket, snmpoid ) - socket:close() + status, users = snmp.snmpWalk( socket, snmpoid ) + socket:close() - if( not(status) ) then - return - end + if( not(status) ) then + return + end - users = process_answer( users ) + users = process_answer( users ) - if ( users == nil ) or ( #users == 0 ) then - return - end + if ( users == nil ) or ( #users == 0 ) then + return + end - nmap.set_port_state(host, port, "open") + nmap.set_port_state(host, port, "open") - return stdnse.format_output( true, users ) + return stdnse.format_output( true, users ) end diff --git a/scripts/socks-auth-info.nse b/scripts/socks-auth-info.nse index 63185dad4..f3141473b 100644 --- a/scripts/socks-auth-info.nse +++ b/scripts/socks-auth-info.nse @@ -42,25 +42,25 @@ portrule = shortport.port_or_service({1080, 9050}, {"socks", "socks5", "tor-sock action = function(host, port) - local helper = socks.Helper:new(host, port) - local auth_methods = {} + local helper = socks.Helper:new(host, port) + local auth_methods = {} - -- iterate over all authentication methods as the server only responds with - -- a single supported one if we send a list. + -- iterate over all authentication methods as the server only responds with + -- a single supported one if we send a list. local mt = { __tostring = function(t) return t.name end } - for _, method in pairs(socks.AuthMethod) do - local status, response = helper:connect( method ) - if ( status ) then + for _, method in pairs(socks.AuthMethod) do + local status, response = helper:connect( method ) + if ( status ) then local out = { method = response.method, name = helper:authNameByNumber(response.method) } setmetatable(out, mt) - table.insert(auth_methods, out) - end - end + table.insert(auth_methods, out) + end + end - helper:close() - if ( 0 == #auth_methods ) then return end - return auth_methods + helper:close() + if ( 0 == #auth_methods ) then return end + return auth_methods end diff --git a/scripts/socks-brute.nse b/scripts/socks-brute.nse index e78f16db7..9edc12fc8 100644 --- a/scripts/socks-brute.nse +++ b/scripts/socks-brute.nse @@ -30,72 +30,72 @@ portrule = shortport.port_or_service({1080, 9050}, {"socks", "socks5", "tor-sock Driver = { - new = function (self, host, port) - local o = { host = host, port = port } - setmetatable (o,self) - self.__index = self - return o - end, + new = function (self, host, port) + local o = { host = host, port = port } + setmetatable (o,self) + self.__index = self + return o + end, - connect = function ( self ) - self.helper = socks.Helper:new(self.host, self.port, { timeout = 10000 }) - return self.helper:connect() - end, + connect = function ( self ) + self.helper = socks.Helper:new(self.host, self.port, { timeout = 10000 }) + return self.helper:connect() + end, - login = function( self, username, password ) - local status, err = self.helper:authenticate({username=username, password=password}) + login = function( self, username, password ) + local status, err = self.helper:authenticate({username=username, password=password}) - if (not(status)) then - -- the login failed - if ( "Authentication failed" == err ) then - return false, brute.Error:new( "Login failed" ) - end + if (not(status)) then + -- the login failed + if ( "Authentication failed" == err ) then + return false, brute.Error:new( "Login failed" ) + end - -- something else happend, let's retry - local err = brute.Error:new( err ) - err:setRetry( true ) - return false, err - end + -- something else happend, let's retry + local err = brute.Error:new( err ) + err:setRetry( true ) + return false, err + end - return true, brute.Account:new(username, password, creds.State.VALID) - end, + return true, brute.Account:new(username, password, creds.State.VALID) + end, - disconnect = function( self ) - return self.helper:close() - end, + disconnect = function( self ) + return self.helper:close() + end, } local function checkAuth(host, port) - local helper = socks.Helper:new(host, port) - local status, response = helper:connect() - if ( not(status) ) then - return false, response - end + local helper = socks.Helper:new(host, port) + local status, response = helper:connect() + if ( not(status) ) then + return false, response + end - if ( response.method == socks.AuthMethod.NONE ) then - return false, "\n No authentication required" - end + if ( response.method == socks.AuthMethod.NONE ) then + return false, "\n No authentication required" + end - local status, err = helper:authenticate({username="nmap", password="nmapbruteprobe"}) - if ( err ~= "Authentication failed" ) then - return false, ("\n ERROR: %s"):format(err) - end + local status, err = helper:authenticate({username="nmap", password="nmapbruteprobe"}) + if ( err ~= "Authentication failed" ) then + return false, ("\n ERROR: %s"):format(err) + end - helper:close() - return true + helper:close() + return true end action = function(host, port) - local status, response = checkAuth(host, port) - if ( not(status) ) then - return response - end + local status, response = checkAuth(host, port) + if ( not(status) ) then + return response + end - local engine = brute.Engine:new(Driver, host, port) - engine.options.script_name = SCRIPT_NAME - local result - status, result = engine:start() - return result + local engine = brute.Engine:new(Driver, host, port) + engine.options.script_name = SCRIPT_NAME + local result + status, result = engine:start() + return result end diff --git a/scripts/sshv1.nse b/scripts/sshv1.nse index 600d651e3..a9667a35c 100644 --- a/scripts/sshv1.nse +++ b/scripts/sshv1.nse @@ -22,53 +22,53 @@ categories = {"default", "safe"} portrule = shortport.port_or_service(22, "ssh") action = function(host, port) - local socket = nmap.new_socket() - local result; - local status = true; + local socket = nmap.new_socket() + local result; + local status = true; - socket:connect(host, port) - status, result = socket:receive_lines(1); + socket:connect(host, port) + status, result = socket:receive_lines(1); - if (not status) then - socket:close() - return - end + if (not status) then + socket:close() + return + end - if (result == "TIMEOUT") then - socket:close() - return - end + if (result == "TIMEOUT") then + socket:close() + return + end - if not string.match(result, "^SSH%-.+\n$") then - socket:close() - return - end + if not string.match(result, "^SSH%-.+\n$") then + socket:close() + return + end - socket:send("SSH-1.5-NmapNSE_1.0\n") + socket:send("SSH-1.5-NmapNSE_1.0\n") - -- should be able to consume at least 13 bytes - -- key length is a 4 byte integer - -- padding is between 1 and 8 bytes - -- type is one byte - -- key is at least several bytes - status, result = socket:receive_bytes(13); + -- should be able to consume at least 13 bytes + -- key length is a 4 byte integer + -- padding is between 1 and 8 bytes + -- type is one byte + -- key is at least several bytes + status, result = socket:receive_bytes(13); - if (not status) then - socket:close() - return - end + if (not status) then + socket:close() + return + end - if (result == "TIMEOUT") then - socket:close() - return - end + if (result == "TIMEOUT") then + socket:close() + return + end - if not string.match(result, "^....[\0]+\002") then - socket:close() - return - end + if not string.match(result, "^....[\0]+\002") then + socket:close() + return + end - socket:close(); + socket:close(); - return true, "Server supports SSHv1" + return true, "Server supports SSHv1" end diff --git a/scripts/stun-info.nse b/scripts/stun-info.nse index 7d36ecc93..aea3bd6a8 100644 --- a/scripts/stun-info.nse +++ b/scripts/stun-info.nse @@ -27,22 +27,22 @@ portrule = shortport.port_or_service(3478, "stun", "udp") local function fail(err) return ("\n ERROR: %s"):format(err or "") end action = function(host, port) - local helper = stun.Helper:new(host, port) - local status = helper:connect() - if ( not(status) ) then - return fail("Failed to connect to server") - end + local helper = stun.Helper:new(host, port) + local status = helper:connect() + if ( not(status) ) then + return fail("Failed to connect to server") + end - local status, result = helper:getExternalAddress() - if ( not(status) ) then - return fail("Failed to retrieve external IP") - end + local status, result = helper:getExternalAddress() + if ( not(status) ) then + return fail("Failed to retrieve external IP") + end - port.version.name = "stun" - nmap.set_port_state(host, port, "open") - nmap.set_port_version(host, port) + port.version.name = "stun" + nmap.set_port_state(host, port, "open") + nmap.set_port_version(host, port) - if ( result ) then - return "\n External IP: " .. result - end + if ( result ) then + return "\n External IP: " .. result + end end diff --git a/scripts/stun-version.nse b/scripts/stun-version.nse index e65fa9a00..e40b661d6 100644 --- a/scripts/stun-version.nse +++ b/scripts/stun-version.nse @@ -23,19 +23,19 @@ portrule = shortport.version_port_or_service(3478, "stun", "udp") local function fail(err) return ("\n ERROR: %s"):format(err or "") end action = function(host, port) - local helper = stun.Helper:new(host, port) - local status = helper:connect() - if ( not(status) ) then - return fail("Failed to connect to server") - end + local helper = stun.Helper:new(host, port) + local status = helper:connect() + if ( not(status) ) then + return fail("Failed to connect to server") + end - local status, result = helper:getVersion() - if ( not(status) ) then - return fail("Failed to retrieve external IP") - end + local status, result = helper:getVersion() + if ( not(status) ) then + return fail("Failed to retrieve external IP") + end - port.version.name = "stun" - port.version.product = result - nmap.set_port_state(host, port, "open") - nmap.set_port_version(host, port) + port.version.name = "stun" + port.version.product = result + nmap.set_port_state(host, port, "open") + nmap.set_port_version(host, port) end diff --git a/scripts/targets-asn.nse b/scripts/targets-asn.nse index f0c8825e4..020c71f60 100644 --- a/scripts/targets-asn.nse +++ b/scripts/targets-asn.nse @@ -37,64 +37,64 @@ categories = {"discovery", "external", "safe"} prerule = function() - return true + return true end action = function(host, port) - local asns, whois_server, whois_port, err, status, newtargets - local results = {} + local asns, whois_server, whois_port, err, status, newtargets + local results = {} - asns = stdnse.get_script_args('targets-asn.asn') or stdnse.get_script_args('asn-to-prefix.asn') - whois_server = stdnse.get_script_args('targets-asn.whois_server') or stdnse.get_script_args('asn-to-prefix.whois_server') - whois_port = stdnse.get_script_args('targets-asn.whois_port') or stdnse.get_script_args('asn-to-prefix.whois_port') + asns = stdnse.get_script_args('targets-asn.asn') or stdnse.get_script_args('asn-to-prefix.asn') + whois_server = stdnse.get_script_args('targets-asn.whois_server') or stdnse.get_script_args('asn-to-prefix.whois_server') + whois_port = stdnse.get_script_args('targets-asn.whois_port') or stdnse.get_script_args('asn-to-prefix.whois_port') - if not asns then - return stdnse.format_output(true, "targets-asn.asn is a mandatory parameter") - end - if not whois_server then - whois_server = "asn.shadowserver.org" - end - if not whois_port then - whois_port = 43 - end - if type(asns) ~= "table" then - asns = {asns} - end + if not asns then + return stdnse.format_output(true, "targets-asn.asn is a mandatory parameter") + end + if not whois_server then + whois_server = "asn.shadowserver.org" + end + if not whois_port then + whois_port = 43 + end + if type(asns) ~= "table" then + asns = {asns} + end - for _, asn in ipairs(asns) do - local socket = nmap.new_socket() + for _, asn in ipairs(asns) do + local socket = nmap.new_socket() - local prefixes = {} - prefixes['name'] = asn + local prefixes = {} + prefixes['name'] = asn - status, err = socket:connect(whois_server, whois_port) - if ( not(status) ) then - table.insert(prefixes, err) - else - status, err = socket:send("prefix " .. asn .. "\n") - if ( not(status) ) then - table.insert(prefixes, err) - else - while true do - local status, data = socket:receive_lines(1) - if ( not(status) ) then - table.insert(prefixes, err) - break - else - for i, prefix in ipairs(stdnse.strsplit("\n",data)) do - if ( #prefix > 1 ) then - table.insert(prefixes,prefix) - if target.ALLOW_NEW_TARGETS then - stdnse.print_debug("Added targets: "..prefix) - local status,err = target.add(prefix) - end - end - end - end - end - end - end - table.insert(results,prefixes) - end - return stdnse.format_output(true, results) + status, err = socket:connect(whois_server, whois_port) + if ( not(status) ) then + table.insert(prefixes, err) + else + status, err = socket:send("prefix " .. asn .. "\n") + if ( not(status) ) then + table.insert(prefixes, err) + else + while true do + local status, data = socket:receive_lines(1) + if ( not(status) ) then + table.insert(prefixes, err) + break + else + for i, prefix in ipairs(stdnse.strsplit("\n",data)) do + if ( #prefix > 1 ) then + table.insert(prefixes,prefix) + if target.ALLOW_NEW_TARGETS then + stdnse.print_debug("Added targets: "..prefix) + local status,err = target.add(prefix) + end + end + end + end + end + end + end + table.insert(results,prefixes) + end + return stdnse.format_output(true, results) end diff --git a/scripts/telnet-encryption.nse b/scripts/telnet-encryption.nse index 65f1d73d2..5617e5b65 100644 --- a/scripts/telnet-encryption.nse +++ b/scripts/telnet-encryption.nse @@ -33,67 +33,67 @@ author = "Patrik Karlsson, David Fifield, Fyodor" license = "Same as Nmap--See http://nmap.org/book/man-legal.html" local COMMAND = { - SubCommand = 0xFA, - Will = 0xFB, - Do = 0xFD, - Dont = 0xFE, - Wont = 0xFC, + SubCommand = 0xFA, + Will = 0xFB, + Do = 0xFD, + Dont = 0xFE, + Wont = 0xFC, } local function processOptions(data) - local pos = 1 - local result = {} - while ( pos < #data ) do - local iac, cmd, option - pos, iac, cmd = bin.unpack("CC", data, pos) - if ( 0xFF ~= iac ) then - break - end - if ( COMMAND.SubCommand == cmd ) then - repeat - pos, iac = bin.unpack("C", data, pos) - until( pos == #data or 0xFF == iac ) - pos, cmd = bin.unpack("C", data, pos) - if ( not(cmd) == 0xF0 ) then - return false, "Failed to parse options" - end - else - pos, option = bin.unpack("H", data, pos) - result[option] = result[option] or {} - table.insert(result[option], cmd) - end - end - return true, { done=( not(#data == pos - 1) ), cmds = result } + local pos = 1 + local result = {} + while ( pos < #data ) do + local iac, cmd, option + pos, iac, cmd = bin.unpack("CC", data, pos) + if ( 0xFF ~= iac ) then + break + end + if ( COMMAND.SubCommand == cmd ) then + repeat + pos, iac = bin.unpack("C", data, pos) + until( pos == #data or 0xFF == iac ) + pos, cmd = bin.unpack("C", data, pos) + if ( not(cmd) == 0xF0 ) then + return false, "Failed to parse options" + end + else + pos, option = bin.unpack("H", data, pos) + result[option] = result[option] or {} + table.insert(result[option], cmd) + end + end + return true, { done=( not(#data == pos - 1) ), cmds = result } end action = function(host, port) - local socket = nmap.new_socket() - local status = socket:connect(host, port) - local data = bin.pack("H", "FFFD26FFFB26") - local result + local socket = nmap.new_socket() + local status = socket:connect(host, port) + local data = bin.pack("H", "FFFD26FFFB26") + local result - socket:set_timeout(7500) - status, result = socket:send(data) - if ( not(status) ) then - return ("\n ERROR: Failed to send packet: %s"):format(result) - end + socket:set_timeout(7500) + status, result = socket:send(data) + if ( not(status) ) then + return ("\n ERROR: Failed to send packet: %s"):format(result) + end - repeat - status, data = socket:receive() - if ( not(status) ) then - return ("\n ERROR: Receiving packet: %s"):format(data) - end - status, result = processOptions(data) - if ( not(status) ) then - return "\n ERROR: Failed to process telnet options" - end - until( result.done or result.cmds['26'] ) + repeat + status, data = socket:receive() + if ( not(status) ) then + return ("\n ERROR: Receiving packet: %s"):format(data) + end + status, result = processOptions(data) + if ( not(status) ) then + return "\n ERROR: Failed to process telnet options" + end + until( result.done or result.cmds['26'] ) - for _, cmd in ipairs(result.cmds['26'] or {}) do - if ( COMMAND.Will == cmd or COMMAND.Do == cmd ) then - return "\n Telnet server supports encryption" - end - end - return "\n Telnet server does not support encryption" + for _, cmd in ipairs(result.cmds['26'] or {}) do + if ( COMMAND.Will == cmd or COMMAND.Do == cmd ) then + return "\n Telnet server supports encryption" + end + end + return "\n Telnet server does not support encryption" end diff --git a/scripts/upnp-info.nse b/scripts/upnp-info.nse index 6baee3f4c..d5e106901 100644 --- a/scripts/upnp-info.nse +++ b/scripts/upnp-info.nse @@ -37,17 +37,17 @@ portrule = shortport.portnumber(1900, "udp", {"open", "open|filtered"}) -- Sends UPnP discovery packet to host, -- and extracts service information from results action = function(host, port) - local override = stdnse.get_script_args("upnp-info.override") - local helper = upnp.Helper:new( host, port ) - if ( override ~= nil ) and ( string.lower(override) == "false" ) then - helper:setOverride( false ) - else - helper:setOverride( true ) - end - local status, result = helper:queryServices() + local override = stdnse.get_script_args("upnp-info.override") + local helper = upnp.Helper:new( host, port ) + if ( override ~= nil ) and ( string.lower(override) == "false" ) then + helper:setOverride( false ) + else + helper:setOverride( true ) + end + local status, result = helper:queryServices() - if ( status ) then - nmap.set_port_state(host, port, "open") - return stdnse.format_output(true, result) - end + if ( status ) then + nmap.set_port_state(host, port, "open") + return stdnse.format_output(true, result) + end end diff --git a/scripts/vnc-info.nse b/scripts/vnc-info.nse index 09c257220..19db0d51e 100644 --- a/scripts/vnc-info.nse +++ b/scripts/vnc-info.nse @@ -44,28 +44,28 @@ portrule = shortport.port_or_service( {5900, 5901, 5902} , "vnc", "tcp", "open") action = function(host, port) - local vnc = vnc.VNC:new( host.ip, port.number ) - local status, data - local result = stdnse.output_table() + local vnc = vnc.VNC:new( host.ip, port.number ) + local status, data + local result = stdnse.output_table() - status, data = vnc:connect() - if ( not(status) ) then return " \n ERROR: " .. data end + status, data = vnc:connect() + if ( not(status) ) then return " \n ERROR: " .. data end - status, data = vnc:handshake() - if ( not(status) ) then return " \n ERROR: " .. data end + status, data = vnc:handshake() + if ( not(status) ) then return " \n ERROR: " .. data end - status, data = vnc:getSecTypesAsTable() - if ( not(status) ) then return " \n ERROR: " .. data end + status, data = vnc:getSecTypesAsTable() + if ( not(status) ) then return " \n ERROR: " .. data end - result["Protocol version"] = vnc:getProtocolVersion() + result["Protocol version"] = vnc:getProtocolVersion() - if ( data and #data ~= 0 ) then - result["Security types"] = data - end + if ( data and #data ~= 0 ) then + result["Security types"] = data + end - if ( vnc:supportsSecType(vnc.sectypes.NONE) ) then - result["WARNING"] = "Server does not require authentication" - end + if ( vnc:supportsSecType(vnc.sectypes.NONE) ) then + result["WARNING"] = "Server does not require authentication" + end - return result + return result end diff --git a/scripts/vuze-dht-info.nse b/scripts/vuze-dht-info.nse index 0ee4d9b41..836e81015 100644 --- a/scripts/vuze-dht-info.nse +++ b/scripts/vuze-dht-info.nse @@ -40,46 +40,46 @@ categories = {"discovery", "safe"} portrule = function(host, port) - local allports = stdnse.get_script_args('vuze-dht-info.allports') - if ( tonumber(allports) == 1 or allports == 'true' ) then - return true - else - local f = shortport.port_or_service({17555, 49160, 49161, 49162}, "vuze-dht", "udp", {"open", "open|filtered"}) - return f(host, port) - end + local allports = stdnse.get_script_args('vuze-dht-info.allports') + if ( tonumber(allports) == 1 or allports == 'true' ) then + return true + else + local f = shortport.port_or_service({17555, 49160, 49161, 49162}, "vuze-dht", "udp", {"open", "open|filtered"}) + return f(host, port) + end end local function getDHTInfo(host, port, lhost) - local helper = vuzedht.Helper:new(host, port, lhost) - local status = helper:connect() + local helper = vuzedht.Helper:new(host, port, lhost) + local status = helper:connect() - if ( not(status) ) then - return false, "\n ERROR: Failed to connect to server" - end + if ( not(status) ) then + return false, "\n ERROR: Failed to connect to server" + end - local response - status, response = helper:ping() - if ( not(status) ) then - return false, "\n ERROR: Failed to ping vuze node" - end - helper:close() + local response + status, response = helper:ping() + if ( not(status) ) then + return false, "\n ERROR: Failed to ping vuze node" + end + helper:close() - return true, response + return true, response end action = function(host, port) - local status, response = getDHTInfo(host, port) + local status, response = getDHTInfo(host, port) - -- check whether we have an error due to an incorrect address - -- ie. we're on a NAT:ed network and we're announcing our private ip - if ( status and response.header.action == vuzedht.Response.Actions.ERROR ) then - status, response = getDHTInfo(host, port, response.addr.ip) - end + -- check whether we have an error due to an incorrect address + -- ie. we're on a NAT:ed network and we're announcing our private ip + if ( status and response.header.action == vuzedht.Response.Actions.ERROR ) then + status, response = getDHTInfo(host, port, response.addr.ip) + end - if ( status ) then - nmap.set_port_state(host, port, "open") - return tostring(response) - end + if ( status ) then + nmap.set_port_state(host, port, "open") + return tostring(response) + end end diff --git a/scripts/weblogic-t3-info.nse b/scripts/weblogic-t3-info.nse index fdcbec626..3771644fc 100644 --- a/scripts/weblogic-t3-info.nse +++ b/scripts/weblogic-t3-info.nse @@ -20,7 +20,7 @@ action = function(host, port) "t3 12.1.2\nAS:2048\nHL:19\n\n", {proto=port.protocol, timeout=5000}) - if (not status) then + if (not status) then return nil end @@ -34,10 +34,10 @@ action = function(host, port) else extrainfo = extrainfo .. "; " end - if weblogic_version then + if weblogic_version then port.version.version = weblogic_version port.version.extrainfo = extrainfo .. "T3 enabled" - rval = "T3 protocol in use (WebLogic version: " .. weblogic_version .. ")" + rval = "T3 protocol in use (WebLogic version: " .. weblogic_version .. ")" elseif string.match(result, "^LGIN:") then port.version.extrainfo = extrainfo .. "T3 enabled" rval = "T3 protocol in use (handshake failed)" @@ -71,5 +71,5 @@ action = function(host, port) nmap.set_port_version(host, port, "hardmatched") end - return rval + return rval end diff --git a/scripts/wsdd-discover.nse b/scripts/wsdd-discover.nse index 05bf6a7f1..6c62c32c8 100644 --- a/scripts/wsdd-discover.nse +++ b/scripts/wsdd-discover.nse @@ -44,48 +44,48 @@ portrule = shortport.portnumber(3702, "udp", {"open", "open|filtered"}) -- the name should be one of the discovery functions in wsdd.Helper -- @param result table into which the results are stored discoverThread = function( funcname, host, port, results ) - -- calculates a timeout based on the timing template (default: 5s) - local timeout = ( 20000 / ( nmap.timing_level() + 1 ) ) - local condvar = nmap.condvar( results ) - local helper = wsdd.Helper:new(host, port) - helper:setTimeout(timeout) + -- calculates a timeout based on the timing template (default: 5s) + local timeout = ( 20000 / ( nmap.timing_level() + 1 ) ) + local condvar = nmap.condvar( results ) + local helper = wsdd.Helper:new(host, port) + helper:setTimeout(timeout) - local status, result = helper[funcname](helper) - if ( status ) then table.insert(results, result) end - condvar("broadcast") + local status, result = helper[funcname](helper) + if ( status ) then table.insert(results, result) end + condvar("broadcast") end local function sortfunc(a,b) - if ( a and b and a.name and b.name ) and ( a.name < b.name ) then - return true - end - return false + if ( a and b and a.name and b.name ) and ( a.name < b.name ) then + return true + end + return false end action = function(host, port) - local threads, results = {}, {} - local condvar = nmap.condvar( results ) + local threads, results = {}, {} + local condvar = nmap.condvar( results ) - -- Attempt to discover both devices and WCF web services - for _, f in ipairs( {"discoverDevices", "discoverWCFServices"} ) do - threads[stdnse.new_thread( discoverThread, f, host, port, results )] = true - end + -- Attempt to discover both devices and WCF web services + for _, f in ipairs( {"discoverDevices", "discoverWCFServices"} ) do + threads[stdnse.new_thread( discoverThread, f, host, port, results )] = true + end - local done - -- wait for all threads to finish - while( not(done) ) do - done = true - for thread in pairs(threads) do - if (coroutine.status(thread) ~= "dead") then done = false end - end - if ( not(done) ) then - condvar("wait") - end - end + local done + -- wait for all threads to finish + while( not(done) ) do + done = true + for thread in pairs(threads) do + if (coroutine.status(thread) ~= "dead") then done = false end + end + if ( not(done) ) then + condvar("wait") + end + end - if ( results ) then - table.sort( results, sortfunc ) - return stdnse.format_output(true, results) - end + if ( results ) then + table.sort( results, sortfunc ) + return stdnse.format_output(true, results) + end end diff --git a/scripts/xdmcp-discover.nse b/scripts/xdmcp-discover.nse index a5da1c134..29522423f 100644 --- a/scripts/xdmcp-discover.nse +++ b/scripts/xdmcp-discover.nse @@ -34,34 +34,34 @@ local function fail(err) return ("\n ERROR: %s"):format(err or "") end action = function(host, port) - local DISPLAY_ID = 1 - local result = {} + local DISPLAY_ID = 1 + local result = {} - local helper = xdmcp.Helper:new(host, port) - local status = helper:connect() - if ( not(status) ) then - return fail("Failed to connect to server") - end + local helper = xdmcp.Helper:new(host, port) + local status = helper:connect() + if ( not(status) ) then + return fail("Failed to connect to server") + end - local status, response = helper:createSession(nil, - {"MIT-MAGIC-COOKIE-1", "XDM-AUTHORIZATION-1"}, DISPLAY_ID) + local status, response = helper:createSession(nil, + {"MIT-MAGIC-COOKIE-1", "XDM-AUTHORIZATION-1"}, DISPLAY_ID) - if ( not(status) ) then - return fail("Failed to create xdmcp session") - end + if ( not(status) ) then + return fail("Failed to create xdmcp session") + end - table.insert(result, ("Session id: 0x%.8X"):format(response.session_id)) - if ( response.auth_name and 0 < #response.auth_name ) then - table.insert(result, ("Authentication name: %s"):format(response.auth_name)) - end - if ( response.auth_data and 0 < #response.auth_data ) then - table.insert(result, ("Authentication data: %s"):format(stdnse.tohex(response.auth_data))) - end - if ( response.authr_name and 0 < #response.authr_name ) then - table.insert(result, ("Authorization name: %s"):format(response.authr_name)) - end - if ( response.authr_data and 0 < #response.authr_data ) then - table.insert(result, ("Authorization data: %s"):format(stdnse.tohex(response.authr_data))) - end - return stdnse.format_output(true, result) + table.insert(result, ("Session id: 0x%.8X"):format(response.session_id)) + if ( response.auth_name and 0 < #response.auth_name ) then + table.insert(result, ("Authentication name: %s"):format(response.auth_name)) + end + if ( response.auth_data and 0 < #response.auth_data ) then + table.insert(result, ("Authentication data: %s"):format(stdnse.tohex(response.auth_data))) + end + if ( response.authr_name and 0 < #response.authr_name ) then + table.insert(result, ("Authorization name: %s"):format(response.authr_name)) + end + if ( response.authr_data and 0 < #response.authr_data ) then + table.insert(result, ("Authorization data: %s"):format(stdnse.tohex(response.authr_data))) + end + return stdnse.format_output(true, result) end