1
0
mirror of https://github.com/nmap/nmap.git synced 2025-12-07 21:21:31 +00:00

Reformat and merge documentation for stdnse, shortport, strbuf, snmp, ssh1,

ssh2, smb, pop3, and msrpc.
This commit is contained in:
david
2008-10-16 00:38:53 +00:00
parent a31f0890d5
commit f58f559b81
10 changed files with 281 additions and 357 deletions

View File

@@ -1428,58 +1428,6 @@ if(s) code_to_be_done_on_match end
<indexterm class="endofrange" startref="nse-openssl-indexterm"/> <indexterm class="endofrange" startref="nse-openssl-indexterm"/>
</sect2> </sect2>
<sect2 id="nse-lib-shortport">
<title>Short Portrules</title>
<indexterm><primary><varname>shortport</varname> NSE module</primary></indexterm>
<para>
Since portrules are mostly the same for many scripts, the
<literal>shortport</literal> module provides functions for the most common tests.
The arguments in brackets (<literal>[]</literal>) are optional. If no
<literal>proto</literal> is provided, <literal>tcp</literal> is used. The default
<literal>state</literal> is <literal>open</literal>
</para>
<variablelist>
<varlistentry>
<term><option>shortport.portnumber(port,[proto],[state])</option>
</term>
<listitem>
<para>
The port argument is either a number or a table of numbers which are
interpreted as port numbers, against which the script should run.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>shortport.service(service,[proto],[state])</option>
</term>
<listitem>
<para>
The service argument is either a string or a table
of strings which are interpreted as service names
(e.g. <literal>"http"</literal>, <literal>"https"</literal>, <literal>"smtp"</literal> or <literal>"ftp"</literal>) against which the
script should run. These service names are
determined by Nmap's version scan or (if no version
scan information is available) the service assigned
to the port in <filename>nmap-services</filename>
(e.g. <literal>"http"</literal> for TCP port 80).
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>shortport.port_or_service(port,service,[proto],[state])</option>
</term>
<listitem>
<para>
This is a combination of the above functions, since many scripts
explicitly try to run against the well-known ports, but want
also to run against any other port which was discovered to run the
named service. A typical example for this function is:
<literal>portrule = shortport.port_or_service(22,"ssh")</literal>.
</para>
</listitem>
</varlistentry>
</variablelist>
</sect2>
<sect2 id="nse-lib-strbuf"> <sect2 id="nse-lib-strbuf">
<title>String Buffer Operations</title> <title>String Buffer Operations</title>
<indexterm><primary><varname>strbuf</varname> NSE module</primary></indexterm> <indexterm><primary><varname>strbuf</varname> NSE module</primary></indexterm>
@@ -1664,108 +1612,6 @@ if(s) code_to_be_done_on_match end
</variablelist> </variablelist>
</sect2> </sect2>
</sect2>
<sect2 id="nse-lib-stdnse">
<title>Various Utility Functions</title>
<indexterm><primary><varname>stdnse</varname> NSE module</primary></indexterm>
<para>
The <literal>stdnse</literal> library contains various handy
functions which are too small to justify modules of their own:
</para>
<variablelist>
<varlistentry>
<term><option>stdnse.print_debug([verbosity,] format, ...)</option>
</term>
<listitem>
<para>
Wrapper function around <literal>print_debug_unformatted()</literal>
in the <literal>nmap</literal> namespace. The first optional numeric
argument, <literal>verbosity</literal>, is
used as the necessary debug level to print the message (it defaults
to 1 if omitted). All remaining arguments are processed with
Lua's <literal>string.format()</literal> function, which provides a
C-style printf interface.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>list = stdnse.strsplit("delimiter", "text")</option>
</term>
<listitem>
<para>
This function will certainly be appreciated by Perl programmers.
It takes two strings as arguments and splits the second one around
all occurrences of the first one, returning a list (table), which
contains the substrings without the delimiting string.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>string = stdnse.strjoin("delimiter", list)</option>
</term>
<listitem>
<para>
Inverse function to <literal>strsplit()</literal>. Basically this is
Lua's <literal>table.concat()</literal> function with the parameters
swapped for coherence.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>string = stdnse.tobinary(n)</option>
</term>
<listitem>
<para>
Converts the given number, <literal>n</literal>, to a string
in a binary number format (e.g. 5 becomes "101").
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>string = stdnse.tooctal(n)</option>
</term>
<listitem>
<para>
Converts the given number, <literal>n</literal>, to a string
in an octal number format (e.g. 9 becomes "11").
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>string = stdnse.tohex(s, options)</option>
</term>
<listitem>
<para>
Converts the given number or string, <literal>s</literal>, to a
string in a hexadecimal number format (e.g. 10 becomes "a").
<literal>options</literal> is a table containing parameters to
control the formatting. You may specify <literal>options.separator</literal>
which will be used as separator for groups of consecutive bytes.
With <literal>options.group</literal> you can control the group
length to be used with <literal>options.separator</literal>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>string = stdnse.make_buffer(socket, sep)</option>
</term>
<listitem>
<para>
This function operates on a socket attempting to read data.
It separates the data by <literal>sep</literal> and, for each
invocation, returns a piece of the separated data. Typically
this is used to iterate over the lines of data received from a
socket (<literal>sep = "\r?\n"</literal>). The returned string
does not include the separator. It will return the final data
even if it is not followed by the separator. Once an error or
EOF is reached, it returns <literal>nil, msg</literal>.
<literal>msg</literal> is what is returned by
<literal>nmap.receive_lines()</literal>.
</para>
</listitem>
</varlistentry>
</variablelist>
</sect2>
<indexterm class="endofrange" startref="nse-library-indexterm"/> <indexterm class="endofrange" startref="nse-library-indexterm"/>
</sect1> </sect1>

