7¤0ìw� A¨2ê0333333333uØˆv#R
Û"{£ôve»¦eq4ž±À–5Í¢ØOl›]Œ&¾ßKKËÅ¥�°�C†™hÂÃ  ŒÇãy<ê €š�¨›“#i˜1Œ¢BÆC1 FDFFF    T4çÁHL:†�1                  e_prog	100077	# Database manipulation
kerbd		100078	kerbprog	# Kerberos authentication daemon
rpc.operd	100080	opermsg autodump_prog	# Sun Online-Backup
event_svc	100081	# Event protocol
bugtraq_qd	100082	# bugtraq_qd
ttdbserverd	100083	rpc.ttdbserverd ttdbserverd ttdbserver tooltalk database service	# ToolTalk and Link Service Project
admind		100087	adm_agent	# Jupiter Administration
libdsd/dsd	100090	#_NAME..".uri") or "/"
  local timeout = stdnse.parse_timespec(stdnse.get_script_args(SCRIPT_NAME..".timeout"))
  timeout = (timeout or 10) * 1000
  local vuln = {
    title = 'Authentication bypass by HTTP verb tampering',
    state = vulns.STATE.NOT_VULN,
    description = [[
This web server contains password protected resources vulnerable to authentication bypass
vulnerabilities via HTTP verb tampering. This is often found in web servers that only limit access to the
 common HTTP methods and in misconfigured .htaccess files.
    e time specification string (like "10s", "120ms"...)
-- @return the equivalent number of milliseconds or nil on failure
local function parse_timespec_ms(spec)
  local t = stdnse.parse_timespec(spec)
  if t then
    return t * 1000
  else
    return nil
  end
end

--- set scan parameters using user values if specified or defaults otherwise
local function getopts()

  -- assign parameters to scan constants or use defaults

  MaxRetries = tonumber(stdnse.get_script_args("firewalk.max-retries")) or DEFAULT_MAX_RETRIES

  MaxActiveProbecp.tcp_offset + 1, tcp.buf:len())
    ip:build_ipv6_packet(host.bin_ip_src, host.bin_ip, packet.IPPROTO_TCP, tcp_buf, ttl)

    return ip
  end,

}

-- UDP related functions (IPv6 versions)
local udp_funcs_v6 = {

  --- update the global scan status with a reply
  -- @param scanner the scanner handle
  -- @param ip the ICMP time exceeded error packet
  -- @param ip2 the ICMP payload (our original expired probe)
  update_scan = function(scanner, ip, ip2)

    local port = ip2.udp_dport

    if port and scanner.ports.udp[port] then


-- 443/tcp open  https   syn-ack
-- | http-sap-netweaver-leak:
-- |   VULNERABLE:
-- |   Anonymous access to SAP Netweaver Portal
-- |     State: VULNERABLE (Exploitable)
-- |             SAP Netweaver Portal with the Knowledge Management Unit allows attackers to obtain system information
-- |             including file system structure, LDAP users, emails and other information.
-- |
-- |     Disclosure date: 2018-02-1
-- |     Check results:
-- |       Visit /irj/go/km/navigation?Uri=/ to access this SAP instance.
-- |     Extra B,Y6,Newport"},
  Y7 = {ip=1353763984, desc="GB,Y7,Haverfordwest"},
  Y8 = {ip=1043430344, desc="GB,Y8,Welshpool"},
  Z1 = {ip=40116224, desc="GB,Z1,Swansea"},
  Z2 = {ip=40189952, desc="GB,Z2,Pontypool"},
  Z3 = {ip=35147776, desc="GB,Z3,Barry"},
  Z4 = {ip=40321024, desc="GB,Z4,Wrexham"}
}

local get_addresses = function(address, mask, domain, nameserver, port)

  -- translate the IP's in the areaIPs to strings, as this is what the
  -- DNS library expects
  if ( "number" == type(address) ) then
    address = ipOps.fromdword(addr see:
* http://www.security-assessment.com/files/advisories/2010-02-22_Multiple_Adobe_Products-XML_External_Entity_and_XML_Injection.pdf
* https://www.securityfocus.com/bid/38197
* Metasploit module: auxiliary/scanner/http/adobe_xml_inject
]]

---
-- @see http-adobe-coldfusion-apsa1301.nse
-- @see http-coldfusion-subzero.nse
-- @see http-vuln-cve2010-2861.nse
--
-- @args http-vuln-cve2009-3960.root Points to the root path. Defaults to "/"
-- @args http-vuln-cve2009-3960.readfile target file to be read. Defaults to "/etc/passwd"
--
pack("<I4", hash)

  -- Encrypt the full packet, except for the key and optional length
  packet = string.sub(packet, 1, 8) .. p2p_cipher(string.sub(packet, 9), key1, key2)

  -- Add the length in front if it's TCP
  if(protocol == "tcp") then
    packet = string.pack("<s2", packet)
  end

  return true, packet
end

---Checks if conficker is present on the given port/protocol. The ports Conficker uses are fairly standard, so
-- those should generally be used for this check. This can also be sent to any open port on the system.
--
-_or_service(11211, "memcached", {"tcp", "udp"})

