diff --git a/nselib/isns.lua b/nselib/isns.lua index 80b593cb2..e827d0905 100644 --- a/nselib/isns.lua +++ b/nselib/isns.lua @@ -413,6 +413,7 @@ Session = { local hdr = Header.parse(buf_hdr) -- receive the data + local buf_data = nil status, buf_data = self.socket:receive_buf(match.numbytes(hdr.pdu_len), true) if ( not(status) ) then return status, buf_data diff --git a/scripts/afp-brute.nse b/scripts/afp-brute.nse index 94bea27ca..aa698f60c 100644 --- a/scripts/afp-brute.nse +++ b/scripts/afp-brute.nse @@ -50,6 +50,7 @@ action = function( host, port ) local result, response, status = {}, nil, nil local valid_accounts, found_users = {}, {} local helper + local usernames, passwords status, usernames = unpwdb.usernames() if not status then return end diff --git a/scripts/afp-ls.nse b/scripts/afp-ls.nse index 7d205648d..573c2de5b 100644 --- a/scripts/afp-ls.nse +++ b/scripts/afp-ls.nse @@ -115,6 +115,7 @@ action = function(host, port) return end + local vols status, vols = afpHelper:ListShares() if status then diff --git a/scripts/afp-serverinfo.nse b/scripts/afp-serverinfo.nse index 0e17450dc..b5ba213f6 100644 --- a/scripts/afp-serverinfo.nse +++ b/scripts/afp-serverinfo.nse @@ -71,7 +71,7 @@ action = function(host, port) try( socket:connect(host, port) ) -- get our data - afp_proto = afp.Proto:new( { socket=socket } ) + local afp_proto = afp.Proto:new( { socket=socket } ) local response = afp_proto:fp_get_server_info( socket ) response = response.result diff --git a/scripts/ajp-brute.nse b/scripts/ajp-brute.nse index b1925725f..88f063dd9 100644 --- a/scripts/ajp-brute.nse +++ b/scripts/ajp-brute.nse @@ -65,7 +65,7 @@ Driver = { local status, response = self.helper:get(arg_url, headers) if ( not(status) ) then - local err = brute.Error:new( data ) + local err = brute.Error:new( response ) err:setRetry( true ) return false, err elseif( response.status ~= 401 ) then diff --git a/scripts/ajp-methods.nse b/scripts/ajp-methods.nse index c0b825728..e258c5246 100644 --- a/scripts/ajp-methods.nse +++ b/scripts/ajp-methods.nse @@ -56,6 +56,8 @@ local function filter_out(t, filter) 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) diff --git a/scripts/asn-query.nse b/scripts/asn-query.nse index b24a7bb15..8d78f8832 100644 --- a/scripts/asn-query.nse +++ b/scripts/asn-query.nse @@ -404,6 +404,7 @@ function get_assignment( ip, prefix ) local hostbits = string.sub( some_ip, prefix + 1 ) hostbits = string.gsub( hostbits, "1", "0" ) local first = string.sub( some_ip, 1, prefix ) .. hostbits + local last err = {} first, err[#err+1] = ipOps.bin_to_ip( first ) last, err[#err+1] = ipOps.get_last_ip( ip, prefix ) diff --git a/scripts/backorifice-info.nse b/scripts/backorifice-info.nse index 8b94b0795..fcee64b6d 100644 --- a/scripts/backorifice-info.nse +++ b/scripts/backorifice-info.nse @@ -223,7 +223,7 @@ end local function BOunpack(packet) local pos, magic = bin.unpack("A8",packet) - if magic ~= MAGICSTRING then return nul,TYPE.ERROR end --received non-BO packet + if magic ~= MAGICSTRING then return nil,TYPE.ERROR end --received non-BO packet local packetsize, packetid, type_packet, data pos, packetsize, packetid, type_packet = bin.unpack("AA",ip_bin, icmp_msg) --Packet - icmp = packet.Packet:new(icmp_bin,#icmp_bin) + local icmp = packet.Packet:new(icmp_bin,#icmp_bin) assert(icmp,"Mistake during ICMP packet parsing") icmp:ip_set_bin_src(packet.iptobin(srcIP)) @@ -153,7 +153,7 @@ local broadcast_if = function(if_table,icmp_responders) -- raw IPv4 socket local dnet = nmap.new_dnet() - try = nmap.new_try() + local try = nmap.new_try() try = nmap.new_try(function() dnet:ethernet_close() end) -- raw sniffing socket (icmp echoreply style) diff --git a/scripts/broadcast-rip-discover.nse b/scripts/broadcast-rip-discover.nse index 755fdec7c..3023bd2a9 100644 --- a/scripts/broadcast-rip-discover.nse +++ b/scripts/broadcast-rip-discover.nse @@ -122,7 +122,7 @@ RIPv2 = { tab.addrow(routes, "ip", "netmask", "nexthop", "metric") while( #data - pos >= 20 ) do - local family, address, metric, _ + local family, address, metric, _, netmask, nexthop pos, family, _, address, netmask, nexthop, metric = bin.unpack(">SSI", data, pos) diff --git a/scripts/broadcast-tellstick-discover.nse b/scripts/broadcast-tellstick-discover.nse index 4f02841b9..aee64a6f5 100644 --- a/scripts/broadcast-tellstick-discover.nse +++ b/scripts/broadcast-tellstick-discover.nse @@ -27,6 +27,8 @@ categories = {"broadcast", "safe"} 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" } diff --git a/scripts/broadcast-xdmcp-discover.nse b/scripts/broadcast-xdmcp-discover.nse index 1db237c7d..7e805b677 100644 --- a/scripts/broadcast-xdmcp-discover.nse +++ b/scripts/broadcast-xdmcp-discover.nse @@ -39,7 +39,7 @@ action = function() local req = xdmcp.Packet[xdmcp.OpCode.BCAST_QUERY]:new(nil) local status, err = helper:send(req) if ( not(status) ) then - return false, response + return false, err end local timeout = arg_timeout or 5 diff --git a/scripts/cccam-version.nse b/scripts/cccam-version.nse index 00820cbd0..664758562 100644 --- a/scripts/cccam-version.nse +++ b/scripts/cccam-version.nse @@ -46,9 +46,9 @@ end -- splitbits("abc", 5) --> {"01100", "00101", "10001", "00110"} -- Any short final group is omitted. local function splitbits(s, n) - local bits, seq + local seq - _, bits = bin.unpack("B" .. #s, s) + local _, bits = bin.unpack("B" .. #s, s) seq = {} for i = 1, #bits - n, n do seq[#seq + 1] = bits:sub(i, i + n - 1) diff --git a/scripts/citrix-enum-apps.nse b/scripts/citrix-enum-apps.nse index 1d24e6331..a996570e3 100644 --- a/scripts/citrix-enum-apps.nse +++ b/scripts/citrix-enum-apps.nse @@ -51,7 +51,7 @@ function process_pa_response(response) end -- the list of published applications starts at offset 40 - offset = 41 + local offset = 41 while offset < packet_len do pos, app_name = bin.unpack("z", response:sub(offset)) @@ -119,7 +119,7 @@ action = function(host, port) local socket = nmap.new_socket() socket:set_timeout(5000) - try = nmap.new_try(function() socket:close() end) + local try = nmap.new_try(function() socket:close() end) try( socket:connect(host, port) ) diff --git a/scripts/citrix-enum-servers.nse b/scripts/citrix-enum-servers.nse index 8f164282a..a4b1387dc 100644 --- a/scripts/citrix-enum-servers.nse +++ b/scripts/citrix-enum-servers.nse @@ -49,7 +49,7 @@ function process_server_response(response) end -- the list of published applications starts at offset 40 - offset = 41 + local offset = 41 while offset < packet_len do pos, server_name = bin.unpack("z", response:sub(offset)) @@ -108,7 +108,7 @@ action = function(host, port) socket = nmap.new_socket() socket:set_timeout(5000) - try = nmap.new_try(function() socket:close() end) + local try = nmap.new_try(function() socket:close() end) try(socket:connect(host, port)) -- send the two first packets and never look back diff --git a/scripts/couchdb-stats.nse b/scripts/couchdb-stats.nse index 58264a542..e89c2d7a8 100644 --- a/scripts/couchdb-stats.nse +++ b/scripts/couchdb-stats.nse @@ -89,7 +89,7 @@ action = function(host, port) -- check that body was received if not data.body or data.body == "" then - local msg = ("%s did not respond with any data."):format(hostrgetname or host.ip ) + local msg = ("%s did not respond with any data."):format(host.targetname or host.ip ) dbg( msg ) return msg end diff --git a/scripts/cvs-brute-repository.nse b/scripts/cvs-brute-repository.nse index 2ad3b004b..a0da1af95 100644 --- a/scripts/cvs-brute-repository.nse +++ b/scripts/cvs-brute-repository.nse @@ -102,7 +102,7 @@ action = function(host, port) end end - repository_iterator = function() + local repository_iterator = function() local function next_repo() for line in f:lines() do if ( not(line:match("#!comment")) ) then diff --git a/scripts/daap-get-library.nse b/scripts/daap-get-library.nse index 4a84fb468..e0880a19c 100644 --- a/scripts/daap-get-library.nse +++ b/scripts/daap-get-library.nse @@ -68,6 +68,7 @@ function getLibraryName( host, port ) pos = string.find(response.body, "minm") if pos > 0 then + local len pos = pos + 4 pos, len = bin.unpack( ">I", response.body, pos ) pos, libname = bin.unpack( "A" .. len, response.body, pos ) @@ -88,6 +89,7 @@ local function getAttributeAsInt( data, name ) if pos and pos > 0 then pos = pos + 4 + local len pos, len = bin.unpack( ">I", data, pos ) if ( len ~= 4 ) then diff --git a/scripts/db2-das-info.nse b/scripts/db2-das-info.nse index b9e758445..8eda45e55 100644 --- a/scripts/db2-das-info.nse +++ b/scripts/db2-das-info.nse @@ -167,7 +167,6 @@ function read_db2_packet(socket) local header_len = 41 local total_len = 0 local buf - local endian local DATA_LENGTH_OFFSET = 38 local ENDIANESS_OFFSET = 23 @@ -188,7 +187,7 @@ function read_db2_packet(socket) stdnse.print_debug("db2-das-info: Got DB2DAS packet") - _, endian = bin.unpack( "A2", packet.header.raw, ENDIANESS_OFFSET ) + local _, endian = bin.unpack( "A2", packet.header.raw, ENDIANESS_OFFSET ) if endian == "9z" then _, packet.header.data_len = bin.unpack("I", packet.header.raw, DATA_LENGTH_OFFSET ) @@ -381,6 +380,7 @@ action = function(host, port) socket:close() -- The next block of code is essentially the version extraction code from db2-info.nse + local server_version if string.sub(db2response.version,1,3) == "SQL" then local major_version = string.sub(db2response.version,4,5) diff --git a/scripts/dns-brute.nse b/scripts/dns-brute.nse index 54f74826f..767098be2 100644 --- a/scripts/dns-brute.nse +++ b/scripts/dns-brute.nse @@ -156,7 +156,7 @@ local function srv_main(domainname, srvresults, srv_iter) local hostn = name..'.'..domainname addr = stdnse.strsplit(":",addr) for _, dtype in ipairs({"A", "AAAA"}) do - local srvres = resolve(addr[4], dtype) + local srvres = resolve(addr[4], dtype) if(srvres) then for srvhost,srvip in ipairs(srvres) do stdnse.print_debug("Hostname: "..hostn.." IP: "..srvip) @@ -186,6 +186,8 @@ action = function(host) if not nmap.registry.bruteddomains then nmap.registry.bruteddomains = {} end + + local dosrv if(not table.contains(nmap.registry.bruteddomains,domainname)) then table.insert(nmap.registry.bruteddomains, domainname) stdnse.print_debug("Starting dns-brute at: "..domainname) @@ -247,7 +249,7 @@ action = function(host) local condvar = nmap.condvar( srvresults ) stdnse.print_debug("SRV's per thread: "..howmany_ip) repeat - local j = math.min(i+howmany_ip, #srvlist) + local j = math.min(i+howmany_ip, #srvlist) local name_iter = array_iter(srvlist, i, j) threads[stdnse.new_thread(srv_main, domainname, srvresults, name_iter)] = true i = j+1 @@ -263,8 +265,8 @@ action = function(host) end end - response = {} - t_dns = {} + local response = {} + local t_dns = {} t_dns['name'] = "DNS Brute-force hostnames" if(#results==0) then table.insert(t_dns,"No results.") @@ -274,7 +276,7 @@ action = function(host) end response[#response + 1] = t_dns if(dosrv) then - t_srv = {} + local t_srv = {} t_srv['name'] = "SRV results" if(#srvresults==0) then table.insert(t_srv,"No results.") diff --git a/scripts/dns-check-zone.nse b/scripts/dns-check-zone.nse index 5487c5a76..4deab6db7 100644 --- a/scripts/dns-check-zone.nse +++ b/scripts/dns-check-zone.nse @@ -213,7 +213,7 @@ local dns_checks = { end if ( 0 < #result ) then - output = ("The following servers were found in the zone, but not in the parent: %s"):format(stdnse.strjoin(", ", result)) + local output = ("The following servers were found in the zone, but not in the parent: %s"):format(stdnse.strjoin(", ", result)) return true, { status = Status.FAIL, output = output } end @@ -261,7 +261,7 @@ local dns_checks = { end if ( 0 < #result ) then - output = ("The following servers were found in the parent, but not in the zone: %s"):format(stdnse.strjoin(", ", result)) + local output = ("The following servers were found in the parent, but not in the zone: %s"):format(stdnse.strjoin(", ", result)) return true, { status = Status.FAIL, output = output } end diff --git a/scripts/dns-fuzz.nse b/scripts/dns-fuzz.nse index 37f35136f..58d85d60a 100644 --- a/scripts/dns-fuzz.nse +++ b/scripts/dns-fuzz.nse @@ -58,7 +58,7 @@ recursiveServer = "scanme.nmap.org" -- @param port The servers port -- @return Bool, true if and only if the server is alive function pingServer (host, port, attempts) - local status, response + local status, response, result -- If the server doesn't respond to the first in a multiattempt probe, slow down local slowDown = 1 if not recursiveOnly then @@ -84,7 +84,7 @@ function pingServer (host, port, attempts) else -- just do a vanilla recursive lookup of scanme.nmap.org for i = 1, attempts do - status, respons = dns.query(recursiveServer, {host=host.ip, port=port.number, tries=1, timeout=math.pow(DNStimeout,slowDown)}) + status, response = dns.query(recursiveServer, {host=host.ip, port=port.number, tries=1, timeout=math.pow(DNStimeout,slowDown)}) if status then return true end diff --git a/scripts/domcon-cmd.nse b/scripts/domcon-cmd.nse index 186be88ca..443d00fc9 100644 --- a/scripts/domcon-cmd.nse +++ b/scripts/domcon-cmd.nse @@ -111,7 +111,7 @@ action = function(host, port) cmds = stdnse.strsplit(";%s*", cmd) socket:set_timeout(10000) - status = socket:connect( host.ip, port.number, "tcp") + local status = socket:connect( host.ip, port.number, "tcp") if ( status ) then socket:reconnect_ssl() end diff --git a/scripts/eap-info.nse b/scripts/eap-info.nse index 5ef4825ac..ec8ab1f4b 100644 --- a/scripts/eap-info.nse +++ b/scripts/eap-info.nse @@ -75,7 +75,7 @@ action = function() end stdnse.print_debug(1, "iface: %s", iface.device) - timeout = 10 * 1000 + local timeout = 10 * 1000 if arg_timeout then timeout = arg_timeout * 1000 end diff --git a/scripts/epmd-info.nse b/scripts/epmd-info.nse index be03f17ad..aebe54dbd 100644 --- a/scripts/epmd-info.nse +++ b/scripts/epmd-info.nse @@ -45,9 +45,9 @@ action = function(host, port) data = data .. tmp status, tmp = socket:receive() end - pos, realport = bin.unpack(">I", data) - nodestring = string.sub(data, pos, -2) - nodes = stdnse.strsplit("\n", nodestring) + 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 diff --git a/scripts/firewalk.nse b/scripts/firewalk.nse index fb5125492..c9260f57f 100644 --- a/scripts/firewalk.nse +++ b/scripts/firewalk.nse @@ -931,6 +931,7 @@ local function send_next_probes(scanner) -- this prevents sending too much probes at the same time while #scanner.active_probes < MaxActiveProbes do + local probe -- perform resends if #scanner.pending_resends > 0 then diff --git a/scripts/ftp-anon.nse b/scripts/ftp-anon.nse index eef41615e..2ed36fcb7 100644 --- a/scripts/ftp-anon.nse +++ b/scripts/ftp-anon.nse @@ -48,12 +48,12 @@ local function list(socket, target, max_lines) -- ask the server for a Passive Mode: it should give us a port to -- listen to, where it will dump the directory listing - buffer = stdnse.make_buffer(socket, "\r?\n") + local buffer = stdnse.make_buffer(socket, "\r?\n") status, err = socket:send("PASV\r\n") if not status then return status, err end - code, message = ftp.read_reply(buffer) + local code, message = ftp.read_reply(buffer) -- Compute the PASV port as given by the server -- The server should answer with something like @@ -120,7 +120,7 @@ action = function(host, port) local try = nmap.new_try(err_catch) try(socket:connect(host, port)) - buffer = stdnse.make_buffer(socket, "\r?\n") + local buffer = stdnse.make_buffer(socket, "\r?\n") -- Read banner. code, message = ftp.read_reply(buffer) diff --git a/scripts/ftp-brute.nse b/scripts/ftp-brute.nse index 9fac3cb81..70abecc33 100644 --- a/scripts/ftp-brute.nse +++ b/scripts/ftp-brute.nse @@ -52,7 +52,7 @@ Driver = { connect = function( self ) self.socket = nmap.new_socket() - status, err = self.socket:connect(self.host, self.port) + local status, err = self.socket:connect(self.host, self.port) self.socket:set_timeout(tonumber(arg_timeout) * 1000) if(not(status)) then return false, brute.Error:new( "Couldn't connect to host: " .. err ) diff --git a/scripts/ftp-proftpd-backdoor.nse b/scripts/ftp-proftpd-backdoor.nse index 5298eba13..1f1c3243e 100644 --- a/scripts/ftp-proftpd-backdoor.nse +++ b/scripts/ftp-proftpd-backdoor.nse @@ -68,7 +68,7 @@ action = function(host, port) end -- Read banner. - buffer = stdnse.make_buffer(sock, "\r?\n") + local buffer = stdnse.make_buffer(sock, "\r?\n") local code, message = ftp.read_reply(buffer) if not code then stdnse.print_debug(1, "Can't read banner: %s", message) diff --git a/scripts/http-axis2-dir-traversal.nse b/scripts/http-axis2-dir-traversal.nse index bcd3d9eb5..83b926ec2 100644 --- a/scripts/http-axis2-dir-traversal.nse +++ b/scripts/http-axis2-dir-traversal.nse @@ -152,7 +152,7 @@ action = function(host, port) --if body is empty something wrong could have happened... if string.len(req.body) <= 0 then if nmap.verbosity() >= 2 then - print_debug(1, "%s:Response was empty. The file does not exists or the web server does not have sufficient permissions", SCRIPT_NAME) + stdnse.print_debug(1, "%s:Response was empty. The file does not exists or the web server does not have sufficient permissions", SCRIPT_NAME) end return end diff --git a/scripts/http-barracuda-dir-traversal.nse b/scripts/http-barracuda-dir-traversal.nse index 64bb8bca3..2f91d81d0 100644 --- a/scripts/http-barracuda-dir-traversal.nse +++ b/scripts/http-barracuda-dir-traversal.nse @@ -96,7 +96,7 @@ action = function(host, port) for _, path in ipairs(paths) do -- Retrieve file - data = http.get(host, port, tostring(path)) + local data = http.get(host, port, tostring(path)) if data and data.status then -- Check if file exists diff --git a/scripts/http-cors.nse b/scripts/http-cors.nse index a833ad55b..88cb617b9 100644 --- a/scripts/http-cors.nse +++ b/scripts/http-cors.nse @@ -48,7 +48,7 @@ local function origin_ok(raw, origin) if raw == "null" then return false end - allowed = stdnse.strsplit(" ", raw) + local allowed = stdnse.strsplit(" ", raw) for _, ao in ipairs(allowed) do if origin == ao then return true @@ -73,7 +73,7 @@ local function method_ok(raw, method) end local function test(host, port, method, origin) - header = { + local header = { ["Origin"] = origin, ["Access-Control-Request-Method"] = method, } diff --git a/scripts/http-default-accounts.nse b/scripts/http-default-accounts.nse index acb8ad3a9..33639c68c 100644 --- a/scripts/http-default-accounts.nse +++ b/scripts/http-default-accounts.nse @@ -220,7 +220,7 @@ end -- the login routine is initialized to check for default credentials authentication --- action = function(host, port) - local fingerprintload_status, fingerprints, requests, results + local fingerprintload_status, status, fingerprints, requests, results local fingerprint_filename = stdnse.get_script_args("http-default-accounts.fingerprintfile") or "http-default-accounts-fingerprints.lua" local category = stdnse.get_script_args("http-default-accounts.category") or false local basepath = stdnse.get_script_args("http-default-accounts.basepath") or "/" diff --git a/scripts/http-generator.nse b/scripts/http-generator.nse index b99856b13..c39a62a6e 100644 --- a/scripts/http-generator.nse +++ b/scripts/http-generator.nse @@ -54,7 +54,7 @@ local follow_redirects = function(host, port, path, n) while (response['status-line'] or ""):match(pattern) and n > 0 do n = n - 1 - loc = response.header['location'] + local loc = response.header['location'] response = http.get_url(loc) end diff --git a/scripts/http-gitweb-projects-enum.nse b/scripts/http-gitweb-projects-enum.nse index 15db4c1a1..d8be93c2a 100644 --- a/scripts/http-gitweb-projects-enum.nse +++ b/scripts/http-gitweb-projects-enum.nse @@ -41,6 +41,7 @@ portrule = shortport.http --- get_owner = function(res) local result=res + local _ if ( res:match('') end if security_token then diff --git a/scripts/http-majordomo2-dir-traversal.nse b/scripts/http-majordomo2-dir-traversal.nse index f91cf1e25..8b45a0c34 100644 --- a/scripts/http-majordomo2-dir-traversal.nse +++ b/scripts/http-majordomo2-dir-traversal.nse @@ -79,6 +79,7 @@ action = function(host, port) stdnse.print_debug(1, "%s:[Error] The server is not vulnerable, '%s' was not found or the web server has insufficient permissions to read it", SCRIPT_NAME, rfile) return end + local _ _, _, rfile_content = string.find(response.body, '
(.*)')
     output_lines[#output_lines+1] = rfile.." was found:\n"..rfile_content
     if filewrite then
diff --git a/scripts/http-open-proxy.nse b/scripts/http-open-proxy.nse
index 9d4a15e01..91bb442f4 100644
--- a/scripts/http-open-proxy.nse
+++ b/scripts/http-open-proxy.nse
@@ -112,6 +112,7 @@ function default_test(host, port)
   local hostname = "www.google.com"
   local pattern  = "^server: gws"
   get_status, get_r1, get_cstatus = proxy.test_get(host, port, "http", test_url, hostname, pattern)
+  local _
   head_status, _, head_cstatus = proxy.test_head(host, port, "http", test_url, hostname, pattern)
   conn_status = proxy.test_connect(host, port, "http", hostname)
 
diff --git a/scripts/http-proxy-brute.nse b/scripts/http-proxy-brute.nse
index f0ce43d19..6dab42aae 100644
--- a/scripts/http-proxy-brute.nse
+++ b/scripts/http-proxy-brute.nse
@@ -108,6 +108,7 @@ action = function(host, port)
 
 	local engine = brute.Engine:new(Driver, host, port)
 	engine.options.script_name = SCRIPT_NAME
+	local result
 	status, result = engine:start()
 
 	return result
diff --git a/scripts/http-vhosts.nse b/scripts/http-vhosts.nse
index 610187b34..a7794709b 100644
--- a/scripts/http-vhosts.nse
+++ b/scripts/http-vhosts.nse
@@ -482,7 +482,7 @@ local HOSTNAMES = {
 defineDomain = function(host)
   if stdnse.get_script_args("http-vhosts.domain") then return stdnse.get_script_args("http-vhosts.domain") end
 
-  name = stdnse.get_hostname(host)
+  local name = stdnse.get_hostname(host)
   if name and name ~= host.ip then
     local pos = string.find (name, ".",1,true)
     if not pos then return name end
diff --git a/scripts/iax2-brute.nse b/scripts/iax2-brute.nse
index 19950ea4a..d5087dbf1 100644
--- a/scripts/iax2-brute.nse
+++ b/scripts/iax2-brute.nse
@@ -71,6 +71,6 @@ Driver = {
 action = function(host, port)
 	local engine = brute.Engine:new(Driver, host, port)
 	engine.options.script_name = SCRIPT_NAME
-	status, result = engine:start()
+	local status, result = engine:start()
 	return result
 end
diff --git a/scripts/imap-brute.nse b/scripts/imap-brute.nse
index dd3fc932a..ff93af669 100644
--- a/scripts/imap-brute.nse
+++ b/scripts/imap-brute.nse
@@ -133,7 +133,8 @@ action = function(host, port)
 	end
 		
 	local engine = brute.Engine:new(Driver, host, port)
-	engine.options.script_name = SCRIPT_NAME	
+	engine.options.script_name = SCRIPT_NAME
+	local result
 	status, result = engine:start()
 	
 	for _, helper in pairs(ConnectionPool) do helper:close() end
diff --git a/scripts/imap-capabilities.nse b/scripts/imap-capabilities.nse
index 5b1e2a5b7..dc4ae93e3 100644
--- a/scripts/imap-capabilities.nse
+++ b/scripts/imap-capabilities.nse
@@ -42,8 +42,8 @@ action = function(host, port)
 	table.insert(capstrings, cap)
      end
      return stdnse.strjoin(" ", capstrings)
-  elseif type(err) == "string" then
-     stdnse.print_debug(1, "%s: '%s' for %s", SCRIPT_NAME, err, host.ip)
+  elseif type(capa) == "string" then
+     stdnse.print_debug(1, "%s: '%s' for %s", SCRIPT_NAME, capa, host.ip)
      return
   else
      return "server doesn't support CAPABILITIES"
diff --git a/scripts/informix-tables.nse b/scripts/informix-tables.nse
index 13a653ad4..2477442a5 100644
--- a/scripts/informix-tables.nse
+++ b/scripts/informix-tables.nse
@@ -91,6 +91,7 @@ action = function( host, port )
 	status, data = helper:Login(user, pass)
 	if ( not(status) ) then	return stdnse.format_output(status, data) end
 
+  local databases
 	status, databases = helper:GetDatabases()
 	if ( not(status) ) then
 		return "  \n  ERROR: Failed to retrieve a list of databases"
diff --git a/scripts/ip-geolocation-maxmind.nse b/scripts/ip-geolocation-maxmind.nse
index d8311fa94..e450c51df 100644
--- a/scripts/ip-geolocation-maxmind.nse
+++ b/scripts/ip-geolocation-maxmind.nse
@@ -410,7 +410,7 @@ local GeoIP = {
 		o._filehandle:seek("end",-3)
 		
 		for i=1,MaxmindDef.STRUCTURE_INFO_MAX_SIZE do
-			delim = o._filehandle:read(3)
+			local delim = o._filehandle:read(3)
 			
 			if delim == '\255\255\255' then
 				o._databaseType = o._filehandle:read(1):byte()
diff --git a/scripts/ipv6-node-info.nse b/scripts/ipv6-node-info.nse
index 04710d8eb..16ae84674 100644
--- a/scripts/ipv6-node-info.nse
+++ b/scripts/ipv6-node-info.nse
@@ -102,7 +102,7 @@ local function send_queries(host)
 
 	dnet = nmap.new_dnet()
 	dnet:ip_open()
-	p = build_ni_query(host.bin_ip_src, host.bin_ip, QTYPE_NODEADDRESSES)
+	local p = build_ni_query(host.bin_ip_src, host.bin_ip, QTYPE_NODEADDRESSES)
 	dnet:ip_send(p)
 	p = build_ni_query(host.bin_ip_src, host.bin_ip, QTYPE_NODENAME)
 	dnet:ip_send(p)
diff --git a/scripts/irc-brute.nse b/scripts/irc-brute.nse
index 57ce5af20..355d38764 100644
--- a/scripts/irc-brute.nse
+++ b/scripts/irc-brute.nse
@@ -60,7 +60,7 @@ Driver = {
 
 	login = function(self, _, password)
 		local msg = ("PASS %s\r\nNICK nmap_brute\r\nUSER anonymous 0 * :Nmap brute\r\n"):format(password)
-		local status = self.socket:send(msg)
+		local status, data = self.socket:send(msg)
 		local success = false
 		
 		if ( not(status) ) then
@@ -136,6 +136,7 @@ action = function(host, port)
 	engine.options.script_name = SCRIPT_NAME	
     engine.options.firstonly = true
     engine.options.passonly = true
+  local result
 	status, result = engine:start()
 
 	return result
diff --git a/scripts/irc-unrealircd-backdoor.nse b/scripts/irc-unrealircd-backdoor.nse
index c870d1724..f69dd8ae5 100644
--- a/scripts/irc-unrealircd-backdoor.nse
+++ b/scripts/irc-unrealircd-backdoor.nse
@@ -157,7 +157,7 @@ action = function(host, port)
 	end
 
 	-- Get the current time so we can measure the delay
-	time = os.time(os.date('*t'))
+	local time = os.time(os.date('*t'))
 	socket:set_timeout((delay + 5) * 1000)
 
 	-- Accumulate the response in the 'data' string
diff --git a/scripts/ldap-rootdse.nse b/scripts/ldap-rootdse.nse
index 9d7130a09..68cd8827d 100644
--- a/scripts/ldap-rootdse.nse
+++ b/scripts/ldap-rootdse.nse
@@ -106,6 +106,7 @@ function action(host,port)
 	-- In order to discover what protocol to use (SSL/TCP) we need to send a few bytes to the server
 	-- An anonymous bind should do it
 	local ldap_anonymous_bind = string.char( 0x30, 0x0c, 0x02, 0x01, 0x01, 0x60, 0x07, 0x02, 0x01, 0x03, 0x04, 0x00, 0x80, 0x00 )
+	local _
 	socket, _, opt = comm.tryssl( host, port, ldap_anonymous_bind, nil )
 	
 	if not socket then
diff --git a/scripts/ldap-search.nse b/scripts/ldap-search.nse
index 2dfd33eb9..6e4731d1a 100644
--- a/scripts/ldap-search.nse
+++ b/scripts/ldap-search.nse
@@ -121,6 +121,7 @@ function action(host,port)
 	-- In order to discover what protocol to use (SSL/TCP) we need to send a few bytes to the server
 	-- An anonymous bind should do it
 	local ldap_anonymous_bind = string.char( 0x30, 0x0c, 0x02, 0x01, 0x01, 0x60, 0x07, 0x02, 0x01, 0x03, 0x04, 0x00, 0x80, 0x00 )
+	local _
 	socket, _, opt = comm.tryssl( host, port, ldap_anonymous_bind, nil )
 	
 	if not socket then
diff --git a/scripts/membase-http-info.nse b/scripts/membase-http-info.nse
index acc2f16c6..28f51f690 100644
--- a/scripts/membase-http-info.nse
+++ b/scripts/membase-http-info.nse
@@ -123,7 +123,7 @@ action = function(host, port)
 
 	local urls = { "/pools/default/buckets", "/pools" }
 	
-	local result
+	local status, result
 	for _, u in ipairs(urls) do
 		status, result = cmdReq(host, port, u, result)
 	end
diff --git a/scripts/metasploit-xmlrpc-brute.nse b/scripts/metasploit-xmlrpc-brute.nse
index 3afda6b43..27ad46caf 100644
--- a/scripts/metasploit-xmlrpc-brute.nse
+++ b/scripts/metasploit-xmlrpc-brute.nse
@@ -93,7 +93,7 @@ action = function(host, port)
 	local engine = brute.Engine:new(Driver, host, port, opts)
 	engine.options.script_name = SCRIPT_NAME
 	engine.options.firstonly = true
-	status, result = engine:start()
+	local status, result = engine:start()
 	return result
 end
 
diff --git a/scripts/modbus-discover.nse b/scripts/modbus-discover.nse
index c6449c340..9c1905e5b 100644
--- a/scripts/modbus-discover.nse
+++ b/scripts/modbus-discover.nse
@@ -105,7 +105,7 @@ end
 local extract_slave_id = function(response)
     local byte_count = string.byte(response, 9)
     if ( byte_count == nil or byte_count == 0) then return nil end
-    offset, slave_id = bin.unpack("A"..byte_count, response, 10)
+    local offset, slave_id = bin.unpack("A"..byte_count, response, 10)
     return slave_id
 end
 
@@ -130,7 +130,7 @@ action = function(host, port)
 
     for sid = 1, 246 do
         stdnse.print_debug(3, "Sending command with sid = %d", sid)
-        rsid = form_rsid(sid, 0x11, "")
+        local rsid = form_rsid(sid, 0x11, "")
 
         local status, result = comm.exchange(host, port, rsid, opts)
         if ( status and (#result >= 8) ) then
diff --git a/scripts/mongodb-brute.nse b/scripts/mongodb-brute.nse
index 3e731e16e..9f314165b 100644
--- a/scripts/mongodb-brute.nse
+++ b/scripts/mongodb-brute.nse
@@ -51,7 +51,7 @@ Driver = {
 		if ( status ) then
 			return true, brute.Account:new(username, password, creds.State.VALID)
 		elseif ( resp ~= "Authentication failed" ) then
-			local err = brute.Error:new( err )
+			local err = brute.Error:new( resp )
 			err:setRetry( true )
 			return false, err					
 		end
@@ -100,7 +100,7 @@ action = function(host, port)
 	
 	engine.options.script_name = SCRIPT_NAME
 	engine.options.firstonly = true
-	status, result = engine:start()
+	local status, result = engine:start()
 
 	return result
 end
diff --git a/scripts/mongodb-info.nse b/scripts/mongodb-info.nse
index 438391c60..fa72a44c5 100644
--- a/scripts/mongodb-info.nse
+++ b/scripts/mongodb-info.nse
@@ -96,7 +96,8 @@ function action(host,port)
 	
 	local status, packet = mongodb.serverStatusQuery()
 	if not status then return packet end
-	
+
+	local statQResult, buildQResult
 	status,statQResult = mongodb.query(socket, packet)
 	
 	if not status then return statQResult end
diff --git a/scripts/ms-sql-empty-password.nse b/scripts/ms-sql-empty-password.nse
index 36a2cb57d..48dfdc1aa 100644
--- a/scripts/ms-sql-empty-password.nse
+++ b/scripts/ms-sql-empty-password.nse
@@ -95,7 +95,7 @@ local function test_credentials( instance, helper, username, password )
 	if ( passwordIsGood ) then
 		local loginResultMessage = "Login Success"
 		if loginErrorCode then
-			loginResultMessage = mssql.LoginErrorMessage[ errorCode ] or "unknown error"
+			loginResultMessage = mssql.LoginErrorMessage[ loginErrorCode ] or "unknown error"
 		end
 		table.insert( instance.ms_sql_empty, string.format( "%s:%s => %s", username, password:len()>0 and password or "", loginResultMessage ) )
 		
diff --git a/scripts/ms-sql-tables.nse b/scripts/ms-sql-tables.nse
index ab6787239..598b89c08 100644
--- a/scripts/ms-sql-tables.nse
+++ b/scripts/ms-sql-tables.nse
@@ -189,7 +189,7 @@ local function process_instance( instance )
 	
 				for k, v in pairs(dbs.rows) do
 					if ( not( table_contains( done_dbs, v[1] ) ) ) then
-						query = [[ SELECT so.name 'table', sc.name 'column', st.name 'type', sc.length 
+						local query = [[ SELECT so.name 'table', sc.name 'column', st.name 'type', sc.length 
 									FROM %s..syscolumns sc, %s..sysobjects so, %s..systypes st
 									WHERE so.id = sc.id AND sc.xtype=st.xtype AND
 									so.id IN (SELECT %s id FROM %s..sysobjects WHERE xtype='U') %s ORDER BY so.name, sc.name, st.name]]
@@ -218,7 +218,7 @@ local function process_instance( instance )
 		local restrict_tbl = {}
 		
 		if ( stdnse.get_script_args( {'ms-sql-tables.keywords', 'mssql-tables.keywords' } ) ) then
-			tmp = stdnse.get_script_args( {'ms-sql-tables.keywords', 'mssql-tables.keywords' } )
+			local tmp = stdnse.get_script_args( {'ms-sql-tables.keywords', 'mssql-tables.keywords' } )
 			if ( type(tmp) == 'table' ) then
 				tmp = stdnse.strjoin(',', tmp)
 			end
diff --git a/scripts/mysql-brute.nse b/scripts/mysql-brute.nse
index 4dc4875fb..cb9dc668a 100644
--- a/scripts/mysql-brute.nse
+++ b/scripts/mysql-brute.nse
@@ -49,7 +49,7 @@ Driver = {
 
 	connect = function( self )
 		self.socket = nmap.new_socket()
-		status, err = self.socket:connect(self.host, self.port)
+		local status, err = self.socket:connect(self.host, self.port)
 		self.socket:set_timeout(tonumber(arg_timeout) * 1000)
 		if(not(status)) then
 			return false, brute.Error:new( "Couldn't connect to host: " .. err )
@@ -58,7 +58,7 @@ Driver = {
 	end,
 
 	login = function (self, user, pass)
-		status, response = mysql.receiveGreeting(self.socket)
+		local status, response = mysql.receiveGreeting(self.socket)
 		if(not(status)) then
 			return false,brute.Error:new(response)
 		end
diff --git a/scripts/mysql-users.nse b/scripts/mysql-users.nse
index 94f6a1062..7f9e9e296 100644
--- a/scripts/mysql-users.nse
+++ b/scripts/mysql-users.nse
@@ -84,9 +84,9 @@ action = function( host, port )
 		status, response = mysql.loginRequest( socket, { authversion = "post41", charset = response.charset }, username, password, response.salt )
 	
 		if status and response.errorcode == 0 then
-			status, rs = mysql.sqlQuery( socket, "SELECT DISTINCT user FROM mysql.user" )
+			status, rows = mysql.sqlQuery( socket, "SELECT DISTINCT user FROM mysql.user" )
 			if status then
-				result = mysql.formatResultset(rs, { noheaders = true })
+				result = mysql.formatResultset(rows, { noheaders = true })
 			end
 		end
 		socket:close()
diff --git a/scripts/nessus-brute.nse b/scripts/nessus-brute.nse
index da9507888..2d75744f3 100644
--- a/scripts/nessus-brute.nse
+++ b/scripts/nessus-brute.nse
@@ -147,7 +147,7 @@ action = function(host, port)
 
 	-- the nessus service doesn't appear to do very well with multiple threads
 	engine:setMaxThreads(1)
-	status, result = engine:start()
+	local status, result = engine:start()
 
 	return result
 end
diff --git a/scripts/nessus-xmlrpc-brute.nse b/scripts/nessus-xmlrpc-brute.nse
index fdcbc0e1f..9b0747b88 100644
--- a/scripts/nessus-xmlrpc-brute.nse
+++ b/scripts/nessus-xmlrpc-brute.nse
@@ -123,6 +123,7 @@ action = function(host, port)
 		engine:setMaxThreads(arg_threads)
 	end
 	engine.options.script_name = SCRIPT_NAME
+	local result
 	status, result = engine:start()
 	return result
 end
diff --git a/scripts/nexpose-brute.nse b/scripts/nexpose-brute.nse
index b11b306be..3ba8510c3 100644
--- a/scripts/nexpose-brute.nse
+++ b/scripts/nexpose-brute.nse
@@ -65,7 +65,7 @@ Driver =
 			stdnse.print_debug(1, "nexpose-brute: Good login: %s/%s", username, password)
 			return true, brute.Account:new(username, password, creds.State.VALID)
 		end
-		stdnse.print_debug(1, "nexpose-brute: WARNING: Unhandled response: %s", body)
+		stdnse.print_debug(1, "nexpose-brute: WARNING: Unhandled response: %s", response.body)
 		return false, brute.Error:new( "incorrect response from server" )
 	end,
 
@@ -76,6 +76,6 @@ action = function(host, port)
 	local engine = brute.Engine:new(Driver, host, port)
 	engine.options.script_name = SCRIPT_NAME
 	engine.options.max_guesses = tonumber(stdnse.get_script_args('brute.guesses')) or 3
-	status, result = engine:start()
+	local status, result = engine:start()
 	return result
 end
diff --git a/scripts/ntp-monlist.nse b/scripts/ntp-monlist.nse
index b6c187db9..2268e9669 100644
--- a/scripts/ntp-monlist.nse
+++ b/scripts/ntp-monlist.nse
@@ -617,7 +617,7 @@ function parse_monlist_1(pkt, recs)
     if #recs + #recs.peerlist >= MAX_RECORDS then
       return remaining
     end
-    pos = off + isize * (i-1) -- beginning of item
+    local pos = off + isize * (i-1) -- beginning of item
     local t = {}
 
     -- src and dst addresses
@@ -685,7 +685,7 @@ function parse_peerlist(pkt, recs)
     if #recs + #recs.peerlist >= MAX_RECORDS then
       return remaining
     end
-    pos = off + (i * isize) -- beginning of item
+    local pos = off + (i * isize) -- beginning of item
     local t = {}
 
     -- src address
@@ -1069,7 +1069,7 @@ function output_ips(t)
   local i = 1
   local limit = #t['6']
   while i <= limit do
-    work = {}
+    local work = {}
     local len = 0
     local j = i
     repeat
diff --git a/scripts/openvas-otp-brute.nse b/scripts/openvas-otp-brute.nse
index 45ae9d482..53de084d1 100644
--- a/scripts/openvas-otp-brute.nse
+++ b/scripts/openvas-otp-brute.nse
@@ -81,6 +81,7 @@ Driver =
 		end
 
 		-- Create a buffer and receive the first line
+		local line
 		status, line = self.socket:receive_buf("\r?\n", false)
 
 		if (line == nil or string.match(line,"Bad login")) then
@@ -105,7 +106,7 @@ action = function(host, port)
 	local engine = brute.Engine:new(Driver, host, port)
 	engine:setMaxThreads(1)
 	engine.options.script_name = SCRIPT_NAME
-	status, result = engine:start()
+	local status, result = engine:start()
 	return result
 end
 
diff --git a/scripts/oracle-sid-brute.nse b/scripts/oracle-sid-brute.nse
index 831b9e22f..cfc5cb15e 100644
--- a/scripts/oracle-sid-brute.nse
+++ b/scripts/oracle-sid-brute.nse
@@ -116,6 +116,7 @@ local function process_tns_packet( packet )
 	local tnspacket = {}
 	
 	-- just pull out the bare minimum to be able to match
+	local _
 	_, tnspacket.Length, tnspacket.Checksum, tnspacket.Type = bin.unpack(">SSC", packet)
 	
 	return tnspacket
@@ -134,7 +135,7 @@ action = function(host, port)
 	socket:set_timeout(5000)
 
 	-- open the sid file specified by the user or fallback to the default oracle-sids file
-	sidfilename = nmap.registry.args.oraclesids or nmap.fetchfile("nselib/data/oracle-sids")
+	local sidfilename = nmap.registry.args.oraclesids or nmap.fetchfile("nselib/data/oracle-sids")
 	
 	sidfile = io.open(sidfilename)
 	
diff --git a/scripts/p2p-conficker.nse b/scripts/p2p-conficker.nse
index db38f5116..2536bc6f9 100644
--- a/scripts/p2p-conficker.nse
+++ b/scripts/p2p-conficker.nse
@@ -498,8 +498,7 @@ local function conficker_check(ip, port, protocol)
 
 	-- If it's TCP, get the length and make sure we have the full packet
 	if(protocol == "tcp") then
-		local length
-		_, length = bin.unpack(" (#response - 2) do
 			local response2
@@ -577,6 +576,7 @@ action = function(host)
 	-- Reverse the IP's endianness
 	ip = ipOps.todword(ip)
 	ip = bin.pack(">I", ip)
+	local _
 	_, ip = bin.unpack("S", value)}
+		local parts = {bin.unpack("CCCC>S", value)}
 		if #parts > 5 then
 			local o1 = parts[2]
 			local o2 = parts[3]
@@ -150,6 +152,7 @@ end
 local function dropdupes(tables, stringify)
 	local unique = {}
 	local dupe = {}
+	local s
 	for _, v in ipairs(tables) do
 		s = stringify(v)
 		if not dupe[s] then
@@ -208,10 +211,10 @@ local function protocols()
 	local t = tab.new()
 	tab.addrow(t, '#', 'PROTOCOL', 'GAME', 'SERVERS')
 	for i, p in ipairs(sortable) do
-		pos = i .. '.'
-		protocol = p[1]
+		local pos = i .. '.'
+		local protocol = p[1]
 		count = p[2]
-		game = KNOWN_PROTOCOLS[protocol]
+		local game = KNOWN_PROTOCOLS[protocol]
 		if game == "unknown" then
 			game = ""
 		end
diff --git a/scripts/rdp-vuln-ms12-020.nse b/scripts/rdp-vuln-ms12-020.nse
index f22e9d1f8..e5cef59df 100644
--- a/scripts/rdp-vuln-ms12-020.nse
+++ b/scripts/rdp-vuln-ms12-020.nse
@@ -198,9 +198,9 @@ action = function(host, port)
 	status, response = socket:receive_bytes(0) -- recieve another attach user confirm
 	pos,user2 = bin.unpack(">S",response:sub(10,11)) -- second user's channel - 1001
 	user2 = user2+1001 -- second user's channel
-	data4 = bin.pack(">SS",user1,user2)
-	data5 = bin.pack("H","0300000c02f08038") -- channel join request TPDU
-	channelJoinRequest = data5 .. data4
+	local data4 = bin.pack(">SS",user1,user2)
+	local data5 = bin.pack("H","0300000c02f08038") -- channel join request TPDU
+	local channelJoinRequest = data5 .. data4
 	status, err = socket:send(channelJoinRequest) -- bogus channel join request user1 requests channel of user2
 	status, response = socket:receive_bytes(0)
 	if response:sub(8,9) == bin.pack("H","3e00") then
diff --git a/scripts/redis-brute.nse b/scripts/redis-brute.nse
index a225d1505..7baccc854 100644
--- a/scripts/redis-brute.nse
+++ b/scripts/redis-brute.nse
@@ -104,7 +104,8 @@ action = function(host, port)
 	engine.options.script_name = SCRIPT_NAME
 	engine.options.firstonly = true
 	engine.options:setOption( "passonly", true )
-	
+
+	local result
 	status, result = engine:start()
 	return result
 end
diff --git a/scripts/rexec-brute.nse b/scripts/rexec-brute.nse
index 1d8811267..df6505717 100644
--- a/scripts/rexec-brute.nse
+++ b/scripts/rexec-brute.nse
@@ -97,6 +97,6 @@ action = function(host, port)
 
 	local engine = brute.Engine:new(Driver, host, port, options)
 	engine.options.script_name = SCRIPT_NAME	
-	status, result = engine:start()
+	local status, result = engine:start()
 	return result
 end
diff --git a/scripts/rlogin-brute.nse b/scripts/rlogin-brute.nse
index 91ddd11fb..485fa7d0d 100644
--- a/scripts/rlogin-brute.nse
+++ b/scripts/rlogin-brute.nse
@@ -63,6 +63,7 @@ Driver = {
 		local srcport = math.random(513, 1024)
 		self.socket:bind(nil, srcport)
 		self.socket:set_timeout(self.timeout)
+		local err
 		status, err = self.socket:connect(self.host, self.port)
 
 		if ( status ) then
@@ -153,6 +154,6 @@ action = function(host, port)
 
 	local engine = brute.Engine:new(Driver, host, port, options)
 	engine.options.script_name = SCRIPT_NAME
-	status, result = engine:start()
+	local status, result = engine:start()
 	return result
 end
diff --git a/scripts/rmi-dumpregistry.nse b/scripts/rmi-dumpregistry.nse
index f42d7a857..b71b27c3b 100644
--- a/scripts/rmi-dumpregistry.nse
+++ b/scripts/rmi-dumpregistry.nse
@@ -187,7 +187,7 @@ function customDataFormatter(className, customData)
 	for k,v in ipairs(customData) do
 		if v:find("file:/") == 1 then
 			-- This is a classpath
-			cp = split(v, "; ") -- Splits into table
+			local cp = split(v, "; ") -- Splits into table
 			table.insert(retData, "Classpath")
 			table.insert(retData, cp)
 		else
diff --git a/scripts/rmi-vuln-classloader.nse b/scripts/rmi-vuln-classloader.nse
index 0b4342b43..869d44db7 100644
--- a/scripts/rmi-vuln-classloader.nse
+++ b/scripts/rmi-vuln-classloader.nse
@@ -106,7 +106,7 @@ action = function (host, port)
     -- 0x51 : Returndata
     return false, "No return data received from server";
   end
-  data = registry.out.dis.bReader.readBuffer;
+  local data = registry.out.dis.bReader.readBuffer;
 
   if string.find(data, "RMI class loader disabled") == nil then
     rmi_vuln.state = vulns.STATE.VULN;
diff --git a/scripts/rsync-brute.nse b/scripts/rsync-brute.nse
index 9a2713a1e..cf2eb2cc8 100644
--- a/scripts/rsync-brute.nse
+++ b/scripts/rsync-brute.nse
@@ -102,6 +102,7 @@ action = function(host, port)
 	
 	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/rtsp-url-brute.nse b/scripts/rtsp-url-brute.nse
index baae32905..b8683e70d 100644
--- a/scripts/rtsp-url-brute.nse
+++ b/scripts/rtsp-url-brute.nse
@@ -79,6 +79,7 @@ local function processURL(host, port, url_iter, result)
 			break
 		end
 
+    local response
 		status, response = helper:describe(url)
 		if ( not(status) ) then
 			stdnse.print_debug(2, "ERROR: Sending DESCRIBE request to url: %s", url)
diff --git a/scripts/samba-vuln-cve-2012-1182.nse b/scripts/samba-vuln-cve-2012-1182.nse
index 42ffb3075..841eb1068 100644
--- a/scripts/samba-vuln-cve-2012-1182.nse
+++ b/scripts/samba-vuln-cve-2012-1182.nse
@@ -94,12 +94,14 @@ from an anonymous connection.
 	samba_cve.state = vulns.STATE.NOT_VULN
 
 	-- create SMB session
+	local status, smbstate
 	status, smbstate = msrpc.start_smb(host, msrpc.SAMR_PATH,true)
 	if(status == false) then
 		return false, smbstate
 	end
 	
 	-- bind to SAMR service
+	local bind_result
 	status, bind_result = msrpc.bind(smbstate, msrpc.SAMR_UUID, msrpc.SAMR_VERSION, nil)
 	if(status == false) then
 		msrpc.stop_smb(smbstate)
@@ -107,14 +109,14 @@ from an anonymous connection.
 	end
 
 	-- create malicious packet, same as in the PoC
-	data = bin.pack(" \\\\%s\\%s", config.local_service_file, config.share, config.service_file)
+	local status, err
 	status, err = smb.file_upload(host, config.local_service_file, config.share, "\\" .. config.service_file, overrides, is_xor_encoded)
 	if(status == false) then
 		cleanup(host, config)
@@ -1052,7 +1053,7 @@ end
 --@return status true or false
 --@return err    An error message if status is false. 
 local function create_service(host, config)
-	status, err = msrpc.service_create(host, config.service_name, config.path .. "\\" .. config.service_file)
+	local status, err = msrpc.service_create(host, config.service_name, config.path .. "\\" .. config.service_file)
 	if(status == false) then
 		stdnse.print_debug(1, "smb-psexec: Couldn't create the service: %s", err)
 		cleanup(host, config)
@@ -1109,7 +1110,7 @@ end
 --@return status true or false
 --@return err    An error message if status is false. 
 local function start_service(host, config, params)
-	status, err = msrpc.service_start(host, config.service_name, params)
+	local status, err = msrpc.service_start(host, config.service_name, params)
 	if(status == false) then
 		stdnse.print_debug(1, "smb-psexec: Couldn't start the service: %s", err)
 		return false, string.format("Couldn't start the service on the remote machine: %s", err)
@@ -1434,9 +1435,10 @@ and place it in nselib/data/psexec/ under the Nmap DATADIR.
 	end
 
 	-- Build the output into a nice table
+	local response
 	status, response = parse_output(config, result)
 	if(status == false) then
-		return stdnse.format_output(false, "Couldn't parse output: " .. results)
+		return stdnse.format_output(false, "Couldn't parse output: " .. response)
 	end
 
 	-- Add a warning if nothing was enabled
diff --git a/scripts/smtp-brute.nse b/scripts/smtp-brute.nse
index 716d8d713..3f59bc755 100644
--- a/scripts/smtp-brute.nse
+++ b/scripts/smtp-brute.nse
@@ -129,7 +129,8 @@ action = function(host, port)
 		
 	local engine = brute.Engine:new(Driver, host, port)
 	
-	engine.options.script_name = SCRIPT_NAME	
+	engine.options.script_name = SCRIPT_NAME
+	local result
 	status, result = engine:start()
 	
 	for _, sock in pairs(ConnectionPool) do sock:close() end
diff --git a/scripts/smtp-commands.nse b/scripts/smtp-commands.nse
index 9669e4222..e234421fc 100644
--- a/scripts/smtp-commands.nse
+++ b/scripts/smtp-commands.nse
@@ -121,7 +121,7 @@ action = function(host, port)
         return result
     else
         if #result > 0 then
-            final = {}
+            local final = {}
             for index, test in ipairs(result) do
                 table.insert(final, test)
             end
diff --git a/scripts/smtp-enum-users.nse b/scripts/smtp-enum-users.nse
index 2be6447b6..75691dfc6 100644
--- a/scripts/smtp-enum-users.nse
+++ b/scripts/smtp-enum-users.nse
@@ -214,6 +214,7 @@ issued_from = false
 -- @param domain Domain to use in the command
 -- @return Status and depending on the code, a error message
 function do_rcpt(socket, username, domain)
+    local status, response
     if not issued_from then
     -- Lets try to issue MAIL FROM command.
     status, response = smtp.query(socket, "MAIL",
diff --git a/scripts/smtp-open-relay.nse b/scripts/smtp-open-relay.nse
index d16ee0ffc..73f60954d 100644
--- a/scripts/smtp-open-relay.nse
+++ b/scripts/smtp-open-relay.nse
@@ -269,7 +269,7 @@ action = function(host, port)
         -- will print all the successful tests. Otherwise it will only
         -- print the conclusion.
         if #result > 0 then
-            final = {}
+            local final = {}
             table.insert(final,
                         string.format("Server is an open relay (%i/16 tests)",
                         (#result)))
diff --git a/scripts/smtp-vuln-cve2010-4344.nse b/scripts/smtp-vuln-cve2010-4344.nse
index b9dccbfd8..69b0e5441 100644
--- a/scripts/smtp-vuln-cve2010-4344.nse
+++ b/scripts/smtp-vuln-cve2010-4344.nse
@@ -311,7 +311,7 @@ local function check_exim(smtp_opts)
   local heap_cve, priv_cve = 'CVE-2010-4344', 'CVE-2010-4345'
   local heap_str = "Exim heap overflow vulnerability ("..heap_cve.."):"
   local priv_str = "Exim privileges escalation vulnerability ("..priv_cve.."):"
-  local exip_heap_result, exip_priv_result = "", ""
+  local exim_heap_result, exim_priv_result = "", ""
 
   local socket, ret = smtp.connect(smtp_opts.host,
                           smtp_opts.port,
diff --git a/scripts/snmp-brute.nse b/scripts/snmp-brute.nse
index fdcfb3b58..cd6a72c44 100644
--- a/scripts/snmp-brute.nse
+++ b/scripts/snmp-brute.nse
@@ -143,7 +143,7 @@ local send_snmp_queries = function(socket, result, nextcommunity)
 
 	local request = snmp.buildGetRequest({}, "1.3.6.1.2.1.1.3.0")
 
-	local payload, status, response
+	local payload, status, response, err
 	local community = nextcommunity()
 
 	while community do
diff --git a/scripts/snmp-ios-config.nse b/scripts/snmp-ios-config.nse
index d1f130086..80b998ebe 100644
--- a/scripts/snmp-ios-config.nse
+++ b/scripts/snmp-ios-config.nse
@@ -46,6 +46,8 @@ dependencies = {"snmp-brute"}
 
 portrule = shortport.portnumber(161, "udp", {"open", "open|filtered"})
 
+local try
+
 local function sendrequest(socket, oid, setparam)
 	local payload
 	local options = {}
@@ -72,16 +74,15 @@ action = function(host, port)
 		return "ERROR: tftproot needs to end with slash"
 	end
 
-   	-- create the socket used for our connection
+  -- create the socket used for our connection
 	local socket = nmap.new_socket()
-	
+
 	-- set a reasonable timeout value
 	socket:set_timeout(5000)
-	
-	-- do some exception handling / cleanup
-	catch = function() socket:close() end
-	
-	try = nmap.new_try(catch)
+
+  -- do some exception handling / cleanup
+  local catch = function() socket:close() end
+  try = nmap.new_try(catch)
 	
 	-- connect to the potential SNMP system
 	try(socket:connect(host.ip, port.number, "udp"))
diff --git a/scripts/snmp-win32-shares.nse b/scripts/snmp-win32-shares.nse
index 92c52c008..b39876d88 100644
--- a/scripts/snmp-win32-shares.nse
+++ b/scripts/snmp-win32-shares.nse
@@ -83,6 +83,7 @@ action = function(host, port)
 	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))
diff --git a/scripts/socks-brute.nse b/scripts/socks-brute.nse
index cdc8aa0d3..6929df5b1 100644
--- a/scripts/socks-brute.nse
+++ b/scripts/socks-brute.nse
@@ -95,6 +95,7 @@ action = function(host, port)
 
 	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/ssl-enum-ciphers.nse b/scripts/ssl-enum-ciphers.nse
index a478a8493..eeedcca1e 100644
--- a/scripts/ssl-enum-ciphers.nse
+++ b/scripts/ssl-enum-ciphers.nse
@@ -454,6 +454,7 @@ local function record_read(buffer, i)
 	elseif h["type"] == "handshake" then
 		-- Parse body.
 		j, b["type"] = bin.unpack("C", buffer, j)
+		local _
 		j, _ = bin.unpack("A3", buffer, j)
 
 		-- Convert to human-readable form.
@@ -799,7 +800,7 @@ local filltable = function(filename,table)
 
 		-- Comments takes up a whole line
 		if not l:match("#!comment:") then
-			lsplit=stdnse.strsplit("%s+", l)
+			local lsplit=stdnse.strsplit("%s+", l)
 			if cipherstrength[lsplit[2]] then
 				table[lsplit[1]] = lsplit[2]
 			else
diff --git a/scripts/svn-brute.nse b/scripts/svn-brute.nse
index 1af0e5c30..25aecc712 100644
--- a/scripts/svn-brute.nse
+++ b/scripts/svn-brute.nse
@@ -68,7 +68,8 @@ svn =
 		local status, msg
 		
 		self.socket = nmap.new_socket()
-								
+
+		local result
 		status, result = self.socket:connect(self.host.ip, self.port.number, "tcp")
 		if( not(status) ) then
 			return false, result
diff --git a/scripts/targets-asn.nse b/scripts/targets-asn.nse
index b2b76c12b..7729b620b 100644
--- a/scripts/targets-asn.nse
+++ b/scripts/targets-asn.nse
@@ -41,7 +41,7 @@ prerule = function()
 end
 
 action = function(host, port)
-	local asns, whois_server, whois_port, err, status
+	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')
diff --git a/scripts/tftp-enum.nse b/scripts/tftp-enum.nse
index ddb91a4e8..5500db647 100644
--- a/scripts/tftp-enum.nse
+++ b/scripts/tftp-enum.nse
@@ -209,7 +209,7 @@ action = function(host, port)
   nmap.set_port_state(host, port, "open")
 
   local results = {}
-  filenames = generate_filenames(host)
+  local filenames = generate_filenames(host)
 
   for i, filename in ipairs(filenames) do
     local request_status = check_file_present(host, port, filename)
diff --git a/scripts/versant-info.nse b/scripts/versant-info.nse
index f6d15f3e4..bbbd75504 100644
--- a/scripts/versant-info.nse
+++ b/scripts/versant-info.nse
@@ -66,6 +66,7 @@ action = function(host, port)
 		return fail("Failed to connect to server")
 	end
 
+  local result
 	status, result = v:getVODInfo()
 	if ( not(status) ) then
 		return fail("Failed to get VOD information")
diff --git a/scripts/vmauthd-brute.nse b/scripts/vmauthd-brute.nse
index 260cc7400..49b5c910e 100644
--- a/scripts/vmauthd-brute.nse
+++ b/scripts/vmauthd-brute.nse
@@ -114,6 +114,7 @@ action = function(host, port)
 
 	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/wdb-version.nse b/scripts/wdb-version.nse
index 6aa6b5d7c..c7a491a26 100644
--- a/scripts/wdb-version.nse
+++ b/scripts/wdb-version.nse
@@ -53,6 +53,7 @@ local WDB_Procedure = {
 local function checksum(data)
 	local sum = 0
 	local p = 0
+	local _
 	p, _ = bin.unpack(">I", data)
 	while p < data:len() do
 		local c
@@ -80,6 +81,7 @@ local function decode_reply(data, pos)
 	local wdberr, len
 	local done = data:len()
 	local info = {}
+	local _
 	pos, _ = rpc.Util.unmarshall_uint32(data, pos)
 	pos, _ = rpc.Util.unmarshall_uint32(data, pos)
 	pos, wdberr = rpc.Util.unmarshall_uint32(data, pos)
diff --git a/scripts/whois.nse b/scripts/whois.nse
index 69585fe31..c0d819447 100644
--- a/scripts/whois.nse
+++ b/scripts/whois.nse
@@ -1174,6 +1174,7 @@ function get_assignment( ip, prefix )
   local first = string.sub( some_ip, 1, prefix ) .. hostbits
   err = {}
   first, err[#err+1] = ipOps.bin_to_ip( first )
+  local last
   last, err[#err+1] = ipOps.get_last_ip( ip, prefix )
   if #err > 0 then return nil, table.concat( err, " " ) end
 
diff --git a/scripts/xmpp-brute.nse b/scripts/xmpp-brute.nse
index f728f730a..d5175f3ab 100644
--- a/scripts/xmpp-brute.nse
+++ b/scripts/xmpp-brute.nse
@@ -131,7 +131,8 @@ action = function(host, port)
 	end
 	
 	local engine = brute.Engine:new(Driver, host, port, options)
-	engine.options.script_name = SCRIPT_NAME	
+	engine.options.script_name = SCRIPT_NAME
+	local result
 	status, result = engine:start()
 		
 	return result
diff --git a/scripts/xmpp-info.nse b/scripts/xmpp-info.nse
index 8c26024b9..022e39c62 100644
--- a/scripts/xmpp-info.nse
+++ b/scripts/xmpp-info.nse
@@ -542,7 +542,7 @@ action = function(host, port)
 
     local r = {}
 
-    format_block = format_block_12
+    local format_block = format_block_12
     if not id_tls then
         format_block = format_block_1
         if starttls_failed then table.insert(r, "STARTTLS Failed") end