View File

@@ -1,4 +1,6 @@
--- By making heavy use of the 'smb' library, this library will call various MSRPC --- Call various MSRPC functions.
-- \n\n
-- By making heavy use of the smb library, this library will call various MSRPC
-- functions. The functions used here can be access over TCP ports 445 and 139, -- functions. The functions used here can be access over TCP ports 445 and 139,
-- with an established session. A NULL session (the default) will work for some -- with an established session. A NULL session (the default) will work for some
-- functions and operating systems (or configurations), but not for others. \n -- functions and operating systems (or configurations), but not for others. \n

View File

@@ -1,4 +1,4 @@
--- POP3 functions --- POP3 functions.
--@copyright See nmaps COPYING for licence --@copyright See nmaps COPYING for licence
module(... or "pop3",package.seeall) module(... or "pop3",package.seeall)
@@ -24,9 +24,9 @@ err = {
} }
--- ---
-- Checks POP3 response for -- Check a POP3 response for "+OK".
--@param line First line returned from an POP3 request --@param line First line returned from an POP3 request.
--@return Found "+OK" string or nil --@return Found "+OK" string or nil.
function stat(line) function stat(line)
return string.match(line, "+OK") return string.match(line, "+OK")
end end
@@ -34,11 +34,11 @@ end
--- ---
-- Try to login using USER/PASS commands -- Try to log in using USER/PASS commands.
--@param socket Socket connected to POP3 server --@param socket Socket connected to POP3 server.
--@param user User string --@param user User string.
--@param pw Password string --@param pw Password string.
--@return Success as boolean and error code as in err table --@return Success as boolean and error code as in err table.
function login_user(socket, user, pw) function login_user(socket, user, pw)
socket:send("USER " .. user .. "\r\n") socket:send("USER " .. user .. "\r\n")
status, line = socket:receive_lines(1) status, line = socket:receive_lines(1)
@@ -54,11 +54,11 @@ end
--- ---
-- Try to login using AUTH command using SASL/Plain method -- Try to login using AUTH command using SASL/Plain method.
--@param socket Socket connected to POP3 server --@param socket Socket connected to POP3 server.
--@param user User string --@param user User string.
--@param pw Password string --@param pw Password string.
--@return Success as boolean and error code as in err table --@return Success as boolean and error code as in err table.
function login_sasl_plain(socket, user, pw) function login_sasl_plain(socket, user, pw)
local auth64 = base64.enc(user .. "\0" .. user .. "\0" .. pw) local auth64 = base64.enc(user .. "\0" .. user .. "\0" .. pw)
@@ -74,11 +74,11 @@ function login_sasl_plain(socket, user, pw)
end end
--- ---
-- Try to login using AUTH command using SASL/Login method -- Try to login using AUTH command using SASL/Login method.
--@param user User string --@param user User string.
--@param pw Password string --@param pw Password string.
--@param pw String containing password to login --@param pw String containing password to login.
--@return Success as boolean and error code as in err table --@return Success as boolean and error code as in err table.
function login_sasl_login(socket, user, pw) function login_sasl_login(socket, user, pw)
local user64 = base64.enc(user) local user64 = base64.enc(user)
@@ -112,12 +112,12 @@ function login_sasl_login(socket, user, pw)
end end
--- ---
-- Try to login using APOP command -- Try to login using APOP command.
--@param socket Socket connected to POP3 server --@param socket Socket connected to POP3 server.
--@param user User string --@param user User string.
--@param pw Password string --@param pw Password string.
--@param challenge String containing challenge from POP3 server greeting --@param challenge String containing challenge from POP3 server greeting.
--@return Success as boolean and error code as in err table --@return Success as boolean and error code as in err table.
function login_apop(socket, user, pw, challenge) function login_apop(socket, user, pw, challenge)
if type(challenge) ~= "string" then return false, err.informationMissing end if type(challenge) ~= "string" then return false, err.informationMissing end
@@ -135,9 +135,9 @@ end
--- ---
-- Asks POP3 server for capabilities -- Asks POP3 server for capabilities
--@param host Host to be queried --@param host Host to be queried.
--@param port Port to connect to --@param port Port to connect to.
--@return Table containing capabilities --@return Table containing capabilities.
function capabilities(host, port) function capabilities(host, port)
local socket = nmap.new_socket() local socket = nmap.new_socket()
local capas = {} local capas = {}
@@ -178,11 +178,11 @@ function capabilities(host, port)
end end
--- ---
-- Try to login using AUTH command using SASL/CRAM-MD5 method -- Try to login using AUTH command using SASL/CRAM-MD5 method.
--@param socket Socket connected to POP3 server --@param socket Socket connected to POP3 server.
--@param user User string --@param user User string.
--@param pw Password string --@param pw Password string.
--@return Success as boolean and error code as in err table --@return Success as boolean and error code as in err table.
function login_sasl_crammd5(socket, user, pw) function login_sasl_crammd5(socket, user, pw)
socket:send("AUTH CRAM-MD5\r\n") socket:send("AUTH CRAM-MD5\r\n")
@@ -204,7 +204,7 @@ function login_sasl_crammd5(socket, user, pw)
end end
end end
--- overwrite functions requiring OpenSSL if we got no OpenSSL -- Overwrite functions requiring OpenSSL if we got no OpenSSL.
if not HAVE_SSL then if not HAVE_SSL then
local no_ssl = function() local no_ssl = function()

View File