local filter = {

  ["pid"] = { name = "Process ID" },
  ["uptime"] = { name = "Uptime", func = function(v) return ("%d seconds"):format(v) end },
  ["time"] = { name = "Server time", func = datetime.format_timestamp },
  ["pointer_size"] = { name = "Architecture", func = function(v) return v .. " bit" end },
  ["rusage_user"] = { name = "Used CPU (user)" },
  ["rusage_system"] = { name = "Used CPU (system)"},
  ["curr_connections"] = { name = "Current connections"},
  ["total_connece, 'Could not get to CESL (CICS Logon Screen)'
end

-- Filter iterator for unpwdb
-- IDs are limited to 8 alpha numeric and @, #, $ and can't start with a number
-- pattern:
--  ^%D     = The first char must NOT be a digit
-- [%w@#%$] = All letters including the special chars @, #, and $.
local valid_name = function(x)
  if  nmap.registry.tsoinvalid and nmap.registry.tsoinvalid[x] then
    return false
  end
  return (string.len(x) <= 8 and string.match(x,"^%D+[%w@#%$]"))
end

-- Checks string to see if it follows valid password li and format for output
    combined_records = process_answers( records, output, host.ip )

  end -- if not in_cache


  mutex "done"

  return nice_output( output, combined_records )

end -- action



---
-- Checks whether the target IP address is within any BGP prefixes for which a query has
-- already been performed and returns a pointer to the HOST SCRIPT RESULT displaying the applicable answers.
-- @param ip String representing the target IP address.
-- @return   Boolean true if there are cached answers for the supplied target,es = {"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))
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 cormation from an Apache Hadoop TaskTracker HTTP status page.

Information gathered:
* Hadoop version
* Hadoop Compile date
* Log directory (relative to http://host:port/)
]]

---
-- @usage
-- nmap --script hadoop-tasktracker-info -p 50060 host
--
-- @output
-- PORT      STATE SERVICE            REASON
-- 50060/tcp open  hadoop-tasktracker syn-ack
-- | hadoop-tasktracker-info:
-- |   Version: 0.20.1 (f415ef415ef415ef415ef415ef415ef415ef415e)
-- |   Compiled: Wed May 11 22:33:44 PDT 2011 by bob from unknown
-- |_  Logs: /logs/
--
-- (presumably received from a telnet server)
-- indicates a failed login
--
-- @param str The string to analyze
-- @return Verdict (true or false)
local is_login_failure = function (str)
  local lcstr = str:lower()
  return lcstr:find("%f[%w]incorrect%f[%W]")
      or lcstr:find("%f[%w]failed%f[%W]")
      or lcstr:find("%f[%w]denied%f[%W]")
      or lcstr:find("%f[%w]invalid%f[%W]")
      or lcstr:find("%f[%w]bad%f[%W]")
end

Driver = {

  -- creates a new Driver instance
  -- @param host table as received by the action function
  -ates over the credentials and attempts to run
the command for each available set of credentials.

NOTE: The "owner" field in the results will be truncated at 20 characters. This
is a limitation of the <code>sp_MShasdbaccess</code> stored procedure that the
script uses.

NOTE: Communication with instances via named pipes depends on the <code>smb</code>
library. To communicate with (and possibly to discover) instances via named pipes,
the host must have at least one SMB port (e.g. TCP 445) that was scanned and
found to be open. Additinvite request and listens for responses.
-- @arg session SIP Session to use.
-- @arg ua User Agent to use.
-- @arg from SIP From field.
-- @arg src Request source address to spoof.
-- @arg extension Request SIP extension.
-- @arg timeout Max time to wait for responses other than ringing.
-- @return ringing True if we got a ringing response, false else.
-- @return responsecode Code for the latest meaningful response.
--  could be 180, 200, 486, 408 or 603
local invitespoof = function(session, ua, from, src, extension, timeout)

  lndle   The handle to the hive (HKLM or HKU, for example).
--@param key      The full path of the key to retrieve (like <code>"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"</code>).
--@param value    The value to retrieve (like <code>"NUMBER_OF_PROCESSORS"</code>).
--@return Status (true or false).
--@return The value (if status is true) or an error string (if status is false).
local function reg_get_value(smbstate, handle, key, value)
  -- Open the key
  local status, openkey_result = msrpc.winreg_openkey(smbsta"SRV", data="", ttl=0 } )
--

-- Version 0.2

-- Created 01/09/2011 - v0.1 - created by Patrik Karlsson <patrik@cqure.net>
-- Revised 01/10/2011 - v0.2 - added test function <patrik@cqure.net>


portrule = shortport.port_or_service( 53, "dns", {"udp", "tcp"} )

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.debug1("SUCCESS") else stdnse.debug1("FAIL: " .. (err or "")) end
  status, err = dns.update( "www2", { zals, account expired
-- |   disabled.user:disabled1 => Valid credentials, account disabled
-- |_  must.change:need2change => Valid credentials, password must be changed at next logon
--
-- @args ldap.base If set, the script will use it as a base for the password
--       guessing attempts. If both ldap.base and ldap.upnsuffix are unset the user
--       list must either contain the distinguished name of each user or the server
--       must support authentication using a simple user name. See the AD discussion
--       in the descr    -- packet type
    2+2+1+game_name:len()+1+1, -- packet length
    ccreq_server_info,         -- operation code
    game_name,
    net_protocol_released)     -- net protocol version
  -- iptables -m u32 --u32 '0x1c=0x8000000c&&0x20=0x02515541&&0x24=0x4b450003'

  local status, rep_pl = comm.exchange(host, port, req_pl)
  assert_w_table(status, "No response to request for server info")
  assert_w_table(#rep_pl >= 4, "Response too small for packet header")

  nmap.set_port_state(host, port, 'open')
  server_info.server_ratio = stdata)
      rte.prefix = ipOps.str_to_ip(ip, 'inet6')
      return rte
    end,

    -- Converts a RTE instance to string
    -- @return string of bytes to send to the server
    __tostring = function(self)
      local ipstr = ipOps.ip_to_str(self.prefix)
      assert(16 == #ipstr, "Invalid IPv6 address encountered")
      return ipstr .. string.pack(">I2 BB", self.tag, self.prefix_len, self.metric)
    end,


  },

  -- The Request class contains functions to build a RIPv2 Request
  Request = {

    -- Creates a new Request instan,
    scores = {
      CVSSv2 = "7.1 (HIGH) (AV:N/AC:M/AU:N/C:N/I:N/A:C)",
    },
    description = [[
The SIP inspection engine in Cisco Adaptive Security Appliance (ASA) Software 8.2 before 8.2(5.48), 8.4 before 8.4(6.5), 9.0 before 9.0(3.1), and 9.1 before 9.1(2.5) allows remote attackers to cause a denial of service (memory consumption or device reload) via crafted SIP packets, aka Bug ID CSCuh44052.
    ]],

    references = {
      'http://tools.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-20140409-asa',
 esult = msrpc.svcctl_startservicew(smbstate, open_service_result['handle'], strsplit(" ", "install software-update 1 " .. webexec_command))
  if not status then
    vuln.check_results = "Could not start WebExService"
    return report:make_output(vuln)
  end

  -- We need some time for the service to run then stop again before we continue
  stdnse.sleep(1)

  -- Try and get a handle to the service with zero permissions
  stdnse.debug1("Checking if the test service exists")
  local test_status, test_result = msrpc.svcctl_openserviceWindows 2000 systems is vulnerable to denial of service caused by a null deference
--|       pointer. This script will crash the service if it is vulnerable. This vulnerability was discovered by Ron Bowes
--|       while working on smb-enum-sessions.
--|_
---

author = {"Ron Bowes", "Jiayi Ye", "Paulino Calderon <calderon()websec.mx>"}
copyright = "Ron Bowes"
license = "Same as Nmap--See https://nmap.org/book/man-legal.html"
categories = {"intrusive","exploit","dos","vuln"}
-- run after all smb-* scripts (so if it DOES crash somethbug1("Failed to send: %s", err)
    return nil
  end

  local asdu_address
  local ioas = 0
  -- Have to draw the line somewhere.
  local limit = 10
  while limit > 0 do
    limit = limit - 1
    apcitype, recv = get_asdu(socket)
    if not apcitype then
      stdnse.debug1("Error in C_IC_NA_1: %s", recv)
      break
    end
    if apcitype & 0x01 == 0 then -- Type I, numbered information transfer
      -- skip 2 bytes Tx, 2 bytes Rx
      local typeid = recv:byte(5)
      if typeid == 70 then
        -- ME_EI_NA_1, End of Initiali the NFS file system and close the connections
local function unmount_nfs(mount, mnt_obj, nfs_obj)
  rpc.Helper.NfsClose(nfs_obj)
  rpc.Helper.UnmountPath(mnt_obj, mount)
end

local function nfs_ls(nfs, mount, output)
  local dirs, attr, acs = {}, {}, {}
  local nfsobj = rpc.NFS:new()
  local mnt_comm, nfs_comm, fhandle

  mnt_comm, fhandle = procedures.MountPath(nfs.host, mount)
  if mnt_comm == nil then
    ls.report_error(output, fhandle)
    return false
  end

  local nfs_comm, status = procedures.NfsOpen(nfs.host)
  if nfs_cormation
local function vendor_lookup(vennum)
	return vendor_id[vennum] or "Unknown Vendor Number"
end

--  Table to look up the Device Type based on Device ID Number
--    Returns "Unknown Device Type" if Device ID Number not recognized
--  Table data from Wireshark dissector ( link to unofficial mirror )
--  https://github.com/avsej/wireshark/blob/master/epan/dissectors/packet-enip.c
--  Fetched on 4/19/2014
--
-- key is Device ID  number parsed out of the EtherNet/IP packet
local device_type = {
	[0] = "Generic Device (deprecatedational Transportation Corp",
	[464] = "Huettinger Elektronik GmbH + Co. KG",
	[465] = "OCM Technology Inc.",
	[466] = "Professional Supply Inc.",
	[467] = "Control Solutions",
	[468] = "Baumer IVO GmbH & Co. KG",
	[469] = "Worcester Controls Corporation",
	[470] = "Pyramid Technical Consultants Inc.",
	[471] = "Eilersen Electric A/S",
	[472] = "Apollo Fire Detectors Limited",
	[473] = "Avtron Manufacturing Inc.",
	[474] = "Reserved",
	[475] = "Tokyo Keiso Co.Ltd.",
	[476] = "Daishowa Swiki Co.Ltd.",
	[477] = "Kojima Instruments In[134] = "TR Systemtechnik GmbH",
	[135] = "UNIPULSE Corporation",
	[136] = "Reserved",
	[137] = "Reserved",
	[138] = "Conxall Corporation Inc.",
	[139] = "Reserved",
	[140] = "Reserved",
	[141] = "Kuramo Electric Co.Ltd.",
	[142] = "Creative Micro Designs",
	[143] = "GE Industrial Systems",
	[144] = "Leybold Vacuum GmbH",
	[145] = "Siemens Energy & Automation/Drives",
	[146] = "Kodensha Ltd",
	[147] = "Motion Engineering Inc.",
	[148] = "Honda Engineering Co.Ltd",
	[149] = "EIM Valve Controls",
	[150] = "Melec Inc.",
	[151] = "Sonyption = [[
Connects to a dictionary server using the DICT protocol, runs the SHOW
SERVER command, and displays the result. The DICT protocol is defined in RFC
2229 and is a protocol which allows a client to query a dictionary server for
definitions from a set of natural language dictionary databases.

The SHOW server command must be implemented and depending on access will show
server information and accessible databases. If authentication is required, the
list of databases will not be shown.
]]

---
-- @usage
-- nmap -p 2628 <ip> ,
    { ["FIPS 140-1"] = 16 }
  }

  local ENC_LEVELS = {
    [0] = "None",
    [1] = "Low",
    [2] = "Client Compatible",
    [3] = "High",
    [4] = "FIPS Compliant",
  }

  local res_ciphers = {}
  local proto_version

  local function get_ordered_ciphers()
    local i = 0
    return function()
      i = i + 1
      if ( not(CIPHERS[i]) ) then  return end
      for k,v in pairs(CIPHERS[i]) do
        return k, v
      end
    end
  end

  for k, v in get_ordered_ciphers() do
    -- Prevent reconnecting too quickly, improves relost>
-- nmap -p 1433 --script ms-sql-info --script-args mssql.instance-port=1433 <host>
--
-- @output
-- | ms-sql-info:
-- |   Windows server name: WINXP
-- |   192.168.100.128\PROD:
-- |     Instance name: PROD
-- |     Version:
-- |       name: Microsoft SQL Server 2000 SP3
-- |       number: 8.00.760
-- |       Product: Microsoft SQL Server 2000
-- |       Service pack level: SP3
-- |       Post-SP patches applied: No
-- |     TCP port: 1278
-- |     Named pipe: \\192.168.100.128\pipe\MSSQL$PROD\sql\query
-- |     Clustered: No
ttp methods if requested
  if retest_http_methods then
    output["Status Lines"] = {}
    for _, method in ipairs(methods) do
      local str
      if method == "OPTIONS" then
        -- Use the saved value.
        str = options_status_line
      elseif tableaux.contains(to_test, method) then
        -- use the value saved earlier.
        str = status_lines[method]
      -- this case arises when methods in the Public or Allow headers are retested.
      else
        response = http.generic_request(host, port, method, path)
     ocket("udp")
  socket:set_timeout(stdnse.get_timeout(host))
  socket:connect(host, port)
  local status, lhost, lport, rhost, rport = socket:get_info()

  -- Generate a Read Request.
  local req = (">Hzz"):pack(tftp.OpCode.RRQ, path, "octet")

  -- Send the Read Request.
  socket:sendto(host, port, req)
  socket:close()

  -- Listen for a response, but if nothing comes back we have to assume that
  -- this is not a TFTP service and exit quietly.
  --
  -- We don't have to worry about other instance of this script running on other
 rn
  end

  -- We are only interested in capturing the TLS responses from the
  -- server, not our traffic. We need to set the snaplen to be fairly
  -- large to accommodate packets with many or large certificates.
  local filter = ("src host %s and tcp and src port %d and dst port %d"):format(host.ip, port.number, lport)
  local pcap = nmap.new_socket()
  pcap:set_timeout(5)
  pcap:pcap_open(host.interface, 4096, false, filter)

  -- Initiate the TLS negotiation on the already-connected socket, and
  -- then immediately close the with "\r?\n\r?\n".
  --            Does not require captures.
  --
  -- The remaining key-value pairs for each object should conform to the following:
  -- key:    is a short name for the field in a whois record and which will be displayed in the scripts output to identify the field.
  -- value:  is a pattern for the field and contains a capture for the data required to be captured.

  nmap.registry.whois.fields_meta = {
    rpsl = {
      ob_exist =  "\r?\n?%s*[Ii]net6?num:%s*.-\r?\n",
      ob_netnum = {
        ob_start = "\r?\nna
  else
    iana_count = 0
  end

  if not meta or not meta.redirects then
    return found, redirect, iana_count
  end

  ---
  -- Decides the value of a redirect and whether it should be followed.  Referrals to IANA, found in whois records that represent the
  -- "Whole Address Space",  are acted upon by redirecting to ARIN or accepting the record from ARIN if it was previously queried.  This
  -- function also catches (ignores) referrals to the referring service - which happens as a side-effect of the method of redirection detreturn data

end



---
-- Extracts Whois record objects (or a single object) and accompanying fields from the supplied (possibly partial) response to a whois query.
-- If a fifth parameter specific_object is not supplied, all objects defined in fields_meta will be captured if they are present in the response.
-- @param response_string  String obtained from a service in response to our query.
-- @param db               String id of the whois service queried.
-- @param meta             Table, nmap.registry.whois.whoisdb[db] where dbparam ip        String representing the Target's IP address.
-- @param addr_fam  String representing the Target's IP address family.
-- @return          The supplied and possibly modified tracking table.
-- @see             tracking, check_response_cache, get_db_from_assignments

function get_next_action( tracking, ip, addr_fam )

  if type( ip ) ~= "string" or ip == "" or type( tracking ) ~= "table" or type( tracking.completed ) ~= "table" then return nil end

  --next_db should always be nil when calling this
  if tracking.next_deturn "\n" .. tab.dump(output)
end
description = [[
Checks if the website holds a mobile version.
]]

---
-- @usage nmap -p80 --script http-mobileversion-checker.nse <host>
--
-- This script sets an Android User-Agent header and checks if the request
-- will be redirected to a page different than a (valid) browser request
-- would be. If so, this page is most likely to be a mobile version of the
-- app.
--
-- @args newtargets If this is set, add any newly discovered hosts to nmap
--                  scanning queue. Default: nil
--
and we are searching for specific text, do the search
  found   = false
  if(mod.find and #mod.find > 0 and not(removed)) then
    -- Make a single string a table to save duplicate code
    if(type(mod.find) ~= 'table') then
      mod.find = {mod.find}
    end

    -- Loop through the module's find table to see if any of the lines match
    for _, find in ipairs(mod.find) do
      if(string.match(line, find)) then
        found = true
        break
      end
    end
  else
    found = true
  end

  -- Only display the line if it's filename_full
end

---Generate an array of all files that will be uploaded/created, including
-- the temporary file and the output file. This is done so the files can
-- all be deleted during the cleanup phase.
--
--@param config The config table.
--@return The array of files.
local function get_all_files(config)
  local files = {config.service_file, config.output_file, config.temp_output_file}
  for _, mod in ipairs(config.enabled_modules) do
    -- We're going to delete the module itself
    table.insert(files, mod.upload_name)

 |  |_ Reply from 10.0.0.138: bytes=32 time<10ms TTL=64
-- |  |  Traceroute back to the scanner
-- |  |  |_   1   <10 ms   <10 ms   <10 ms  10.0.0.138
-- |  |  ARP Cache from arp.exe
-- |  |  |    Internet Address      Physical Address      Type
-- |  |  |_   10.0.0.138            00-50-56-a1-27-4b     dynamic
-- |  |  List of listening and established connections (netstat -an)
-- |  |  |    Proto  Local Address          Foreign Address        State
-- |  |  |    TCP    0.0.0.0:22             0.0.0.0:0              LISTENING
-- |  AC Address
|  | Ethernet adapter Local Area Connection:
|  |    MAC Address: 00:0C:29:12:E6:DB
|  |_   IP Address: 192.168.1.21|  Example 3: IP Address and MAC Address
</code>

Another interesting part of this script is that variables can be used in any
script fields. There are two types of variables: built-in and user-supplied.
Built-in variables can be anything found in the <code>config</code> table,
most of which are listed below. The more interesting ones are:

* <code>$lhost</code>: The address of the scanner
* <code>$rhost</cm key="DNS_Tree_Name">somedomain.com</elem>
-- <elem key="Product_Version">6.1.7601</elem>


author = "Justin Cacak"
license = "Same as Nmap--See https://nmap.org/book/man-legal.html"
categories = {"default", "discovery", "safe"}


local ntlm_auth_blob = base64.enc( select(2,
  smbauth.get_security_blob(nil, nil, nil, nil, nil, nil,
    0x00000001 + -- Negotiate Unicode
    0x00000002 + -- Negotiate OEM strings
    0x00000004 + -- Request Target
    0x00000200 + -- Negotiate NTLM
    0x00008000 + -- Negotiate Always Sign
    0x0008ers on a certain interface
local LLTDDiscover = function(if_table, lltd_responders, timeout)
  local timeout_s = 3
  local condvar = nmap.condvar(lltd_responders)
  local pcap = nmap.new_socket()
  pcap:set_timeout(5000)

  local dnet = nmap.new_dnet()
  local try = nmap.new_try(function() dnet:ethernet_close() pcap:close() end)

  pcap:pcap_open(if_table.device, 256, false, "")
  try(dnet:ethernet_open(if_table.device))

  local packet = QuickDiscoveryPacket(if_table.mac)
  try( dnet:ethernet_send(packet) )
  stdnse.sleep(0.5)
  tessage id, response status and sequence number
  -- abort if no response
  local _, _, _, res_status, _ = string.unpack(">BBBBI2", response, 1)
  if (res_status ~= 0) then
    stdnse.debug(1, "#- command 84 Read Sub-Device Identity Summary response - FAIL.")
    output['Device Information'] = deviceInfo
    return output
  end
  stdnse.debug(1, "#- command 84 Read Sub-Device Identity Summary response - SUCCESS.")

  --- get sub-device information from Command 84
  local subDeviceInfo = stdnse.output_table()

  -- get response code
 has an actual version for this, no need to send more probes and decode.
    not (port.version and port.version.version and port.version.version ~= "")
    -- Otherwise, normal checking for port numbers etc.
    and shortport.version_port_or_service({1521,1522,1523}, "oracle-tns")(host, port)
    )
end

-- Lifted from nmap-service-probes
-- TODO: Figure out if we can send a better probe than this. We might need to
--       send ADDRESS, CID, etc.
local oracle_tns_probe = "\0Z\0\0\x01\0\0\0\x016\x01,\0\0\x08\0\x7F\xFF\x7F\x08\0\0\0\ 1] = "Version of stylesheet: " .. table.concat(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 table.concat(output_lines, "\n")
  end
end
local comm = require 'comm'
local string = require 'string'
local stdnse = require 'stdnse'
local shortport = require 'shortport'

description = [[
Check if the Secure Socket Tunneling Protocol is supported. This is
ac00,0x00,0x00)


-- The Rules
portrule = shortport.port_or_service(34964, "profinet-cm", "udp")
if not nmap.is_privileged() then
    stdnse.debug(1, "Nmap is NOT running as privileged.")
    portrule = nil
    prerule = function() return false end
end

-- The Action

---
-- Parses the EPM Lookup Response extracting the annotation field containing the
-- product name and the article number of the scanned PNIO Device
---
parse_response = function(host, port, layer3)
  -- print raw bytes of reponse
  stdnse.debug(2, "Raw hex: %s", stdnmatch("Quorum</td><td>([^][<]+)"):gsub("%s+", " ")
    stdnse.debug1("Zookeeper Quorum %s",quorum)
    result["Zookeeper Quorum"] = quorum
    if target.ALLOW_NEW_TARGETS then
      if quorum:match("([%w%.]+)") then
        local newtarget = quorum:match("([%w%.]+)")
        stdnse.debug1("Added target: %s", newtarget)
        local status,err = target.add(newtarget)
      end
    end
  end
  for line in string.gmatch(body, "[^\n]+") do
    stdnse.debug3("Line %s\n",line)
    if line:match("maxHeap") then
      local region_server=se.body then
    local status, parsed = json.parse(response.body)
    if not(status) then
      stdnse.debug1('Parsing JSON failed(version checking). Probably not running Elasticsearch')
      return nil
    else
      if parsed.version.number then
          --check if a vulnerable version is running
          if (tostring(parsed.version.number):find('1.3.[0-7]') or tostring(parsed.version.number):find('1.4.[0-2]')) then
            vuln_table.state = vulns.STATE.LIKELY_VULN
          end
          --help the version/service detectebug1("IGMP version %s doesn't exist.", version)
    return
  end

  -- Let's craft an IGMP Membership Query
  local igmp_raw = string.pack(">BB I2 I4",
    0x11, -- Membership Query, same for all versions
    version == 1 and 0 or 0x16, -- Max response time: 10 Seconds, for version 2 and 3
    0, -- Checksum, calculated later
    0  -- Multicast Address: 0.0.0.0
    )

  if version == 3 then
    igmp_raw = igmp_raw .. string.pack(">BB I2",
      0, -- Reserved = 4 bits (Should be zeroed)
      -- Supress Flag = 1 bit
      -- QRV 
  [15] = "CEN",
  [16] = "Sound System",
  [17] = "Scenario Programming",
  [18] = "Energy Management",
  [24] = "Lighting Management",
  [25] = "CEN plus",
  [1000] = "Diagnostic",
  [1001] = "Automation Diagnostic",
  [1004] = "Heating Diagnostic",
  [1008] = "Door Entry System Diagnostic",
  [1013] = "Device Diagnostic"
}

local device_dimension = {
  ["Time"] = "0",
  ["Date"] = "1",
  ["IP Address"] = "10",
  ["Net Mask"] = "11",
  ["MAC Address"] = "12",
  ["Device Type"] = "15",
  ["Firmware Version"] = "16",
  ["Hardware Vetection it can augment the
standard nmap version detection information with data that this script has discovered.

Retrieving the name and operating system of a server is a vital step in targeting
an attack against it, and this script makes that retrieval easy. Additionally, if
a penetration tester is choosing between multiple targets, the time can help identify
servers that are being poorly maintained (for more information/random thoughts on
using the time, see http://www.skullsecurity.org/blog/?p=76.

Although the standard <codeame=<username>,password=<password>]'
--
-- @output
-- PORT     STATE SERVICE
-- 3306/tcp open  mysql
-- | mysql-query:
-- |   host       user
-- |   127.0.0.1  root
-- |   localhost  debian-sys-maint
-- |   localhost  root
-- |   ubu1110    root
-- |
-- |   Query: SELECT host, user FROM mysql.user
-- |_  User: root
--
-- @args mysql-query.query the query for which to return the results
-- @args mysql-query.username (optional) the username used to authenticate to the database server
-- @args mysql-query.password (optional) the passwit results:
-- |       The backdoor was already triggered
-- |       Shell command: id
-- |       Results: uid=0(root) gid=0(root) groups=0(root)
-- |     References:
-- |       https://www.securityfocus.com/bid/48539
-- |       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2011-2523
-- |       http://scarybeastsecurity.blogspot.com/2011/07/alert-vsftpd-download-backdoored.html
-- |_      https://github.com/rapid7/metasploit-framework/blob/master/modules/exploits/unix/ftp/vsftpd_234_backdoor.rb
--

author = "Daniel Miller"
liclename .. ".tar.bz2")



  return variations
end

-- simplify unlocking the mutex, ensuring we don't try to parse again, and returning an error.
local function bad_prints(mutex, err)
  nmap.registry.http_fingerprints = err
  mutex "done"
  return false, err
end

---Get the list of fingerprints from files. The files are defined in <code>fingerprint_files</code>. If category
-- is non-nil, only choose scripts that are in that category.
--
--@return An array of entries, each of which have a <code>checkdir</code> field, and possibly a ion = "Unfiltered ' (apostrophe). An indication of potential XSS vulnerability." },
}


-- Create customized requests for all of our payloads.
local makeRequests = function(host, port, submission, fields, fieldvalues)

  local postdata = {}
  for _, p in ipairs(payloads) do
    for __, field in ipairs(fields) do
      if field["type"] == "text" or field["type"] == "textarea" or field["type"] == "radio" or field["type"] == "checkbox" then

        local value = fieldvalues[field["name"]]
        if value == nil then
          value hrough cookies.")
          bigip.detected = true
          return
        end
      end
    end
  end,
  intensive = function(host, port, root, responses)
  end,
}

local webknight
webknight = {
  name = "Webknight",
  detected = false,
  version = nil,

  match = function(responses)
    for name, response in pairs(responses) do
      if response.header.server and string.find(response.header.server, 'WebKnight/') then --
        stdnse.debug1("WebKnight detected through Server Header.")
        webknight.version = string.sub(respo"] = "Windows 2012 R2"

portrule = shortport.port_or_service({389,636}, {"ldap","ldapssl"},{'tcp','udp'})

function action(host,port)
  local status, searchResEntries, req, result, opt

  if port.protocol == 'tcp' then

    local socket = nmap.new_socket()

    -- 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 = "\x30\x0c\x02\x01\x01\x60\x07\x02\x01\x03\x04\x00\x80\x00"
    local _
    socket, _, opt = comm.tryssl( hosm-enum.command="exit;logon applid(logos)",vtam-enum.macros=true
-- vtam-enum.path="/home/dade/screenshots/" -p 23 -sV <targets>
--
--@output
-- PORT   STATE SERVICE VERSION
-- 23/tcp open  tn3270  IBM Telnet TN3270
-- | vtam-enum:
-- |   VTAM Application ID:
-- |     applid:TSO - Valid credentials
-- |     applid:CICSTS51 - Valid credentials
-- |_  Statistics: Performed 14 guesses in 5 seconds, average tps: 2
--
-- @changelog
-- 2015-07-04 - v0.1 - created by Soldier of Fortran
-- 2015-11-04 - v0.2 - significant upgrades and speed -END CERTIFICATE REQUEST%-%-%-%-%-")
  string.gsub(csr_b64, "\n", "")
  local decoded_csr = base64.dec(csr_b64)
  return string.find(decoded_csr, node)
end


action = function(host, port)
  local puppet_table = {
    "Puppet Naive autosigning enabled! Naive autosigning causes the Puppet CA to autosign ALL CSRs.",
    "Attackers will be able to obtain a configuration catalog, which might contain sensitive information."
  }
  local scan_success = false
  local options = {}
  options['header'] = {}

  -- parse args
  local node = stdn dtype="SRV", retAll=true, retPkt=true } )
    for host, port, prio, weight in parseSrvResponse(resp) do
      if target.ALLOW_NEW_TARGETS then
        target.add(host)
      end
      local proto = query:sub(-3)
      tab.addrow(svc_result, ("%d/%s"):format(port, proto), prio, weight, host)
    end
  end
  if ( #svc_result ~= 1 ) then
    table.insert(result, { name = name, tab.dump(svc_result) })
  end
  condvar "signal"
end

action = function(host)

  local services = {
    { name = "Active Directory Global Catalog", query = {"_ult
end

--- Converts a 6 byte string into the familiar MAC address formatting
--
-- @param mac string containing the MAC address
-- @return formatted string suitable for printing
function get_mac_addr( mac )
  local catch = function() return end
  local try = nmap.new_try(catch)
  local mac_prefixes = try(datafiles.parse_mac_prefixes())

  if mac:len() ~= 6 then
    return "Unknown"
  else
    local prefix = string.upper(string.format("%02x%02x%02x", mac:byte(1), mac:byte(2), mac:byte(3)))
    local manuf = mac_prefixes[prefix] or     info.channels[channel.CID] = channel
    end
  end

  -- clients
  pos, info.clientcount = str_find(data, "CLIENTCOUNT: ([^\n]*)", pos)
  pos, info.clientfields = str_find(data, "CLIENTFIELDS: ([^\n]*)", pos)

  -- construct client fields as a nice list instead of the raw data
  local clientfields = {}
  for clientfield in string.gmatch(info.clientfields, "[^,\n]+") do
    clientfields[#clientfields + 1] = clientfield
  end
  info.clientfields = clientfields

  -- parse and add clients
  while string.sub(data, pos + 2, pos + 9ons }
    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(brute.new_socket())
  end,

  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 )
   . string.char(pkt_len) .. req_id
  buf = buf .. '\000\000\000\001\000\000\000\000\000\000'
  buf = buf .. name .. '\000\252\000\001'
  try(soc:send(strbuf.dump(buf)))

  -- read all data returned. Common to have
  -- multiple packets from a single request
  local response = strbuf.new()
  while true do
    local status, data = soc:receive_bytes(1)
    if not status then break end
    response = response .. data
  end
  soc:close()

  local response_str = strbuf.dump(response)
  local length = #response_str

  -- check server respon flags, service, regexp, replacement)
  end,
  KX = parse_num_domain,
  --CERT
  A6 = function(data, offset) -- obsoleted by AAAA
    local prefix, addr, name
    prefix = string.byte(data, offset)
    local pbytes = prefix >> 3
    addr = ipOps.str_to_ip(string.rep("\000", pbytes) .. data:sub(offset+1, 16-pbytes))
    offset, name = parse_domain(data, offset + 17 - pbytes)
    return offset, string.format("%d %s %s", prefix, addr, name)
  end,
  DNAME = parse_domain,
  SINK = function(data, offset) -- https://tools.ietf.org/html/ds 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.debug1("No credentials supplied, aborting ...")
    return
  end

  --
  -- Iterates over credentials, breaks once it successfully receives results
  --
  for username, password in pairs(users) do

    try( socket:connect(host, port) )

    response = try( mysql.receiveGreeting( socket ) )
    status, response = mysql.loginRequest( socket, { authversion = "post41", charset = res.outfile Output file
-- @args http-axis2-dir-traversal.basepath Basepath to the services page. Default: <code>/axis2/services/</code>

author = "Paulino Calderon <calderon@websec.mx>"
license = "Same as Nmap--See https://nmap.org/book/man-legal.html"
categories = {"vuln", "intrusive", "exploit"}


portrule = shortport.http

--Default configuration values
local DEFAULT_FILE = "../conf/axis2.xml"
local DEFAULT_PATH = "/axis2/services/"

---
--Checks the given URI looks like an Apache Axis2 installation
-- @param host Host table
-- @p = name .. ": " .. id
        stdnse.debug1("found id:" .. result[#result])
        add_key_to_registry(host, port, url_path, result[#result])
        ids[id] = true
      end
    end
  end

  return stdnse.format_output(true, result)
end

--- iterate over the list of gathered ids and look for related sites (sharing the same siteids)
local function postaction()
  local siteids = {}
  local output = {}

  -- create a reverse mapping affiliate ids -> site(s)
  for site, ids in pairs(nmap.registry["http-affiliate-id"]) do
    for _, ie the form needs to be submitted
  local form_submission_path
  if action_absolute then
    form_submission_path = form["action"]
  else
    local path_cropped = string.match(path, "(.*/).*")
    path_cropped = path_cropped and path_cropped or ""
    form_submission_path = path_cropped..form["action"]
  end

  -- determine should the form be sent by post or get
  local sending_function
  if form["method"]=="post" then
    sending_function = function(data) return http.post(host, port, form_submission_path, nil, nil, data) end
  elsen = [[
Retrieves information (such as node name and architecture) from a Basho Riak distributed database using the HTTP protocol.
]]

---
-- @usage
-- nmap -p 8098 <ip> --script riak-http-info
--
-- @output
-- PORT     STATE SERVICE
-- 8098/tcp open  http
-- | riak-http-info:
-- |   Node name                  riak@127.0.0.1
-- |   Architecture               x86_64-unknown-linux-gnu
-- |   Storage backend            riak_kv_bitcask_backend
-- |   Total Memory               516550656
-- |   Crypto version             2.0.3
-- |   Skeose("Found accepted key: " .. publickeys[i] .. " for user " .. usernames[j] .. " on host " .. host.ip .. ":" .. port.number)
          elseif err then
            stdnse.debug("Error in publickey_canauth: %s", err)
          end
          helper:disconnect()
        else
          -- Allow 3 connection attempts, then bail
          failures = failures + 1
          stdnse.debug1("Connect failed.")
          if failures > 2 then
            if successes == 0 then
              -- If we haven't succeeded even once, don't report resul/19/2010 - v0.3 - removed debugging output and renamed file
-- Revised 04/11/2010 - v0.4 - moved snmp_walk to snmp library <patrik@cqure.net>


portrule = shortport.port_or_service(161, "snmp", "udp", {"open", "open|filtered"})

--- Gets a value for the specified oid
--
-- @param tbl table containing <code>oid</code> and <code>value</code>
-- @param oid string containing the object id for which the value should be extracted
-- @return value of relevant type or nil if oid was not found
function get_value_from_table( tbl, oid )

  foxt attempt.
  -- if we do not receive any valid status code,
  -- there is no reason to keep testing... the proxy is probably not open
  if not (get_cstatus or head_cstatus or conn_status) then return false, nil end
  stdnse.debug1("Test 1 - Google Web Server\nReceived valid status codes, but pattern does not match")

  test_url = "http://www.wikipedia.org"
  hostname = "www.wikipedia.org"
  pattern  = "wikimedia"
  get_status, get_r2, get_cstatus = proxy.test_get(host, port, "http", test_url, hostname, pattern)
  head_status, _, hle[TAG_FOCALLENGTH_35MM]      = "FocalLengthIn35mmFilm"
TagTable[TAG_SUBJECTAREA]           = "SubjectArea"
TagTable[TAG_SCENE_CAPTURE_TYPE]    = "SceneCaptureType"
TagTable[TAG_GAIN_CONTROL]          = "GainControl"
TagTable[TAG_CONTRAST]              = "Contrast"
TagTable[TAG_SATURATION]            = "Saturation"
TagTable[TAG_SHARPNESS]             = "Sharpness"
TagTable[TAG_DISTANCE_RANGE]        = "SubjectDistanceRange"
TagTable[TAG_IMAGE_UNIQUE_ID]       = "ImageUniqueId"

GPS_TAG_VERSIONID        = 0X00
GPS_TAG_LATITUDEREF   :new( "Incorrect password" )
      end
    end
  end
}

--- Tests the target to see if we can even get to TSO
--
-- @param host host NSE object
-- @param port port NSE object
-- @param commands script-args of commands to use to get to TSO
-- @return status true on success, false on failure
-- @return name of security product installed
local function tso_test( host, port, commands )
  stdnse.debug("Checking for TSO")
  local tn = tn3270.Telnet:new()
  tn:disable_tn3270e()
  local status, err = tn:initiate(host,port)
  local tso = faalse, "Couldn't download file: " .. body
  end

  -- Check if the file contains the proper XML
  if(string.find(string.lower(body), "configroot") == nil) then
    return false, "Server didn't return XML -- likely not vulnerable."
  end

  files = fake_xml_parse(body, "vmxcfgpath")

  if(#files == 0) then
    return true, {"No VMs appear to be installed"}
  end

  -- Process each of the .vmx files if verbosity is on
  --if(nmap.verbosity() > 1) then
  --  local result, file = get_file(host, port, files[1])
  --  io.write(nsedebug.togistry.args.oraclesids or nmap.fetchfile("nselib/data/oracle-sids")

  sidfile = io.open(sidfilename)

  if not sidfile then
    return
  end

  -- read sids line-by-line from the sidfile
  for sid in sidfile:lines() do

    -- check for comments
    if not sid:match("#!comment:") then

      try(socket:connect(host, port))
      request = create_connect_packet( host.ip, port.number, sid )
      try(socket:send(request))
      response = try(socket:receive_bytes(1))
      tns_packet = process_tns_packet(response)

      -- If we geICE REASON  VERSION
-- 5222/tcp open  jabber  syn-ack ejabberd (Protocol 1.0)
-- | xmpp-info:
-- |   Respects server name
-- |   info:
-- |     xmpp:
-- |       lang: en
-- |       version: 1.0
-- |     capabilities:
-- |       node: http://www.process-one.net/en/ejabberd/
-- |       ver: TQ2JFyRoSa70h2G1bpgjzuXb2sU=
-- |     features:
-- |       In-Band Registration
-- |     auth_mechanisms:
-- |       DIGEST-MD5
-- |       SCRAM-SHA-1
-- |       PLAIN
-- |   pre_tls:
-- |     features:
-- |_      TLS
--@xmloutput
-- <elem>Respecttes over the
--       available namingContexts
-- @args ldap.attrib If set, the search will include only the attributes
--       specified. For a single attribute a string value can be used, if
--       multiple attributes need to be supplied a table should be used
--       instead.
-- @args ldap.maxobjects If set, overrides the number of objects returned by
--       the script (default 20).  The value -1 removes the limit completely.
-- @args ldap.savesearch If set, the script will save the output to a file
--       beginning withre vulnerable. This script sends 3 harmless
YAML payloads to detect vulnerable installations. If the malformed object
receives a status 500 response, the server is processing YAML objects and
therefore is likely vulnerable.

References:
* https://community.rapid7.com/community/metasploit/blog/2013/01/10/exploiting-ruby-on-rails-with-metasploit-cve-2013-0156',
* https://groups.google.com/forum/?fromgroups=#!msg/rubyonrails-security/61bkgvnSGTQ/nehwjA8tQ8EJ',
* http://cvedetails.com/cve/2013-0156/
]]

---
-- @usage
-- nmap -sV --scrilocal target = require "target"
local coroutine = require "coroutine"
local string = require "string"

description = [[
Performs network discovery and routing information gathering through
Cisco's Enhanced Interior Gateway Routing Protocol (EIGRP).

The script works by sending an EIGRP Hello packet with the specified Autonomous
System value to the 224.0.0.10 multicast address and listening for EIGRP Update
packets. The script then parses the update responses for routing information.

If no A.S value was provided by the user, the sc = {
    header = {
      Range = "bytes=0-100",
      Connection = "close"
    },
    bypass_cache = true
  }

  if hostname then
    request_opts.header.Host = hostname
  end

  local response = http.head(host, port, path, request_opts)

  if not response.status then
    stdnse.debug1("Functionality check HEAD request failed for %s (with path '%s').", hostname or host.ip, path)
  elseif response.status == 206 then
    -- The server handle range requests. Now try to request 11 ranges (one more
    -- than allowed).
    -- Vulnerab)
  results["Version"] = val

  return results
end
local brute = require "brute"
local creds = require "creds"
local math = require "math"
local shortport = require "shortport"
local sip = require "sip"
local stdnse = require "stdnse"

description = [[
Performs brute force password auditing against Session Initiation Protocol
(SIP) accounts. This protocol is most commonly associated with VoIP sessions.
]]

---
-- @usage
-- nmap -sU -p 5060 <target> --script=sip-brute
--
-- PORT     STATE         SERVICE
-- 5060/udp open|filtered siocal collect_interfaces = function (if_table)
    if if_table and if_table.up == "up" and if_table.link=="ethernet" then
      interfaces[if_table.device] = if_table
    end
  end
  stdnse.get_script_interfaces(collect_interfaces)

  if not next(interfaces) then return fail("Failed to retrieve interfaces (try setting one explicitly using -e)") end

  local transaction_id = math.random(0, 0x7F000000)

  local threads = {}
  local result = {}
  local condvar = nmap.condvar(result)

  -- start a listening thread for each interface
  f -- src mac
      .. "\x08\x00" -- ethertype IPv4
      .. icmp.buf -- data
      )

    try( dnet:ethernet_send(ethernet_icmp) )
  end

  local start_time = nmap.clock_ms()
  local now = start_time
  while( now - start_time < timeout ) do
    pcap:set_timeout(timeout - (now - start_time))
    local status, plen, l2, l3data, _ = pcap:pcap_receive()
    if not status then break end

    -- Do stuff with packet
    local icmpreply = packet.Packet:new(l3data,plen,false)
    if icmpreply then
      -- We check whether the packet is parcket()

  -- 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)

  try( socket:connect(host, port) )

  -- ugliness 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- @see dhcp-discover.nse
--
-- @usage
-- nmap -6 --script broadcast-dhcp6-discover
--
-- @output
-- | broadcast-dhcp6-discover:
-- |   Interface: en0
-- |     Message type: Advertise
-- |     Transaction id: 74401
-- |     Options
-- |       Client identifier: MAC: 68:AB:CD:EF:AB:CD; Time: 2012-01-24 20:36:48
-- |       Server identifier: MAC: 08:FE:DC:BA:98:76; Time: 2012-01-20 11:44:58
-- |       Non-temporary Address: 2001:db8:1:2:0:0:0:1000
-- |       DNS Servers: 2001:db8:0:0:0:0:0:35
-- |       Domain Search: example.com, subsnoop.mode which of two supported snooping methods to
-- use. <code>nonrecursive</code>, the default, checks if the server
-- returns results for non-recursive queries. Some servers may disable
-- this. <code>timed</code> measures the difference in time taken to
-- resolve cached and non-cached hosts. This mode will pollute the DNS
-- cache and can only be used once reliably.
-- @args dns-cache-snoop.domains an array of domain to check in place of
-- the default list.
--
-- @usage
-- nmap -sU -p 53 --script dns-cache-snoop.nse --sct("%s!%s@[%s]", domain, to, ip)
    },
    {
      from = string.format("%s@[%s]", from, ip),
      to = string.format("%s!%s@%s", domain, to, srvname)
    },
  }

  -- This function is used when something goes wrong with the connection.
  -- It makes sure that if it found working combinations before the error
  -- occurred, they will be returned. If the debug flag is enabled the
  -- error message will be appended to the combinations list.
  local failure = function(message)
    if #result > 0 then
      table.insert(result, messaories = {"safe", "discovery"}


portrule = shortport.http

action = function(host, port)

  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'
  }

  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[m key="region">Philadelphia, PA</elem>
-- <elem key="country">United States</elem>
--
-- @see ip-geolocation-geoplugin.nse
-- @see ip-geolocation-ipinfodb.nse
-- @see ip-geolocation-map-bing.nse
-- @see ip-geolocation-map-google.nse
-- @see ip-geolocation-map-kml.nse

author = "Gorjan Petrovski"
license = "Same as Nmap--See https://nmap.org/book/man-legal.html"
categories = {"discovery","external","safe"}

local function get_db_file()
  return (stdnse.get_script_args(SCRIPT_NAME .. ".maxmind_db") or
    nmap.fetchfile("nselib/data/isable Ad Hoc Distributed Queries
-- |       Replication XPs   0       0       Enable or disable Replication XPs
-- |     Linked Servers
-- |       srvname   srvproduct      providername
-- |       =======   ==========      ============
-- |_      MAC-MINI  SQL Server      SQLOLEDB
--

-- Created 04/02/2010 - v0.1 - created by Patrik Karlsson <patrik@cqure.net>
-- Revised 02/01/2011 - v0.2 - Added ability to run against all instances on a host;
--                 added compatibility with changes in mssql.lua (Chris Woodbury)

autho"

-- -*- mode: lua -*-
-- vim: set filetype=lua :

description = [[
Queries Microsoft SQL Server (ms-sql) instances for a list of databases, linked servers,
and configuration settings.

SQL Server credentials required: Yes (use <code>ms-sql-brute</code>, <code>ms-sql-empty-password</code>
and/or <code>mssql.username</code> & <code>mssql.password</code>)
Run criteria:
* Host script: Will run if the <code>mssql.instance-all</code>, <code>mssql.instance-name</code>
or <code>mssql.instance-port</code> script arguments are used (see ms result) If status is false, result is an error code; otherwise, result is either
--        <code>INFECTED</code> or <code>INFECTED2</code> for infected or <code>CLEAN</code> for not infected.
function check_conficker(host)
  local status, smbstate
  local bind_result, netpathcompare_result

  -- Create the SMB session
  status, smbstate = msrpc.start_smb(host, "\\\\BROWSER", true)
  if not status then
    return false, smbstate
  end

  -- Bind to SRVSVC service
  status, bind_result = msrpc.bind(smbstate, msrpc.SRVSVC_UUID, msrpc.match(csp_header,'report.to') then
      table.insert(output_info.Content_Security_Policy, "Description: Specifies a group (defined in Report-To header) to which the user agent sends reports about policy violation. ")
    end

  end

  if response.header['x-permitted-cross-domain-policies'] then
    output_info.X_Permitted_Cross_Domain_Policies = {}
    table.insert(output_info.X_Permitted_Cross_Domain_Policies, "Header: X-Permitted-Cross-Domain-Policies: " .. response.header['x-permitted-cross-domain-policies'])

    x_cross_domatable key="CVE-2017-0143">
-- <elem key="title">Remote Code Execution vulnerability in Microsoft SMBv1 servers (ms17-010)</elem>
-- <elem key="state">VULNERABLE</elem>
-- <table key="ids">
-- <elem>CVE:CVE-2017-0143</elem>
-- </table>
-- <table key="description">
-- <elem>A critical remote code execution vulnerability exists in Microsoft SMBv1&#xa; servers (ms17-010).&#xa;</elem>
-- </table>
-- <table key="dates">
-- <table key="disclosure">
-- <elem key="month">03</elem>
-- <elem key="year">2017</elem>
-- <elem key="day">14</elem> port, path)
  stdnse.debug2("Checking %swp-login.php ", path)
  local req = http.get(host, port, path.."wp-login.php", {no_cache=true})
  if req.status and req.status == 200 then
    return true
  end
  return false
end

---
--Writes string to file
--Taken from: hostmap.nse
--@param filename Target filename
--@param contents String to save
--@return true when successful
local function write_file(filename, contents)
  local f, err = io.open(filename, "w")
  if not f then
    return f, err
  end
  f:write(contents)
  f:close()
  ret  return
    end

    attrib, pos = string.unpack( ">I4", data, pos )
  end

  return attrib

end

--- Gets the revision number for the library
--
-- @param host table containing an ip field.
-- @param port table containing number and protocol fields.
-- @return number containing the session identity received from the server
function getSessionId( host, port )

  local sessionid
  local response = http.get( host, port, "/login", nil, nil, nil )

  if response ~= nil then
    sessionid = getAttributeAsInt( response.body, "mlid")
  eam username User name to test
-- @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",
      string.format("FROM:<usertest@%s>", domain))

    if not status then
      -- If this command fails to be sent, then something went wrong
      -- with the connection.
      return STATUS_CODES.ERROR,
     pt><"' }
  local open_session = http.get(host, port, "/"..rand.random_alpha(16), { header = header })
  if open_session and open_session.status == 404 then
    stdnse.debug2("got 404-that's good!")
    if open_session.body:match('"><script>alert%("XSS"%)</script><"') then
      vuln.state = vulns.STATE.EXPLOIT
      -- vuln.extra_info = open_session.body
      stdnse.debug1("VULNERABLE. Router answered correctly!")
      return vuln_report:make_output(vuln)
    end
  end
end
local datetime = require "datetime"
local datafiles = reque
  -- otherwise we return false
  local count = 1
  while not tn:isClear() and count < 6 do
    -- some systems will just kick you off others are slow in responding
    -- this loop continues to try getting out of whatever transaction 5 times. If it can't
    -- then we probably weren't in CICS to begin with.
    stdnse.debug(2,"Sending: F3")
    tn:send_pf(3) -- send F3
    tn:get_all_data()
    stdnse.debug(2,"Clearing the Screen")
    tn:send_clear()
    tn:get_all_data()
    tn:get_screen_debug(2)
    count = count + 1
  end
output["Raw CoAP response"] = result
      return output, stdnse.format_output(true, output)
    end

    result = parsed
  end

  -- Regardless of whether the block2 option was used, we should now have a
  -- parsed payload in some format or another. For now, they should all be
  -- strings or tables.
  assert(type(result) == "string" or type(result) == "table")

  -- If the payload has been parsed, and we requested the default
  -- resource, then we know how to format it nicely.
  local formatted = result
  if true then
    forma true, response
end

--- Function that checks for the returned protocols to a ALPN extension request.
--@args response Response to parse.
--@return results List of found protocols.
local check_alpn = function(response)
  local i, record = tls.record_read(response, 1)
  if record == nil then
    stdnse.debug1("Unknown response from server")
    return nil
  end

  if record.type == "handshake" and record.body[1].type == "server_hello" then
    if record.body[1].extensions == nil then
      stdnse.debug1("Server did not return TLS ALct.maxdepth the maximum amount of directories beneath
--       the initial url to spider. A negative value disables the limit.
--       (default: 3)
-- @args http-open-redirect.maxpagecount the maximum amount of pages to visit.
--       A negative value disables the limit (default: 20)
-- @args http-open-redirect.url the url to start spidering. This is a URL
--       relative to the scanned host eg. /default.html (default: /)
-- @args http-open-redirect.withinhost only spider URLs within the same host.
--       (default: true)
-- @oginResultMessage = 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 "<empty>", loginResultMessage ) )

    -- Add credentials for other ms-sql scripts to use but don't
    -- add accounts that need to change passwords
    if ( canLogin ) then
      instance.credentials[ username ] = password
      -- Legacy storage method (does not distinguish between instances)
      nmap.registry.mssqlusers = nmapl force the checks,
--       and will try to exploit the Exim SMTP server.
-- @args smtp-vuln-cve2010-4344.mailfrom Define the source email address to
--       be used.
-- @args smtp-vuln-cve2010-4344.mailto Define the destination email address
--       to be used.
-- @args exploit.cmd or smtp-vuln-cve2010-4344.cmd An arbitrary command to
--       run under the <code>Exim</code> user privileges on the remote
--       system. If this argument is set then, it will enable the
--       <code>smtp-vuln-cve2010-4344.exploit</code> argumemessage signing isn't required, the server is
  vulnerable to man-in-the-middle attacks or SMB-relay attacks.

This script will allow you to use the <code>smb*</code> script arguments (to
set the username and password, etc.), but it probably won't ever require
them.
]]

---
--@usage
-- nmap --script smb-security-mode.nse -p445 127.0.0.1
-- sudo nmap -sU -sS --script smb-security-mode.nse -p U:137,T:139 127.0.0.1
--
--@output
-- | smb-security-mode:
-- |   account_used: guest
-- |   authentication_level: user
-- |   challenge_responervice RPC functions.

In order to use the script, at least one printer needs to be shared
over SMB. If no printer is specified, script tries to enumerate existing
ones by calling LANMAN API which might not be always available.
LANMAN is available by default on Windows XP, but not on Vista or Windows 7
for example. In that case, you need to specify printer share name manually
using <code>printer</code> script argument. You can find out available shares
by using smb-enum-shares script.

Later versions of Windows require valid creden java.rmi.server.RemoteObject
--
-- @output
-- PORT     STATE SERVICE     REASON
-- 1099/tcp open  rmiregistry syn-ack
-- | rmi-dumpregistry:
-- |   cfassembler/default
-- |     coldfusion.flex.rmi.DataServicesCFProxyServer_Stub
-- |     @192.168.0.3:1271
-- |     extends
-- |       java.rmi.server.RemoteStub
-- |       extends
-- |         java.rmi.server.RemoteObject
-- |     Custom data
-- |       Classpath
-- |         file:/C:/CFusionMX7/runtime/../lib/ant-launcher.jar
-- |         file:/C:/CFusionMX7/runtime/../lib/ant.jar
--(tls.DEFAULT_ELLIPTIC_CURVES),
    -- Enable SNI if a server name is available
    ["server_name"] = tlsname and tls.EXTENSION_HELPERS["server_name"](tlsname),
  }
end

-- Find which ciphers out of group are supported by the server.
local function find_ciphers_group(host, port, protocol, group)
  local name, protocol_worked, record, results
  results = {}
  local t = {
    ["protocol"] = protocol,
    ["extensions"] = base_extensions(host),
  }

  -- This is a hacky sort of tristate variable. There are three conditions:
  -- 1. faltatus, close_result = msrpc.svcctl_closeservicehandle(smbstate, open_result['handle'])
  smb.stop(smbstate)
  return output
end
description = [[
Detects if a system with Intel Active Management Technology is vulnerable to the INTEL-SA-00075
privilege escalation vulnerability (CVE2017-5689).

This script determines if a target is vulnerable by attempting to perform digest authentication
with a blank response parameter. If the authentication succeeds, a HTTP 200 response is received.

References:
* https://www.tenable.com/blog/redisc  -- send two packets, just in case
  local probe = rand.random_string(10)
  for i=1,2 do
    local status = socket:sendto(host, port, probe)
    if ( not(status) ) then
      return stdnse.format_output(false, "Failed to send broadcast probe")
    end
  end

  local timeout = tonumber(arg_timeout) or ( 20 / ( nmap.timing_level() + 1 ) )
  local results = {}
  local stime = os.time()

  -- listen until timeout
  repeat
    local status, data = socket:receive()
    if ( status ) then
      local jenkins_pkt = data:match("^<hudson>(.n3270:disconnect()
    self.tn3270 = nil
  end,
  login = function (self, user, pass) -- pass is actually the username we want to try
    local path = self.options['path']
    local original = self.options['no_lu']
    local threshold = 90
    stdnse.verbose(2,"Trying Logical Unit: %s", pass)
    self.tn3270:set_lu(pass)
    local status, err = self.tn3270:initiate(self.host,self.port)
    if not status then
      stdnse.debug(2,"Could not initiate TN3270: %s", err )
      stdnse.verbose(2, "Invalid LU: %s",string.upper(pass))
     more information, see:
http://seclists.org/fulldisclosure/2010/Oct/119
http://www.exploit-db.com/exploits/15130/
]]

---
-- @usage
-- nmap --script http-barracuda-dir-traversal --script-args http-max-cache-size=5000000 -p <port> <host>
--
-- @args http-max-cache-size
--       Set max cache size. The default value is 100,000.
--       Barracuda config files vary in size mostly due to the number
--       of users. Using a max cache size of 5,000,000 bytes should be
--       enough for config files containing up to 5,000 users.
--
--m an rpc.Comm object
-- @param data the data received so far
-- @param pos the current position in the data where the opaque string is
-- @param additional number of bytes to request after the string for the next
--                   field. Saves a call to GetAdditionalBytes later.
-- @return position of next field or nil on error
-- @return the string extracted or error message
-- @return the data retrieved so far
local function get_zstring (comm, data, pos, additional)
  local pos, len = rpc.Util.unmarshall_uint32(data, pos)
  lo pcap_timeout_count >= 2 or cur_time - start_time >= nse_timeout

  dnet:ethernet_close()
  pcap:pcap_close()

  condvar("signal")
end

local function format_output(results)
  local output = tab.new()

  for _, record in ipairs(results) do
    tab.addrow(output, "IP: " .. record.address, "MAC: " .. record.mac, "IFACE: " .. record.iface)
  end
  if #results > 0 then
    output = { tab.dump(output) }
    if not target.ALLOW_NEW_TARGETS then
      output[#output + 1] = "Use --script-args=newtargets to add the results as targets"
    e} }
Entry { filename = "targets-ipv6-multicast-slaac.nse", categories = { "broadcast", "discovery", } }
Entry { filename = "targets-ipv6-wordlist.nse", categories = { "discovery", } }
Entry { filename = "targets-sniffer.nse", categories = { "broadcast", "discovery", "safe", } }
Entry { filename = "targets-traceroute.nse", categories = { "discovery", "safe", } }
Entry { filename = "targets-xml.nse", categories = { "safe", } }
Entry { filename = "teamspeak2-version.nse", categories = { "version", } }
Entry { filename = "telnet-brute.emap-generator.nse", categories = { "discovery", "intrusive", } }
Entry { filename = "http-slowloris-check.nse", categories = { "safe", "vuln", } }
Entry { filename = "http-slowloris.nse", categories = { "dos", "intrusive", } }
Entry { filename = "http-sql-injection.nse", categories = { "intrusive", "vuln", } }
Entry { filename = "http-stored-xss.nse", categories = { "exploit", "intrusive", "vuln", } }
Entry { filename = "http-svn-enum.nse", categories = { "default", "discovery", "safe", } }
Entry { filename = "http-svn-info.nse", { filename = "dns-update.nse", categories = { "intrusive", "vuln", } }
Entry { filename = "dns-zeustracker.nse", categories = { "discovery", "external", "malware", "safe", } }
Entry { filename = "dns-zone-transfer.nse", categories = { "discovery", "intrusive", } }
Entry { filename = "docker-version.nse", categories = { "version", } }
Entry { filename = "domcon-brute.nse", categories = { "brute", "intrusive", } }
Entry { filename = "domcon-cmd.nse", categories = { "auth", "intrusive", } }
Entry { filename = "domino-enum-users.nse", lose()

  local result = {}
  for ip, name in pairs(hosts) do
    table.insert(result, ("%s - %s"):format(ip,name))
  end

  if ( #result > 0 ) then
    result.name = probe.topic
    table.insert(responses, result)
  end

  condvar "signal"
end

action = function()

  -- PC-Duo UDP probes
  local probes = {
    -- PC-Duo Host probe
    {
      host = { ip = "255.255.255.255" },
      port = { number = 1505, protocol = "udp" },
      data =  stdnse.fromhex("00808008ff00"),
      match= "^.........(%w*)\0",
      topic= "PC-Duo Hostses = {"auth", "discovery", "safe"}

dependencies = {"broadcast-ms-sql-discover", "ms-sql-brute", "ms-sql-empty-password"}

local function process_instance(instance)

  local helper = mssql.Helper:new()
  local status, errorMessage = helper:ConnectEx( instance )
  if ( not(status) ) then
    return "ERROR: " .. errorMessage
  end

  status, errorMessage = helper:LoginEx( instance )
  if ( not(status) ) then
    return "ERROR: " .. errorMessage
  end

  local result
  local query = [[
  IF ( OBJECT_ID('master..sysxlogins' ) ) <> 0
   httpspider = require "httpspider"
local table = require "table"
local rand = require "rand"

description = [[
Attempts to discover JSONP endpoints in web servers. JSONP endpoints can be
used to bypass Same-origin Policy restrictions in web browsers.

The script searches for callback functions in the response to detect JSONP
endpoints. It also tries to determine callback function through URL(callback
function may be fully or partially controllable from URL) and also tries to
bruteforce the most common callback variables through the,
    uservar = "j_username",
    passvar = "j_password",
    onfailure = function(response)
      local body = response.body
      local rpath = response.header.location
      return response.status < 300 and body and not (
        (rpath and rpath:match('logonError%.jsp'))
        or (
          body:match('Unable to login%.') or
          body:match('Login failed%.') or
          body:match('Invalid User ID or password')
          )
        )
    end,
    sessioncookies = false,
  },
}

---
-- Test whether a given string (presum.example.com

author = "John R. Bond"
license = "Simplified (2-clause) BSD license--See https://nmap.org/svn/docs/licenses/BSD-simplified"

categories = {"discovery", "intrusive"}


portrule = function (host, port)
  if not shortport.port_or_service(53, "domain", {"tcp", "udp"})(host, port) then
    return false
  end
  -- only check tcp if udp is not open or open|filtered
  if port.protocol == 'tcp' then
    local tmp_port = nmap.get_port_state(host, {number=port.number, protocol="udp"})
    if tmp_port then
      return not strindefaults to SharedDocs)
-- @output
-- Host script results:
-- | smb-vuln-ms10-054:
-- |   VULNERABLE:
-- |   SMB remote memory corruption vulnerability
-- |     State: VULNERABLE
-- |     IDs:  CVE:CVE-2010-2550
-- |     Risk factor: HIGH  CVSSv2: 10.0 (HIGH) (AV:N/AC:L/Au:N/C:C/I:C/A:C)
-- |     Description:
-- |       The SMB Server in Microsoft Windows XP SP2 and SP3, Windows Server 2003 SP2,
-- |       Windows Vista SP1 and SP2, Windows Server 2008 Gold, SP2, and R2, and Windows 7
-- |       does not properly validate fields inutput)
      smb.stop(smbstate)
    end
  end

  return ls.end_listing(output)
end
local os = require "os"
local datetime = require "datetime"
local mssql = require "mssql"
local stdnse = require "stdnse"
local smbauth = require "smbauth"
local string = require "string"


description = [[
This script enumerates information from remote Microsoft SQL services with NTLM
authentication enabled.

Sending a MS-TDS NTLM authentication request with an invalid domain and null
credentials will cause the remote service to respond with a NTLMS  end

  -- Other
  count = #t.other
  if count > 0 then
    table.insert(o,
      {
        ['name'] = ('Other Associations (%d)'):format(count),
        t.other
      }
    )
  end

  return stdnse.format_output(true, o)

end


---
-- Sorts and combines a set of IPv4 and IPv6 addresses into a table of rows.
-- IPv4 addresses are ascending-sorted numerically and arranged in four columns
-- and IPv6 appear in subsequent rows, sorted and arranged to fit as many
-- addresses into a row as possible without the need for wrapping.
--
--or 0x2a,
    0x00, 0x00, 0x00, 0x00
  )
  -- Data 40 Octets: 0
  .. ("\x00"):rep(40)
  -- The following are optional if the Authenticated bit is set:
  -- Encryption Keyid 4 Octets: 0
  -- Message Authentication Code 16 Octets (MD5): 0
end


---
-- Checks that the response from the target is a valid NTP response.
--
-- Starts by checking that the socket read was successful and then creates a
-- packet object from the response (with dummy IP and UDP headers).  Then
-- perform checks that ensure that the response is of the expected tn Destination and source IP addresses and TCP ports
local check = function(layer3)
  local ip = packet.Packet:new(layer3, layer3:len())
  if not ip then return nil end
  return string.pack('>c4c4I2I2', ip.ip_bin_dst, ip.ip_bin_src, ip.tcp_dport, ip.tcp_sport)
end

--- Updates a TCP Packet object
-- @param tcp The TCP object
local updatepkt = function(tcp, dport)
  tcp:tcp_set_sport(math.random(0x401, 0xffff))
  tcp:tcp_set_dport(dport)
  tcp:tcp_set_seq(math.random(1, 0x7fffffff))
  tcp:tcp_count_checksum(tcp.ip_len)
  tcp:ip_counte argument \"http-robtex-reverse-ip.host\" did not contain a valid IPv4 address")
  end

  local htmldata = http.get_url("https://www.robtex.com/ip-lookup/"..target, {any_af=true})
  local domains = parse_robtex_response(htmldata.body)
  if ( #domains > 0 ) then
    return stdnse.format_output(true, domains)
  end
end
]]--
local ipOps = require "ipOps"
local math = require "math"
local nmap = require "nmap"
local packet = require "packet"
local stdnse = require "stdnse"
local string = require "string"
local tab = require "tab"
locad version.

The script works by sending RPC Null call requests with a random high version
unsupported number to the target service with iterated over RPC program numbers
from the nmap-rpc file and check for replies from the target port.
A reply with a RPC accept state 2 (Remote can't support version) means that we
the request sent the matching program number, and we proceed to extract the
supported versions. A reply with an accept state RPC accept state 1 (remote
hasn't exported program) means that we have sent the incorrect prograion: close
-- |   Content-Type: text/html
-- |
-- |_  (Request type: HEAD)
--
--@args path The path to request, such as <code>/index.php</code>. Default <code>/</code>.
--@args useget Set to force GET requests instead of HEAD.
--
--@see http-security-headers.nse

author = "Ron Bowes"

license = "Same as Nmap--See https://nmap.org/book/man-legal.html"

categories = {"discovery", "safe"}

portrule = shortport.http

local function fail (err) return stdnse.format_output(false, err) end

action = function(host, port)
  local path = stdnlocal cics_pass = self.options['pass']
    local timeout = 300
    local max_blank = 1
    local loop = 1
    local err, status
    stdnse.debug(2,"Getting to CICS")
    local run = stringaux.strsplit(";%s*", commands)
    for i = 1, #run do
      stdnse.debug(1,"Issuing Command (#%s of %s): %s", i, #run ,run[i])
      self.tn3270:send_cursor(run[i])
      self.tn3270:get_all_data()
      self.tn3270:get_screen_debug(2)
    end
    while self.tn3270:isClear() and max_blank < 7 do
      stdnse.debug(2, "Screen is not clear for %s. Rlocal tn3270    = require "tn3270"
local brute     = require "brute"
local creds     = require "creds"
local unpwdb    = require "unpwdb"
local io        = require "io"
local table     = require "table"
local string   = require "string"
local stringaux = require "stringaux"


description = [[
CICS transaction ID enumerator for IBM mainframes.
This script is based on mainframe_brute by Dominic White
(https://github.com/sensepost/mainframe_brute). However, this script
doesn't rely on any third party libraries or tools and instead useost, port )
  local vuln_table = {
    title = "The QNX QCONN daemon allows remote command execution.",
    state = vulns.STATE.NOT_VULN,
    risk_factor = "High",
    description = [[
The QNX QCONN daemon allows unauthenticated users to execute arbitrary operating
system commands as the 'root' user.
]],

    references = {
      'http://www.fishnetsecurity.com/6labs/blog/pentesting-qnx-neutrino-rtos',
      'http://metasploit.org/modules/exploit/unix/misc/qnx_qconn_exec'
    }
  }

  -- Set socket timeout
  local timeout = (stdnseerver"
    local version, extra = string.match(result["Server Version"], "^Apache/([%w._-]+)%s*(.-)$")
    if version then
      cpe = cpe .. ":" .. version
      port.version.version = version
    end
    if extra then
      port.version.extrainfo = extra
    end
    port.version.cpe = port.version.cpe or {}
    table.insert(port.version.cpe, cpe)
    nmap.set_port_version(host, port, "hardmatched")
  end

  result.VHosts = {}
  local uniq_requests = {}

  -- Parse the Apache client requests into the result table
  for line in strre seconds after the first
  -- it means that sending additional data prolonged the connection's time
  -- and the server is vulnerable to slowloris attack
  if diff >= 10 then
    slowloris.state = vulns.STATE.LIKELY_VULN
  end
  return report:make_output(slowloris)
end
description = [[
Attempts to retrieve information about the domain name of the target
]]

---
-- @see whois-ip.nse
--
-- @usage nmap --script whois-domain.nse <target>
--
-- This script starts by querying the whois.iana.org (which is the root of the
-- whois serverery", "intrusive", "version"}

-- Helpers
function replaceEmptyStrings(tbl)
  for key, value in pairs(tbl) do
    if type(value) == "table" then
      replaceEmptyStrings(value)
    elseif type(value) == "string" and value == "" then
      tbl[key] = "<EMPTY_STRING>"
    end
  end
end

function searchTable(searchString, myTable)
  local matches = {}
  local uniqueEntries = {}
  local extractedPart
  for i, entry in ipairs(myTable) do
    if string.find(entry, searchString) then
      local dollarIndex = string.find(entry, "%$")
    to those of the domain administrator account.
]],
    disclosure_time = 1416290400,
    disclosure_date = {year=2014, month=11, day=18},
    references = {
      'https://technet.microsoft.com/en-us/library/security/ms14-068.aspx'
    },
  },
}

local function check_vulns(host, port)
  local smbstate, status
  local vulns_detected = {}

  status, smbstate = smb.start(host)
  status = smb2.negotiate_v2(smbstate)

  if not status then
    stdnse.debug2("Negotiation failed")
    return nil, "Protocol negotiation failed (SMB2)"
  end
er = {}
  for key, value in pairs(fields) do
    if string.find(key, "_") == nil then
      basic[key] = value
    else
      other[key] = value
    end
  end
  return basic, other
end

action = function(host, port)
  local GETSTATUS = "\xff\xff\xff\xffgetstatus\n"
  local STATUSRESP = "\xff\xff\xff\xffstatusResponse"

  local status, data = comm.exchange(host, port, GETSTATUS, {["proto"] = "udp"})
  if not status then
    return
  end
  local parts = stringaux.strsplit("\n", data)
  local header = table.remove(parts, 1)
  if headesual( key.fingerprint, key.algorithm, key.bits ) )
    end
    if nmap.verbosity() > 1 or format_mask & format_bits.full ~= 0 then
      table.insert( output, key.full_key )
    end
    setmetatable(out, {
        __tostring = function(self)
          return table.concat(output, "\n")
        end
      })
    table.insert(output_tab, out)
  end

  -- if a known_hosts file was given, then check if it contains a key for the host being scanned
  local known_hosts = stdnse.get_script_args("ssh-hostkey.known-hosts") or false
  if known_ableaux"
local base64 = require "base64"
local comm = require "comm"

local openssl = stdnse.silent_require "openssl"

description = [[
Shows SSH hostkeys.

Shows the target SSH server's key fingerprint and (with high enough
verbosity level) the public key itself.  It records the discovered host keys
in <code>nmap.registry</code> for use by other scripts.  Output can be
controlled with the <code>ssh_hostkey</code> script argument.

You may also compare the retrieved key with the keys in your known-hosts
file using the <code>known-hnfo['user_list_default']()
    end

    -- Make the username lowercase (usernames aren't case sensitive, so making it lower case prevents duplicates)
    if(username ~= nil) then
      username = string.lower(username)
    end

  until username == nil or (hostinfo['invalid_usernames'][username] ~= true and hostinfo['locked_usernames'][username] ~= true and hostinfo['accounts'][username] == nil)

  return username
end

---Reset to the first username.
--
--@param hostinfo The hostinfo table.
local function reset_username(hostinfo)
  "string"
local vulns = require "vulns"
local stdnse = require "stdnse"
local table = require "table"

portrule = shortport.http

action = function(host, port)
  -- Identify servers that answer 200 to invalid HTTP requests and exit as these would invalidate the tests
  local status_404, result_404, _ = http.identify_404(host,port)
  if ( status_404 and result_404 == 200 ) then
    stdnse.debug1("Exiting due to ambiguous response from web server on %s:%s. All URIs return status 200.", host.ip, port.number)
    return nil
  end
  locaction( host, port )

  local result = stdnse.output_table()
  local uri = "/browseDirectory.jsp"
  stdnse.debug1("HTTP GET %s:%s%s", host.targetname or host.ip, port.number, uri)
  local response = http.get( host, port, uri )
  stdnse.debug1("Status %s",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("%%","%%%%")
    if body:match("([^][\"]+)\">Log") then
      port.version.name = "hadoop-datanode"
 "\x01\x00\x5e\x00\x00\x05", tostring(hello_out))
end

-- Listen for OSPF packets on a specified interface.
-- @param interface Interface to use
-- @param timeout   Amount of time to listen in seconds
local ospfListen = function(interface, timeout)
  local status, l2_data, l3_data, ospf_raw, _
  local start  = nmap.clock_ms()

  stdnse.print_debug("Start listening on interface %s...", interface.shortname)
  local listener = nmap.new_socket()
  listener:set_timeout(1000)
  listener:pcap_open(interface.device, 1500, true, "ip proto 8 = packet.Packet:set_icmpv6_option(packet.ND_OPT_SOURCE_LINKADDR,mac_src)
  local icmpv6_payload = ra_msg .. icmpv6_prefix_option .. icmpv6_src_link_option
  return icmpv6_payload
end

local function filter_interfaces(if_table)
  local addr = ipOps.ip_to_str(if_table.address)
  if addr and #addr == 16 and if_table.link == "ethernet" then
    return if_table
  end
end

local function single_interface_broadcast(if_nfo, results)
  stdnse.debug1("Starting " .. SCRIPT_NAME .. " on " .. if_nfo.device)

  local condvar = nmap.condvar(resulocal io = require "io"
local oops = require "oops"
local stdnse = require "stdnse"
local table = require "table"
local url = require "url"

description = [[
This script queries the Nmap registry for the GPS coordinates of targets stored
by previous geolocation scripts and renders a Google Map of markers representing
the targets.

Additional information for the Google Static Maps API can be found at:
- https://developers.google.com/maps/documentation/static-maps/intro
]]

---
-- @usage
-- nmap -sn -Pn --script ip-geolocation-geoplud

      response = r.response
      path = tostring(r.url)
    end

    if response.body then

      for i, pattern in ipairs(PATTERNS) do
        for c in string.gmatch(response.body, pattern) do

          local linenumber = getLineNumber(response.body, c)

          comments[c] = "\nPath: " .. path .. "\nLine number: " ..  linenumber .. "\nComment: \n"
        end
      end

      if (index) then
        index = index + 1
      else
        index = 1
      end
    end

  end

  -- If the table is empty.
  if next(comments) == nerr, line, req, resp, results, sock, status

  -- Get script arguments.
  cmd = stdnse.get_script_args("ftp-proftpd-backdoor.cmd")
  if not cmd then
    cmd = CMD_SHELL
  end

  -- Create socket.
  sock = nmap.new_socket("tcp")
  sock:set_timeout(5000)
  status, err = sock:connect(host, port, "tcp")
  if not status then
    stdnse.debug1("Can't connect: %s", err)
    sock:close()
    return
  end

  -- Read banner.
  local buffer = stdnse.make_buffer(sock, "\r?\n")
  local code, message = ftp.read_reply(buffer)
  if not code then
 e key="interesting-matches">
--     <table key=".git/config">
--       <elem>passw</elem>
--     </table>
--   </table>
-- </table>

categories = { "default", "safe", "vuln" }
author = "Alex Weber"
license = "Same as Nmap--See https://nmap.org/book/man-legal.html"
portrule = shortport.http

-- We consider 200 to mean "okay, file exists and we received its contents".
local STATUS_OK = 200
-- Long strings (like a repository's description) will be truncated to this
-- number of characters in normal output.
local TRUNC_LENGTH = 60

fun, port, uri, http_header, nil)
  if req.status == 200 and req.body:find(rnd, 1, true) then
    local vuln_report = vulns.Report:new(SCRIPT_NAME, host, port)
    local vuln = {
      title = 'HTTP Shellshock vulnerability',
      state = vulns.STATE.NOT_VULN,
      description = [[
This web application might be affected by the vulnerability known
as Shellshock. It seems the server is executing commands injected
via malicious HTTP headers.
      ]],
      IDS = {CVE = 'CVE-2014-6271'},
      references = {
        'http://www.openwald parameters
  -- in order to be secure. Do some rudimentary validation checks here.
  if have_ssl and not is_safe and not DSA_PARAMS[dhparams.p] then
    nosafe[#nosafe + 1] = group
  elseif DSA_PARAMS[dhparams.p] and DSA_PARAMS[dhparams.p] ~= dhparams.g then
    nosafe[#nosafe + 1] = group
  end
end


portrule = function(host, port)
  return port.protocol == "tcp" and (shortport.ssl(host, port) or sslcert.getPrepareTLSWithoutReconnect(port))
end

local function format_check(t, label)
  local out = {}
  for i, v in ipairs(t) do
  96.1.1.1.1.10.9999")

  if (not status) or (response == "TIMEOUT") then
    return fail("Failed to receive cisco configuration file")
  end

  local result = response and response[1] and response[1][1]
  if not result then
    return
  end

  if result == 3 then
    result = ( infile and infile:getContent() )

    if ( tftproot ) then
      local fname = tftproot .. stringaux.filename_escape(host.ip .. "-config")
      local file, err = io.open(fname, "w")
      if ( file ) then
        file:write(result)
        file:close()
     sses without using this script.")
  return xmloutput, stdnse.format_output(true, output)
end

hostaction = function(host)
  local sum = 0
  local output = {}
  local status, list = nmap.resolve(host.targetname, nmap.address_family())
  if not status or #list <= 0 then
    return nil
  end
  -- Don't re-add this same IP!
  for i = #list, 1, -1 do
    if ipOps.compare_ip(list[i], "eq", host.ip) then
      table.remove(list, i)
    end
  end
  if target.ALLOW_NEW_TARGETS then
    sum = sum + addtargets(list)
  end
  table.insert(outpuDP headers
        local knxMessage = string.sub(l3data, p.ip_hl*4 + 8 + 1)
        local co = stdnse.new_thread(knxParseSearchResponse, ips, results, knxMessage)
        threads[co] = true;
      end
    end
  end

  repeat
    for thread in pairs(threads) do
      if coroutine.status(thread) == "dead" then threads[thread] = nil end
    end
    if ( next(threads) ) then
      condvar "wait"
    end
  until next(threads) == nil;
  condvar("signal")
end

--- Returns the network interface used to send packets to a target host.
-- @pactx_log(1, protocol, "Protocol rejected.")
          protocol_worked = nil
          break
        elseif get_body(alert, "description", "handshake_failure") then
          protocol_worked = true
          ctx_log(2, protocol, "%d compressors rejected.", #compressors)
          -- Should never get here, because NULL should be good enough.
          -- The server may just not be able to handle multiple compressors.
          if #compressors > 1 then -- Make extra-sure it's not crazily rejecting the NULL compressor
            compre_info_from_security_blob(response_decoded)

  if ntlm_decoded.timestamp then
    -- 64-bit number of 100ns clicks since 1/1/1601
    local unixstamp = ntlm_decoded.timestamp // 10000000 - 11644473600
    datetime.record_skew(host, unixstamp, recvtime)
  end

  -- Target Name will always be returned under any implementation
  output.Target_Name = ntlm_decoded.target_realm

  -- Display information returned & ignore responses with null values
  if ntlm_decoded.netbios_domain_name and #ntlm_decoded.netbios_domain_name > 0 then
    outon to include NetBIOS, DNS, and OS build version.
]]


---
-- @usage
-- nmap -p 110,995 --script pop3-ntlm-info <target>
--
-- @output
-- 110/tcp   open     pop3
-- | pop3-ntlm-info:
-- |   Target_Name: ACTIVEPOP3
-- |   NetBIOS_Domain_Name: ACTIVEPOP3
-- |   NetBIOS_Computer_Name: POP3-TEST2
-- |   DNS_Domain_Name: somedomain.com
-- |   DNS_Computer_Name: pop3-test2.somedomain.com
-- |   DNS_Tree_Name: somedomain.com
-- |_  Product_Version: 6.1.7601
--
--@xmloutput
-- <elem key="Target_Name">ACTIVEPOP3</elem>
-- <elem key="NetBIOSe, "Failed to detect authentication" end
      tmp = stringaux.strsplit(" ", tmp)
      self.auth_mech = {}
      for _, v in pairs(tmp) do self.auth_mech[v] = true end
    elseif ( msg:match("%( failure") ) then
      return false
    end

    return true
  end,

  --- Attempts to login to the SVN server
  --
  -- @param username string containing the login username
  -- @param password string containing the login password
  -- @return status, true on success, false on failure
  -- @return err string containing error message on faAdditionally, named pipe connections may require Windows
authentication to connect to the Windows host (via SMB) in addition to the
authentication required to connect to the SQL Server instances itself. See the
documentation and arguments for the <code>smb</code> library for more information.

NOTE: By default, the ms-sql-* scripts may attempt to connect to and communicate
with ports that were not included in the port list for the Nmap scan. This can
be disabled using the <code>mssql.scanned-ports-only</code> script argument.
]]

-"})

--- Processes the table and creates the script output
--
-- @param tbl table containing <code>oid</code> and <code>value</code>
-- @return table with just the values
local function process_answer( tbl )

  local new_tab = {}

  for _, v in ipairs( tbl ) do
    table.insert( new_tab, v.value )
  end

  table.sort( new_tab )

  return new_tab

end

action = function(host, port)

  local snmpoid = "1.3.6.1.4.1.77.1.2.25"
  local users = {}
  local status

  local snmpHelper = snmp.Helper:new(host, port)
  snmpHelper:connect()

  ))
  if stdnse.tohex(write_result) == "00000000" then -- patched version would report 4 bytes written
    ms10_061.state = vulns.STATE.VULN -- identified by diffing patched an unpatched version
  end
  -- call abort_printer to stop the actual printing in case the remote system is not vulnerable
  -- we care about the environment and don't want to spend more paper then needed :)
  status,result = msrpc.spoolss_abort_printer(smbstate,printer_handle)

  return report:make_output(ms10_061)
end
local coroutine = require "coroutine"
locan = [[
Performs brute force password auditing against CVS pserver authentication.
]]

---
-- @usage
-- nmap -p 2401 --script cvs-brute <host>
--
-- @output
-- 2401/tcp open  cvspserver syn-ack
-- | cvs-brute:
-- |   Accounts
-- |     hotchner:francisco - Account is valid
-- |     reid:secret - Account is valid
-- |   Statistics
-- |_    Performed 544 guesses in 14 seconds, average tps: 38
--
-- @args cvs-brute.repo string containing the name of the repository to brute
--       if no repo was given the script checks the registry fors", "smb-os-discovery", "smb-enum-processes",
  "smb-psexec",
};


hostrule = function(host)
  return smb.get_port(host) ~= nil
end

local VULNERABLE = 1
local PATCHED    = 2
local UNKNOWN    = 3
local NOTUP      = 8

---Check the existence of ms07_029 vulnerability in Microsoft Dns Server service.
--This check is not safe as it crashes the Dns Server RPC service its dependencies.
--@param host Host object.
--@return (status, result)
--* <code>status == false</code> -> <code>result == NOTUP</code> which designates
--that the targett_port_state(host, port, "open")

end
---
--  Action Function that is used to run the NSE. This function will send the initial query to the
--  host and port that were passed in via nmap. The initial response is parsed to determine if host
--  is a S7COMM device. If it is then more actions are taken to gather extra information.
--
-- @param host Host that was scanned via nmap
-- @param port port that was scanned via nmap
action = function(host, port)
  -- COTP packet with a dst of 102
local COTP = stdnse.fromhex( "0300001611e000000[1])
    table.insert(to_be_searched['ip'], BUILT_IN_PATTERNS["ip"][1])
  end

  -- set timeout to 10 seconds
  crawler:set_timeout(10000)

  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(false, r.reason)
      else
        break
      end
    end
    local count = 0 -- pattern matches per url
       domain. This widens the scope from <code>withinhost</code> and can
--       not be used in combination. (default: false)
-- @args http-grep.breakonmatch Returns output if there is a match for a single pattern type.
-- @args http-grep.builtins supply a single or a list of built in types. supports email, phone, mastercard, discover,
-- visa, amex, ssn and ip addresses. If you just put in script-args http-grep.builtins then all will be enabled.
--
-- @xmloutput
-- <table key="(1) https://nmap.org/book/man-bugs.html">
--   <tableopie-adv.txt',
    },
    dates = {
      disclosure = {year = '2010', month = '05', day = '27'},
    },
  }

  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 err_catch = function()
    socket:close()
  end

  local try = nmap.new_try(err_catch)

  socket:set_timeout(10000)
  try(socket:ories = {"default", "discovery", "safe"}


portrule = shortport.port_or_service({ 25, 465, 587 },
  { "smtp", "smtps", "submission" })

function go(host, port)
  local options = {
    timeout = 10000,
    recv_before = true,
    ssl = true,
  }

  local domain = stdnse.get_script_args('smtp-commands.domain') or
  smtp.get_domain(host)

  local result, status = {}
  -- Try to connect to server.
  local socket, response = smtp.connect(host, port, options)
  if not socket then
    return false, string.format("Couldn't establish connecibs)
  else
    result = unittest.run_tests()
  end
  if #result == 0 then
    return "All tests passed"
  else
    return result
  end
end
local srvloc = require "srvloc"
local table = require "table"

description = [[
Discovers Versant object databases using the broadcast srvloc protocol.
]]

---
-- @usage
-- nmap --script broadcast-versant-locate
--
-- @output
-- Pre-scan script results:
-- | broadcast-versant-locate:
-- |_  vod://192.168.200.222:5019
--
-- @xmloutput
-- <table>
--   <elem>vod://192.168.200.222:5019</elem>
-- </ates']['nbstat'][host] = host.registry['nbstat']
  end

  if ( host.mac_addr_src ) then
    nmap.registry['duplicates']['mac'] = nmap.registry['duplicates']['mac'] or {}
    nmap.registry['duplicates']['mac'][host] = true
  end

  return
end

local Actions = {
  hostrule = hostaction,
  postrule = postaction
}

-- execute the action function corresponding to the current rule
action = function(...) return Actions[SCRIPT_TYPE](...) end
local shortport =  require "shortport"
local json = require "json"
local http = require "http"
locap -p80 --script http-vuln-cve2013-7091 --script-args http-vuln-cve2013-7091=/ZimBra <target>
-- @output
-- PORT   STATE SERVICE REASON
-- 80/tcp open  http    syn-ack
-- | http-vuln-cve2013-7091:
-- |   VULNERABLE:
-- |   Zimbra Local File Inclusion and Disclosure of Credentials
-- |     State: VULNERABLE (Exploitable)
-- |     IDs:  CVE:CVE-2013-7091
-- |     Description:
-- |       An 0 day was released on the 6th December 2013 by rubina119.
-- |       The vulnerability is a local file inclusion that can retrieve the credentials al result = {}

        if ( not(status) ) then
          return false, "Failed to retrieve list of DNS servers"
        end
        for _, srv in ipairs(res or {}) do
          local status, res = dns.query(PROBE_HOST, { host = srv, dtype='A' })
          if ( status ) then
            table.insert(result, res)
          end
        end

        local output = "None of the servers allow recursive queries."
        if ( 0 < #result ) then
          output = ("The following servers allow recursive queries: %s"):format(table.concat(rPE command, and collect the results.
  for _, cmd in pairs(cmds) do
    local status, result = nrpe_check(host, port, cmd)
    if status then
      tab.addrow(
      results,
      cmd,
      NRPE_STATES[result.state],
      result.data
      )
    end
  end

  -- If no queries generated responses, don't output anything.
  if #results == 1 then
    return
  end

  -- Record service description.
  port.version.name = "nrpe"
  port.version.product = "Nagios Remote Plugin Executor"
  nmap.set_port_version(host, port)

  -- Format tabls
-- |       caused when HTTP.sys improperly parses specially crafted HTTP requests. An attacker who
-- |       successfully exploited this vulnerability could execute arbitrary code in the context of the System account.
-- |
-- |     Disclosure date: 2015-04-14
-- |     References:
-- |       https://technet.microsoft.com/en-us/library/security/ms15-034.aspx
-- |_      http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-1635
-- @args http-vuln-cve2015-1635.uri URI to use in request. Default: /
---

author = {"Kl0nEz", "Paulino local output = stdnse.output_table()
  local response = http.get(host, port, '/HNAP1')
  if response.status and response.status == 200 then
    local parser = slaxml.parser:new()
    parser._call = {startElement = function(name)
      parser._call.text = get_text_callback(output, name) end,
      closeElement = function(name) parser._call.text = function() return nil end end
    }
    parser:parseSAX(response.body, {stripWhitespace=true})

    -- exit if the parser does not return output
    if not next(output) then return nil end
, host.ip, port.number, senderr)
    return nil
  end

  -- receive response
  local rcvstatus, response = sock:receive()
  if not rcvstatus then
    stdnse.debug1("Receive error: %s", response)
    return nil
  end

  -- if the response starts with 0x81 then its BACNet
  if( string.byte(response, 1) == 0x81 ) then
    local value = string.byte(response, 7)
    --if the first query resulted in an error
    --
    if( value == 0x50) then
      -- set the nmap output for the port and version
      set_nmap(host, port)
      -- return[535] = "Daintree Networks Inc.",
  [536] = "EURO ICC d.o.o",
  [537] = "TE Connectivity Energy",
  [538] = "GEZE GmbH",
  [539] = "NEC Corporation",
  [540] = "Ho Cheung International Company Limited",
  [541] = "Sharp Manufacturing Systems Corporation",
  [542] = "DOT CONTROLS a.s.",
  [543] = "BeaconMedÃ¦0220",
  [544] = "Midea Commercial Aircon",
  [545] = "WattMaster Controls",
  [546] = "Kamstrup A/S",
  [547] = "CA Computer Automation GmbH",
  [548] = "Laars Heating Systems Company",
  [549] = "Hitachi Systems Ltd.",
  [550]ng.match(line,"Bad login")) then
      stdnse.debug2("Bad login: %s/%s", username, password)
      return false, brute.Error:new( "Bad login" )
    elseif (string.match(line,"SERVER <|>")) then

      stdnse.debug1("Good login: %s/%s", username, password)
      return true, creds.Account:new(username, password, creds.State.VALID)
    end

    stdnse.debug1("WARNING: Unhandled response: %s", line)
    return false, brute.Error:new( "unhandled response" )
  end,

  disconnect = function( self )
    self.socket:close()
  end,
}

actioocket = brute.new_socket()
    if ( not(self.socket:connect(self.host, self.port, "ssl")) ) then
      return false
    end
    return true
  end,

  login = function( self, username, password )
    local status, err = self.socket:send("< OTP/1.0 >\n")

    if ( not ( status ) ) then
      local err = brute.Error:new( "Unable to send handshake" )
      err:setAbort(true)
      return false, err
    end

    local response
    status, response = self.socket:receive_buf(match.pattern_limit("\r?\n", 2048), false)
    if ( not(status) 5:67</elem>
--     <elem key="iface">en0</elem>
--   </table>
-- </table>

author = {"niteesh", "alegen"}
license = "Same as Nmap--See https://nmap.org/book/man-legal.html"
categories = {"discovery", "broadcast", "safe"}


local arg_timeout = stdnse.parse_timespec(stdnse.get_script_args(SCRIPT_NAME .. '.timeout'))

prerule = function()
  if ( not(nmap.is_privileged()) ) then
    stdnse.verbose1("not running for lack of privileges.")
    return false
  end
  return true
end


local function filter_interfaces(if_table)
  if ipOps.ip_ length of this section is found at offset 158 in the db2das.data section
--
--
-- @param packet table as returned from read_db2_packet
-- @return table with parsed data
function parse_db2_packet(packet)

  local info_length_offset = 158
  local info_offset = 160
  local version_offset = 97
  local response = {}

  if packet.header.data_len < info_length_offset then
    stdnse.debug1("packet too short to be DB2 response...")
    return
  end

  local len = string.unpack(">I2", packet.data, info_length_offset)
  response.version = sal request_status = check_file_present(host, port, filename)
    if (request_status == FILE_FOUND) then
      table.insert(results, filename)
    end
  end

  return stdnse.format_output(true, results)
end
local nmap = require "nmap"
local shortport = require "shortport"
local stdnse = require "stdnse"
local string = require "string"
local ipOps = require "ipOps"
local tableaux = require "tableaux"

description = [[
Extracts information from Ubiquiti networking devices.

This script leverages Ubiquiti's Discovery Service which is es)
  if #interfaces == 1 then
    interface = interfaces[1]
  else
    stdnse.debug1("No interface was selected, aborting...")
    return nil
  end

  broadcast_on_interface(interface)
end
local rsync = require "rsync"
local shortport = require "shortport"
local stdnse = require "stdnse"

description = [[
Lists modules available for rsync (remote file sync) synchronization.
]]

---
-- @usage
-- nmap -p 873 --script rsync-list-modules <ip>
--
-- @output
-- PORT    STATE SERVICE
-- 873/tcp open  rsync
-- | rsync-list-modules:
-- |   rn true
  end,

}


action = function(host, port)
  local bruteusers = stdnse.get_script_args(SCRIPT_NAME .. ".bruteusers")
  local status, result
  local engine = brute.Engine:new(Driver, host, port )

  engine.options.script_name = SCRIPT_NAME
  engine.options.firstonly = true
  engine.options:setOption( "passonly", not bruteusers )

  status, result = engine:start()

  return result
end
local msrpc = require "msrpc"
local smb = require "smb"
local stdnse = require "stdnse"
local shortport = require "shortport"

description = [[
ed by the brute
--     library
--
--

--
-- Version 0.1
-- Created 07/12/2010 - v0.1 - created by Patrik Karlsson <patrik@cqure.net>
--

author = "Patrik Karlsson"
license = "Same as Nmap--See https://nmap.org/book/man-legal.html"
categories = {"intrusive", "brute"}


portrule = shortport.port_or_service(5901, "vnc", "tcp", "open")

Driver =
{

  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 )
  mote process execution; authentication performed using passwords and UNIX login names | used by mail system to notify users of new mail received; currently receives messages only from processes on the same machine
biff	512/udp	0.002142	# comsat
login	513/tcp	0.005595	# who | BSD rlogind(8) | remote login a la telnet; automatic authentication performed based on priviledged port numbers and distributed data bases which identify "authentication domains" | maintains data bases showing who's logged in to machines on a local net and the 	0.000511	# secure electronic transaction
fw1-mc-gui	258/tcp	0.000013	# also yak winsock personal chat
yak-chat	258/udp	0.000494	# yak winsock personal chat
esro-gen	259/tcp	0.000201	# efficient short remote operations | Efficient Short Remote Operations
firewall1-rdp	259/udp	0.000840	# Firewall 1 proprietary RDP protocol http://www.inside-security.de/fw1_rdp_poc.html
openport	260/tcp	0.000025
openport	260/udp	0.000362
nsiiops	261/tcp	0.000025	# iiop name service over tls/ssl | IIOP Name Service over TLS/SSL
nsiiops	261/udp	0.00065ication
msg-auth	31/udp	0.000939	# MSG Authentication
unknown	32/tcp	0.000339
dsp	33/tcp	0.001016	# Display Support Protocol
dsp	33/udp	0.000560	# Display Support Protocol
unknown	34/tcp	0.000025
priv-print	35/tcp	0.000038	# any private printer server
priv-print	35/udp	0.000708	# any private printer server
time	37/tcp	0.003161	# timserver
time	37/udp	0.006458	# timserver
rap	38/tcp	0.000025	# Route Access Protocol
rap	38/udp	0.002043	# Route Access Protocol
rlp	39/tcp	0.000000	# Resource Location Protocol
rlp	39/udp	0.000478	# Reso....... -->
<xsl:template match="host">

  <hr class="print_only" />
  
  <xsl:variable name="var_address" select="address/@addr" />
  
  <xsl:element name="a">
    <xsl:attribute name="name">host_<xsl:value-of select="translate(address/@addr, '.', '_') " /></xsl:attribute>
  </xsl:element>

  <xsl:choose>

    <xsl:when test="status/@state = 'up'">
      <h2 class="up"><xsl:value-of select="address/@addr"/>

      <xsl:if test="count(hostnames/hostname) > 0">
        <xsl:for-each select="hostnames/hostname">
          <xsl:sort sDF=N%T=1B-25%TG=20%IPL=38%UN=0%RIPL=G%RID=G%RIPCK=G%RUCK=G%RUD=G)
IE(DFI=N%T=1B-25%TG=20%CD=S)

# BL_AIP6500_7.9.6
Fingerprint Aastra AIP6500 interface card
Class Aastra | embedded || telecom-misc
CPE cpe:/h:aastra:aip6500
SEQ(SP=0-5%GCD=0%ISR=0-5%TI=I%CI=I|RD%II=I%SS=S%TS=U)
OPS(O1=M5B4%O2=M5B4%O3=M5B4%O4=M5B4%O5=M5B4%O6=M5B4)
WIN(W1=2000%W2=2000%W3=2000%W4=2000%W5=2000%W6=2000)
ECN(R=Y%DF=Y%T=3B-45%TG=40%W=2000%O=M5B4%CC=N%Q=)
T1(R=Y%DF=Y%T=3B-45%TG=40%S=O%A=S+%F=AS%RD=0%Q=)
T2(R=Y%DF=Y%T=3B-45%TG=40%W=1%S=Z%A=S%F=AR%O=%RD=0%Q=U)switch_4400_se auto
SEQ(SP=45-4F%GCD=1-6%ISR=4B-55%TI=I%II=I%SS=S%TS=U)
OPS(O1=M218%O2=M218%O3=M218%O4=M218%O5=M218%O6=M218)
WIN(W1=400%W2=400%W3=400%W4=400%W5=400%W6=400)
ECN(R=Y%DF=N%T=FA-104%TG=FF%W=400%O=M218%CC=N%Q=)
T1(R=Y%DF=N%T=FA-104%TG=FF%S=O%A=S+%F=AS%RD=0%Q=)
T2(R=N)
T3(R=N)
T4(R=N)
T5(R=Y%DF=N%T=FA-104%TG=FF%W=0%S=A%A=S+%F=APR%O=%RD=0%Q=)
T6(R=N)
T7(R=N)
U1(DF=N%T=FA-104%TG=FF%IPL=38%UN=BABA%RIPL=G%RID=G%RIPCK=G%RUCK=G%RUD=G)
IE(DFI=N%T=FA-104%TG=FF%CD=S)

# 3Com 5500G-EI 48 Port
# super stack 3 4500  50 port managed s100%S=O%A=S+%F=AS%O=%RD=0%Q=)
T4(R=Y%DF=N%T=3B-45%TG=40%W=0%S=A%A=Z%F=R%O=%RD=0%Q=)
T5(R=Y%DF=N%T=3B-45%TG=40%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)
T6(R=Y%DF=N%T=3B-45%TG=40%W=0%S=A%A=Z%F=R%O=%RD=0%Q=)
T7(R=Y%DF=N%T=3B-45%TG=40%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)
U1(DF=N%T=3B-45%TG=40%IPL=38%UN=0%RIPL=G%RID=G%RIPCK=G%RUCK=G%RUD=G)
IE(DFI=S%T=3B-45%TG=40%CD=S)

# 3Com SuperStack 3 Switch 3300
Fingerprint 3Com SuperStack 3 Switch 3300
Class 3Com | embedded || switch
CPE cpe:/h:3com:superstack_3_switch_3300 auto
SEQ(SP=0-5%GCD=0%ISR=0-5%TI=I%CI=I%I0%F=30%O=10%RD=20%Q=20)
U1(R=50%DF=20%T=15%TG=15%IPL=100%UN=100%RIPL=100%RID=100%RIPCK=100%RUCK=50%RUD=100)
IE(R=50%DFI=40%T=15%TG=15%CD=100)

# 2N VOIP doorbell
Fingerprint 2N Helios IP VoIP doorbell
Class 2N | embedded || specialized
CPE cpe:/h:2n:helios
SEQ(SP=0-5%GCD=51E80C|A3D018|F5B824|147A030|199883C%ISR=C8-D2%TI=I|RD%CI=I%II=RI%SS=S%TS=U)
OPS(O1=M5B4%O2=M5B4%O3=M5B4%O4=M5B4%O5=M5B4%O6=M5B4)
WIN(W1=8000%W2=8000%W3=8000%W4=8000%W5=8000%W6=8000)
ECN(R=Y%DF=N%T=FA-104%TG=FF%W=8000%O=M5B4%CC=N%Q=)
T1(R=Y%DF=N%T=FA-104%TG=FF%S=O%s/a
match cmrcservice m|^0\0\0\x80\.\0E\0R\0R\0O\0R\0_\0E\0X\0I\0S\0T\0I\0N\0G\0_\0S\0E\0S\0S\0I\0O\0N\0\0\0| p/Microsoft Configuration Manager Remote Control service/ i/Error: existing session/ o/Windows/ cpe:/a:microsoft:systems_management_server/ cpe:/o:microsoft:windows/a
match codeforge m|^CFMSERV\(1\)\n| p/CodeForge IDE/
match concertosendlog m|^Concerto Software\r\n\r\nEnsemblePro SendLog Server - Version (\d[-.\w]+)\r\n\r\nEnter Telnet Password\r\n#> | p/Concerto Software EnsemblePro CRM software SendLog Server/ v/$1/
match\0\0\0\0\xff\xff..............\x02(\..)....$|s p/Bitcoin digital currency server/ v/0.3.24$1/ cpe:/a:bitcoin:bitcoind:0.3.24$1/

# https://bitcointalk.org/index.php?topic=55852.0
# http://bitcoin.org/en/alert/2012-02-18-protocol-change
# "In June 2010 the Bitcoin reference software version 0.2.10 introduced a
# change to the protocol: the 'version' messages exchanged by nodes at
# connection time would have a new format that included checksum values to
# detect corruption by broken networks."

# Bitcoin "version" message with proto software vendors already license Nmap technology such as
# host discovery, port scanning, OS detection, and version detection.
# For more details, see https://nmap.org/book/man-legal.html
#
# For details on how Nmap version detection works, why it was added,
# the grammar of this file, and how to detect and contribute new
# services, see https://nmap.org/book/vscan.html.

# The Exclude directive takes a comma separated list of ports.
# The format is exactly the same as the -p switch.
Exclude T:9100-9107

# This is the NULL probe trams);
    if ( script ) then
      sort(script.categories);
      db_text[#db_text+1] = format('Entry { filename = "%s", categories = {', script.basename)
      for j, category in ipairs(script.categories) do
        db_text[#db_text+1] = format(' "%s",', lower(category))
      end
      db_text[#db_text+1] = ' } }\n'
    end
  end
  db_text = concat(db_text)
  local db, status, err
  script_database.chunk, err = load(db_text, "script.db", "t", script_database)
  if not script_database.chunk then
    error("Script database corruptlosure); -- Create a garbage thread
    local status, e = resume(co); -- Get the globals it loads in env
    if not status then
      if quiet_errors[e] then
        print_verbose(1, "Failed to load '%s'.", filename);
        return nil;
      else
        log_error("Failed to load %s:\n%s", filename, traceback(co, e));
        error("could not load script");
      end
    end
    -- Check that all the required fields were set
    for f, t in pairs(required_fields) do
      local field = rawget(env, f);
      if field == nil then
 return status, ...;
    end
  end

  function coroutine.resume (co, ...)
    return handle(co, resume(co, ...));
  end

  local resume = coroutine.resume; -- local reference to new coroutine.resume
  local function aux_wrap (status, ...)
    if not status then
      return error(..., 2);
    else
      return ...;
    end
  end
  function coroutine.wrap (f)
    local co = create(f);
    return function (...)
      return aux_wrap(resume(co, ...));
    end
  end
end

-- Some local helper functions --

local log_write, verbosity, deb8 Brain21
0007C9 Technol Seven
0007CA Creatix Polymedia Ges Fur Kommunikaitonssysteme
0007CB Freebox SAS
0007CC Kaba Benzing GmbH
0007CD Kumoh Electronic
0007CE Cabletime Limited
0007CF Anoto AB
0007D0 Automat Engenharia de AutomaÃ§Ã£o Ltda.
0007D1 Spectrum Signal Processing
0007D2 Logopak Systeme GmbH & KG
0007D3 SPGPrints
0007D4 Zhejiang Yutong Network Communication
0007D5 3e Technologies Int;.
0007D6 Commil
0007D7 Caporis Networks AG
0007D8 Hitron Technologies.
0007D9 Splicecom
0007DA Neuro Telecom
0007DB Kirana Networks
0007DC mmtech
0004FC Stratus Technologies
0004FD Japan Control Engineering
0004FE Pelago Networks
0004FF Acronet
000500 Cisco Systems
000501 Cisco Systems
000502 Apple
000503 Iconag
000504 Naray Information & Communication Enterprise
000505 Systems Integration Solutions
000506 Reddo Networks AB
000507 Fine Appliance
000508 Inetcam
000509 Avoc Nishimura
00050A ICS Spa
00050B Sicom Systems
00050C Network Photonics
00050D Midstream Technologies
00050E 3ware
00050F Tanaka S/S
000510 Infinite Shanghai Communication Terminals
000511 ComplementaSmart Technologies
000276 Primax Electronics
000277 Cash Systemes Industrie
000278 Samsung Electro Mechanics
000279 Control Applications
00027A IOI Technology
00027B Amplify Net
00027C Trilithic
00027D Cisco Systems
00027E Cisco Systems
00027F ask-technologies.com
000280 Mu Net
000281 Madge
000282 ViaClix
000283 Spectrum Controls
000284 UK Grid Solutions Limited
000285 Riverstone Networks
000286 Occam Networks
000287 Adapcom
000288 Global Village Communication
000289 DNE Technologies
00028A Ambit Microsystems
00028B Vdsl Systems OY24
cluinfod	300527	clu_info_prog	# cluster information server (Digital UNIX)
rmfm		300528
c2sdocd		300529
interahelp	300530
callpathasyncmsghandler	300531
optix_arc	300532
optix_ts	300533
optix_wf	300534
maxopenc	300535
cev		300536	cev_server
sitewideprog	300537
drs		300538
drsdm		300539
dasgate		300540
dcdbd		300541
dcpsd		300542
supportlink_prog	300543
broker		300544
listner		300545
multiaccess	300546
spai_interface	300547
spai_adaption	300548
chimera_ci	300549
chimera_pi	300550
teamware_fl	300551
teamware_sl	300552
teamware_ui	3er this with the most popular services first to make scans         *
# * faster.                                                                 *
# ***************************************************************************/
#
# This collection of data is (C) 1996-2022 by Nmap Software LLC.  It
# is distributed under the Nmap Public Source license as provided in
# the LICENSE f