From 520651a9edb5b82ca0994ff3b70e6865757a404d Mon Sep 17 00:00:00 2001 From: dmiller Date: Fri, 21 Sep 2012 02:39:48 +0000 Subject: [PATCH] Check for timeout when trying reserved ports rpc.Comm.Connect was trying to bind to 424 reserved ports, which is overkill. Since nsock doesn't do an actual bind(2) call until socket:connect for TCP, that meant up to 424 connect calls, each of which is currently leaking a socket. This commit contains 3 fixes: 1. Add nmap.new_socket calls for non-privileged code path that were moved inside the privileged loop to originally address the leak. 2. Check for TIMEOUT on each of the TCP connect calls and abandon the Connect, avoiding many timeouts. 3. Try 10 random reserved ports (from 1 to 1024) instead of 400+. Should be good odds of finding one unused, even when lots of threads are trying (though empirical results would be helpful). Also, this should reduce load since thread n won't need to fail n-1 bind attempts. --- nselib/rpc.lua | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/nselib/rpc.lua b/nselib/rpc.lua index 0f434b4ca..1f140414f 100644 --- a/nselib/rpc.lua +++ b/nselib/rpc.lua @@ -166,27 +166,32 @@ Comm = { if ( port.protocol == "tcp" ) then if nmap.is_privileged() then -- Try to bind to a reserved port - for resvport = 600, 1024, 1 do + for i = 1, 10, 1 do + resvport = math.random(1, 1024) socket = nmap.new_socket() status, err = socket:bind(nil, resvport) if status then status, err = socket:connect(host, port) - if status then break end + if status or err == "TIMEOUT" then break end socket:close() end end else + socket = nmap.new_socket() status, err = socket:connect(host, port) end else if nmap.is_privileged() then -- Try to bind to a reserved port - for resvport = 600, 1024, 1 do + for i = 1, 10, 1 do + resvport = math.random(1, 1024) socket = nmap.new_socket("udp") status, err = socket:bind(nil, resvport) if status then break end socket:close() end + else + socket = nmap.new_socket("udp") end end if (not(status)) then