@@ -1,18 +1,18 @@
--- Functions for common port tests.\n\n --- Functions for building short portrules.
-- Takes a number as its argument and returns that many bytes. -- \n\n
-- It can be used to get a buffered version of sockobj:receive_bytes(n) in -- Since portrules are mostly the same for many scripts, this
-- case a script requires more than one fixed-size chunk, as the unbuffered -- module provides functions for the most common tests.
-- version may return more bytes than requested and thus would require you
-- to do the parsing on your own.
--@copyright See nmaps COPYING for licence --@copyright See nmaps COPYING for licence
module(... or "shortport", package.seeall) module(... or "shortport", package.seeall)
--- The port argument is either a number or a table of numbers which are --- Return a portrule that returns true when given an open port matching a
-- interpreted as port numbers, against which the script should run. See -- single port number or a list of port numbers.
-- module description for other arguments. -- @param port A single port number or a list of port numbers.
-- @param port The port or list of ports to run against -- @param _proto The protocol to match against, default "tcp".
-- @param _state A state or list of states to match against, default {"open", "open|filtered"}.
-- @return Function for the portrule. -- @return Function for the portrule.
-- @usage portrule = shortport.portnumber({80, 443})
portnumber = function(port, _proto, _state) portnumber = function(port, _proto, _state)
local port_table, state_table local port_table, state_table
local proto = _proto or "tcp" local proto = _proto or "tcp"
@@ -45,14 +45,19 @@ portnumber = function(port, _proto, _state)
end end
end end
--- The service argument is either a string or a table of strings which are --- Return a portrule that returns true when given an open port with a
-- interpreted as service names (e.g. "http", "https", "smtp" or "ftp") --service name matching a single service name or a list of service
-- against which the script should run. These service names are determined --names.
-- by Nmap's version scan or (if no version scan information is available) -- \n\n
-- the service assigned to the port in nmap-services (e.g. "http" for TCP -- A service name is something like "http", "https", "smtp", or "ftp".
-- port 80). -- These service names are determined by Nmap's version scan or (if no
-- version scan information is available) the service assigned to the
-- port in nmap-services (e.g. "http" for TCP port 80).
-- @param service Service name or a list of names to run against. -- @param service Service name or a list of names to run against.
-- @param _proto The protocol to match against, default "tcp".
-- @param _state A state or list of states to match against, default {"open", "open|filtered"}.
-- @return Function for the portrule. -- @return Function for the portrule.
-- @usage portrule = shortport.service("ftp")
service = function(service, _proto, _state) service = function(service, _proto, _state)
local service_table, state_table local service_table, state_table
local state = _state or {"open", "open|filtered"} local state = _state or {"open", "open|filtered"}
@@ -85,12 +90,19 @@ service = function(service, _proto, _state)
end end
end end
--- Run the script if either the port or service is available. This is --- Return a portrule that returns true when given an open port matching
-- a combination of shortport.portnumber and shortport.service, since -- either a port number or service name.
-- many scripts explicitly try to run against the well-known ports, -- \n\n
-- but want also to run against any other port which was discovered to -- This function is a combination of the portnumber and service
-- run the named service. -- functions. The port and service may be single values or a list of
-- values as in those functions. Many scripts explicitly try to run
-- against the well-known ports, but want also to run against any other
-- port which was discovered to run the named service.
-- @usage portrule = shortport.port_or_service(22,"ssh"). -- @usage portrule = shortport.port_or_service(22,"ssh").
-- @param _port A single port number or a list of port numbers.
-- @param _service Service name or a list of names to run against.
-- @param proto The protocol to match against, default "tcp".
-- @param _state A state or list of states to match against, default {"open", "open|filtered"}.
-- @return Function for the portrule. -- @return Function for the portrule.
port_or_service = function(_port, _service, proto, _state) port_or_service = function(_port, _service, proto, _state)
local state = _state or {"open", "open|filtered"} local state = _state or {"open", "open|filtered"}

View File

@@ -1,4 +1,6 @@
--- A library for SMB (Server Message Block) (aka CIFS) traffic. This traffic is normally --- A library for SMB (Server Message Block) (aka CIFS) traffic.
-- \n\n
-- This traffic is normally
-- sent to/from ports 139 or 445 of Windows systems, although it's also implemented by -- sent to/from ports 139 or 445 of Windows systems, although it's also implemented by
-- others (the most notable one being Samba). \n -- others (the most notable one being Samba). \n
--\n --\n

View File

