1
0
mirror of https://github.com/nmap/nmap.git synced 2025-12-19 14:09:02 +00:00

Proofread and update documentation of nmap, openssl, packet, and pcre.

This commit is contained in:
david
2008-10-24 19:08:27 +00:00
parent ddb5829dcf
commit d0e545b49c
4 changed files with 498 additions and 350 deletions

View File

@@ -1,57 +1,60 @@
--- Interface with Nmap internals. --- Interface with Nmap internals.
-- \n\n --
-- The nmap module is an interface with Nmap's internal functions and data -- The <code>nmap</code> module is an interface with Nmap's internal functions
-- structures. The API provides target host details such as port states and -- and data structures. The API provides target host details such as port
-- version detection results. It also offers an interface to the Nsock library -- states and version detection results. It also offers an interface to the
-- for efficient network I/O. -- Nsock library for efficient network I/O.
-- @copyright Same as Nmap--See http://nmap.org/book/man-legal.html -- @copyright Same as Nmap--See http://nmap.org/book/man-legal.html
module "nmap" module "nmap"
--- Returns the debugging level as a non-negative integer. --- Returns the debugging level as a non-negative integer.
-- \n\n --
-- The debugging level can be set with the -d option. -- The debugging level can be set with the <code>-d</code> option.
-- @return The debugging level. -- @return The debugging level.
-- @usage if nmap.debugging() > 0 then ... end -- @usage if nmap.debugging() > 0 then ... end
function debugging() function debugging()
--- Determines whether Nmap was compiled with SSL support. --- Determines whether Nmap was compiled with SSL support.
-- \n\n --
-- This can be used to avoid sending SSL probes when SSL is not available. -- This can be used to avoid sending SSL probes when SSL is not available.
-- @return true if Nmap was compiled with SSL support, false otherwise. -- @return True if Nmap was compiled with SSL support, false otherwise.
function have_ssl() function have_ssl()
--- Returns the verbosity level as a non-negative integer. --- Returns the verbosity level as a non-negative integer.
-- \n\n --
-- The verbosity level can be set with the -v option. -- The verbosity level can be set with the <code>-v</code> option.
-- @return The verbosity level. -- @return The verbosity level.
-- @usage if nmap.verbosity() > 0 then ... end -- @usage if nmap.verbosity() > 0 then ... end
function verbosity() function verbosity()
--- Searches for the specified file and returns a string containing its path if --- Searches for the specified file and returns a string containing its path if
-- it is found and readable (to the process). -- it is found and readable (to the process).
-- \n\n --
-- If the file is not found, not readable, or is a directory, nil is returned. -- If the file is not found, not readable, or is a directory, <code>nil</code>
-- The call nmap.fetchfile("nmap-rpc") will search for the data file nmap-rpc -- is returned.
-- and, assuming it's found (which it should be), return a string like -- @usage
-- "/usr/local/share/nmap/nmap-rpc". -- nmap.fetchfile("nmap-rpc") --> "/usr/local/share/nmap/nmap-rpc"
-- @param filename Filename to search for. -- @param filename Filename to search for.
-- @return String representing the full path to the file or nil. -- @return String representing the full path to the file or <code>nil</code>.
function fetchfile(filename) function fetchfile(filename)
--- Returns the timing level as a non-negative integer. Possible return values --- Returns the timing level as a non-negative integer.
-- vary from 0 to 5, corresponding to the six built-in Nmap timing templates. --
-- The timing level can be set with the -T option. -- Possible return values vary from <code>0</code> to <code>5</code>,
-- corresponding to the six built-in Nmap timing templates. The timing level
-- can be set with the <code>-T</code> option.
-- @return The timing level. -- @return The timing level.
function timing_level() function timing_level()
--- Gets a port table for a port on a given host. --- Gets a port table for a port on a given host.
-- \n\n --
-- This function takes a host table and a port table and returns a port table -- This function takes a host table and a port table and returns a port table
-- for the queried port. The port table returned is similar in structure to the -- for the queried port. The port table returned is similar in structure to the
-- ones passed to the rule and action functions. -- ones passed to the <code>hostrule</code>, <code>portrule</code>, and
-- \n\n -- <code>action</code> functions.
-- You can of course reuse the host and port tables passed to the port rule --
-- You can of course reuse the host and port tables passed to a script's rule
-- function. The purpose of this call is to be able to match scripts against -- function. The purpose of this call is to be able to match scripts against
-- more than one open port. For example if the target host has an open port 22 -- more than one open port. For example if the target host has an open port 22
-- and a running identd server, then you can write a script which will only fire -- and a running identd server, then you can write a script which will only fire
@@ -59,50 +62,58 @@ function timing_level()
-- While it is possible to specify IP addresses different to the currently -- While it is possible to specify IP addresses different to the currently
-- scanned target, the result will only be correct if the target is in the -- scanned target, the result will only be correct if the target is in the
-- currently scanned group of hosts. -- currently scanned group of hosts.
-- @param host Host table, containing an "ip" field. -- @param host Host table, containing an <code>ip</code> field.
-- @param port Port table, containing "number" and "protocol" fields. -- @param port Port table, containing <code>number</code> and
-- <code>protocol</code> fields.
-- @return A new port table holding the status and information for the port. -- @return A new port table holding the status and information for the port.
-- @usage p = nmap.get_port_state({ip="127.0.0.1"}, {number="80", protocol="tcp"}) -- @usage p = nmap.get_port_state({ip="127.0.0.1"}, {number="80", protocol="tcp"})
function get_port_state(host, port) function get_port_state(host, port)
--- Sets the state of a port on a given host. --- Sets the state of a port on a given host.
-- \n\n --
-- Using this function, the final port state, reflected in Nmap's results, -- Using this function, the final port state, reflected in Nmap's results, can
-- can be changed for a target. This is useful when Nmap detects a port as -- be changed for a target. This is useful when Nmap detects a port as
-- "open|filtered", but the script successfully connects to that port. In this -- <code>open|filtered</code>, but the script successfully connects to that
-- case, the script can set the port state to "open". Note that the port.state -- port. In this case, the script can set the port state to <code>open</code>.
-- value, which is passed to the script's action function will not be changed by -- This function doesn't change the original port table passed a script's
-- this call. -- action function.
-- @param host Host table, containing an "ip" field. -- @param host Host table, containing an <code>ip</code> field.
-- @param port Port table, containing "number" and "protocol" fields. -- @param port Port table, containing <code>number</code> and
-- @param state Port state, like "open" or "closed". -- <code>protocol</code> fields.
-- @param state Port state, like <code>"open"</code> or <code>"closed"</code>.
function set_port_state(host, port, state) function set_port_state(host, port, state)
--- Sets version information on a port. --- Sets version information on a port.
-- \n\n --
-- NSE scripts are sometimes able to determine the service name and application -- NSE scripts are sometimes able to determine the service name and application
-- version listening on a port. A whole script category (version) was designed -- version listening on a port. A whole script category (<code>version</code>)
-- for this purpose. set_port_version function is used to record version -- was designed for this purpose. This function is used to record version
-- information when it is discovered. -- information when it is discovered.
-- \n\n --
-- The host and port arguments to this function should either be the tables -- The host and port arguments to this function should either be the tables
-- passed to the action method or they should have the same structure. The port -- passed to the action method or they should have the same structure. The port
-- argument specifies the port to operate on through its "number" and "protocol" -- argument specifies the port to operate on through its <code>number</code>
-- fields. and also contains the new version information to set. The version -- and <code>protocol</code> fields. and also contains the new version
-- detection fields this function looks at are "name", "product", "version", -- information to set. The version detection fields this function looks at are
-- "extrainfo", "hostname", "ostype", "devicetype", and "service_tunnel". All -- <code>name</code>, <code>product</code>, <code>version</code>,
-- these keys are optional. -- <code>extrainfo</code>, <code>hostname</code>, <code>ostype</code>,
-- \n\n -- <code>devicetype</code>, and <code>service_tunnel</code>. All these keys are
-- The probestate argument describes the state in which the script completed. It -- optional.
-- is a string, one of: "hardmatched", "softmatched", "nomatch", "tcpwrapped", --
-- or "incomplete". "hardmatched" is almost always used, as it signifies a -- The <code>probestate</code> argument describes the state in which the script
-- completed. It is a string, one of: <code>"hardmatched"</code>,
-- <code>"softmatched"</code>, <code>"nomatch"</code>,
-- <code>"tcpwrapped"</code>, or <code>"incomplete"</code>.
-- <code>"hardmatched"</code> is almost always used, as it signifies a
-- successful match. The other possible states are generally only used for -- successful match. The other possible states are generally only used for
-- standard version detection rather than the NSE enhancement. -- standard version detection rather than the NSE enhancement.
-- @param host Host table, containing and "ip" field. -- @param host Host table, containing and <code>ip</code> field.
-- @param port Port table, containing "number" and "protocol" fields, as well as -- @param port Port table, containing <code>number</code> and
-- any additional version information fields. -- <code>protocol</code> fields, as well as any additional version information
-- @param probestate The state of the probe: "hardmatched", "softmatched", -- fields.
-- "nomatch", "tcpwrapped", or "incomplete". -- @param probestate The state of the probe: <code>"hardmatched"</code>,
-- <code>"softmatched"</code>, <code>"nomatch"</code>,
-- <code>"tcpwrapped"</code>, or <code>"incomplete"</code>.
function set_port_version(host, port, probestate) function set_port_version(host, port, probestate)
--- Returns the current date and time in milliseconds. --- Returns the current date and time in milliseconds.
@@ -112,49 +123,46 @@ function set_port_version(host, port, probestate)
function clock_ms() function clock_ms()
--- Gets the link-level hardware type of an interface. --- Gets the link-level hardware type of an interface.
-- \n\n --
-- This function takes a dnet-style interface name and returns a string -- This function takes a dnet-style interface name and returns a string
-- representing the hardware type of the interface. Possible return values are -- representing the hardware type of the interface. Possible return values are
-- "ethernet", "loopback", "p2p", or nil if none of the other types apply. -- <code>"ethernet"</code>, <code>"loopback"</code>, <code>"p2p"</code>, or
-- <code>nil</code> if none of the other types apply.
-- @param interface_name The name of the interface. -- @param interface_name The name of the interface.
-- @return "ethernet", "loopback", "p2p", or nil. -- @return <code>"ethernet"</code>, <code>"loopback"</code>,
-- <code>"p2p"</code>, or <code>nil</code>.
-- @usage iface_type = nmap.get_interface_list("eth0") -- @usage iface_type = nmap.get_interface_list("eth0")
function get_interface_link(interface_name) function get_interface_link(interface_name)
--- Create a mutex on an object. --- Create a mutex on an object.
-- \n\n --
-- This function returns another function that works as a mutex on the object -- This function returns another function that works as a mutex on the object
-- passed. This object can be any Lua data type except nil, booleans, and -- passed. This object can be any Lua data type except <code>nil</code>,
-- numbers. The returned function allows you to lock, try to lock, and release -- Booleans, and numbers. The returned function allows you to lock, try to
-- the mutex. The returned function takes only one argument, which must be one -- lock, and release the mutex. The returned function takes only one argument,
-- of\n -- which must be one of
-- "lock": makes a blocking lock on the mutex. If the mutex is busy then -- * <code>"lock"</code>: makes a blocking lock on the mutex. If the mutex is busy then the thread will yield and wait. The function returns with the mutex locked.
-- the thread will yield and wait. The function returns with the mutex locked.\n -- * <code>"trylock"</code>: makes a non-blocking lock on the mutex. If the mutex is busy then it immediately returns with a return value of false. Otherwise, the mutex locks the mutex and returns true.
-- "trylock": makes a non-blocking lock on the mutex. If the mutex is -- * <code>"done"</code>: releases the mutex and allows another thread to lock it. If the thread does not have a lock on the mutex, an error will be raised.
-- busy then it immediately returns with a return value of false. Otherwise, -- * <code>"running"</code>: returns the thread locked on the mutex or <code>nil</code> if no thread is locked. This should only be used for debugging as it interferes with finished threads from being collected.
-- the mutex locks the mutex and returns true.\n
-- "done": releases the mutex and allows another thread to lock it. If
-- the thread does not have a lock on the mutex, an error will be raised.\n
-- "running": returns the thread locked on the mutex or nil if no thread
-- is locked. This should only be used for debugging as it interferes with
-- finished threads from being collected.
-- @param object Object to create a mutex for. -- @param object Object to create a mutex for.
-- @return Mutex function which takes one of the following arguments: "lock", -- @return Mutex function which takes one of the following arguments:
-- "trylock", "done", or "running". -- <code>"lock"</code>, <code>"trylock"</code>, <code>"done"</code>, or
-- <code>"running"</code>.
-- @usage -- @usage
-- id = "My Script's Unique ID";\n -- id = "My Script's Unique ID"
-- \n --
-- local mutex = nmap.mutex(id);\n -- local mutex = nmap.mutex(id)
-- function action(host, port)\n -- function action(host, port)
-- mutex "lock";\n -- mutex "lock"
-- -- do stuff\n -- -- do stuff
-- mutex "done";\n -- mutex "done"
-- return script_output;\n -- return script_output
-- end -- end
function mutex(object) function mutex(object)
--- Creates a new exception handler. --- Creates a new exception handler.
-- \n\n --
-- This function returns another function, an exception handler. The returned -- This function returns another function, an exception handler. The returned
-- function takes a variable number of arguments, which are assumed to be the -- function takes a variable number of arguments, which are assumed to be the
-- return values of another function. It checks the return values for an -- return values of another function. It checks the return values for an
@@ -165,69 +173,69 @@ function mutex(object)
-- closing a socket. -- closing a socket.
-- @param handler Exception handler function (optional). -- @param handler Exception handler function (optional).
-- @usage -- @usage
-- local result, socket, try, catch\n -- local result, socket, try, catch
-- \n --
-- result = ""\n -- result = ""
-- socket = nmap.new_socket()\n -- socket = nmap.new_socket()
-- catch = function()\n -- catch = function()
-- socket:close()\n -- socket:close()
-- end\n -- end
-- try = nmap.new_try(catch)\n -- try = nmap.new_try(catch)
-- try(socket:connect(host.ip, port.number))\n -- try(socket:connect(host.ip, port.number))
-- result = try(socket:receive_lines(1))\n -- result = try(socket:receive_lines(1))
-- try(socket:send(result)) -- try(socket:send(result))
function new_try(handler) function new_try(handler)
--- Returns a new NSE socket object. --- Returns a new NSE socket object.
-- \n\n --
-- To allow for efficient and parallelizable network I/O, NSE provides an -- To allow for efficient and parallelizable network I/O, NSE provides an
-- interface to Nsock, the Nmap socket library. The smart callback mechanism -- interface to Nsock, the Nmap socket library. The smart callback mechanism
-- Nsock uses is fully transparent to NSE scripts. The main benefit of NSE's -- Nsock uses is fully transparent to NSE scripts. The main benefit of NSE's
-- sockets is that they never block on I/O operations, allowing many scripts to -- sockets is that they never block on I/O operations, allowing many scripts to
-- be run in parallel. The I/O parallelism is fully transparent to authors of -- be run in parallel. The I/O parallelism is fully transparent to authors of
-- NSE scripts. In NSE you can either program as if you were using a single non -- NSE scripts. In NSE you can either program as if you were using a single
-- blocking socket or you can program as if your connection is blocking. -- non-blocking socket or you can program as if your connection is blocking.
-- Seemingly blocking I/O calls still return once a specified timeout has been -- Seemingly blocking I/O calls still return once a specified timeout has been
-- exceeded. -- exceeded.
-- \n\n --
-- NSE sockets are the recommended way to do network I/O. They support -- NSE sockets are the recommended way to do network I/O. They support
-- connect-style sending and receiving over TCP and UDP (and SSL), as well as -- <code>connect</code>-style sending and receiving over TCP and UDP (and SSL),
-- raw socket receiving. -- as well as raw socket receiving.
-- @return A new NSE socket. -- @return A new NSE socket.
-- @see pcap_open -- @see pcap_open
-- @usage local socket = nmap.new_socket() -- @usage local socket = nmap.new_socket()
function new_socket() function new_socket()
--- Establishes a connection. --- Establishes a connection.
-- \n\n --
-- The connect puts a socket in a state ready for communication. It takes as -- This method puts a socket in a state ready for communication. It takes as
-- arguments a host descriptor (either an IP address or a hostname), a port -- arguments a host descriptor (either an IP address or a hostname), a port
-- number and optionally a protocol. The protocol must be one of "tcp", "udp" or -- number and optionally a protocol. The protocol must be one of
-- "ssl"; it is "tcp" if not specified. -- <code>"tcp"</code>, <code>"udp"</code> or <code>"ssl"</code>; it is
-- \n\n -- <code>"tcp"</code> if not specified.
--
-- On success the function returns true. On failure it returns false and an -- On success the function returns true. On failure it returns false and an
-- error string. Those strings are taken from the gai_strerror C function. They -- error string. Those strings are taken from the <code>gai_strerror()</code> C
-- are (with the error code in parentheses):\n -- function. They are (with the error code in parentheses):
-- "Address family for hostname not supported" (EAI_ADDRFAMILY)\n -- * <code>"Address family for hostname not supported"</code> (<code>EAI_ADDRFAMILY</code>)
-- "Temporary failure in name resolution" (EAI_AGAIN)\n -- * <code>"Temporary failure in name resolution"</code> (<code>EAI_AGAIN</code>)
-- "Bad value for ai_flags" (EAI_BADFLAGS)\n -- * <code>"Bad value for ai_flags"</code> (<code>EAI_BADFLAGS</code>)
-- "Non-recoverable failure in name resolution" (EAI_FAIL)\n -- * <code>"Non-recoverable failure in name resolution"</code> (<code>EAI_FAIL</code>)
-- "ai_family not supported" (EAI_FAMILY)\n -- * <code>"ai_family not supported"</code> (<code>EAI_FAMILY</code>)
-- "Memory allocation failure" (EAI_MEMORY)\n -- * <code>"Memory allocation failure"</code> (<code>EAI_MEMORY</code>)
-- "No address associated with hostname" (EAI_NODATA)\n -- * <code>"No address associated with hostname"</code> (<code>EAI_NODATA</code>)
-- "Name or service not known" (EAI_NONAME)\n -- * <code>"Name or service not known"</code> (<code>EAI_NONAME</code>)
-- "Servname not supported for ai_socktype" (EAI_SERVICE)\n -- * <code>"Servname not supported for ai_socktype"</code> (<code>EAI_SERVICE</code>)
-- "ai_socktype not supported" (EAI_SOCKTYPE)\n -- * <code>"ai_socktype not supported"</code> (<code>EAI_SOCKTYPE</code>)
-- "System error" (EAI_SYSTEM)\n -- * <code>"System error"</code> (<code>EAI_SYSTEM</code>)
-- In addition to these standard system error based messages are the following -- In addition to these standard system error messages there are two
-- two NSE-specific errors:\n -- NSE-specific errors:
-- "Sorry, you don't have OpenSSL" occurs if the protocol is "ssl" but but Nmap -- * <code>"Sorry, you don't have OpenSSL"</code>: The protocol is <code>"ssl"</code> but but Nmap was compiled without OpenSSL support.
-- was compiled without OpenSSL support.\n -- * <code>"invalid connection method"</code>: The second parameter is not one of <code>"tcp"</code>, <code>"udp"</code>, and <code>"ssl"</code>.
-- "invalid connection method" occurs if the second parameter is not one of
-- "tcp", "udp", and "ssl".
-- @param hostid Hostname or IP address. -- @param hostid Hostname or IP address.
-- @param port Port number. -- @param port Port number.
-- @param protocol "tcp", "udp", or "ssl" (default "tcp"). -- @param protocol <code>"tcp"</code>, <code>"udp"</code>, or
-- <code>"ssl"</code> (default <code>"tcp"</code>).
-- @return Status (true or false). -- @return Status (true or false).
-- @return Error code (if status is false). -- @return Error code (if status is false).
-- @see new_socket -- @see new_socket
@@ -235,19 +243,17 @@ function new_socket()
function connect(hostid, port, protocol) function connect(hostid, port, protocol)
--- Sends data on an open socket. --- Sends data on an open socket.
-- \n\n --
-- The send method sends the data contained in the data string through an open -- This socket method sends the data contained in the data string through an
-- connection. On success the function returns true. If the send -- open connection. On success the function returns true. If the send operation
-- operation has failed, the function returns true along with an error string. -- has failed, the function returns true along with an error string. The error
-- The error strings are:\n -- strings are
-- "Trying to send through a closed socket": there was no call to socket:connect -- * <code>"Trying to send through a closed socket"</code>: There was no call to <code>socket:connect</code> before the send operation.
-- before the send operation.\n -- * <code>"TIMEOUT"</code>: The operation took longer than the specified timeout for the socket.
-- "TIMEOUT": the operation took longer than the specified timeout for the -- * <code>"ERROR"</code>: An error occurred inside the underlying Nsock library.
-- socket.\n -- * <code>"CANCELLED"</code>: The operation was cancelled.
-- "ERROR": an error occurred inside the underlying Nsock library.\n -- * <code>"KILL"</code>: For example the script scan is aborted due to a faulty script.
-- "CANCELLED": the operation was cancelled.\n -- * <code>"EOF"</code>: An EOF was read (probably will not occur for a send operation).
-- "KILL": for example the script scan is aborted due to a faulty script.\n
-- "EOF": an EOF was read (probably will not occur for a send operation).\n
-- @param data The data to send. -- @param data The data to send.
-- @return Status (true or false). -- @return Status (true or false).
-- @return Error code (if status is false). -- @return Error code (if status is false).
@@ -256,14 +262,14 @@ function connect(hostid, port, protocol)
function send(data) function send(data)
--- Receives data from an open socket. --- Receives data from an open socket.
-- \n\n --
-- The receive method does a non-blocking receive operation on an open socket. -- The receive method does a non-blocking receive operation on an open socket.
-- On success the function returns true along with the received data. If -- On success the function returns true along with the received data. On
-- receiving data has failed, the function returns false along with an error -- failure the function returns false along with an error string. A failure
-- string. A failure occurs for example if receive is called on a closed socket. -- occurs for example if <code>receive</code> is called on a closed socket. The
-- The receive call returns to the NSE script all the data currently stored in -- receive call returns to the NSE script all the data currently stored in the
-- the receive buffer of the socket. Error conditions are the same as for the -- receive buffer of the socket. Error conditions are the same as for
-- send operation. -- <code>send</code>.
-- @return Status (true or false). -- @return Status (true or false).
-- @return Data (if status is true) or error string (if status is false). -- @return Data (if status is true) or error string (if status is false).
-- @see new_socket -- @see new_socket
@@ -271,16 +277,18 @@ function send(data)
function receive() function receive()
--- Receives lines from an open connection. --- Receives lines from an open connection.
-- \n\n --
-- Tries to receive at least n lines from an open connection. A line is a string -- Tries to receive at least <code>n</code> lines from an open connection. A
-- delimited with \n characters. If it was not possible to receive at least n -- line is a string delimited with <code>\n</code> characters. If it was not
-- lines before the operation times out a "TIMEOUT" error occurs. On the other -- possible to receive at least <code>n</code> lines before the operation times
-- hand, if more than n lines were received, all are returned, not just n. Use -- out a <code>"TIMEOUT"</code> error occurs. On the other hand, if more than
-- stdnse.make_buffer to guarantee one line is returned per call. -- <code>n</code> lines were received, all are returned, not just
-- \n\n -- <code>n</code>. Use <code>stdnse.make_buffer</code> to guarantee only one
-- line is returned per call.
--
-- On success the function returns true along with the received data. If -- On success the function returns true along with the received data. If
-- receiving data has failed, the function returns false along with an error -- receiving data has failed, the function returns false along with an error
-- string. Error conditions are the same as for the send operation. -- string. Error conditions are the same as for <code>send</code>.
-- @param n Minimum number of lines to read. -- @param n Minimum number of lines to read.
-- @return Status (true or false). -- @return Status (true or false).
-- @return Data (if status is true) or error string (if status is false). -- @return Data (if status is true) or error string (if status is false).
@@ -289,15 +297,16 @@ function receive()
function receive_lines(n) function receive_lines(n)
--- Receives bytes from an open connection. --- Receives bytes from an open connection.
-- \n\n --
-- Tries to receive at least n bytes from an open connection. Like in -- Tries to receive at least <code>n</code> bytes from an open connection. Like
-- receive_lines, n is the minimum amount of characters we would like to -- in <code>receive_lines</code>, <code>n</code> is the minimum amount of
-- receive. If more arrive, we get all of them. If fewer than n characters -- characters we would like to receive. If more arrive, we get all of them. If
-- arrive before the operation times out, a "TIMEOUT" error occurs. -- fewer than <code>n</code> characters arrive before the operation times out,
-- \n\n -- a <code>"TIMEOUT"</code> error occurs.
--
-- On success the function returns true along with the received data. If -- On success the function returns true along with the received data. If
-- receiving data has failed, the function returns false along with an error -- receiving data has failed, the function returns false along with an error
-- string. Error conditions are the same as for the send operation. -- string. Error conditions are the same as for <code>send</code>.
-- @param n Minimum number of bytes to read. -- @param n Minimum number of bytes to read.
-- @return Status (true or false). -- @return Status (true or false).
-- @return Data (if status is true) or error string (if status is false). -- @return Data (if status is true) or error string (if status is false).
@@ -306,40 +315,37 @@ function receive_lines(n)
function receive_bytes(n) function receive_bytes(n)
--- Reads from a socket using a buffer and an arbitrary delimiter. --- Reads from a socket using a buffer and an arbitrary delimiter.
-- \n\n --
-- The receive_buf method reads data from the network until it encounters the -- This method reads data from the network until it encounters the given
-- given delimiter string (or matches the function passed in). This function -- delimiter string (or matches the function passed in). This function
-- continues to read from the network until the delimiter is found or the -- continues to read from the network until the delimiter is found or the
-- function times out. If data is read beyond the delimiter, that data is saved -- function times out. If data is read beyond the delimiter, that data is
-- in a buffer for the next call to receive_buf. This buffer is cleared on -- saved in a buffer for the next call to <code>receive_buf</code>. This
-- subsequent calls to other Network I/O API functions. -- buffer is cleared on subsequent calls to other Network I/O API functions.
-- \n\n --
-- The first argument may be either a pattern or a function. If a pattern, that -- The first argument may be either a pattern or a function. If a pattern, that
-- pattern is used to separate the data. If a function, it must take exactly one -- pattern is used to separate the data. If a function, it must take exactly
-- parameter (the buffer) and its return values must be in the same format as -- one parameter (the buffer) and its return values must be in the same format
-- string.find (offsets to the start and the end of the delimiter inside the -- as those of <code>string.find</code> (offsets to the start and the end of
-- buffer, or nil if the delimiter is not found). The nselib match.lua module -- the delimiter inside the buffer, or <code>nil</code> if the delimiter is not
-- provides functions for matching against regular expressions or byte counts. -- found). The nselib <code>match.lua</code> module provides functions for
-- These functions are suitable as arguments to receive_buf. -- matching against regular expressions or byte counts. These functions are
-- \n\n -- suitable as arguments to <code>receive_buf</code>.
-- The second argument to receive_buf is a Boolean value controlling whether the --
-- delimiting string is returned along with the received data (true) or -- The second argument to <code>receive_buf</code> is a Boolean value
-- discarded (false). -- controlling whether the delimiting string is returned along with the
-- \n\n -- received data (true) or discarded (false).
-- On success the function returns true along with the received data. If --
-- receiving data has failed, the function returns false along with an error -- On success the function returns true along with the received data. On failure
-- string. Possible error messages are the same as those that the other receive -- the function returns false along with an error string. Possible error
-- function can return, with the addition of\n -- messages are the same as those that the other receive functions can return,
-- "Error inside splitting-function": the first argument was a function which -- with the addition of
-- caused an error while being called.\n -- * <code>"Error inside splitting-function"</code>: The first argument was a function which caused an error while being called.
-- "Error in string.find (nsockobj:receive_buf)!": a string was provided as the -- * <code>"Error in string.find (nsockobj:receive_buf)!"</code>: A string was provided as the first argument, and string.find() yielded an error while being called.
-- first argument, and string.find() yielded an error while being called.\n -- * <code>"Expected either a function or a string!"</code>: The first argument was neither a function nor a string.
-- "Expected either a function or a string!": the first argument was neither a -- * <code>"Delimiter has negative size!"</code>: The returned start offset is greater than the end offset.
-- function nor a string.\n
-- "Delimiter has negative size!": the returned start offset is greater than the
-- end offset.\n
-- @param delimiter A Lua pattern or a function with return values like those of -- @param delimiter A Lua pattern or a function with return values like those of
-- string.find. -- <code>string.find</code>.
-- @param keeppattern Whether to return the delimiter string with any returned -- @param keeppattern Whether to return the delimiter string with any returned
-- data. -- data.
-- @return Status (true or false). -- @return Status (true or false).
@@ -349,12 +355,12 @@ function receive_bytes(n)
function receive_buf(delimiter, keeppattern) function receive_buf(delimiter, keeppattern)
--- Closes an open connection. --- Closes an open connection.
-- \n\n --
-- On success the function returns true. If the close fails, the function -- On success the function returns true. If the close fails, the function
-- returns false and an error string. Currently the only error message is -- returns false and an error string. Currently the only error message is
-- "Trying to close a closed socket", which is issued if the socket has already -- <code>"Trying to close a closed socket"</code>, which is issued if the
-- been closed. -- socket has already been closed.
-- \n\n --
-- Sockets are subject to garbage collection. Should you forget to close a -- Sockets are subject to garbage collection. Should you forget to close a
-- socket, it will get closed before it gets deleted (on the next occasion Lua's -- socket, it will get closed before it gets deleted (on the next occasion Lua's
-- garbage collector is run). However since garbage collection cycles are -- garbage collector is run). However since garbage collection cycles are
@@ -366,14 +372,14 @@ function receive_buf(delimiter, keeppattern)
function close() function close()
--- Gets information about a socket. --- Gets information about a socket.
-- \n\n --
-- This function returns information about the socket object. It returns 5 -- This function returns information about a socket object. It returns five
-- values. If an error occurred, the first value is nil and the second value -- values. If an error occurred, the first value is <code>nil</code> and the
-- describes the error condition. Otherwise the first value describes the -- second value is an error string. Otherwise the first value is true and the
-- success of the operation and the remaining 4 values describe both endpoints -- remaining 4 values describe both endpoints of the TCP connection. If you put
-- of the TCP connection. If you put the call in a try() statement the status -- the call inside an exception handler created by <code>new_try()</code> the
-- value is consumed. The call can be used for example if you want to query an -- status value is consumed. The call can be used for example if you want to
-- authentication server. -- query an authentication server.
-- @return Status (true or false). -- @return Status (true or false).
-- @return Local IP address (if status is true) or error string (if status is -- @return Local IP address (if status is true) or error string (if status is
-- false). -- false).
@@ -385,7 +391,7 @@ function close()
function get_info() function get_info()
--- Sets a timeout for socket input and output operations. --- Sets a timeout for socket input and output operations.
-- \n\n --
-- After this time, given in milliseconds, socket operations will time out and -- After this time, given in milliseconds, socket operations will time out and
-- return. The default value is 30,000 (30 seconds). The lowest allowed value is -- return. The default value is 30,000 (30 seconds). The lowest allowed value is
-- 10 ms, since this is the granularity of NSE network I/O. -- 10 ms, since this is the granularity of NSE network I/O.
@@ -395,20 +401,20 @@ function get_info()
function set_timeout(t) function set_timeout(t)
--- Opens a socket for raw packet capture. --- Opens a socket for raw packet capture.
-- \n\n --
-- The callback function is a function that receives a packet with headers and -- The callback function is a function that receives a packet with headers and
-- computes a "packet hash"--some value derived from the packet. For example, -- computes a "packet hash", some value derived from the packet. For example,
-- the callback function could extract the source IP address from a packet. The -- the callback function could extract the source IP address from a packet. The
-- hash of each packet received is compared against all the strings registered -- hash of each packet received is compared against all the strings registered
-- with the pcap_register function. -- with the <code>pcap_register</code> function.
-- @param device The dnet-style interface name of the device you want to capture -- @param device The dnet-style interface name of the device you want to capture
-- from. -- from.
-- @param snaplen The length of each packet you want to capture (similar to the -- @param snaplen The length of each packet you want to capture (similar to the
-- -s option to tcpdump)\n -- <code>-s</code> option to tcpdump)
-- @param promisc Should be set to 1 if the interface should activate -- @param promisc Set to 1 if the interface should activate promiscuous mode,
-- promiscuous mode, and 0 otherwise. -- and 0 otherwise.
-- @param test_function Callback function used to compute the packet hash. -- @param test_function Callback function used to compute the packet hash.
-- @param bpf A string describing a Berkeley packet filter expression (like -- @param bpf A string describing a Berkeley Packet Filter expression (like
-- those provided to tcpdump). -- those provided to tcpdump).
-- @see new_socket, pcap_register, pcap_receive -- @see new_socket, pcap_register, pcap_receive
-- @usage -- @usage
@@ -416,19 +422,20 @@ function set_timeout(t)
-- socket:pcap_open("eth0", 64, 0, callback, "tcp") -- socket:pcap_open("eth0", 64, 0, callback, "tcp")
function pcap_open(device, snaplen, promisc, test_function, bpf) function pcap_open(device, snaplen, promisc, test_function, bpf)
--- Starts listening for incoming packages. --- Starts listening for incoming packets.
-- \n\n --
-- The provided packet_hash is a binary string which has to match the hash -- The provided <code>packet_hash</code> is a binary string which has to match
-- returned by the test_function parameter provided to pcap_open(). If you want -- the hash returned by the <code>test_function</code> parameter provided to
-- to receive all packets, just provide the empty string (""). There has to be a -- <code>pcap_open()</code>. If you want to receive all packets, just provide
-- call to pcap_register() before a call to pcap_receive(). -- the empty string (<code>""</code>). There has to be a call to
-- <code>pcap_register()</code> before a call to <code>pcap_receive()</code>.
-- @param packet_hash A binary string that is compared against packet hashes. -- @param packet_hash A binary string that is compared against packet hashes.
-- @see pcap_open, pcap_receive -- @see pcap_open, pcap_receive
-- @usage socket:pcap_register("") -- @usage socket:pcap_register("")
function pcap_register(packet_hash) function pcap_register(packet_hash)
--- Receives a captured packet. --- Receives a captured packet.
-- \n\n --
-- If an error or timeout occurs, the function returns false and an error -- If an error or timeout occurs, the function returns false and an error
-- message. Otherwise, the function returns true followed by the packet length, -- message. Otherwise, the function returns true followed by the packet length,
-- the layer two header, and the layer three header. -- the layer two header, and the layer three header.
@@ -442,7 +449,7 @@ function pcap_register(packet_hash)
-- @usage status, plen, l2_data, l3_data = socket:pcap_receive() -- @usage status, plen, l2_data, l3_data = socket:pcap_receive()
function pcap_receive() function pcap_receive()
--- Closes the pcap device. --- Closes a pcap device.
-- @see close, pcap_close -- @see close, pcap_close
-- @usage socket:pcap_close() -- @usage socket:pcap_close()
function pcap_close() function pcap_close()
@@ -452,29 +459,29 @@ function pcap_close()
function new_dnet() function new_dnet()
--- Opens an ethernet interface for raw packet sending. --- Opens an ethernet interface for raw packet sending.
-- \n\n --
-- An error ("device is not valid ethernet interface") is thrown in case the -- An error (<code>"device is not valid ethernet interface"</code>) is thrown
-- provided argument is not valid. -- in case the provided argument is not valid.
-- @param interface_name The dnet-style name of the interface to open. -- @param interface_name The dnet-style name of the interface to open.
-- @see new_dnet -- @see new_dnet
-- @usage dnet:ethernet_open("eth0") -- @usage dnet:ethernet_open("eth0")
function ethernet_open(interface_name) function ethernet_open(interface_name)
--- Sends a raw ethernet frame. --- Sends a raw ethernet frame.
-- \n\n --
-- The dnet object must be associated with a previously opened interface. The -- The dnet object must be associated with a previously opened interface. The
-- packet must include the IP and ethernet headers If there was no previous -- packet must include the IP and ethernet headers. If there was no previous
-- valid call to ethernet_open() an error is thrown ("dnet is not valid opened -- valid call to <code>ethernet_open()</code> an error is thrown
-- ethernet interface"). -- (<code>"dnet is not valid opened ethernet interface"</code>).
-- @param packet An ethernet frame to send. -- @param packet An ethernet frame to send.
-- @see new_dnet -- @see new_dnet
-- @usage dnet:ethernet_open(packet) -- @usage dnet:ethernet_open(packet)
function ethernet_send(packet) function ethernet_send(packet)
--- Closes an ethernet interface. --- Closes an ethernet interface.
-- \n\n --
-- An error ("device is not valid ethernet interface") is thrown in case the -- An error (<code>"device is not valid ethernet interface"</code>) is thrown
-- provided argument is not valid. -- in case the provided argument is not valid.
-- @see new_dnet, ethernet_open -- @see new_dnet, ethernet_open
-- @usage dnet:ethernet_close() -- @usage dnet:ethernet_close()
function ethernet_close() function ethernet_close()

View File

@@ -1,20 +1,19 @@
--- OpenSSL bindings. --- OpenSSL bindings.
-- \n\n --
-- This module is a wrapper for OpenSSL functions that provide encryption and -- This module is a wrapper for OpenSSL functions that provide encryption and
-- decryption, hashing, and multiprecision integers. -- decryption, hashing, and multiprecision integers.
-- \n\n --
-- The openssl module may not always be available--it depends on whether -- The <code>openssl</code> module may not always be available. It depends on
-- OpenSSL support was enabled at compile time. Scripts using the module should -- whether OpenSSL support was enabled at compile time. Scripts using the
-- be made to fail gracefully using code like the following: -- module should be made to fail gracefully using code like the following:
-- \n\n
-- <code> -- <code>
-- if not pcall(require, "openssl") then\n -- if not pcall(require, "openssl") then
-- action = function(host, port)\n -- action = function(host, port)
-- stdnse.print_debug(2, "Skipping \"%s\" because OpenSSL is missing.", id)\n -- stdnse.print_debug(2, "Skipping \"%s\" because OpenSSL is missing.", id)
-- end\n -- end
-- end\n -- end
-- action = action or function(host, port)\n -- action = action or function(host, port)
-- ...\n -- ...
-- end -- end
-- </code> -- </code>
-- @author Sven Klemm <sven@c3d2.de> -- @author Sven Klemm <sven@c3d2.de>
@@ -22,102 +21,168 @@
module "openssl" module "openssl"
--- Returns the size of bignum in bits. --- Returns the size of <code>bignum</code> in bits.
-- @param bignum bignum to operate on.
-- @return Size of <code>bignum</code>.
function bignum_num_bits(bignum) function bignum_num_bits(bignum)
--- Returns the size of bignum in bytes. --- Returns the size of <code>bignum</code> in bytes.
-- @param bignum bignum to operate on.
-- @return Size of <code>bignum</code>.
function bignum_num_bytes(bignum) function bignum_num_bytes(bignum)
--- Sets the bit at position in bignum. --- Sets the bit at <code>position</code> in <code>bignum</code>.
-- @param bignum bignum to operate on.
-- @param position Bit position.
function bignum_set_bit(bignum, position) function bignum_set_bit(bignum, position)
--- Clears the bit at position in bignum. --- Clears the bit at <code>position</code> in <code>bignum</code>.
-- @param bignum bignum to operate on.
-- @param position Bit position.
function bignum_clear_bit(bignum, position) function bignum_clear_bit(bignum, position)
--- Gets the state of the bit at position in bignum. --- Gets the state of the bit at <code>position</code> in <code>bignum</code>.
-- @param bignum bignum to operate on.
-- @param position Bit position.
-- @return True if the selected bit is set, false otherwise.
function bignum_is_bit_set(bignum, position) function bignum_is_bit_set(bignum, position)
--- Sets the sign of bignum. If negative is true the sign becomes negative, --- Sets the sign of <code>bignum</code>.
-- otherwise it becomes positive. -- @param bignum bignum to operate on.
-- @param negative If true, the sign becomes negative, otherwise it becomes
-- positive.
function bignum_set_negative(bignum, negative) function bignum_set_negative(bignum, negative)
--- Returns true if bignum is negative, false otherwise. --- Gets the sign of <code>bignum</code>.
-- @param bignum bignum to operate on.
-- @return True if <code>bignum</code> is negative, false otherwise.
function bignum_is_negative(bignum) function bignum_is_negative(bignum)
--- Converts the binary-encoded string into a bignum. --- Converts a binary-encoded string into a bignum.
-- @param string Binary string.
-- @return bignum.
function bignum_bin2bn(string) function bignum_bin2bn(string)
--- Converts the decimal-encoded string into a bignum. --- Converts a decimal-encoded string into a bignum.
-- @param string Decimal string.
-- @return bignum.
function bignum_dec2bn(string) function bignum_dec2bn(string)
--- Converts the hex-encoded string into a bignum. --- Converts a hex-encoded string into a bignum.
-- @param string Hex string.
-- @return bignum.
function bignum_hex2bn(string) function bignum_hex2bn(string)
--- Converts bignum into a binary-encoded string. --- Converts <code>bignum</code> into a binary-encoded string.
-- @param bignum bignum to operate on.
-- @return Binary string.
function bignum_bn2bin(bignum) function bignum_bn2bin(bignum)
--- Converts bignum into a decimal-encoded string. --- Converts <code>bignum</code> into a decimal-encoded string.
-- @param bignum bignum to operate on.
-- @return Decimal string.
function bignum_bn2dec(bignum) function bignum_bn2dec(bignum)
--- Converts bignum into a hex-encoded string. --- Converts <code>bignum</code> into a hex-encoded string.
-- @param bignum bignum to operate on.
-- @return Hex string.
function bignum_bn2hex(bignum) function bignum_bn2hex(bignum)
--- Returns a random bignum with a --- Returns a random bignum.
-- @param bits Size of the returned bignum in bits.
-- @return Random bignum.
function bignum_rand(bits) function bignum_rand(bits)
--- Returns a pseudorandom bignum with a the given size in bits. --- Returns a pseudorandom bignum.
-- @param bits Size of the returned bignum in bits.
-- @return Pseudoandom bignum.
function bignum_pseudo_rand(bits) function bignum_pseudo_rand(bits)
--- Returns the bignum which is the result of a^p mod m. --- Returns the bignum which is the result of <code>a</code>^<code>p</code> mod
-- <code>m</code>.
-- @param a Base.
-- @param p Exponent.
-- @param m Modulus.
-- @return bignum.
function bignum_mod_exp(a, p, m) function bignum_mod_exp(a, p, m)
--- Returns a string of length bytes containing random data. --- Returns a string containing random data.
-- @param bytes Length of the returned string in bytes.
-- @return Random string.
function rand_bytes(bytes) function rand_bytes(bytes)
--- Returns a string of length bytes containing pseudorandom data. --- Returns a string containing pseudorandom data.
-- @param bytes Length of the returned string in bytes.
-- @return Pseudorandom string.
function rand_pseudo_bytes(bytes) function rand_pseudo_bytes(bytes)
--- Returns the MD2 digest of message. --- Returns the MD2 digest of a string.
-- @param message String to digest.
-- @return MD2 digest.
function md2(message) function md2(message)
--- Returns the MD4 digest of message. --- Returns the MD4 digest of a string.
-- @param message String to digest.
-- @return MD4 digest.
function md4(message) function md4(message)
--- Returns the MD5 digest of message. --- Returns the MD5 digest of a string.
-- @param message String to digest.
-- @return MD5 digest.
function md5(message) function md5(message)
--- Returns the SHA-1 digest of message. --- Returns the SHA-1 digest of a string.
-- @param message String to digest.
-- @return SHA-1 digest.
function sha1(message) function sha1(message)
--- Returns the RIPEMD-160 digest of message. --- Returns the RIPEMD-160 digest of a string.
-- @param message String to digest.
-- @return RIPEMD-160 digest.
function ripemd160(message) function ripemd160(message)
--- Returns the digest of message using the algorithm given by the string --- Returns the digest of a string using a named algorithm.
-- algorithm. The algorithm name may be anything returned by the -- @param algorithm Any of the strings returned by
-- openssl.supported_digests function. -- <code>openssl.supported_digests</code>.
-- @param message String to digest.
function digest(algorithm, message) function digest(algorithm, message)
--- Returns the message authentication code of message using the given algorithm --- Returns the message authentication code of a string using a named algorithm.
-- and key. algorithm may be anything returned by the openssl.supported_digests -- @param algorithm Any of the strings returned by
-- function. -- <code>openssl.supported_digests</code>.
-- @param key Key.
-- @param message String.
function hmac(algorithm, key, message) function hmac(algorithm, key, message)
--- Encrypt data with the given algorithm, key, and initialization vector. --- Encrypt data with a given algorithm, key, and initialization vector.
-- algorithm may be anything returned by the openssl.supported_ciphers function. -- @param algorithm Any of the strings returned by
-- If padding is true then a partial final block will be padded and encrypted. -- <code>openssl.supported_ciphers</code>.
function encrypt(algorithm, key, iv, data, padding = false) -- @param key Key.
-- @param iv Initialization vector.
-- @param data Data to encrypt.
-- @param padding If true, then a partial final block will be padded and
-- encrypted (default false).
function encrypt(algorithm, key, iv, data, padding)
--- Encrypt data with the given algorithm, key, and initialization vector. --- Descrypt data with a given algorithm, key, and initialization vector.
-- algorithm may be anything returned by the openssl.supported_ciphers function. -- @param algorithm Any of the strings returned by
-- If padding is true then the final block must be padded correctly. -- <code>openssl.supported_ciphers</code>.
function decrypt(algorithm, key, iv, data, padding = false) -- @param key Key.
-- @param iv Initialization vector.
-- @param data Data to encrypt.
-- @param padding If true, then the final block must be padded correctly
-- (default false).
function decrypt(algorithm, key, iv, data, padding)
--- Returns a table with the names of the supported cipher algorithms. --- Returns a table with the names of the supported cipher algorithms.
-- @return Array containing cipher names as strings.
function supported_ciphers() function supported_ciphers()
--- Returns a table with the names of the supported digest algorithms. --- Returns a table with the names of the supported digest algorithms.
-- @return Array containing digest names as strings.
function supported_digests() function supported_digests()
--- Converts data, which must be a 7-byte string, into an 8-byte DES key and --- Converts a 56-bit DES key into a 64-bit key with the correct parity.
-- sets the parity. -- @param data A 7-byte string.
-- @return An 8-byte string.
function DES_string_to_key(string data) function DES_string_to_key(string data)

View File

@@ -8,18 +8,27 @@ require "bit"
---------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------
--- Get an 8-bit integer at a 0-based byte offset in a binary string. --- Get an 8-bit integer at a 0-based byte offset in a byte string.
-- @param b A byte string.
-- @param i Offset.
-- @return An 8-bit integer.
function u8(b, i) function u8(b, i)
return string.byte(b, i+1) return string.byte(b, i+1)
end end
--- Get a 16-bit integer at a 0-based byte offset in a binary string. --- Get a 16-bit integer at a 0-based byte offset in a byte string.
-- @param b A byte string.
-- @param i Offset.
-- @return A 16-bit integer.
function u16(b, i) function u16(b, i)
local b1,b2 local b1,b2
b1, b2 = string.byte(b, i+1), string.byte(b, i+2) b1, b2 = string.byte(b, i+1), string.byte(b, i+2)
-- 2^8 2^0 -- 2^8 2^0
return b1*256 + b2 return b1*256 + b2
end end
--- Get a 32-bit integer at a 0-based byte offset in a binary string. --- Get a 32-bit integer at a 0-based byte offset in a byte string.
-- @param b A byte string.
-- @param i Offset.
-- @return A 32-bit integer.
function u32(b,i) function u32(b,i)
local b1,b2,b3,b4 local b1,b2,b3,b4
b1, b2 = string.byte(b, i+1), string.byte(b, i+2) b1, b2 = string.byte(b, i+1), string.byte(b, i+2)
@@ -28,20 +37,29 @@ function u32(b,i)
return b1*16777216 + b2*65536 + b3*256 + b4 return b1*16777216 + b2*65536 + b3*256 + b4
end end
--- Set an 8-bit integer at a 0-based byte offset in a binary string --- Set an 8-bit integer at a 0-based byte offset in a byte string
-- (big-endian). -- (big-endian).
-- @param b A byte string.
-- @param i Offset.
-- @param num Integer to store.
function set_u8(b, i, num) function set_u8(b, i, num)
local s = string.char(bit.band(num, 0xff)) local s = string.char(bit.band(num, 0xff))
return b:sub(0+1, i+1-1) .. s .. b:sub(i+1+1) return b:sub(0+1, i+1-1) .. s .. b:sub(i+1+1)
end end
--- Set a 16-bit integer at a 0-based byte offset in a binary string --- Set a 16-bit integer at a 0-based byte offset in a byte string
-- (big-endian). -- (big-endian).
-- @param b A byte string.
-- @param i Offset.
-- @param num Integer to store.
function set_u16(b, i, num) function set_u16(b, i, num)
local s = string.char(bit.band(bit.rshift(num, 8), 0xff)) .. string.char(bit.band(num, 0xff)) local s = string.char(bit.band(bit.rshift(num, 8), 0xff)) .. string.char(bit.band(num, 0xff))
return b:sub(0+1, i+1-1) .. s .. b:sub(i+1+2) return b:sub(0+1, i+1-1) .. s .. b:sub(i+1+2)
end end
--- Set a 32-bit integer at a 0-based byte offset in a binary string --- Set a 32-bit integer at a 0-based byte offset in a byte string
-- (big-endian). -- (big-endian).
-- @param b A byte string.
-- @param i Offset.
-- @param num Integer to store.
function set_u32(b,i, num) function set_u32(b,i, num)
local s = string.char(bit.band(bit.rshift(num,24), 0xff)) .. local s = string.char(bit.band(bit.rshift(num,24), 0xff)) ..
string.char(bit.band(bit.rshift(num,16), 0xff)) .. string.char(bit.band(bit.rshift(num,16), 0xff)) ..
@@ -51,8 +69,9 @@ function set_u32(b,i, num)
end end
-- Checksum
--- Calculate a standard Internet checksum. --- Calculate a standard Internet checksum.
-- @param b Data to checksum.
-- @return Checksum.
function in_cksum(b) function in_cksum(b)
local sum = 0 local sum = 0
local c local c
@@ -101,14 +120,14 @@ IPPROTO_UDPLITE = 136 -- UDP-Lite (RFC 3828)
Packet = {} Packet = {}
--- Create a new Packet object. --- Create a new Packet object.
-- @param packet binary string with packet data. -- @param packet Binary string with packet data.
-- @param packet_len packet length, it could be more than string.len(packet). -- @param packet_len Packet length. It could be more than
-- @param force_continue whether error in parsing headers should be -- <code>string.len(packet)</code>.
-- fatal or not. Especially useful at parsing ICMP packets, where a -- @param force_continue whether an error in parsing headers should be fatal or
-- small ICMP payload could be a TCP header. The problem is that parsing -- not. This is especially useful when parsing ICMP packets, where a small ICMP
-- this payload normally would fail (broken packet, because TCP header -- payload could be a TCP header. The problem is that parsing this payload
-- is too small) The basic question is if too short TCP header should be -- normally would fail because the TCP header is too small.
-- treated as fatal error. -- @return A new Packet.
function Packet:new(packet, packet_len, force_continue) function Packet:new(packet, packet_len, force_continue)
local o = setmetatable({}, {__index = Packet}) local o = setmetatable({}, {__index = Packet})
o.buf = packet o.buf = packet
@@ -131,8 +150,10 @@ end
-- Helpers -- Helpers
--- Convert a dotted-quad IP address string (like 1.2.3.4) to a raw --- Convert a dotted-quad IP address string (like <code>"1.2.3.4"</code>) to a
-- string four bytes long. -- raw string four bytes long.
-- @param str IP address string.
-- @return Four-byte string.
function iptobin(str) function iptobin(str)
local ret = "" local ret = ""
for c in string.gmatch(str, "[0-9]+") do for c in string.gmatch(str, "[0-9]+") do
@@ -141,6 +162,8 @@ function iptobin(str)
return ret return ret
end end
--- Convert a four-byte raw string to a dotted-quad IP address string. --- Convert a four-byte raw string to a dotted-quad IP address string.
-- @param raw_ip_addr Four-byte string.
-- @return IP address string.
function toip(raw_ip_addr) function toip(raw_ip_addr)
if not raw_ip_addr then if not raw_ip_addr then
return "?.?.?.?" return "?.?.?.?"
@@ -148,42 +171,59 @@ function toip(raw_ip_addr)
return string.format("%i.%i.%i.%i", string.byte(raw_ip_addr,1,4)) return string.format("%i.%i.%i.%i", string.byte(raw_ip_addr,1,4))
end end
--- Get an 8-bit integer at a 0-based byte offset in the packet. --- Get an 8-bit integer at a 0-based byte offset in the packet.
-- @param index Offset.
-- @return An 8-bit integer.
function Packet:u8(index) function Packet:u8(index)
return u8(self.buf, index) return u8(self.buf, index)
end end
--- Get a 16-bit integer at a 0-based byte offset in the packet. --- Get a 16-bit integer at a 0-based byte offset in the packet.
-- @param index Offset.
-- @return A 16-bit integer.
function Packet:u16(index) function Packet:u16(index)
return u16(self.buf, index) return u16(self.buf, index)
end end
--- Get a 32-bit integer at a 0-based byte offset in the packet. --- Get a 32-bit integer at a 0-based byte offset in the packet.
-- @param index Offset.
-- @return An 32-bit integer.
function Packet:u32(index) function Packet:u32(index)
return u32(self.buf, index) return u32(self.buf, index)
end end
--- Return the packet contents as a byte string. --- Return part of the packet contents as a byte string.
-- @param index The beginning of the part of the packet to extract.
-- @param length The length of the part of the packet to extract.
-- @return A string.
function Packet:raw(index, length) function Packet:raw(index, length)
return string.char(string.byte(self.buf, index+1, index+1+length-1)) return string.char(string.byte(self.buf, index+1, index+1+length-1))
end end
--- Set an 8-bit integer at a 0-based byte offset in the packet. --- Set an 8-bit integer at a 0-based byte offset in the packet.
-- (big-endian). -- (big-endian).
-- @param index Offset.
-- @param num Integer to store.
function Packet:set_u8(index, num) function Packet:set_u8(index, num)
self.buf = set_u8(self.buf, index, num) self.buf = set_u8(self.buf, index, num)
return self.buf return self.buf
end end
--- Set a 16-bit integer at a 0-based byte offset in the packet. --- Set a 16-bit integer at a 0-based byte offset in the packet.
-- (big-endian). -- (big-endian).
-- @param index Offset.
-- @param num Integer to store.
function Packet:set_u16(index, num) function Packet:set_u16(index, num)
self.buf = set_u16(self.buf, index, num) self.buf = set_u16(self.buf, index, num)
return self.buf return self.buf
end end
--- Set a 32-bit integer at a 0-based byte offset in the packet. --- Set a 32-bit integer at a 0-based byte offset in the packet.
-- (big-endian). -- (big-endian).
-- @param index Offset.
-- @param num Integer to store.
function Packet:set_u32(index, num) function Packet:set_u32(index, num)
self.buf = set_u32(self.buf, index, num) self.buf = set_u32(self.buf, index, num)
return self.buf return self.buf
end end
--- Parse an IP packet header. --- Parse an IP packet header.
-- @param force_continue Ignored.
-- @return Whether the parsing succeeded.
function Packet:ip_parse(force_continue) function Packet:ip_parse(force_continue)
self.ip_offset = 0 self.ip_offset = 0
if string.len(self.buf) < 20 then -- too short if string.len(self.buf) < 20 then -- too short
@@ -222,14 +262,17 @@ function Packet:ip_set_hl(len)
self.ip_hl = bit.band(self:u8(self.ip_offset + 0), 0x0F) -- header_length or data_offset self.ip_hl = bit.band(self:u8(self.ip_offset + 0), 0x0F) -- header_length or data_offset
end end
--- Set the packet length field. --- Set the packet length field.
-- @param len Packet length.
function Packet:ip_set_len(len) function Packet:ip_set_len(len)
self:set_u16(self.ip_offset + 2, len) self:set_u16(self.ip_offset + 2, len)
end end
--- Set the TTL. --- Set the TTL.
-- @param ttl TTL.
function Packet:ip_set_ttl(ttl) function Packet:ip_set_ttl(ttl)
self:set_u8(self.ip_offset + 8, ttl) self:set_u8(self.ip_offset + 8, ttl)
end end
--- Set the checksum. --- Set the checksum.
-- @param checksum Checksum.
function Packet:ip_set_checksum(checksum) function Packet:ip_set_checksum(checksum)
self:set_u16(self.ip_offset + 10, checksum) self:set_u16(self.ip_offset + 10, checksum)
end end
@@ -240,12 +283,14 @@ function Packet:ip_count_checksum()
self:ip_set_checksum(csum) self:ip_set_checksum(csum)
end end
--- Set the source IP address. --- Set the source IP address.
-- @param binip The source IP address as a byte string.
function Packet:ip_set_bin_src(binip) function Packet:ip_set_bin_src(binip)
nrip = u32(binip, 0) nrip = u32(binip, 0)
self:set_u32(self.ip_offset + 12, nrip) self:set_u32(self.ip_offset + 12, nrip)
self.ip_bin_src = self:raw(self.ip_offset + 12,4) -- raw 4-bytes string self.ip_bin_src = self:raw(self.ip_offset + 12,4) -- raw 4-bytes string
end end
--- Set the destination IP address. --- Set the destination IP address.
-- @param binip The destination IP address as a byte string.
function Packet:ip_set_bin_dst(binip) function Packet:ip_set_bin_dst(binip)
nrip = u32(binip, 0) nrip = u32(binip, 0)
self:set_u32(self.ip_offset + 16, nrip) self:set_u32(self.ip_offset + 16, nrip)
@@ -253,6 +298,7 @@ function Packet:ip_set_bin_dst(binip)
end end
--- Set the IP options field (and move the data, count new length, --- Set the IP options field (and move the data, count new length,
-- etc.). -- etc.).
-- @param ipoptions IP options.
function Packet:ip_set_options(ipoptions) function Packet:ip_set_options(ipoptions)
-- packet = <ip header> + ipoptions + <payload> -- packet = <ip header> + ipoptions + <payload>
local buf = self.buf:sub(0+1,self.ip_offset + 20) .. ipoptions .. self.buf:sub(self.ip_data_offset+1) local buf = self.buf:sub(0+1,self.ip_offset + 20) .. ipoptions .. self.buf:sub(self.ip_data_offset+1)
@@ -271,7 +317,8 @@ function Packet:ip_set_options(ipoptions)
end end
end end
--- Return a short string representation of the IP header. --- Get a short string representation of the IP header.
-- @return A string representation of the IP header.
function Packet:ip_tostring() function Packet:ip_tostring()
return string.format( return string.format(
"IP %s -> %s", "IP %s -> %s",
@@ -280,6 +327,9 @@ function Packet:ip_tostring()
end end
--- Parse IP/TCP options into a table. --- Parse IP/TCP options into a table.
-- @param offset Offset at which options start.
-- @param length Length of options.
-- @return Table of options.
function Packet:parse_options(offset, length) function Packet:parse_options(offset, length)
local options = {} local options = {}
local op = 1 local op = 1
@@ -307,7 +357,8 @@ function Packet:parse_options(offset, length)
return options return options
end end
--- Return a short string representation of the packet. --- Get a short string representation of the packet.
-- @return A string representation of the packet.
function Packet:tostring() function Packet:tostring()
if self.tcp then if self.tcp then
return self:tcp_tostring() return self:tcp_tostring()
@@ -321,6 +372,8 @@ end
---------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------
--- Parse an ICMP packet header. --- Parse an ICMP packet header.
-- @param force_continue Ignored.
-- @return Whether the parsing succeeded.
function Packet:icmp_parse(force_continue) function Packet:icmp_parse(force_continue)
self.icmp_offset = self.ip_data_offset self.icmp_offset = self.ip_data_offset
if string.len(self.buf) < self.icmp_offset + 8 then -- let's say 8 bytes minimum if string.len(self.buf) < self.icmp_offset + 8 then -- let's say 8 bytes minimum
@@ -342,13 +395,16 @@ function Packet:icmp_parse(force_continue)
end end
return true return true
end end
--- Return a short string representation of the ICMP header. --- Get a short string representation of the ICMP header.
-- @return A string representation of the ICMP header.
function Packet:icmp_tostring() function Packet:icmp_tostring()
return self:ip_tostring() .. " ICMP(" .. self.icmp_payload:tostring() .. ")" return self:ip_tostring() .. " ICMP(" .. self.icmp_payload:tostring() .. ")"
end end
---------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------
-- Parse a TCP packet header. -- Parse a TCP packet header.
-- @param force_continue Whether a short packet causes parsing to fail.
-- @return Whether the parsing succeeded.
function Packet:tcp_parse(force_continue) function Packet:tcp_parse(force_continue)
self.tcp = true self.tcp = true
self.tcp_offset = self.ip_data_offset self.tcp_offset = self.ip_data_offset
@@ -388,7 +444,8 @@ function Packet:tcp_parse(force_continue)
return true return true
end end
--- Return a short string representation of the TCP packet. --- Get a short string representation of the TCP packet.
-- @return A string representation of the ICMP header.
function Packet:tcp_tostring() function Packet:tcp_tostring()
return string.format( return string.format(
"TCP %s:%i -> %s:%i", "TCP %s:%i -> %s:%i",
@@ -420,26 +477,32 @@ function Packet:tcp_parse_options()
end end
--- Set the TCP source port. --- Set the TCP source port.
-- @param port Source port.
function Packet:tcp_set_sport(port) function Packet:tcp_set_sport(port)
self:set_u16(self.tcp_offset + 0, port) self:set_u16(self.tcp_offset + 0, port)
end end
--- Set the TCP destination port. --- Set the TCP destination port.
-- @param port Destination port.
function Packet:tcp_set_dport(port) function Packet:tcp_set_dport(port)
self:set_u16(self.tcp_offset + 2, port) self:set_u16(self.tcp_offset + 2, port)
end end
--- Set the TCP sequence field. --- Set the TCP sequence field.
-- @param new_seq Sequence.
function Packet:tcp_set_seq(new_seq) function Packet:tcp_set_seq(new_seq)
self:set_u32(self.tcp_offset + 4, new_seq) self:set_u32(self.tcp_offset + 4, new_seq)
end end
--- Set the TCP flags field (like SYN, ACK, RST). --- Set the TCP flags field (like SYN, ACK, RST).
-- @param new_flags Flags, represented as an 8-bit number.
function Packet:tcp_set_flags(new_flags) function Packet:tcp_set_flags(new_flags)
self:set_u8(self.tcp_offset + 13, new_flags) self:set_u8(self.tcp_offset + 13, new_flags)
end end
--- Set the urgent pointer field. --- Set the urgent pointer field.
-- @param urg_ptr Urgent pointer.
function Packet:tcp_set_urp(urg_ptr) function Packet:tcp_set_urp(urg_ptr)
self:set_u16(self.tcp_offset + 18, urg_ptr) self:set_u16(self.tcp_offset + 18, urg_ptr)
end end
--- Set the TCP checksum field. --- Set the TCP checksum field.
-- @param checksum Checksum.
function Packet:tcp_set_checksum(checksum) function Packet:tcp_set_checksum(checksum)
self:set_u16(self.tcp_offset + 16, checksum) self:set_u16(self.tcp_offset + 16, checksum)
end end
@@ -459,6 +522,7 @@ function Packet:tcp_count_checksum()
end end
--- Map an MTU to a link type string. Stolen from p0f. --- Map an MTU to a link type string. Stolen from p0f.
-- @return A string describing the link type.
function Packet:tcp_lookup_link() function Packet:tcp_lookup_link()
local mtu_def = { local mtu_def = {
{["mtu"]=256, ["txt"]= "radio modem"}, {["mtu"]=256, ["txt"]= "radio modem"},
@@ -521,7 +585,9 @@ end
-- UTILS -- UTILS
--- Convert a binary string to a hex string. --- Convert a byte string to a hex string.
-- @param str Byte string.
-- @return Hex string.
function bintohex(str) function bintohex(str)
local b = "" local b = ""
if not str then -- nil if not str then -- nil
@@ -535,14 +601,17 @@ end
--- Convert a hex string to a binary string. --- Convert a hex string to a byte string.
-- \n\n --
-- Only bytes [a-f0-9A-F] from input are interpreted. The rest is ignored. -- Only bytes <code>[a-f0-9A-F]</code> from input are interpreted. The rest is
-- Number of interpreted bytes _must_ be even. *The input is interpreted in pairs*.\n -- ignored. The number of interpreted bytes must be even.
-- hextobin("20 20 20") -> " "\n -- @param str Hex string.
-- hextobin("414243") -> "ABC"\n -- @return Byte string.
-- hextobin("\\41\\42\\43") -> "ABC"\n -- @usage
-- hextobin(" 41 42 43 ")-> "ABC" -- hextobin("20 20 20") --> " "
-- hextobin("414243") --> "ABC"
-- hextobin("\\41\\42\\43") --> "ABC"
-- hextobin(" 41 42 43 ") --> "ABC"
function hextobin(str) function hextobin(str)
local ret = "" local ret = ""
local a,b local a,b

View File

@@ -1,5 +1,5 @@
--- Perl Compatible Regular Expressions. --- Perl Compatible Regular Expressions.
-- \n\n --
-- One of Lua's quirks is its string patterns. While they have great performance -- One of Lua's quirks is its string patterns. While they have great performance
-- and are tightly integrated into the Lua interpreter, they are very different -- and are tightly integrated into the Lua interpreter, they are very different
-- in syntax and not as powerful as standard regular expressions. So we have -- in syntax and not as powerful as standard regular expressions. So we have
@@ -15,10 +15,10 @@
-- separate pattern compilation step, which saves execution time when patterns -- separate pattern compilation step, which saves execution time when patterns
-- are reused. Compiled patterns can be cached in the NSE registry and reused -- are reused. Compiled patterns can be cached in the NSE registry and reused
-- by other scripts. -- by other scripts.
-- \n\n --
-- The documentation for this module is derived from that supplied by the PCRE -- The documentation for this module is derived from that supplied by the PCRE
-- Lua lib. -- Lua lib.
-- \n\n --
-- Warning: PCRE has a history of security vulnerabilities allowing attackers -- Warning: PCRE has a history of security vulnerabilities allowing attackers
-- who are able to compile arbitrary regular expressions to execute arbitrary -- who are able to compile arbitrary regular expressions to execute arbitrary
-- code. More such vulnerabilities may be discovered in the future. These have -- code. More such vulnerabilities may be discovered in the future. These have
@@ -32,50 +32,53 @@
module "pcre" module "pcre"
--- Returns a compiled regular expression. --- Returns a compiled regular expression.
-- \n\n --
-- The resulting compiled regular expression is ready to be matched against -- The resulting compiled regular expression is ready to be matched against
-- strings. Compiled regular expressions are subject to Lua's garbage -- strings. Compiled regular expressions are subject to Lua's garbage
-- collection. -- collection.
-- \n\n --
-- The compilation flags are set bitwise. If you want to set the 3rd -- The compilation flags are set bitwise. If you want to set the 3rd
-- (corresponding to the number 4) and the 1st (corresponding to 1) bit for -- (corresponding to the number 4) and the 1st (corresponding to 1) bit for
-- example you would pass the number 5 as a second argument. The compilation -- example you would pass the number 5 as a second argument. The compilation
-- flags accepted are those of the PCRE C library. These include flags for case -- flags accepted are those of the PCRE C library. These include flags for case
-- insensitive matching (1), matching line beginnings (^) and endings ($) even -- insensitive matching (<code>1</code>), matching line beginnings
-- in multiline strings (i.e. strings containing newlines) (2) and a flag for -- (<code>^</code>) and endings (<code>$</code>) even in multiline strings
-- matching across line boundaries (4). No compilation flags yield a default -- (i.e. strings containing newlines) (<code>2</code>) and a flag for matching
-- value of 0. -- across line boundaries (<code>4</code>). No compilation flags yield a
-- @param pattern a string describing the pattern, such as "^foo$". -- default value of <code>0</code>.
-- @param pattern a string describing the pattern, such as <code>"^foo$"</code>.
-- @param flags a number describing which compilation flags are set. -- @param flags a number describing which compilation flags are set.
-- @param locale a string describing the locale which should be used to compile -- @param locale a string describing the locale which should be used to compile
-- the regular expression (optional). The value is a string which is passed to -- the regular expression (optional). The value is a string which is passed to
-- the C standard library function setlocale. For more information on this -- the C standard library function <code>setlocale</code>. For more
-- argument refer to the documentation of setlocale. -- information on this argument refer to the documentation of
-- <code>setlocale</code>.
-- @usage local regex = pcre.new("pcre-pattern",0,"C") -- @usage local regex = pcre.new("pcre-pattern",0,"C")
function new(pattern, flags, locale) function new(pattern, flags, locale)
--- Returns a table of the available PCRE option flags (numbers) keyed by their --- Returns a table of the available PCRE option flags (numbers) keyed by their
-- names (strings). -- names (strings).
-- \n\n --
-- Possible names of the available strings can be retrieved from the -- Possible names of the available strings can be retrieved from the
-- documentation of the PCRE library used to link against Nmap. The key is the -- documentation of the PCRE library used to link against Nmap. The key is the
-- option name in the manual minus the PCRE prefix. PCRE_CASELESS becomes -- option name in the manual minus the <code>PCRE_</code> prefix.
-- CASELESS for example. -- <code>PCRE_CASELESS</code> becomes <code>CASELESS</code> for example.
function flags() function flags()
--- Returns the version of the PCRE library in use as a string. --- Returns the version of the PCRE library in use as a string.
-- \n\n --
-- For example "6.4 05-Sep-2005". -- For example <code>"6.4 05-Sep-2005"</code>.
function version() function version()
--- Matches a string against a compiled regular expression. --- Matches a string against a compiled regular expression.
-- \n\n --
-- Returns the start point and the end point of the first match of the compiled -- Returns the start point and the end point of the first match of the compiled
-- regular expression pcre_obj in the string. -- regular expression in the string.
-- @param string the string to match against. -- @param string the string to match against.
-- @param start where to start the match in the string (optional). -- @param start where to start the match in the string (optional).
-- @param flags execution flags (optional). -- @param flags execution flags (optional).
-- @return nil if no match, otherwise the start point of the first match. -- @return <code>nil</code> if no match, otherwise the start point of the first
-- match.
-- @return the end point of the first match. -- @return the end point of the first match.
-- @return a table which contains false in the positions where the pattern did -- @return a table which contains false in the positions where the pattern did
-- not match. If named sub-patterns were used, the table also contains substring -- not match. If named sub-patterns were used, the table also contains substring
@@ -87,34 +90,38 @@ function match(string, start, flags)
--- Matches a string against a compiled regular expression, returning positions --- Matches a string against a compiled regular expression, returning positions
-- of substring matches. -- of substring matches.
-- \n\n --
-- This function is like match() except that a table returned as a third result -- This function is like <code>match()</code> except that a table returned as a
-- contains offsets of substring matches rather than substring matches -- third result contains offsets of substring matches rather than substring
-- themselves. That table will not contain string keys, even if named -- matches themselves. That table will not contain string keys, even if named
-- sub-patterns are used. For example, if the whole match is at offsets 10, 20 -- sub-patterns are used. For example, if the whole match is at offsets 10, 20
-- and substring matches are at offsets 12, 14 and 16, 19 then the function -- and substring matches are at offsets 12, 14 and 16, 19 then the function
-- returns the following: 10, 20, {12,14,16,19} -- returns <code>10, 20, {12,14,16,19}</code>.
-- @param string the string to match against. -- @param string the string to match against.
-- @param start where to start the match in the string (optional). -- @param start where to start the match in the string (optional).
-- @param flags execution flags (optional). -- @param flags execution flags (optional).
-- @return a table which contains a list of substring match start and end -- @return <code>nil</code> if no match, otherwise the start point of the match
-- positions. -- of the whole string.
-- @return the end point of the match of the whole string.
-- @return a table containing a list of substring match start and end positions.
-- @usage -- @usage
-- i, j, substrings = regex:exec("string to be searched", 0, 0) -- i, j, substrings = regex:exec("string to be searched", 0, 0)
-- if (i) then ... end -- if (i) then ... end
function exec(string, start, flags) function exec(string, start, flags)
--- Matches a string against a regular expression multiple times. --- Matches a string against a regular expression multiple times.
-- \n\n --
-- Tries to match the regular expression pcre_obj against string up to n times -- Tries to match the regular expression pcre_obj against string up to
-- (or as many as possible if n is either not given or is not a positive -- <code>n</code> times (or as many as possible if <code>n</code> is not given
-- number), subject to the execution flags ef. Each time there is a match, func -- or is not a positive number), subject to the execution flags
-- is called as func(m, t), where m is the matched string and t is a table of -- <code>ef</code>. Each time there is a match, <code>func</code> is called as
-- substring matches. This table contains false in the positions where the -- <code>func(m, t)</code>, where <code>m</code> is the matched string and
-- corresponding sub-pattern did not match. If named sub-patterns are used then -- <code>t</code> is a table of substring matches. This table contains false in
-- the table also contains substring matches keyed by their correspondent -- the positions where the corresponding sub-pattern did not match. If named
-- sub-pattern names (strings). If func returns a true value, then gmatch -- sub-patterns are used then the table also contains substring matches keyed
-- immediately returns; gmatch returns the number of matches made. -- by their correspondent sub-pattern names (strings). If <code>func</code>
-- returns a true value, then <code>gmatch()</code> immediately returns;
-- <code>gmatch()</code> returns the number of matches made.
-- @param string the string to match against. -- @param string the string to match against.
-- @param func the function to call for each match. -- @param func the function to call for each match.
-- @param n the maximum number of matches to do (optional). -- @param n the maximum number of matches to do (optional).