fix(winbox): harden mikrotik-routeros-username-brute, improve version probe

mikrotik-routeros-username-brute aborts on a Lua error whenever the
wordlist holds a line longer than 219 characters: the payload is framed
with a single length byte, so string.char() rejects the result and the
whole script dies, leaving the rest of the wordlist untried.

The wordlist reader also probes blank and whitespace-only lines as
usernames, and treats lines beginning with '#' as candidates, sending a
needless request for each.

Fixes:
  - validate the payload length and skip overlong usernames instead of
    aborting (default cap 32, matching the RouterOS limit, overridable
    with ...maxuserlen)
  - skip blank lines, '#' comments and duplicate entries
  - return argument errors through the standard status/message pair;
    they were previously returned silently because NSE only renders the
    second return value when the first is false

Adds:
  - ...threads   number of parallel worker threads (default 5)
  - ...delay     per-thread delay between attempts (default 0.5)
  - ...retries   connection attempts per username (default 1)

Attempts still use a fresh TCP session per username, as the device stops
answering after roughly three on the same session.

For mikrotik-routeros-version:
  - ...attempts  restrict which probes run (index, list)
  - reject implausible response lengths advertised by the peer, which
    could otherwise leave the socket waiting on a body that never arrives
  - when no version can be read (RouterOS 7.1+ uses a different
    handshake), still record the port as MikroTik WinBox
This commit is contained in:
Abdellah Erraoui 2026-10-11 20:38:55 +00:00
parent 1c7be2c6fc
commit 57e0859984
2 changed files with 250 additions and 106 deletions

View file