@@ -1,4 +1,4 @@
--- SNMP functions --- SNMP functions.
--@copyright See nmaps COPYING for licence --@copyright See nmaps COPYING for licence
@@ -6,9 +6,9 @@ module(... or "snmp",package.seeall)
--- ---
-- Encodes an Integer according to ASN.1 basic encoding rules -- Encodes an Integer according to ASN.1 basic encoding rules.
--@param val Value to be encoded --@param val Value to be encoded.
--@return encoded integer --@return encoded integer.
local function encodeInt(val) local function encodeInt(val)
local lsb = 0 local lsb = 0
if val > 0 then if val > 0 then
@@ -44,9 +44,9 @@ end
--- ---
-- Encodes the length part of a ASN.1 encoding triplet -- Encodes the length part of a ASN.1 encoding triplet.
--@param val Value to be encoded --@param val Value to be encoded.
--@return encoded length value --@return encoded length value.
local function encodeLength(val) local function encodeLength(val)
if (val >= 128) then if (val >= 128) then
local valStr = "" local valStr = ""
@@ -65,9 +65,9 @@ end
--- ---
-- Encodes a given value according to ASN.1 basic encoding -- Encodes a given value according to ASN.1 basic encoding
-- rules for SNMP packet creation -- rules for SNMP packet creation.
--@param val Value to be encoded --@param val Value to be encoded.
--@return encoded value --@return encoded value.
function encode(val) function encode(val)
local vtype = type(val) local vtype = type(val)
if (vtype == 'number') then if (vtype == 'number') then
@@ -119,10 +119,10 @@ end
--- ---
-- Decodes length part of encoded value according to -- Decodes length part of encoded value according to
-- ASN.1 basic encoding rules -- ASN.1 basic encoding rules.
--@param encStr Encoded string --@param encStr Encoded string.
--@param pos Current position in the string --@param pos Current position in the string.
--@return The position after decoding and the length of the following value --@return The position after decoding and the length of the following value.
local function decodeLength(encStr, pos) local function decodeLength(encStr, pos)
local elen local elen
pos, elen = bin.unpack('C', encStr, pos) pos, elen = bin.unpack('C', encStr, pos)
@@ -143,11 +143,11 @@ end
--- ---
-- Decodes an Integer according to ASN.1 basic -- Decodes an Integer according to ASN.1 basic
-- encoding rules -- encoding rules.
--@param encStr Encoded string --@param encStr Encoded string.
--@param len Length of integer in bytes --@param len Length of integer in bytes.
--@param pos Current position in the string --@param pos Current position in the string.
--@return The position after decoding and the decoded integer --@return The position after decoding and the decoded integer.
local function decodeInt(encStr, len, pos) local function decodeInt(encStr, len, pos)
local hexStr local hexStr
pos, hexStr = bin.unpack("H" .. len, encStr, pos) pos, hexStr = bin.unpack("H" .. len, encStr, pos)
@@ -160,11 +160,11 @@ end
--- ---
-- Decodes a sequence according to ASN.1 basic -- Decodes a sequence according to ASN.1 basic
-- encoding rules -- encoding rules.
--@param encStr Encoded string --@param encStr Encoded string.
--@param len Length of sequence in bytes --@param len Length of sequence in bytes.
--@param pos Current position in the string --@param pos Current position in the string.
--@return The position after decoding and the decoded sequence as a table --@return The position after decoding and the decoded sequence as a table.
local function decodeSeq(encStr, len, pos) local function decodeSeq(encStr, len, pos)
local seq = {} local seq = {}
local sPos = 1 local sPos = 1
@@ -181,10 +181,10 @@ end
--- ---
-- Decodes an SNMP packet or a part of it according -- Decodes an SNMP packet or a part of it according
-- to ASN.1 basic encoding rules -- to ASN.1 basic encoding rules.
--@param encStr Encoded string --@param encStr Encoded string.
--@param pos Current position in the string --@param pos Current position in the string.
--@return The position after decoding and the decoded value(s) --@return The position after decoding and the decoded value(s).
function decode(encStr, pos) function decode(encStr, pos)
local etype, elen local etype, elen
pos, etype = bin.unpack("H1", encStr, pos) pos, etype = bin.unpack("H1", encStr, pos)
@@ -273,10 +273,10 @@ end
--- ---
-- Decodes an SNMP packet or a part of it according -- Decodes an SNMP packet or a part of it according
-- to ASN.1 basic encoding rules -- to ASN.1 basic encoding rules.
--@param encStr Encoded string --@param encStr Encoded string.
--@param pos Current position in the string --@param pos Current position in the string.
--@return The decoded value(s) --@return The decoded value(s).
function dec(encStr, pos) function dec(encStr, pos)
local result local result
local _ local _
@@ -285,10 +285,10 @@ function dec(encStr, pos)
end end
--- ---
-- Create SNMP packet -- Create SNMP packet.
--@param PDU SNMP Protocol Data Unit to be encapsulated in the packet --@param PDU SNMP Protocol Data Unit to be encapsulated in the packet.
--@param version SNMP version, default 0 (SNMP V1) --@param version SNMP version, default 0 (SNMP V1).
--@param commStr community string, if not already supplied in registry or as script argument --@param commStr community string, if not already supplied in registry or as script argument.
function buildPacket(PDU, version, commStr) function buildPacket(PDU, version, commStr)
local comm = nmap.registry.args.snmpcommunity local comm = nmap.registry.args.snmpcommunity
if (not comm) then comm = nmap.registry.snmpcommunity end if (not comm) then comm = nmap.registry.snmpcommunity end
@@ -305,10 +305,13 @@ end
--- ---
-- Create SNMP Get Request PDU -- Create SNMP Get Request PDU.
--@param options Configure PDU: request ID (reqId), error and error index (err, errIdx) --@param options A table containing the following keys and values:\n
--@param OIDs Object identifiers to be queried --"reqId": request ID\n
--@return Table representing PDU --"err": error\n
--"errIdx": error index
--@param ... Object identifiers to be queried.
--@return Table representing PDU.
function buildGetRequest(options, ...) function buildGetRequest(options, ...)
if not options then options = {} end if not options then options = {} end
@@ -337,10 +340,13 @@ end
--- ---
-- Create SNMP Get Next Request PDU -- Create SNMP Get Next Request PDU.
--@param options Configure PDU: request ID (reqId), error and error index (err, errIdx) --@param options A table containing the following keys and values:\n
--@param OIDs Object identifiers to be queried --"reqId": request ID\n
--@return Table representing PDU --"err": error\n
--"errIdx": error index
--@param ... Object identifiers to be queried.
--@return Table representing PDU.
function buildGetNextRequest(options, ...) function buildGetNextRequest(options, ...)
if not options then options = {} end if not options then options = {} end
@@ -368,12 +374,16 @@ function buildGetNextRequest(options, ...)
end end
--- ---
-- Create SNMP Set Request PDU -- Create SNMP Set Request PDU.
-- Takes one OID/value pair or an already prepared table -- \n\n
--@param options Configure PDU: request ID (reqId), error and error index (err, errIdx) -- Takes one OID/value pair or an already prepared table.
--@param OIDs Object identifiers of object to be set --@param options A table containing the following keys and values:\n
--@param value To which value object should be set. If given a table, use table instead of OID/value pair --"reqId": request ID\n
--@return Table representing PDU --"err": error\n
--"errIdx": error index
--@param oid Object identifiers of object to be set.
--@param value To which value object should be set. If given a table, use table instead of OID/value pair.
--@return Table representing PDU.
function buildSetRequest(options, oid, value) function buildSetRequest(options, oid, value)
if not options then options = {} end if not options then options = {} end
@@ -437,12 +447,16 @@ function buildTrap(enterpriseOid, agentIp, genTrap, specTrap, timeStamp)
end end
--- ---
-- Create SNMP Get Response PDU -- Create SNMP Get Response PDU.
-- Takes one OID/value pair or an already prepared table -- \n\n
--@param options Configure PDU: request ID (reqId), error and error index (err, errIdx) -- Takes one OID/value pair or an already prepared table.
--@param OIDs Object identifiers of object to be sent back --@param options A table containing the following keys and values:\n
--@param value To which value object or returned object. If given a table, use table instead of OID/value pair --"reqId": request ID\n
--@return Table representing PDU --"err": error\n
--"errIdx": error index
--@param oid Object identifiers of object to be sent back.
--@param value To which value object or returned object. If given a table, use table instead of OID/value pair.
--@return Table representing PDU.
function buildGetResponse(options, oid, value) function buildGetResponse(options, oid, value)
if not options then options = {} end if not options then options = {} end
@@ -475,9 +489,9 @@ function buildGetResponse(options, oid, value)
end end
--- ---
-- Transforms a string into an object identifier table -- Transforms a string into an object identifier table.
--@param oidStr Object identifier as string, for example "1.3.6.1.2.1.1.1.0" --@param oidStr Object identifier as string, for example "1.3.6.1.2.1.1.1.0".
--@return Table representing OID --@return Table representing OID.
function str2oid(oidStr) function str2oid(oidStr)
local oid = {} local oid = {}
for n in string.gmatch(oidStr, "%d+") do for n in string.gmatch(oidStr, "%d+") do
@@ -488,18 +502,18 @@ function str2oid(oidStr)
end end
--- ---
-- Transforms a table representing an object identifier to a string -- Transforms a table representing an object identifier to a string.
--@param oid Object identifier table --@param oid Object identifier table.
--@return OID string --@return OID string.
function oid2str(oid) function oid2str(oid)
if (type(oid) ~= "table") then return 'invalid oid' end if (type(oid) ~= "table") then return 'invalid oid' end
return table.concat(oid, '.') return table.concat(oid, '.')
end end
--- ---
-- Transforms a table representing an IP to a string -- Transforms a table representing an IP to a string.
--@param ip IP table --@param ip IP table.
--@return IP string --@return IP string.
function ip2str(ip) function ip2str(ip)
if (type(ip) ~= "table") then return 'invalid ip' end if (type(ip) ~= "table") then return 'invalid ip' end
return table.concat(ip, '.') return table.concat(ip, '.')
@@ -507,9 +521,9 @@ end
--- ---
-- Transforms a string into an IP table -- Transforms a string into an IP table.
--@param ipStr IP as string --@param ipStr IP as string.
--@return Table representing IP --@return Table representing IP.
function str2ip(ipStr) function str2ip(ipStr)
local ip = {} local ip = {}
for n in string.gmatch(ipStr, "%d+") do for n in string.gmatch(ipStr, "%d+") do
@@ -521,9 +535,9 @@ end
--- ---
-- Fetches values from a SNMP response -- Fetches values from a SNMP response.
--@param resp SNMP Response (will be decoded if necessary) --@param resp SNMP Response (will be decoded if necessary).
--@result Table with all decoded responses and their OIDs --@result Table with all decoded responses and their OIDs.
function fetchResponseValues(resp) function fetchResponseValues(resp)
if (type(resp) == "string") then if (type(resp) == "string") then
local _ local _
@@ -568,8 +582,8 @@ end
--- ---
-- Fetches first value from a SNMP response. -- Fetches first value from a SNMP response.
--@param response SNMP Response (will be decoded if necessary) --@param response SNMP Response (will be decoded if necessary).
--@return First decoded value of the response --@return First decoded value of the response.
function fetchFirst(response) function fetchFirst(response)
local result = fetchResponseValues(response) local result = fetchResponseValues(response)
if type(result) == "table" and result[1] and result[1][1] then return result[1][1] if type(result) == "table" and result[1] and result[1][1] then return result[1][1]

View File

@@ -1,5 +1,7 @@
--- Functions for the SSH-1 protocol.
-- @author = Sven Klemm <sven@c3d2.de> -- \n\n
-- This module also contains functions for formatting key fingerprints.
-- @author Sven Klemm <sven@c3d2.de>
-- @copyright See nmaps COPYING for licence -- @copyright See nmaps COPYING for licence
module(... or "ssh1",package.seeall) module(... or "ssh1",package.seeall)
@@ -10,9 +12,11 @@ local math = require "math"
local stdnse = require "stdnse" local stdnse = require "stdnse"
local openssl = require "openssl" local openssl = require "openssl"
--- fetch SSH1 host key --- Fetch a SSH-1 host key.
--@param host nmap host table --@param host Nmap host table.
--@param port nmap port table --@param port Nmap port table.
--@return A table with the following keys: "exp", "mod", "bits", "key_type",
--"fp_input", "full_key", "algorithm", and "fingerprint".
fetch_host_key = function(host, port) fetch_host_key = function(host, port)
local socket = nmap.new_socket() local socket = nmap.new_socket()
local catch = function() socket:close() end local catch = function() socket:close() end
@@ -61,13 +65,13 @@ fetch_host_key = function(host, port)
end end
end end
--- format key as hexadecimal fingerprint --- Format a key fingerprint in hexadecimal.
fingerprint_hex = function( fingerprint, algorithm, bits ) fingerprint_hex = function( fingerprint, algorithm, bits )
fingerprint = stdnse.tohex(fingerprint,{separator=":",group=2}) fingerprint = stdnse.tohex(fingerprint,{separator=":",group=2})
return ("%d %s (%s)"):format( bits, fingerprint, algorithm ) return ("%d %s (%s)"):format( bits, fingerprint, algorithm )
end end
--- format key as bubblebabble fingerprint --- Format a key fingerprint in Bubble Babble.
fingerprint_bubblebabble = function( fingerprint, algorithm, bits ) fingerprint_bubblebabble = function( fingerprint, algorithm, bits )
local vowels = {'a','e','i','o','u','y'} local vowels = {'a','e','i','o','u','y'}
local consonants = {'b','c','d','f','g','h','k','l','m','n','p','r','s','t','v','z','x'} local consonants = {'b','c','d','f','g','h','k','l','m','n','p','r','s','t','v','z','x'}
@@ -100,8 +104,9 @@ fingerprint_bubblebabble = function( fingerprint, algorithm, bits )
return ("%d %s (%s)"):format( bits, s, algorithm ) return ("%d %s (%s)"):format( bits, s, algorithm )
end end
--- format key as visual fingerprint --- Format a key fingerprint into a visual ASCII art representation.
-- ported from http://www.openbsd.org/cgi-bin/cvsweb/~checkout~/src/usr.bin/ssh/key.c -- \n\n
-- Ported from http://www.openbsd.org/cgi-bin/cvsweb/~checkout~/src/usr.bin/ssh/key.c.
fingerprint_visual = function( fingerprint, algorithm, bits ) fingerprint_visual = function( fingerprint, algorithm, bits )
local i,j,field,characters,input,fieldsize_x,fieldsize_y,s local i,j,field,characters,input,fieldsize_x,fieldsize_y,s
fieldsize_x, fieldsize_y = 17, 9 fieldsize_x, fieldsize_y = 17, 9