@ -4,135 +4,243 @@ Attempts to enumerate valid usernames on MikroTik devices running the Winbox ser
This script takes a wordlist from the user and modifies a baseline payload by
adding the username to it. If the server responds with 35 bytes, the username
is invalid; if the response is 51 bytes, the username is valid.
Blank lines, whitespace-only lines and lines starting with <code>#</code> are
ignored, duplicate usernames are only tried once, and usernames longer than
<code>maxuserlen</code> are skipped instead of breaking the payload framing.
This script uses a new tcp session for every username because the router
doesn't respond to usernames after sending 3 tries within the same tcp session!
Attempts can be spread over several worker threads.
]]
author = "deauther890"
license = "Same as Nmap--See https://nmap.org/book/man-legal.html"
categories = {"intrusive", "discovery"}
---@usage
-- nmap -p 8291 --script mikrotik-routeros-username-brute --script-args=wordlist=<wordlist path> <target>
-- @args mikrotik-routeros-username-brute.wordlist A file with usernames to try, one per line.
---
-- @usage
-- nmap -p 8291 --script mikrotik-routeros-username-brute --script-args mikrotik-routeros-username-brute.wordlist=<wordlist path> <target>
--
-- @args mikrotik-routeros-username-brute.wordlist A file with usernames to try, one per line.
-- @args mikrotik-routeros-username-brute.threads Number of parallel worker threads. Default 5.
-- @args mikrotik-routeros-username-brute.delay Seconds to wait between attempts, per thread. Default 0.5.
-- @args mikrotik-routeros-username-brute.retries Connection attempts per username. Default 1.
-- @args mikrotik-routeros-username-brute.maxuserlen Longest username to try, RouterOS allows 32. Default 32.
--
-- @output
-- PORT STATE SERVICE
-- 8291/tcp open winbox
-- | mikrotik-routeros-username-brute:
-- | admin
-- |_ mikrotik
--@Note
-- This script uses a new tcp session for every username because the router
-- doesn't respond to usernames after sending 3 tries within the same tcp session!
-- Import required libraries
local io = require "io"
local table = require "table"
local nmap = require "nmap"
local oops = require "oops"
local shortport = require "shortport"
local nmap = require "nmap"
local stdnse = require "stdnse"
local string = require "string"
local table = require "table"
-- Define the port rule
portrule = shortport.port_or_service(8291, "winbox", "tcp")
-- Define the Driver for socket handling
Driver = {
new = function(self, host, port)
local o = { host = host, port = port }
setmetatable(o, self)
self.__index = self
return o
end,
-- Length of the null padding appended after the username.
local PADDING = 34
-- Length of the server response that means "username is valid".
local VALID_LEN = 51
connect = function(self)
self.s = nmap.new_socket()
self.s:set_timeout(stdnse.get_timeout(self.host))
return self.s:connect(self.host, self.port, "tcp")
end,
local function get_num_arg(name, default)
local n = tonumber(stdnse.get_script_args(SCRIPT_NAME .. "." .. name))
if n == nil or n < 0 then
return default
end
return n
end
send_payload = function(self, payload)
local try = nmap.new_try(function() return false end)
try(self.s:send(payload))
return try(self.s:receive_bytes(35))
end,
--- Reads the wordlist, filtering out blank lines, comments and duplicates.
--@param file_path Path to the wordlist.
--@param maxuserlen Usernames longer than this are skipped.
--@return Array of usernames, or nil plus an error message.
local function read_wordlist(file_path, maxuserlen)
local wordlist, seen = {}, {}
local blank, comments, dupes, overlong = 0, 0, 0, 0
disconnect = function(self)
if self.s then
self.s:close()
end
end,
}
-- Read usernames from a wordlist file provided by the user
local function read_wordlist(file_path)
local wordlist = {}
local f, err = io.open(file_path, "r")
if not f then
stdnse.print_debug("Error opening wordlist: %s", err)
return nil
return nil, err
end
for line in f:lines() do
table.insert(wordlist, line:match("^%s*(.-)%s*$")) -- Remove leading and trailing whitespaces
end
f:close()
return wordlist
end
-- Function to create the payload
local function create_payload(username)
local payload = username .. "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
return string.char(#payload) .. "\x06" .. payload
end
local wordlist_path = stdnse.get_script_args(SCRIPT_NAME .. ".wordlist")
-- Main action function
action = function(host, port)
if not wordlist_path then
return oops.err("No wordlist provided. Use --script-args=".. SCRIPT_NAME .. ".wordlist=<file>")
end
local usernames = read_wordlist(wordlist_path)
if not usernames then
return "Failed to read the wordlist."
end
local valid_usernames = {}
local driver = Driver:new(host, port)
local retry = 0
for _, username in ipairs(usernames) do
::try_again::
if not driver:connect() then
if retry <= 0 then
return "Failed to connect to the target."
end
stdnse.print_debug("Failed to reconnect for username: %s", username)
retry = retry - 1
stdnse.sleep(0.5)
goto try_again
local username = line:match("^%s*(.-)%s*$")
if username == "" then
blank = blank + 1
elseif username:match("^#") then
comments = comments + 1
elseif #username > maxuserlen then
overlong = overlong + 1
stdnse.debug2("Skipping overlong username (%d > %d chars): %s",
#username, maxuserlen, username:sub(1, 20) .. "...")
elseif seen[username] then
dupes = dupes + 1
else
retry = 1
local payload = create_payload(username)
stdnse.print_debug("Sending payload for username: %s", username)
local success, response = pcall(driver.send_payload, driver, payload)
if success and response then
local response_length = #response
stdnse.print_debug("Response length for username %s: %d", username, response_length)
if response_length == 51 then
table.insert(valid_usernames, username)
end
end
stdnse.sleep(0.5) -- Delay between requests
-- Terminate the current connection and attempt to reconnect
driver:disconnect()
seen[username] = true
wordlist[#wordlist + 1] = username
end
end
driver:disconnect()
if #valid_usernames > 0 then
return valid_usernames
else
return "No valid usernames found."
end
f:close()
stdnse.debug1("Wordlist: %d usernames to try (%d blank, %d comments, %d duplicates, %d overlong skipped)",
#wordlist, blank, comments, dupes, overlong)
return wordlist
end
--- Builds the Winbox probe payload for a single username.
local function create_payload(username)
local payload = username .. string.rep("\0", PADDING)
-- The payload is framed with a single length byte, so guard the range
-- instead of letting string.char() throw and kill the whole script.
if #payload > 255 then
return nil, ("payload too long: %d bytes"):format(#payload)
end
return string.char(#payload) .. "\x06" .. payload
end
--- Opens a fresh session, sends one username and reports the reply length.
--@return Response length on success, or nil plus an error message.
local function try_username(host, port, username)
local payload, perr = create_payload(username)
if not payload then
return nil, perr
end
local socket = nmap.new_socket()
socket:set_timeout(stdnse.get_timeout(host))
local status, cerr = socket:connect(host, port, "tcp")
if not status then
socket:close()
return nil, cerr
end
-- NOTE: nmap.new_try() returns only the data argument, dropping the status.
-- socket:send() returns just a status (no data), so it must NOT go through
-- try() -- doing so would make every successful send look like a failure.
status = socket:send(payload)
if not status then
socket:close()
return nil, "send failed"
end
local try = nmap.new_try(function() return nil, "no response" end)
-- receive_bytes(35) returns as soon as at least the minimum reply arrives,
-- so both the 35-byte and the 51-byte reply are handled by the same call.
local response = try(socket:receive_bytes(35))
socket:close()
if not response then
return nil, "no response"
end
return #response
end
--- Worker thread: tries usernames [first..last], one fresh session each.
local function worker(host, port, usernames, first, last, results, delay, retries)
local condvar = nmap.condvar(results)
for i = first, last do
local username = usernames[i]
local length, err
for attempt = 1, retries do
length, err = try_username(host, port, username)
if length then
break
end
stdnse.debug2("Attempt %d for username '%s' failed: %s", attempt, username, tostring(err))
if delay > 0 then
stdnse.sleep(delay)
end
end
if length then
stdnse.debug2("Username '%s' -> %d bytes", username, length)
if length == VALID_LEN then
results[#results + 1] = username
stdnse.debug1("Valid username: %s", username)
end
else
stdnse.debug1("Giving up on username '%s': %s", username, tostring(err))
end
if delay > 0 and i < last then
stdnse.sleep(delay)
end
end
condvar "signal"
end
action = function(host, port)
local wordlist_path = stdnse.get_script_args(SCRIPT_NAME .. ".wordlist")
or stdnse.get_script_args("wordlist")
if not wordlist_path then
-- NSE renders the second return value only when the first is false.
return false, oops.err("No wordlist provided. Use --script-args=" .. SCRIPT_NAME .. ".wordlist=<file>")
end
local threads = get_num_arg("threads", 5)
local delay = get_num_arg("delay", 0.5)
local retries = math.max(1, get_num_arg("retries", 1))
local maxuserlen = math.max(1, get_num_arg("maxuserlen", 32))
local usernames, werr = read_wordlist(wordlist_path, maxuserlen)
if not usernames then
return false, oops.err(("Failed to read the wordlist: %s"):format(tostring(werr)))
end
if #usernames == 0 then
stdnse.verbose1("No usable usernames in %s", wordlist_path)
return nil
end
stdnse.debug1("Trying %d usernames with %d thread(s), %.2fs delay, %d retries",
#usernames, threads, delay, retries)
local results = {}
local condvar = nmap.condvar(results)
-- Split the work into one chunk per worker and run the chunks in parallel.
threads = math.min(threads, #usernames)
local per = math.ceil(#usernames / threads)
local running = {}
local i = 1
repeat
local j = math.min(i + per - 1, #usernames)
local co = stdnse.new_thread(worker, host, port, usernames, i, j,
results, delay, retries)
running[co] = true
i = j + 1
until i > #usernames
-- Reap the workers. Checking liveness before waiting avoids missing a
-- signal from a worker that finished before we started waiting.
repeat
for thread in pairs(running) do
if coroutine.status(thread) == "dead" then
running[thread] = nil
end
end
if next(running) then
condvar "wait"
end
until next(running) == nil
stdnse.verbose1("%d of %d usernames were valid", #results, #usernames)
if #results > 0 then
table.sort(results)
return results
end
return nil
end

View file

@ -12,6 +12,10 @@ categories = {"default", "version", "discovery", "safe"}
---@usage
-- nmap -p 8291 --script mikrotik-routeros-version <target>
--
-- @args mikrotik-routeros-version.attempts Comma separated list of probes to run
-- (<code>index</code>, <code>list</code>).
-- Default: run both.
---@output
--| mikrotik-routeros-version:
@ -134,6 +138,11 @@ local table = require "table"
portrule = shortport.version_port_or_service(8291, "winbox", "tcp")
-- Sanity bound for the response length advertised in the reply header. The
-- length is a signed 16-bit value, so an implausible figure would otherwise
-- leave the socket waiting on a body that never arrives.
local MAX_BODY = 8192
Driver = {
new = function(self, host, port)
local o = { host = host, port = port }
@ -155,7 +164,8 @@ Driver = {
stdnse.debug1("header: %s", stdnse.tohex(head))
-- response length is 2 bytes at position 15
local len = string.unpack(">i2", head, 15)
if len < 0 then
if len < 0 or len > MAX_BODY then
stdnse.debug1("Implausible response length %d, skipping probe", len)
-- clear out the receive buffer
try(self.s:receive_buf(".*", true))
return nil
@ -197,9 +207,27 @@ action = function(host, port)
pattern = 'name: "([^"]+)", unique: "[^"]+", version: "([^"]+)"',
},
}
-- Optionally restrict which probes run, e.g.
-- --script-args mikrotik-routeros-version.attempts=index
local only = stdnse.get_script_args(SCRIPT_NAME .. ".attempts")
if only then
local wanted = {}
for name in tostring(only):gmatch("[^,]+") do
wanted[name:match("^%s*(.-)%s*$")] = true
end
local filtered = {}
for _, att in ipairs(attempts) do
if wanted[att.name] then
filtered[#filtered + 1] = att
end
end
stdnse.debug1("Restricted to probes: %s (%d of %d)", tostring(only), #filtered, #attempts)
attempts = filtered
end
for _, att in ipairs(attempts) do
success, result = driver:connect()
if success then
stdnse.debug1("Sending payload")
@ -224,6 +252,14 @@ action = function(host, port)
end
if not version then
-- The payloads above only work up to RouterOS 6.49.17; 7.1+ uses a
-- different handshake. Still worth recording what we did manage to
-- identify, and telling an interested user why the version is missing.
port.version.name = "winbox"
port.version.name_confidence = 10
port.version.product = "MikroTik WinBox"
nmap.set_port_version(host, port)
stdnse.verbose1("Winbox detected, but the RouterOS version could not be read. RouterOS 7.1+ is not enumerable with this probe.")
return nil
end