View File

@@ -1,5 +1,5 @@
--- Functions for the SSH-2 protocol.
-- @author = Sven Klemm <sven@c3d2.de> -- @author Sven Klemm <sven@c3d2.de>
-- @copyright See nmaps COPYING for licence -- @copyright See nmaps COPYING for licence
module(... or "ssh2",package.seeall) module(... or "ssh2",package.seeall)
@@ -12,12 +12,12 @@ require "stdnse"
-- table holding transport layer functions -- table holding transport layer functions
transport = {} transport = {}
-- table of SSH2 constants -- table of SSH-2 constants
local SSH2 local SSH2
--- pack multiprecision integer for sending --- Pack a multiprecision integer for sending.
--@param bn openssl bignum --@param bn openssl bignum.
--@return packed multiprecision integer --@return packed multiprecision integer.
transport.pack_mpint = function( bn ) transport.pack_mpint = function( bn )
local bytes, packed local bytes, packed
bytes = bn:num_bytes() bytes = bn:num_bytes()
@@ -29,9 +29,9 @@ transport.pack_mpint = function( bn )
return bin.pack( ">IA", bytes, packed ) return bin.pack( ">IA", bytes, packed )
end end
--- build a ssh2 packet --- Build an SSH-2 packet.
--@param payload payload of the packet --@param payload payload of the packet.
--@return packet to send on the wire --@return packet to send on the wire.
transport.build = function( payload ) transport.build = function( payload )
local packet_length, padding_length local packet_length, padding_length
padding_length = 8 - ( (payload:len() + 1 + 4 ) % 8 ) padding_length = 8 - ( (payload:len() + 1 + 4 ) % 8 )
@@ -39,9 +39,9 @@ transport.build = function( payload )
return bin.pack( ">IcAA", packet_length, padding_length, payload, openssl.rand_pseudo_bytes( padding_length ) ) return bin.pack( ">IcAA", packet_length, padding_length, payload, openssl.rand_pseudo_bytes( padding_length ) )
end end
--- extract the payload from a received SSH2 packet --- Extract the payload from a received SSH-2 packet.
--@param received SSH2 packet --@param received SSH2 packet.
--@return payload of the SSH2 packet --@return payload of the SSH2 packet.
transport.payload = function( packet ) transport.payload = function( packet )
local packet_length, padding_length, payload_length, payload, offset local packet_length, padding_length, payload_length, payload, offset
offset, packet_length, padding_length = bin.unpack( ">Ic", packet ) offset, packet_length, padding_length = bin.unpack( ">Ic", packet )
@@ -50,12 +50,12 @@ transport.payload = function( packet )
return payload return payload
end end
--- build kexdh_init packet --- Build kexdh_init packet.
transport.kexdh_init = function( e ) transport.kexdh_init = function( e )
return bin.pack( ">cA", SSH2.SSH_MSG_KEXDH_INIT, transport.pack_mpint( e ) ) return bin.pack( ">cA", SSH2.SSH_MSG_KEXDH_INIT, transport.pack_mpint( e ) )
end end
--- build kex_init packet --- Build kex_init packet.
transport.kex_init = function( cookie, options ) transport.kex_init = function( cookie, options )
options = options or {} options = options or {}
kex_algorithms = "diffie-hellman-group1-sha1" kex_algorithms = "diffie-hellman-group1-sha1"
@@ -75,8 +75,9 @@ transport.kex_init = function( cookie, options )
return payload return payload
end end
--- parse kexinit package --- Parse kexinit package.
-- returns an empty table in case of an error -- \n\n
-- Returns an empty table in case of an error
transport.parse_kex_init = function( payload ) transport.parse_kex_init = function( payload )
local _, offset, msg_code, parsed, fields, fieldname local _, offset, msg_code, parsed, fields, fieldname
parsed = {} parsed = {}
@@ -100,11 +101,11 @@ transport.parse_kex_init = function( payload )
end end
--- fetch SSH2 host key --- Fetch an SSH-2 host key.
--@param host nmap host table --@param host Nmap host table.
--@param port nmap port table --@param port Nmap port table.
--@param key_type key type to fetch --@param key_type key type to fetch.
--@return table containing the key and fingerprint --@return table containing the key and fingerprint.
fetch_host_key = function( host, port, key_type ) fetch_host_key = function( host, port, key_type )
local socket = nmap.new_socket() local socket = nmap.new_socket()
local catch = function() socket:close() end local catch = function() socket:close() end

View File

@@ -1,4 +1,6 @@
--- Standard Nmap Engine functions. --- Standard Nmap Scripting Engine functions.
-- \n\n
-- This module contains various handy functions which are too small to justify modules of their own.
--@copyright See nmaps COPYING for licence --@copyright See nmaps COPYING for licence
local assert = assert; local assert = assert;
@@ -14,9 +16,14 @@ local EMPTY = {}; -- Empty constant table
module(... or "stdnse"); module(... or "stdnse");
--- Prints debug information according with verbosity <i>level</i> --- Prints a formatted debug message if the current verbosity level is greater
-- formatted using Lua's standard string.format function. -- than or equal to a given level.
--@param level Optional argument for verbosity. -- \n\n
-- This is a convenience wrapper around nmap.print_debug_unformatted. The first
-- optional numeric argument, verbosity, is used as the necessary debug level
-- to print the message (it defaults to 1 if omitted). All remaining arguments
-- are processed with Lua's string.format() function.
--@param level Optional verbosity level.
--@param fmt Format string according to string.format specifiers. --@param fmt Format string according to string.format specifiers.
--@param ... Arguments to format. --@param ... Arguments to format.
--@see string.format --@see string.format
@@ -29,10 +36,13 @@ print_debug = function(level, fmt, ...)
end end
end end
--- Concat the contents of the parameter list. Each string is --- Join a list of string with a separator string.
-- separated by the string delimiter (just like in perl). -- \n\n
-- Example: strjoin(", ", {"Anna", "Bob", "Charlie", "Dolores"}) -- Example: strjoin(", ", {"Anna", "Bob", "Charlie", "Dolores"})
-- --> "Anna, Bob, Charlie, Dolores" -- --> "Anna, Bob, Charlie, Dolores"
-- \n\n
-- Basically this is Lua's table.concat() function with the parameters swapped
-- for coherence.
--@param delimiter String to delimit each element of the list. --@param delimiter String to delimit each element of the list.
--@param list Array of strings to concatenate. --@param list Array of strings to concatenate.
--@return Concatenated string. --@return Concatenated string.
@@ -40,12 +50,11 @@ function strjoin(delimiter, list)
return concat(list, delimiter); return concat(list, delimiter);
end end
--- Split text into a list consisting of the strings in text, --- Split a string at a given delimiter, which may be a pattern.
-- separated by strings matching delimiter (which may be a pattern). -- Example: strsplit(",%s*", "Anna, Bob, Charlie, Dolores")
-- example: strsplit(",%s*", "Anna, Bob, Charlie, Dolores")
--@param delimiter String which delimits the split strings. --@param delimiter String which delimits the split strings.
--@param text String to split. --@param text String to split.
--@return List of strings. --@return List of substrings without the delimiter.
function strsplit(delimiter, text) function strsplit(delimiter, text)
local list, pos = {}, 1; local list, pos = {}, 1;
@@ -64,7 +73,10 @@ function strsplit(delimiter, text)
return list; return list;
end end
--- This function operates on a socket attempting to read data. It separates --- Return a wrapper closure around a socket that buffers socket reads into
-- chunks separated by a pattern.
-- \n\n
-- This function operates on a socket attempting to read data. It separates
-- the data by sep and, for each invocation, returns a piece of the -- the data by sep and, for each invocation, returns a piece of the
-- separated data. Typically this is used to iterate over the lines of -- separated data. Typically this is used to iterate over the lines of
-- data received from a socket (sep = "\r?\n"). The returned string does -- data received from a socket (sep = "\r?\n"). The returned string does
@@ -132,7 +144,8 @@ do
f = "1111" f = "1111"
}; };
--- Converts the given number, n, to a string in a binary number format. --- Converts the given number, n, to a string in a binary number format (10
-- becomes "1010").
--@param n Number to convert. --@param n Number to convert.
--@return String in binary format. --@return String in binary format.
function tobinary(n) function tobinary(n)
@@ -141,7 +154,8 @@ do
end end
end end
--- Converts the given number, n, to a string in an octal number format. --- Converts the given number, n, to a string in an octal number format (10
-- becomes "12").
--@param n Number to convert. --@param n Number to convert.
--@return String in octal format. --@return String in octal format.
function tooctal(n) function tooctal(n)
@@ -149,16 +163,22 @@ function tooctal(n)
return ("%o"):format(n) return ("%o"):format(n)
end end
--- encode string or number to hexadecimal --- Encode a string or number in hexadecimal (10 becomes "a", "A" becomes
-- example: stdnse.tohex("abc") => "616263" -- "41").
-- stdnse.tohex("abc",{separator=":"}) => "61:62:63" -- \n\n
-- stdnse.tohex("abc",{separator=":",group=4}) => "61:6263" -- The returned string may be chunked into groups of a given size, separated
-- stdnse.tohex(123456) => "1e240" -- by a given string.
-- stdnse.tohex(123456,{separator=":"}) => "1:e2:40" -- \n\n
-- stdnse.tohex(123456,{separator=":",group=4}) => "1:e240" -- Examples:\n
--@param s string or number to be encoded -- stdnse.tohex("abc") => "616263"\n
--@param options table specifiying formatting options -- stdnse.tohex("abc",{separator=":"}) => "61:62:63"\n
--@return hexadecimal encoded string -- stdnse.tohex("abc",{separator=":",group=4}) => "61:6263"\n
-- stdnse.tohex(123456) => "1e240"\n
-- stdnse.tohex(123456,{separator=":"}) => "1:e2:40"\n
-- stdnse.tohex(123456,{separator=":",group=4}) => "1:e240"\n
--@param s string or number to be encoded.
--@param options table specifiying formatting options.
--@return hexadecimal encoded string.
function tohex( s, options ) function tohex( s, options )
options = options or EMPTY options = options or EMPTY
local separator = options.separator local separator = options.separator

View File

@@ -1,4 +1,38 @@
--- String Buffer Facilities --- String Buffer facilities.
-- \n\n
-- Lua's string operations are very flexible and offer an easy-to-use way to
-- manipulate strings. Concatenation using the .. operator is such an
-- operation. The drawback of the built-in API however is the way it handles
-- concatenation of many string values. Since strings in Lua are immutable
-- values, each time you concatenate two strings both get copied into the result
-- string.
-- \n\n
-- The strbuf module offers a workaround for this problem, while
-- maintaining the nice syntax. This is accomplished by overloading the
-- concatenation operator (..) the equality operator (==) and the tostring
-- operator. By overloading these operators, we reduce the overhead of using a
-- string buffer instead of a plain string to wrap the first literal string
-- assigned to a variable inside a strbuf.new() call. Afterwards you can append
-- to the string buffer, or compare two string buffers for equality just as you
-- would do with normal strings.
-- \n\n
-- When looking at the details there are some more
-- restrictions/oddities: The concatenation operator requires its left-hand
-- value to be a string buffer. Therefore, if you want to prepend a string to a
-- given string buffer you have to create a new string buffer out of the string
-- you want to prepend. The string buffer's tostring operator concatenates the
-- strings inside the buffer using newlines by default, since this appears to be
-- the separator used most often.
-- \n\n
-- Example usage:\n
-- local buf = strbuf.new()\n
-- local buf2 = strbuf.new('hello')\n
-- buf = buf .. 'string'\n
-- buf = buf .. 'data'\n
-- print(buf) -- default separator is a new line\n
-- print(strbuf.dump(buf)) -- no separator\n
-- print(strbuf.dump(buf, ' ')) -- separated by spaces\n
-- strbuf.clear(buf)
--@copyright See nmaps COPYING for license --@copyright See nmaps COPYING for license
-- DEPENDENCIES -- -- DEPENDENCIES --
@@ -19,23 +53,10 @@ module(... or "strbuf");
-- operations are needed a string buffer should be used instead -- operations are needed a string buffer should be used instead
-- e.g. for i = 1, 10 do s = s..i end -- e.g. for i = 1, 10 do s = s..i end
--[[
local buf = strbuf.new()
-- from here buf may be used like a string for concatenation operations
-- (the lefthand-operand has to be a strbuf, the righthand-operand may be
-- a string or a strbuf)
-- alternativly you can assign a value (which will become the first string
-- inside the buffer) with new
local buf2 = strbuf.new('hello')
buf = buf .. 'string'
buf = buf .. 'data'
print(buf) -- default seperator is a new line
print(strbuf.dump(buf)) -- no seperator
print(strbuf.dump(buf, ' ')) -- seperated by spaces
strbuf.clear(buf)
--]]
--- Dumps the string buffer as a string. --- Dumps the string buffer as a string.
-- \n\n
-- The second parameter is used as a delimiter between the strings stored inside
-- strbuf.
--@name dump --@name dump
--@class function --@class function
--@param sbuf String buffer to dump. --@param sbuf String buffer to dump.
@@ -102,10 +123,11 @@ local mt = {
__index = _M, __index = _M,
}; };
--- Create a new string buffer. The equals and tostring operators for String --- Create a new string buffer.
-- \n\n
-- The optional arguments are added to the string buffer. The result of adding
-- non-strings is undefined. The equals and tostring operators for string
-- buffers are overloaded to be strbuf.eqbuf and strbuf.tostring respectively. -- buffers are overloaded to be strbuf.eqbuf and strbuf.tostring respectively.
-- All functions in strbuf can be accessed by a String buffer using the self
-- calling mechanism in Lua (e.g. strbuf:dump(...)).
--@param ... Strings to add to the buffer initially. --@param ... Strings to add to the buffer initially.
--@return String buffer. --@return String buffer.
function new(...) function new(...)