PageRenderTime 38ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/nselib/http.lua

https://gitlab.com/g10h4ck/nmap-gsoc2015
Lua | 2886 lines | 2566 code | 58 blank | 262 comment | 97 complexity | 470a24c1ec40b61a76841dcb544e9963 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, Apache-2.0, LGPL-2.0, LGPL-2.1, MIT
  1. ---Implements the HTTP client protocol in a standard form that Nmap scripts can
  2. -- take advantage of.
  3. --
  4. -- Because HTTP has so many uses, there are a number of interfaces to this library.
  5. -- The most obvious and common ones are simply <code>get</code>, <code>post</code>,
  6. -- and <code>head</code>; or, if more control is required, <code>generic_request</code>
  7. -- can be used. These functions do what one would expect. The <code>get_url</code>
  8. -- helper function can be used to parse and retrieve a full URL.
  9. --
  10. -- HTTPS support is transparent. The library uses <code>comm.tryssl</code> to
  11. -- determine whether SSL is required for a request.
  12. --
  13. -- These functions return a table of values, including:
  14. -- * <code>status-line</code> - A string representing the status, such as "HTTP/1.1 200 OK". In case of an error, a description will be provided in this line.
  15. -- * <code>status</code>: The HTTP status value; for example, "200". If an error occurs during a request, then this value is going to be nil.
  16. -- * <code>header</code> - An associative array representing the header. Keys are all lowercase, and standard headers, such as 'date', 'content-length', etc. will typically be present.
  17. -- * <code>rawheader</code> - A numbered array of the headers, exactly as the server sent them. While header['content-type'] might be 'text/html', rawheader[3] might be 'Content-type: text/html'.
  18. -- * <code>cookies</code> - A numbered array of the cookies the server sent. Each cookie is a table with the following keys: <code>name</code>, <code>value</code>, <code>path</code>, <code>domain</code>, and <code>expires</code>.
  19. -- * <code>body</code> - The full body, as returned by the server.
  20. --
  21. -- If a script is planning on making a lot of requests, the pipelining functions can
  22. -- be helpful. <code>pipeline_add</code> queues requests in a table, and
  23. -- <code>pipeline</code> performs the requests, returning the results as an array,
  24. -- with the responses in the same order as the queries were added. As a simple example:
  25. --<code>
  26. -- -- Start by defining the 'all' variable as nil
  27. -- local all = nil
  28. --
  29. -- -- Add two 'GET' requests and one 'HEAD' to the queue. These requests are not performed
  30. -- -- yet. The second parameter represents the 'options' table, which we don't need.
  31. -- all = http.pipeline_add('/book', nil, all)
  32. -- all = http.pipeline_add('/test', nil, all)
  33. -- all = http.pipeline_add('/monkeys', nil, all, 'HEAD')
  34. --
  35. -- -- Perform all three requests as parallel as Nmap is able to
  36. -- local results = http.pipeline('nmap.org', 80, all)
  37. --</code>
  38. --
  39. -- At this point, <code>results</code> is an array with three elements. Each element
  40. -- is a table containing the HTTP result, as discussed above.
  41. --
  42. -- One more interface provided by the HTTP library helps scripts determine whether or not
  43. -- a page exists. The <code>identify_404</code> function will try several URLs on the
  44. -- server to determine what the server's 404 pages look like. It will attempt to identify
  45. -- customized 404 pages that may not return the actual status code 404. If successful,
  46. -- the function <code>page_exists</code> can then be used to determine whether or not
  47. -- a page existed.
  48. --
  49. -- Some other miscellaneous functions that can come in handy are <code>response_contains</code>,
  50. -- <code>can_use_head</code>, and <code>save_path</code>. See the appropriate documentation
  51. -- for them.
  52. --
  53. -- The response to each function is typically a table with the following keys:
  54. -- * <code>status-line</code>: The HTTP status line; for example, "HTTP/1.1 200 OK" (note: this is followed by a newline). In case of an error, a description will be provided in this line.
  55. -- * <code>status</code>: The HTTP status value; for example, "200". If an error occurs during a request, then this value is going to be nil.
  56. -- * <code>header</code>: A table of header values, where the keys are lowercase and the values are exactly what the server sent
  57. -- * <code>rawheader</code>: A list of header values as "name: value" strings, in the exact format and order that the server sent them
  58. -- * <code>cookies</code>: A list of cookies that the server is sending. Each cookie is a table containing the keys <code>name</code>, <code>value</code>, and <code>path</code>. This table can be sent to the server in subsequent responses in the <code>options</code> table to any function (see below).
  59. -- * <code>body</code>: The body of the response
  60. -- * <code>location</code>: a list of the locations of redirects that were followed.
  61. --
  62. -- Many of the functions optionally allow an 'options' table. This table can alter the HTTP headers
  63. -- or other values like the timeout. The following are valid values in 'options' (note: not all
  64. -- options will necessarily affect every function):
  65. -- * <code>timeout</code>: A timeout used for socket operations.
  66. -- * <code>header</code>: A table containing additional headers to be used for the request. For example, <code>options['header']['Content-Type'] = 'text/xml'</code>
  67. -- * <code>content</code>: The content of the message (content-length will be added -- set header['Content-Length'] to override). This can be either a string, which will be directly added as the body of the message, or a table, which will have each key=value pair added (like a normal POST request).
  68. -- * <code>cookies</code>: A list of cookies as either a string, which will be directly sent, or a table. If it's a table, the following fields are recognized: <code>name</code>, <code>value</code>, <code>path</code>, <code>expires</code>. Only <code>name</code> and <code>value</code> fields are required.
  69. -- * <code>auth</code>: A table containing the keys <code>username</code> and <code>password</code>, which will be used for HTTP Basic authentication.
  70. -- If a server requires HTTP Digest authentication, then there must also be a key <code>digest</code>, with value <code>true</code>.
  71. -- If a server requires NTLM authentication, then there must also be a key <code>ntlm</code>, with value <code>true</code>.
  72. -- * <code>bypass_cache</code>: Do not perform a lookup in the local HTTP cache.
  73. -- * <code>no_cache</code>: Do not save the result of this request to the local HTTP cache.
  74. -- * <code>no_cache_body</code>: Do not save the body of the response to the local HTTP cache.
  75. -- * <code>redirect_ok</code>: Closure that overrides the default redirect_ok used to validate whether to follow HTTP redirects or not. False, if no HTTP redirects should be followed. Alternatively, a number may be passed to change the number of redirects to follow.
  76. -- The following example shows how to write a custom closure that follows 5 consecutive redirects, without the safety checks in the default redirect_ok:
  77. -- <code>
  78. -- redirect_ok = function(host,port)
  79. -- local c = 5
  80. -- return function(url)
  81. -- if ( c==0 ) then return false end
  82. -- c = c - 1
  83. -- return true
  84. -- end
  85. -- end
  86. -- </code>
  87. --
  88. -- @args http.max-cache-size The maximum memory size (in bytes) of the cache.
  89. --
  90. -- @args http.useragent The value of the User-Agent header field sent with
  91. -- requests. By default it is
  92. -- <code>"Mozilla/5.0 (compatible; Nmap Scripting Engine; http://nmap.org/book/nse.html)"</code>.
  93. -- A value of the empty string disables sending the User-Agent header field.
  94. --
  95. -- @args http.pipeline If set, it represents the number of HTTP requests that'll be
  96. -- sent on one connection. This can be set low to make debugging easier, or it
  97. -- can be set high to test how a server reacts (its chosen max is ignored).
  98. -- @args http.max-pipeline If set, it represents the number of outstanding HTTP requests
  99. -- that should be pipelined. Defaults to <code>http.pipeline</code> (if set), or to what
  100. -- <code>getPipelineMax</code> function returns.
  101. --
  102. -- TODO
  103. -- Implement cache system for http pipelines
  104. --
  105. local base64 = require "base64"
  106. local bin = require "bin"
  107. local bit = require "bit"
  108. local comm = require "comm"
  109. local coroutine = require "coroutine"
  110. local nmap = require "nmap"
  111. local os = require "os"
  112. local sasl = require "sasl"
  113. local stdnse = require "stdnse"
  114. local string = require "string"
  115. local table = require "table"
  116. local url = require "url"
  117. local smbauth = require "smbauth"
  118. local unicode = require "unicode"
  119. _ENV = stdnse.module("http", stdnse.seeall)
  120. ---Use ssl if we have it
  121. local have_ssl, openssl = pcall(require,'openssl')
  122. USER_AGENT = stdnse.get_script_args('http.useragent') or "Mozilla/5.0 (compatible; Nmap Scripting Engine; http://nmap.org/book/nse.html)"
  123. local MAX_REDIRECT_COUNT = 5
  124. -- Recursively copy a table.
  125. -- Only recurs when a value is a table, other values are copied by assignment.
  126. local function tcopy (t)
  127. local tc = {};
  128. for k,v in pairs(t) do
  129. if type(v) == "table" then
  130. tc[k] = tcopy(v);
  131. else
  132. tc[k] = v;
  133. end
  134. end
  135. return tc;
  136. end
  137. --- Recursively copy into a table any elements from another table whose key it
  138. -- doesn't have.
  139. local function table_augment(to, from)
  140. for k, v in pairs(from) do
  141. if type( to[k] ) == 'table' then
  142. table_augment(to[k], from[k])
  143. else
  144. to[k] = from[k]
  145. end
  146. end
  147. end
  148. --- Get a value suitable for the Host header field.
  149. -- See RFC 2616 sections 14.23 and 5.2.
  150. local function get_host_field(host, port)
  151. return stdnse.get_hostname(host)
  152. end
  153. -- Skip *( SP | HT ) starting at offset. See RFC 2616, section 2.2.
  154. -- @return the first index following the spaces.
  155. -- @return the spaces skipped over.
  156. local function skip_space(s, offset)
  157. local _, i, space = s:find("^([ \t]*)", offset)
  158. return i + 1, space
  159. end
  160. -- Get a token starting at offset. See RFC 2616, section 2.2.
  161. -- @return the first index following the token, or nil if no token was found.
  162. -- @return the token.
  163. local function get_token(s, offset)
  164. -- All characters except CTL and separators.
  165. local _, i, token = s:find("^([^()<>@,;:\\\"/%[%]?={} \0\001-\031\127]+)", offset)
  166. if i then
  167. return i + 1, token
  168. else
  169. return nil
  170. end
  171. end
  172. -- Get a quoted-string starting at offset. See RFC 2616, section 2.2. crlf is
  173. -- used as the definition for CRLF in the case of LWS within the string.
  174. -- @return the first index following the quoted-string, or nil if no
  175. -- quoted-string was found.
  176. -- @return the contents of the quoted-string, without quotes or backslash
  177. -- escapes.
  178. local function get_quoted_string(s, offset, crlf)
  179. local result = {}
  180. local i = offset
  181. assert(s:sub(i, i) == "\"")
  182. i = i + 1
  183. while i <= s:len() do
  184. local c = s:sub(i, i)
  185. if c == "\"" then
  186. -- Found the closing quote, done.
  187. return i + 1, table.concat(result)
  188. elseif c == "\\" then
  189. -- This is a quoted-pair ("\" CHAR).
  190. i = i + 1
  191. c = s:sub(i, i)
  192. if c == "" then
  193. -- No character following.
  194. error(string.format("\\ escape at end of input while parsing quoted-string."))
  195. end
  196. -- Only CHAR may follow a backslash.
  197. if c:byte(1) > 127 then
  198. error(string.format("Unexpected character with value > 127 (0x%02X) in quoted-string.", c:byte(1)))
  199. end
  200. else
  201. -- This is qdtext, which is TEXT except for '"'.
  202. -- TEXT is "any OCTET except CTLs, but including LWS," however "a CRLF is
  203. -- allowed in the definition of TEXT only as part of a header field
  204. -- continuation." So there are really two definitions of quoted-string,
  205. -- depending on whether it's in a header field or not. This function does
  206. -- not allow CRLF.
  207. c = s:sub(i, i)
  208. if c ~= "\t" and c:match("^[\0\001-\031\127]$") then
  209. error(string.format("Unexpected control character in quoted-string: 0x%02X.", c:byte(1)))
  210. end
  211. end
  212. result[#result + 1] = c
  213. i = i + 1
  214. end
  215. return nil
  216. end
  217. -- Get a ( token | quoted-string ) starting at offset.
  218. -- @return the first index following the token or quoted-string, or nil if
  219. -- nothing was found.
  220. -- @return the token or quoted-string.
  221. local function get_token_or_quoted_string(s, offset, crlf)
  222. if s:sub(offset, offset) == "\"" then
  223. return get_quoted_string(s, offset)
  224. else
  225. return get_token(s, offset)
  226. end
  227. end
  228. -- Returns the index just past the end of LWS.
  229. local function skip_lws(s, pos)
  230. local _, e
  231. while true do
  232. while string.match(s, "^[ \t]", pos) do
  233. pos = pos + 1
  234. end
  235. _, e = string.find(s, "^\r?\n[ \t]", pos)
  236. if not e then
  237. return pos
  238. end
  239. pos = e + 1
  240. end
  241. end
  242. ---Validate an 'options' table, which is passed to a number of the HTTP functions. It is
  243. -- often difficult to track down a mistake in the options table, and requires fiddling
  244. -- with the http.lua source, but this should make that a lot easier.
  245. local function validate_options(options)
  246. local bad = false
  247. if(options == nil) then
  248. return true
  249. end
  250. for key, value in pairs(options) do
  251. if(key == 'timeout') then
  252. if(type(tonumber(value)) ~= 'number') then
  253. stdnse.debug1('http: options.timeout contains a non-numeric value')
  254. bad = true
  255. end
  256. elseif(key == 'header') then
  257. if(type(value) ~= 'table') then
  258. stdnse.debug1("http: options.header should be a table")
  259. bad = true
  260. end
  261. elseif(key == 'content') then
  262. if(type(value) ~= 'string' and type(value) ~= 'table') then
  263. stdnse.debug1("http: options.content should be a string or a table")
  264. bad = true
  265. end
  266. elseif(key == 'cookies') then
  267. if(type(value) == 'table') then
  268. for _, cookie in ipairs(value) do
  269. for cookie_key, cookie_value in pairs(cookie) do
  270. if(cookie_key == 'name') then
  271. if(type(cookie_value) ~= 'string') then
  272. stdnse.debug1("http: options.cookies[i].name should be a string")
  273. bad = true
  274. end
  275. elseif(cookie_key == 'value') then
  276. if(type(cookie_value) ~= 'string') then
  277. stdnse.debug1("http: options.cookies[i].value should be a string")
  278. bad = true
  279. end
  280. elseif(cookie_key == 'path') then
  281. if(type(cookie_value) ~= 'string') then
  282. stdnse.debug1("http: options.cookies[i].path should be a string")
  283. bad = true
  284. end
  285. elseif(cookie_key == 'expires') then
  286. if(type(cookie_value) ~= 'string') then
  287. stdnse.debug1("http: options.cookies[i].expires should be a string")
  288. bad = true
  289. end
  290. else
  291. stdnse.debug1("http: Unknown field in cookie table: %s", cookie_key)
  292. bad = true
  293. end
  294. end
  295. end
  296. elseif(type(value) ~= 'string') then
  297. stdnse.debug1("http: options.cookies should be a table or a string")
  298. bad = true
  299. end
  300. elseif(key == 'auth') then
  301. if(type(value) == 'table') then
  302. if(value['username'] == nil or value['password'] == nil) then
  303. stdnse.debug1("http: options.auth should contain both a 'username' and a 'password' key")
  304. bad = true
  305. end
  306. else
  307. stdnse.debug1("http: options.auth should be a table")
  308. bad = true
  309. end
  310. elseif (key == 'digestauth') then
  311. if(type(value) == 'table') then
  312. local req_keys = {"username","realm","nonce","digest-uri","response"}
  313. for _,k in ipairs(req_keys) do
  314. if not value[k] then
  315. stdnse.debug1("http: options.digestauth missing key: %s",k)
  316. bad = true
  317. break
  318. end
  319. end
  320. else
  321. bad = true
  322. stdnse.debug1("http: options.digestauth should be a table")
  323. end
  324. elseif (key == 'ntlmauth') then
  325. stdnse.debug1("Proceeding with ntlm message")
  326. elseif(key == 'bypass_cache' or key == 'no_cache' or key == 'no_cache_body') then
  327. if(type(value) ~= 'boolean') then
  328. stdnse.debug1("http: options.bypass_cache, options.no_cache, and options.no_cache_body must be boolean values")
  329. bad = true
  330. end
  331. elseif(key == 'redirect_ok') then
  332. if(type(value)~= 'function' and type(value)~='boolean' and type(value) ~= 'number') then
  333. stdnse.debug1("http: options.redirect_ok must be a function or boolean or number")
  334. bad = true
  335. end
  336. else
  337. stdnse.debug1("http: Unknown key in the options table: %s", key)
  338. end
  339. end
  340. return not(bad)
  341. end
  342. -- The following recv functions, and the function <code>next_response</code>
  343. -- follow a common pattern. They each take a <code>partial</code> argument
  344. -- whose value is data that has been read from the socket but not yet used in
  345. -- parsing, and they return as their second return value a new value for
  346. -- <code>partial</code>. The idea is that, for example, in reading from the
  347. -- socket to get the Status-Line, you will probably read too much and read part
  348. -- of the header. That part (the "partial") has to be retained when you go to
  349. -- parse the header. The common use pattern is this:
  350. -- <code>
  351. -- local partial
  352. -- status_line, partial = recv_line(socket, partial)
  353. -- ...
  354. -- header, partial = recv_header(socket, partial)
  355. -- ...
  356. -- </code>
  357. -- On error, the functions return <code>nil</code> and the second return value
  358. -- is an error message.
  359. -- Receive a single line (up to <code>\n</code>).
  360. local function recv_line(s, partial)
  361. local _, e
  362. local status, data
  363. local pos
  364. partial = partial or ""
  365. pos = 1
  366. while true do
  367. _, e = string.find(partial, "\n", pos, true)
  368. if e then
  369. break
  370. end
  371. status, data = s:receive()
  372. if not status then
  373. return status, data
  374. end
  375. pos = #partial
  376. partial = partial .. data
  377. end
  378. return string.sub(partial, 1, e), string.sub(partial, e + 1)
  379. end
  380. local function line_is_empty(line)
  381. return line == "\r\n" or line == "\n"
  382. end
  383. -- Receive up to and including the first blank line, but return everything up
  384. -- to and not including the final blank line.
  385. local function recv_header(s, partial)
  386. local lines = {}
  387. partial = partial or ""
  388. while true do
  389. local line
  390. line, partial = recv_line(s, partial)
  391. if not line then
  392. return line, partial
  393. end
  394. if line_is_empty(line) then
  395. break
  396. end
  397. lines[#lines + 1] = line
  398. end
  399. return table.concat(lines), partial
  400. end
  401. -- Receive until the connection is closed.
  402. local function recv_all(s, partial)
  403. local parts
  404. partial = partial or ""
  405. parts = {partial}
  406. while true do
  407. local status, part = s:receive()
  408. if not status then
  409. break
  410. else
  411. parts[#parts + 1] = part
  412. end
  413. end
  414. return table.concat(parts), ""
  415. end
  416. -- Receive exactly <code>length</code> bytes. Returns <code>nil</code> if that
  417. -- many aren't available.
  418. local function recv_length(s, length, partial)
  419. local parts, last
  420. partial = partial or ""
  421. parts = {}
  422. last = partial
  423. length = length - #last
  424. while length > 0 do
  425. local status
  426. parts[#parts + 1] = last
  427. status, last = s:receive()
  428. if not status then
  429. return nil
  430. end
  431. length = length - #last
  432. end
  433. -- At this point length is 0 or negative, and indicates the degree to which
  434. -- the last read "overshot" the desired length.
  435. if length == 0 then
  436. return table.concat(parts) .. last, ""
  437. else
  438. return table.concat(parts) .. string.sub(last, 1, length - 1), string.sub(last, length)
  439. end
  440. end
  441. -- Receive until the end of a chunked message body, and return the dechunked
  442. -- body.
  443. local function recv_chunked(s, partial)
  444. local chunks, chunk
  445. local chunk_size
  446. local pos
  447. chunks = {}
  448. repeat
  449. local line, hex, _, i
  450. line, partial = recv_line(s, partial)
  451. if not line then
  452. return nil, partial
  453. end
  454. pos = 1
  455. pos = skip_space(line, pos)
  456. -- Get the chunk-size.
  457. _, i, hex = string.find(line, "^([%x]+)", pos)
  458. if not i then
  459. return nil, string.format("Chunked encoding didn't find hex; got %q.", string.sub(line, pos, pos + 10))
  460. end
  461. pos = i + 1
  462. chunk_size = tonumber(hex, 16)
  463. if not chunk_size or chunk_size < 0 then
  464. return nil, string.format("Chunk size %s is not a positive integer.", hex)
  465. end
  466. -- Ignore chunk-extensions that may follow here.
  467. -- RFC 2616, section 2.1 ("Implied *LWS") seems to allow *LWS between the
  468. -- parts of a chunk-extension, but that is ambiguous. Consider this case:
  469. -- "1234;a\r\n =1\r\n...". It could be an extension with a chunk-ext-name
  470. -- of "a" (and no value), and a chunk-data beginning with " =", or it could
  471. -- be a chunk-ext-name of "a" with a value of "1", and a chunk-data
  472. -- starting with "...". We don't allow *LWS here, only ( SP | HT ), so the
  473. -- first interpretation will prevail.
  474. chunk, partial = recv_length(s, chunk_size, partial)
  475. if not chunk then
  476. return nil, partial
  477. end
  478. chunks[#chunks + 1] = chunk
  479. line, partial = recv_line(s, partial)
  480. if not line then
  481. -- this warning message was initially an error but was adapted
  482. -- to support broken servers, such as the Citrix XML Service
  483. stdnse.debug2("Didn't find CRLF after chunk-data.")
  484. elseif not string.match(line, "^\r?\n") then
  485. return nil, string.format("Didn't find CRLF after chunk-data; got %q.", line)
  486. end
  487. until chunk_size == 0
  488. return table.concat(chunks), partial
  489. end
  490. -- Receive a message body, assuming that the header has already been read by
  491. -- <code>recv_header</code>. The handling is sensitive to the request method
  492. -- and the status code of the response.
  493. local function recv_body(s, response, method, partial)
  494. local connection_close, connection_keepalive
  495. local version_major, version_minor
  496. local transfer_encoding
  497. local content_length
  498. local err
  499. partial = partial or ""
  500. -- First check for Connection: close and Connection: keep-alive. This is
  501. -- necessary to handle some servers that don't follow the protocol.
  502. connection_close = false
  503. connection_keepalive = false
  504. if response.header.connection then
  505. local offset, token
  506. offset = 0
  507. while true do
  508. offset, token = get_token(response.header.connection, offset + 1)
  509. if not offset then
  510. break
  511. end
  512. if string.lower(token) == "close" then
  513. connection_close = true
  514. elseif string.lower(token) == "keep-alive" then
  515. connection_keepalive = true
  516. end
  517. end
  518. end
  519. -- The HTTP version may also affect our decisions.
  520. version_major, version_minor = string.match(response["status-line"], "^HTTP/(%d+)%.(%d+)")
  521. -- See RFC 2616, section 4.4 "Message Length".
  522. -- 1. Any response message which "MUST NOT" include a message-body (such as
  523. -- the 1xx, 204, and 304 responses and any response to a HEAD request) is
  524. -- always terminated by the first empty line after the header fields...
  525. --
  526. -- Despite the above, some servers return a body with response to a HEAD
  527. -- request. So if an HTTP/1.0 server returns a response without Connection:
  528. -- keep-alive, or any server returns a response with Connection: close, read
  529. -- whatever's left on the socket (should be zero bytes).
  530. if string.upper(method) == "HEAD"
  531. or (response.status >= 100 and response.status <= 199)
  532. or response.status == 204 or response.status == 304 then
  533. if connection_close or (version_major == "1" and version_minor == "0" and not connection_keepalive) then
  534. return recv_all(s, partial)
  535. else
  536. return "", partial
  537. end
  538. end
  539. -- 2. If a Transfer-Encoding header field (section 14.41) is present and has
  540. -- any value other than "identity", then the transfer-length is defined by
  541. -- use of the "chunked" transfer-coding (section 3.6), unless the message
  542. -- is terminated by closing the connection.
  543. if response.header["transfer-encoding"]
  544. and response.header["transfer-encoding"] ~= "identity" then
  545. return recv_chunked(s, partial)
  546. end
  547. -- The Citrix XML Service sends a wrong "Transfer-Coding" instead of
  548. -- "Transfer-Encoding".
  549. if response.header["transfer-coding"]
  550. and response.header["transfer-coding"] ~= "identity" then
  551. return recv_chunked(s, partial)
  552. end
  553. -- 3. If a Content-Length header field (section 14.13) is present, its decimal
  554. -- value in OCTETs represents both the entity-length and the
  555. -- transfer-length. The Content-Length header field MUST NOT be sent if
  556. -- these two lengths are different (i.e., if a Transfer-Encoding header
  557. -- field is present). If a message is received with both a
  558. -- Transfer-Encoding header field and a Content-Length header field, the
  559. -- latter MUST be ignored.
  560. if response.header["content-length"] and not response.header["transfer-encoding"] then
  561. content_length = tonumber(response.header["content-length"])
  562. if not content_length then
  563. return nil, string.format("Content-Length %q is non-numeric", response.header["content-length"])
  564. end
  565. return recv_length(s, content_length, partial)
  566. end
  567. -- 4. If the message uses the media type "multipart/byteranges", and the
  568. -- transfer-length is not otherwise specified, then this self-delimiting
  569. -- media type defines the transfer-length. [sic]
  570. -- Case 4 is unhandled.
  571. -- 5. By the server closing the connection.
  572. return recv_all(s, partial)
  573. end
  574. -- Sets response["status-line"] and response.status.
  575. local function parse_status_line(status_line, response)
  576. local version, status, reason_phrase
  577. response["status-line"] = status_line
  578. version, status, reason_phrase = string.match(status_line,
  579. "^HTTP/(%d%.%d) *(%d+) *(.*)\r?\n$")
  580. if not version then
  581. return nil, string.format("Error parsing status-line %q.", status_line)
  582. end
  583. -- We don't have a use for the version; ignore it.
  584. response.status = tonumber(status)
  585. if not response.status then
  586. return nil, string.format("Status code is not numeric: %s", status)
  587. end
  588. return true
  589. end
  590. -- Sets response.header and response.rawheader.
  591. local function parse_header(header, response)
  592. local pos
  593. local name, words
  594. local s, e
  595. response.header = {}
  596. response.rawheader = stdnse.strsplit("\r?\n", header)
  597. pos = 1
  598. while pos <= #header do
  599. -- Get the field name.
  600. e, name = get_token(header, pos)
  601. if not name or e > #header or string.sub(header, e, e) ~= ":" then
  602. return nil, string.format("Can't get header field name at %q", string.sub(header, pos, pos + 30))
  603. end
  604. pos = e + 1
  605. -- Skip initial space.
  606. pos = skip_lws(header, pos)
  607. -- Get non-space words separated by LWS, then join them with a single space.
  608. words = {}
  609. while pos <= #header and not string.match(header, "^\r?\n", pos) do
  610. s = pos
  611. while not string.match(header, "^[ \t]", pos) and
  612. not string.match(header, "^\r?\n", pos) do
  613. pos = pos + 1
  614. end
  615. words[#words + 1] = string.sub(header, s, pos - 1)
  616. pos = skip_lws(header, pos)
  617. end
  618. -- Set it in our table.
  619. name = string.lower(name)
  620. if response.header[name] then
  621. response.header[name] = response.header[name] .. ", " .. table.concat(words, " ")
  622. else
  623. response.header[name] = table.concat(words, " ")
  624. end
  625. -- Next field, or end of string. (If not it's an error.)
  626. s, e = string.find(header, "^\r?\n", pos)
  627. if not e then
  628. return nil, string.format("Header field named %q didn't end with CRLF", name)
  629. end
  630. pos = e + 1
  631. end
  632. return true
  633. end
  634. -- Parse the contents of a Set-Cookie header field. The result is an array
  635. -- containing tables of the form
  636. --
  637. -- { name = "NAME", value = "VALUE", Comment = "...", Domain = "...", ... }
  638. --
  639. -- Every key except "name" and "value" is optional.
  640. --
  641. -- This function attempts to support the cookie syntax defined in RFC 2109
  642. -- along with the backwards-compatibility suggestions from its section 10,
  643. -- "HISTORICAL". Values need not be quoted, but if they start with a quote they
  644. -- will be interpreted as a quoted string.
  645. local function parse_set_cookie(s)
  646. local cookies
  647. local name, value
  648. local _, pos
  649. cookies = {}
  650. pos = 1
  651. while true do
  652. local cookie = {}
  653. -- Get the NAME=VALUE part.
  654. pos = skip_space(s, pos)
  655. pos, cookie.name = get_token(s, pos)
  656. if not cookie.name then
  657. return nil, "Can't get cookie name."
  658. end
  659. pos = skip_space(s, pos)
  660. if pos > #s or string.sub(s, pos, pos) ~= "=" then
  661. return nil, string.format("Expected '=' after cookie name \"%s\".", cookie.name)
  662. end
  663. pos = pos + 1
  664. pos = skip_space(s, pos)
  665. if string.sub(s, pos, pos) == "\"" then
  666. pos, cookie.value = get_quoted_string(s, pos)
  667. else
  668. _, pos, cookie.value = string.find(s, "([^;]*)[ \t]*", pos)
  669. pos = pos + 1
  670. end
  671. if not cookie.value then
  672. return nil, string.format("Can't get value of cookie named \"%s\".", cookie.name)
  673. end
  674. pos = skip_space(s, pos)
  675. -- Loop over the attributes.
  676. while pos <= #s and string.sub(s, pos, pos) == ";" do
  677. pos = pos + 1
  678. pos = skip_space(s, pos)
  679. pos, name = get_token(s, pos)
  680. if not name then
  681. return nil, string.format("Can't get attribute name of cookie \"%s\".", cookie.name)
  682. end
  683. pos = skip_space(s, pos)
  684. if pos <= #s and string.sub(s, pos, pos) == "=" then
  685. pos = pos + 1
  686. pos = skip_space(s, pos)
  687. if string.sub(s, pos, pos) == "\"" then
  688. pos, value = get_quoted_string(s, pos)
  689. else
  690. -- account for the possibility of the expires attribute being empty or improperly formatted
  691. local last_pos = pos
  692. if string.lower(name) == "expires" then
  693. -- For version 0 cookies we must allow one comma for "expires".
  694. _, pos, value = string.find(s, "([^,]*,[^;,]*)[ \t]*", pos)
  695. else
  696. _, pos, value = string.find(s, "([^;,]*)[ \t]*", pos)
  697. end
  698. -- account for the possibility of the expires attribute being empty or improperly formatted
  699. if ( not(pos) ) then
  700. _, pos, value = s:find("([^;]*)", last_pos)
  701. end
  702. pos = pos + 1
  703. end
  704. if not value then
  705. return nil, string.format("Can't get value of cookie attribute \"%s\".", name)
  706. end
  707. else
  708. value = true
  709. end
  710. cookie[name:lower()] = value
  711. pos = skip_space(s, pos)
  712. end
  713. cookies[#cookies + 1] = cookie
  714. if pos > #s then
  715. break
  716. end
  717. if string.sub(s, pos, pos) ~= "," then
  718. return nil, string.format("Syntax error after cookie named \"%s\".", cookie.name)
  719. end
  720. pos = pos + 1
  721. pos = skip_space(s, pos)
  722. end
  723. return cookies
  724. end
  725. -- Read one response from the socket <code>s</code> and return it after
  726. -- parsing.
  727. local function next_response(s, method, partial)
  728. local response
  729. local status_line, header, body
  730. local status, err
  731. partial = partial or ""
  732. response = {
  733. status=nil,
  734. ["status-line"]=nil,
  735. header={},
  736. rawheader={},
  737. body=""
  738. }
  739. status_line, partial = recv_line(s, partial)
  740. if not status_line then
  741. return nil, partial
  742. end
  743. status, err = parse_status_line(status_line, response)
  744. if not status then
  745. return nil, err
  746. end
  747. header, partial = recv_header(s, partial)
  748. if not header then
  749. return nil, partial
  750. end
  751. status, err = parse_header(header, response)
  752. if not status then
  753. return nil, err
  754. end
  755. body, partial = recv_body(s, response, method, partial)
  756. if not body then
  757. return nil, partial
  758. end
  759. response.body = body
  760. -- We have the Status-Line, header, and body; now do any postprocessing.
  761. response.cookies = {}
  762. if response.header["set-cookie"] then
  763. response.cookies, err = parse_set_cookie(response.header["set-cookie"])
  764. if not response.cookies then
  765. -- Ignore a cookie parsing error.
  766. response.cookies = {}
  767. end
  768. end
  769. return response, partial
  770. end
  771. --- Tries to extract the max number of requests that should be made on
  772. -- a keep-alive connection based on "Keep-Alive: timeout=xx,max=yy" response
  773. -- header.
  774. --
  775. -- If the value is not available, an arbitrary value is used. If the connection
  776. -- is not explicitly closed by the server, this same value is attempted.
  777. --
  778. -- @param response The http response - Might be a table or a raw response
  779. -- @return The max number of requests on a keep-alive connection
  780. local function getPipelineMax(response)
  781. -- Allow users to override this with a script-arg
  782. local pipeline = stdnse.get_script_args({'http.pipeline', 'pipeline'})
  783. if(pipeline) then
  784. return tonumber(pipeline)
  785. end
  786. if response then
  787. if response.header and response.header.connection ~= "close" then
  788. if response.header["keep-alive"] then
  789. local max = string.match( response.header["keep-alive"], "max=(%d*)")
  790. if(max == nil) then
  791. return 40
  792. end
  793. return tonumber(max)
  794. else
  795. return 40
  796. end
  797. end
  798. end
  799. return 1
  800. end
  801. --- Builds a string to be added to the request mod_options table
  802. --
  803. -- @param cookies A cookie jar just like the table returned parse_set_cookie.
  804. -- @param path If the argument exists, only cookies with this path are included to the request
  805. -- @return A string to be added to the mod_options table
  806. local function buildCookies(cookies, path)
  807. local cookie = ""
  808. if type(cookies) == 'string' then return cookies end
  809. for _, ck in ipairs(cookies or {}) do
  810. local ckpath = ck["path"]
  811. if not path or not ckpath
  812. or ckpath == path
  813. or ckpath:sub(-1) == "/" and ckpath == path:sub(1, ckpath:len())
  814. or ckpath .. "/" == path:sub(1, ckpath:len()+1)
  815. then
  816. cookie = cookie .. ck["name"] .. "=" .. ck["value"] .. "; "
  817. end
  818. end
  819. return cookie:gsub("; $","")
  820. end
  821. -- HTTP cache.
  822. -- Cache of GET and HEAD requests. Uses <"host:port:path", record>.
  823. -- record is in the format:
  824. -- result: The result from http.get or http.head
  825. -- last_used: The time the record was last accessed or made.
  826. -- get: Was the result received from a request to get or recently wiped?
  827. -- size: The size of the record, equal to #record.result.body.
  828. local cache = {size = 0};
  829. local function check_size (cache)
  830. local max_size = tonumber(stdnse.get_script_args({'http.max-cache-size', 'http-max-cache-size'}) or 1e6);
  831. local size = cache.size;
  832. if size > max_size then
  833. stdnse.debug1(
  834. "Current http cache size (%d bytes) exceeds max size of %d",
  835. size, max_size);
  836. table.sort(cache, function(r1, r2)
  837. return (r1.last_used or 0) < (r2.last_used or 0);
  838. end);
  839. for i, record in ipairs(cache) do
  840. if size <= max_size then break end
  841. local result = record.result;
  842. if type(result.body) == "string" then
  843. size = size - record.size;
  844. record.size, record.get, result.body = 0, false, "";
  845. end
  846. end
  847. cache.size = size;
  848. end
  849. stdnse.debug2("Final http cache size (%d bytes) of max size of %d",
  850. size, max_size);
  851. return size;
  852. end
  853. -- Unique value to signal value is being retrieved.
  854. -- Also holds <mutex, thread> pairs, working thread is value
  855. local WORKING = setmetatable({}, {__mode = "v"});
  856. local function lookup_cache (method, host, port, path, options)
  857. if(not(validate_options(options))) then
  858. return nil
  859. end
  860. options = options or {};
  861. local bypass_cache = options.bypass_cache; -- do not lookup
  862. local no_cache = options.no_cache; -- do not save result
  863. local no_cache_body = options.no_cache_body; -- do not save body
  864. if type(port) == "table" then port = port.number end
  865. local key = stdnse.get_hostname(host)..":"..port..":"..path;
  866. local mutex = nmap.mutex(tostring(lookup_cache)..key);
  867. local state = {
  868. mutex = mutex,
  869. key = key,
  870. method = method,
  871. bypass_cache = bypass_cache,
  872. no_cache = no_cache,
  873. no_cache_body = no_cache_body,
  874. };
  875. while true do
  876. mutex "lock";
  877. local record = cache[key];
  878. if bypass_cache or record == nil or method ~= record.method then
  879. WORKING[mutex] = coroutine.running();
  880. cache[key], state.old_record = WORKING, record;
  881. return nil, state;
  882. elseif record == WORKING then
  883. local working = WORKING[mutex];
  884. if working == nil or coroutine.status(working) == "dead" then
  885. -- thread died before insert_cache could be called
  886. cache[key] = nil; -- reset
  887. end
  888. mutex "done";
  889. else
  890. mutex "done";
  891. record.last_used = os.time();
  892. return tcopy(record.result), state;
  893. end
  894. end
  895. end
  896. local function response_is_cacheable(response)
  897. -- if response.status is nil, then an error must have occurred during the request
  898. -- and we probably don't want to cache the response
  899. if not response.status then
  900. return false
  901. end
  902. -- 206 Partial Content. RFC 2616, 1.34: "...a cache that does not support the
  903. -- Range and Content-Range headers MUST NOT cache 206 (Partial Content)
  904. -- responses."
  905. if response.status == 206 then
  906. return false
  907. end
  908. -- RFC 2616, 13.4. "A response received with any [status code other than 200,
  909. -- 203, 206, 300, 301 or 410] (e.g. status codes 302 and 307) MUST NOT be
  910. -- returned in a reply to a subsequent request unless there are cache-control
  911. -- directives or another header(s) that explicitly allow it."
  912. -- We violate the standard here and allow these other codes to be cached,
  913. -- with the exceptions listed below.
  914. -- 401 Unauthorized. Caching this would prevent us from retrieving it later
  915. -- with the correct credentials.
  916. if response.status == 401 then
  917. return false
  918. end
  919. return true
  920. end
  921. local function insert_cache (state, response)
  922. local key = assert(state.key);
  923. local mutex = assert(state.mutex);
  924. if response == nil or state.no_cache or not response_is_cacheable(response) then
  925. cache[key] = state.old_record;
  926. else
  927. local record = {
  928. result = tcopy(response),
  929. last_used = os.time(),
  930. method = state.method,
  931. size = type(response.body) == "string" and #response.body or 0,
  932. };
  933. response = record.result; -- only modify copy
  934. cache[key], cache[#cache+1] = record, record;
  935. if state.no_cache_body then
  936. response.body = "";
  937. end
  938. if type(response.body) == "string" then
  939. cache.size = cache.size + #response.body;
  940. check_size(cache);
  941. end
  942. end
  943. mutex "done";
  944. end
  945. -- Return true if the given method requires a body in the request. In case no
  946. -- body was supplied we must send "Content-Length: 0".
  947. local function request_method_needs_content_length(method)
  948. return method == "POST"
  949. end
  950. -- For each of the following request functions, <code>host</code> may either be
  951. -- a string or a table, and <code>port</code> may either be a number or a
  952. -- table.
  953. --
  954. -- The format of the return value is a table with the following structure:
  955. -- {status = 200, status-line = "HTTP/1.1 200 OK", header = {}, rawheader = {}, body ="<html>...</html>"}
  956. -- The header table has an entry for each received header with the header name
  957. -- being the key. The table also has an entry named "status" which contains the
  958. -- http status code of the request.
  959. -- In case of an error, the status is nil and status-line describes the problem.
  960. local function http_error(status_line)
  961. return {
  962. status = nil,
  963. ["status-line"] = status_line,
  964. header = {},
  965. rawheader = {},
  966. body = nil,
  967. }
  968. end
  969. --- Build an HTTP request from parameters and return it as a string.
  970. --
  971. -- @param host The host this request is intended for.
  972. -- @param port The port this request is intended for.
  973. -- @param method The method to use.
  974. -- @param path The path for the request.
  975. -- @param options A table of options, which may include the keys:
  976. -- * <code>header</code>: A table containing additional headers to be used for the request.
  977. -- * <code>content</code>: The content of the message (content-length will be added -- set header['Content-Length'] to override)
  978. -- * <code>cookies</code>: A table of cookies in the form returned by <code>parse_set_cookie</code>.
  979. -- * <code>auth</code>: A table containing the keys <code>username</code> and <code>password</code>.
  980. -- @return A request string.
  981. -- @see generic_request
  982. local function build_request(host, port, method, path, options)
  983. if(not(validate_options(options))) then
  984. return nil
  985. end
  986. options = options or {}
  987. -- Private copy of the options table, used to add default header fields.
  988. local mod_options = {
  989. header = {
  990. Connection = "close",
  991. Host = get_host_field(host, port),
  992. ["User-Agent"] = USER_AGENT
  993. }
  994. }
  995. if options.cookies then
  996. local cookies = buildCookies(options.cookies, path)
  997. if #cookies > 0 then
  998. mod_options.header["Cookie"] = cookies
  999. end
  1000. end
  1001. if options.auth and not (options.auth.digest or options.auth.ntlm) then
  1002. local username = options.auth.username
  1003. local password = options.auth.password
  1004. local credentials = "Basic " .. base64.enc(username .. ":" .. password)
  1005. mod_options.header["Authorization"] = credentials
  1006. end
  1007. if options.digestauth then
  1008. local order = {"username", "realm", "nonce", "digest-uri", "algorithm", "response", "qop", "nc", "cnonce"}
  1009. local no_quote = {algorithm=true, qop=true, nc=true}
  1010. local creds = {}
  1011. for _,k in ipairs(order) do
  1012. local v = options.digestauth[k]
  1013. if v then
  1014. if no_quote[k] then
  1015. table.insert(creds, ("%s=%s"):format(k,v))
  1016. else
  1017. if k == "digest-uri" then
  1018. table.insert(creds, ('%s="%s"'):format("uri",v))
  1019. else
  1020. table.insert(creds, ('%s="%s"'):format(k,v))
  1021. end
  1022. end
  1023. end
  1024. end
  1025. local credentials = "Digest "..table.concat(creds, ", ")
  1026. mod_options.header["Authorization"] = credentials
  1027. end
  1028. if options.ntlmauth then
  1029. mod_options.header["Authorization"] = "NTLM " .. base64.enc(options.ntlmauth)
  1030. end
  1031. local body
  1032. -- Build a form submission from a table, like "k1=v1&k2=v2".
  1033. if type(options.content) == "table" then
  1034. local parts = {}
  1035. local k, v
  1036. for k, v in pairs(options.content) do
  1037. parts[#parts + 1] = url.escape(k) .. "=" .. url.escape(v)
  1038. end
  1039. body = table.concat(parts, "&")
  1040. mod_options.header["Content-Type"] = "application/x-www-form-urlencoded"
  1041. elseif options.content then
  1042. body = options.content
  1043. elseif request_method_needs_content_length(method) then
  1044. body = ""
  1045. end
  1046. if body then
  1047. mod_options.header["Content-Length"] = #body
  1048. end
  1049. -- Add any other header fields into the local copy.
  1050. table_augment(mod_options, options)
  1051. -- We concat this string manually to allow null bytes in requests
  1052. local request_line = method.." "..path.." HTTP/1.1"
  1053. local header = {}
  1054. for name, value in pairs(mod_options.header) do
  1055. -- we concat this string manually to allow null bytes in requests
  1056. header[#header + 1] = name..": "..value
  1057. end
  1058. return request_line .. "\r\n" .. stdnse.strjoin("\r\n", header) .. "\r\n\r\n" .. (body or "")
  1059. end
  1060. --- Send a string to a host and port and return the HTTP result. This function
  1061. -- is like <code>generic_request</code>, to be used when you have a ready-made
  1062. -- request, not a collection of request parameters.
  1063. --
  1064. -- @param host The host to connect to.
  1065. -- @param port The port to connect to.
  1066. -- @param options A table of other parameters. It may have any of these fields:
  1067. -- * <code>timeout</code>: A timeout used for socket operations.
  1068. -- * <code>header</code>: A table containing additional headers to be used for the request.
  1069. -- * <code>content</code>: The content of the message (content-length will be added -- set header['Content-Length'] to override)
  1070. -- * <code>cookies</code>: A table of cookies in the form returned by <code>parse_set_cookie</code>.
  1071. -- * <code>auth</code>: A table containing the keys <code>username</code> and <code>password</code>.
  1072. -- @return A response table, see module documentation for description.
  1073. -- @see generic_request
  1074. local function request(host, port, data, options)
  1075. if(not(validate_options(options))) then
  1076. return http_error("Options failed to validate.")
  1077. end
  1078. local method
  1079. local header
  1080. local response
  1081. options = options or {}
  1082. if type(port) == 'table' then
  1083. if port.protocol and port.protocol ~= 'tcp' then
  1084. stdnse.debug1("http.request() supports the TCP protocol only, your request to %s cannot be completed.", host)
  1085. return http_error("Unsupported protocol.")
  1086. end
  1087. end
  1088. method = string.match(data, "^(%S+)")
  1089. local socket, partial, opts = comm.tryssl(host, port, data, { timeout = options.timeout })
  1090. if not socket then
  1091. return http_error("Error creating socket.")
  1092. end
  1093. repeat
  1094. response, partial = next_response(socket, method, partial)
  1095. if not response then
  1096. return http_error("There was an error in next_response function.")
  1097. end
  1098. -- See RFC 2616, sections 8.2.3 and 10.1.1, for the 100 Continue status.
  1099. -- Sometimes a server will tell us to "go ahead" with a POST body before
  1100. -- sending the real response. If we got one of those, skip over it.
  1101. until not (response.status >= 100 and response.status <= 199)
  1102. socket:close()
  1103. -- if SSL was used to retrieve the URL mark this in the response
  1104. response.ssl = ( opts == 'ssl' )
  1105. return response
  1106. end
  1107. ---Do a single request with a given method. The response is returned as the standard
  1108. -- response table (see the module documentation).
  1109. --
  1110. -- The <code>get</code>, <code>head</code>, and <code>post</code> functions are simple
  1111. -- wrappers around <code>generic_request</code>.
  1112. --
  1113. -- Any 1XX (informational) responses are discarded.
  1114. --
  1115. -- @param host The host to connect to.
  1116. -- @param port The port to connect to.
  1117. -- @param method The method to use; for example, 'GET', 'HEAD', etc.
  1118. -- @param path The path to retrieve.
  1119. -- @param options [optional] A table that lets the caller control socket timeouts, HTTP headers, and other parameters. For full documentation, see the module documentation (above).
  1120. -- @return A response table, see module documentation for description.
  1121. -- @see request
  1122. function generic_request(host, port, method, path, options)
  1123. if(not(validate_options(options))) then
  1124. return http_error("Options failed to validate.")
  1125. end
  1126. local digest_auth = options and options.auth and options.auth.digest
  1127. local ntlm_auth = options and options.auth and options.auth.ntlm
  1128. if (digest_auth or ntlm_auth) and not have_ssl then
  1129. stdnse.debug1("http: digest and ntlm auth require openssl.")
  1130. end
  1131. if digest_auth and have_ssl then
  1132. -- If we want to do digest authentication, we have to make an initial
  1133. -- request to get realm, nonce and other fields.
  1134. local options_with_auth_removed = tcopy(options)
  1135. options_with_auth_removed["auth"] = nil
  1136. local r = generic_request(host, port, method, path, options_with_auth_removed)
  1137. local h = r.header['www-authenticate']
  1138. if not r.status or (h and not string.find(h:lower(), "digest.-realm")) then
  1139. stdnse.debug1("http: the target doesn't support digest auth or there was an error during request.")
  1140. return http_error("The target doesn't support digest auth or there was an error during request.")
  1141. end
  1142. -- Compute the response hash
  1143. local dmd5 = sasl.DigestMD5:new(h, options.auth.username, options.auth.password, method, path)
  1144. local _, digest_table = dmd5:calcDigest()
  1145. options.digestauth = digest_table
  1146. end
  1147. if ntlm_auth and have_ssl then
  1148. local custom_options = tcopy(options) -- to be sent with the type 1 request
  1149. custom_options["auth"] = nil -- removing the auth options
  1150. -- let's check if the target supports ntlm with a simple get request.
  1151. -- Setting a timeout here other than nil messes up the authentication if this is the first device sending
  1152. -- a request to the server. Don't know why.
  1153. custom_options.timeout = nil
  1154. local response = generic_request(host, port, method, path, custom_options)
  1155. local authentication_header = response.header['www-authenticate']
  1156. -- get back the timeout option.
  1157. custom_options.timeout = options.timeout
  1158. custom_options.header = options.header or {}
  1159. custom_options.header["Connection"] = "Keep-Alive" -- Keep-Alive headers are needed for authentication.
  1160. if (not authentication_header) or (not response.status) or (not string.find(authentication_header:lower(), "ntlm")) then
  1161. stdnse.debug1("http: the target doesn't support NTLM or there was an error during request.")
  1162. return http_error("The target doesn't support NTLM or there was an error during request.")
  1163. end
  1164. -- ntlm works with three messages. we send a request, it sends
  1165. -- a challenge, we respond to the challenge.
  1166. local hostname = options.auth.hostname or "localhost" -- the hostname to be sent
  1167. local workstation_name = options.auth.workstation_name or "NMAP" -- the workstation name to be sent
  1168. local username = options.auth.username -- the username as specified
  1169. local auth_blob = "NTLMSSP\x00" .. -- NTLM signature
  1170. "\x01\x00\x00\x00" .. -- NTLM Type 1 message
  1171. bin.pack("<I", 0xa208b207) .. -- flags 56, 128, Version, Extended Security, Always Sign, Workstation supplied, Domain Supplied, NTLM Key, OEM, Unicode
  1172. bin.pack("<SSISSI",#workstation_name, #workstation_name, 40 + #hostname, #hostname, #hostname, 40) .. -- Supplied Domain and Workstation
  1173. bin.pack("CC<S", -- OS version info
  1174. 5, 1, 2600) .. -- 5.1.2600
  1175. "\x00\x00\x00\x0f" .. -- OS version info end (static 0x0000000f)
  1176. hostname.. -- HOST NAME
  1177. workstation_name --WORKSTATION name
  1178. custom_options.ntlmauth = auth_blob
  1179. -- check if the protocol is tcp
  1180. if type(port) == 'table' then
  1181. if port.protocol and port.protocol ~= 'tcp' then
  1182. stdnse.debug1("NTLM authentication supports the TCP protocol only, your request to %s cannot be completed.", host)
  1183. return http_error("Unsupported protocol.")
  1184. end
  1185. end
  1186. -- tryssl uses ssl if needed. sends the type 1 message.
  1187. local socket, partial, opts = comm.tryssl(host, port, build_request(host, port, method, path, custom_options), { timeout = options.timeout })
  1188. if not socket then
  1189. return http_error("Could not create socket to send type 1 message.")
  1190. end
  1191. repeat
  1192. response, partial = next_response(socket, method, partial)
  1193. if not response then
  1194. return http_error("There was error in receiving response of type 1 message.")
  1195. end
  1196. until not (response.status >= 100 and response.status <= 199)
  1197. authentication_header = response.header['www-authenticate']
  1198. -- take out the challenge
  1199. local type2_response = authentication_header:sub(authentication_header:find(' ')+1, -1)
  1200. local _, _, message_type, _, _, _, flags_received, challenge= bin.unpack("<A8ISSIIA8", base64.dec(type2_response))
  1201. -- check if the response is a type 2 message.
  1202. if message_type ~= 0x02 then
  1203. stdnse.debug1("Expected type 2 message as response.")
  1204. return
  1205. end
  1206. local is_unicode = (bit.band(flags_received, 0x00000001) == 0x00000001) -- 0x00000001 UNICODE Flag
  1207. local is_extended = (bit.band(flags_received, 0x00080000) == 0x00080000) -- 0x00080000 Extended Security Flag
  1208. local type_3_flags = 0xa2888206 -- flags 56, 128, Version, Target Info, Extended Security, Always Sign, NTLM Key, OEM
  1209. local lanman, ntlm
  1210. if is_extended then
  1211. -- this essentially calls the new ntlmv2_session_response function in smbauth.lua and returns whatever it returns
  1212. lanman, ntlm = smbauth.get_password_response(nil, username, "", options.auth.password, nil, "ntlmv2_session", challenge, true)
  1213. else
  1214. lanman, ntlm = smbauth.get_password_response(nil, username, "", options.auth.password, nil, "ntlm", challenge, false)
  1215. type_3_flags = type_3_flags - 0x00080000 -- Removing the Extended Security Flag as server doesn't support it.
  1216. end
  1217. local domain = ""
  1218. local session_key = ""
  1219. -- if server supports unicode, then strings are sent in unicode format.
  1220. if is_unicode then
  1221. username = unicode.utf8to16(username)
  1222. hostname = unicode.utf8to16(hostname)
  1223. type_3_flags = type_3_flags - 0x00000001 -- OEM flag is 0x00000002. removing 0x00000001 results in UNICODE flag.
  1224. end
  1225. local BASE_OFFSET = 72 -- Version 3 -- The Session Key<empty in our case>, flags, and OS Version structure are all present.
  1226. auth_blob = bin.pack("<zISSISSISSISSISSISSIICCSAAAAA",
  1227. "NTLMSSP",
  1228. 0x00000003,
  1229. #lanman,
  1230. #lanman,
  1231. BASE_OFFSET + #username + #hostname,
  1232. ( #ntlm ),
  1233. ( #ntlm ),
  1234. BASE_OFFSET + #username + #hostname + #lanman,
  1235. #domain,
  1236. #domain,
  1237. BASE_OFFSET,
  1238. #username,
  1239. #username,
  1240. BASE_OFFSET,
  1241. #hostname,
  1242. #hostname,
  1243. BASE_OFFSET + #username,
  1244. #session_key,
  1245. #session_key,
  1246. BASE_OFFSET + #username + #hostname + #lanman + #ntlm,
  1247. type_3_flags,
  1248. 5,
  1249. 1,
  1250. 2600,
  1251. "\x00\x00\x00\x0f",
  1252. username,
  1253. hostname,
  1254. lanman,
  1255. ntlm)
  1256. custom_options.ntlmauth = auth_blob
  1257. socket:send(build_request(host, port, method, path, custom_options))
  1258. repeat
  1259. response, partial = next_response(socket, method, partial)
  1260. if not response then
  1261. return http_error("There was error in receiving response of type 3 message.")
  1262. end
  1263. until not (response.status >= 100 and response.status <= 199)
  1264. socket:close()
  1265. response.ssl = ( opts == 'ssl' )
  1266. return response
  1267. end
  1268. return request(host, port, build_request(host, port, method, path, options), options)
  1269. end
  1270. ---Uploads a file using the PUT method and returns a result table. This is a simple wrapper
  1271. -- around <code>generic_request</code>
  1272. --
  1273. -- @param host The host to connect to.
  1274. -- @param port The port to connect to.
  1275. -- @param path The path to retrieve.
  1276. -- @param options [optional] A table that lets the caller control socket timeouts, HTTP headers, and other parameters. For full documentation, see the module documentation (above).
  1277. -- @param putdata The contents of the file to upload
  1278. -- @return A response table, see module documentation for description.
  1279. -- @see http.generic_request
  1280. function put(host, port, path, options, putdata)
  1281. if(not(validate_options(options))) then
  1282. return http_error("Options failed to validate.")
  1283. end
  1284. if ( not(putdata) ) then
  1285. return http_error("No file to PUT.")
  1286. end
  1287. local mod_options = {
  1288. content = putdata,
  1289. }
  1290. table_augment(mod_options, options or {})
  1291. return generic_request(host, port, "PUT", path, mod_options)
  1292. end
  1293. -- A battery of tests a URL is subjected to in order to decide if it may be
  1294. -- redirected to. They incrementally fill in loc.host, loc.port, and loc.path.
  1295. local redirect_ok_rules = {
  1296. -- Check if there's any credentials in the url
  1297. function (url, host, port)
  1298. -- bail if userinfo is present
  1299. return ( url.userinfo and false ) or true
  1300. end,
  1301. -- Check if the location is within the domain or host
  1302. function (url, host, port)
  1303. local hostname = stdnse.get_hostname(host)
  1304. if ( hostname == host.ip and host.ip == url.host.ip ) then
  1305. return true
  1306. end
  1307. local domain = hostname:match("^[^%.]-%.(.*)") or hostname
  1308. local match = ("^.*%s$"):format(domain)
  1309. if ( url.host:match(match) ) then
  1310. return true
  1311. end
  1312. return false
  1313. end,
  1314. -- Check whether the new location has the same port number
  1315. function (url, host, port)
  1316. -- port fixup, adds default ports 80 and 443 in case no url.port was
  1317. -- defined, we do this based on the url scheme
  1318. local url_port = url.port
  1319. if ( not(url_port) ) then
  1320. if ( url.scheme == "http" ) then
  1321. url_port = 80
  1322. elseif( url.scheme == "https" ) then
  1323. url_port = 443
  1324. end
  1325. end
  1326. if (not url_port) or tonumber(url_port) == port.number then
  1327. return true
  1328. end
  1329. return false
  1330. end,
  1331. -- Check whether the url.scheme matches the port.service
  1332. function (url, host, port)
  1333. -- if url.scheme is present then it must match the scanned port
  1334. if url.scheme and url.port then return true end
  1335. if url.scheme and url.scheme ~= port.service then return false end
  1336. return true
  1337. end,
  1338. -- make sure we're actually being redirected somewhere and not to the same url
  1339. function (url, host, port)
  1340. -- path cannot be unchanged unless host has changed
  1341. -- loc.path must be set if returning true
  1342. if ( not url.path or url.path == "/" ) and url.host == ( host.targetname or host.ip) then return false end
  1343. if not url.path then return true end
  1344. return true
  1345. end,
  1346. }
  1347. --- Check if the given URL is okay to redirect to. Return a table with keys
  1348. -- "host", "port", and "path" if okay, nil otherwise.
  1349. --
  1350. -- Redirects will be followed unless they:
  1351. -- * contain credentials
  1352. -- * are on a different domain or host
  1353. -- * have a different port number or URI scheme
  1354. -- * redirect to the same URI
  1355. -- * exceed the maximum number of redirects specified
  1356. -- @param url table as returned by url.parse
  1357. -- @param host table as received by the action function
  1358. -- @param port table as received by the action function
  1359. -- @param counter number of redirects to follow.
  1360. -- @return loc table containing the new location
  1361. function redirect_ok(host, port, counter)
  1362. -- convert a numeric port to a table
  1363. if ( "number" == type(port) ) then
  1364. port = { number = port }
  1365. end
  1366. return function(url)
  1367. if ( counter == 0 ) then return false end
  1368. counter = counter - 1
  1369. for i, rule in ipairs( redirect_ok_rules ) do
  1370. if ( not(rule( url, host, port )) ) then
  1371. --stdnse.debug1("Rule failed: %d", i)
  1372. return false
  1373. end
  1374. end
  1375. return true
  1376. end
  1377. end
  1378. --- Handles a HTTP redirect
  1379. -- @param host table as received by the script action function
  1380. -- @param port table as received by the script action function
  1381. -- @param path string
  1382. -- @param response table as returned by http.get or http.head
  1383. -- @return url table as returned by <code>url.parse</code> or nil if there's no
  1384. -- redirect taking place
  1385. function parse_redirect(host, port, path, response)
  1386. if ( not(tostring(response.status):match("^30[01237]$")) or
  1387. not(response.header) or
  1388. not(response.header.location) ) then
  1389. return nil
  1390. end
  1391. port = ( "number" == type(port) ) and { number = port } or port
  1392. local u = url.parse(response.header.location)
  1393. if ( not(u.host) ) then
  1394. -- we're dealing with a relative url
  1395. u.host = stdnse.get_hostname(host)
  1396. u.path = ((u.path:sub(1,1) == "/" and "" ) or "/" ) .. u.path -- ensuring leading slash
  1397. end
  1398. -- do port fixup
  1399. if ( not(u.port) ) then
  1400. if ( u.scheme == "http" ) then u.port = 80
  1401. elseif ( u.scheme == "https") then u.port = 443
  1402. else u.port = port.number end
  1403. end
  1404. if ( not(u.path) ) then
  1405. u.path = "/"
  1406. end
  1407. if ( u.query ) then
  1408. u.path = ("%s?%s"):format( u.path, u.query )
  1409. end
  1410. return u
  1411. end
  1412. -- Retrieves the correct function to use to validate HTTP redirects
  1413. -- @param host table as received by the action function
  1414. -- @param port table as received by the action function
  1415. -- @param options table as passed to http.get or http.head
  1416. -- @return redirect_ok function used to validate HTTP redirects
  1417. local function get_redirect_ok(host, port, options)
  1418. if ( options ) then
  1419. if ( options.redirect_ok == false ) then
  1420. return function() return false end
  1421. elseif( "function" == type(options.redirect_ok) ) then
  1422. return options.redirect_ok(host, port)
  1423. elseif( type(options.redirect_ok) == "number") then
  1424. return redirect_ok(host, port, options.redirect_ok)
  1425. else
  1426. return redirect_ok(host, port, MAX_REDIRECT_COUNT)
  1427. end
  1428. else
  1429. return redirect_ok(host, port, MAX_REDIRECT_COUNT)
  1430. end
  1431. end
  1432. ---Fetches a resource with a GET request and returns the result as a table.
  1433. --
  1434. -- This is a simple wrapper around <code>generic_request</code>, with the added
  1435. -- benefit of having local caching and support for HTTP redirects. Redirects
  1436. -- are followed only if they pass all the validation rules of the redirect_ok
  1437. -- function. This function may be overridden by supplying a custom function in
  1438. -- the <code>redirect_ok</code> field of the options array. The default
  1439. -- function redirects the request if the destination is:
  1440. -- * Within the same host or domain
  1441. -- * Has the same port number
  1442. -- * Stays within the current scheme
  1443. -- * Does not exceed <code>MAX_REDIRECT_COUNT</code> count of redirects
  1444. --
  1445. -- Caching and redirects can be controlled in the <code>options</code> array,
  1446. -- see module documentation for more information.
  1447. --
  1448. -- @param host The host to connect to.
  1449. -- @param port The port to connect to.
  1450. -- @param path The path to retrieve.
  1451. -- @param options [optional] A table that lets the caller control socket
  1452. -- timeouts, HTTP headers, and other parameters. For full
  1453. -- documentation, see the module documentation (above).
  1454. -- @return A response table, see module documentation for description.
  1455. -- @see http.generic_request
  1456. function get(host, port, path, options)
  1457. if(not(validate_options(options))) then
  1458. return http_error("Options failed to validate.")
  1459. end
  1460. local redir_check = get_redirect_ok(host, port, options)
  1461. local response, state, location
  1462. local u = { host = host, port = port, path = path }
  1463. repeat
  1464. response, state = lookup_cache("GET", u.host, u.port, u.path, options);
  1465. if ( response == nil ) then
  1466. response = generic_request(u.host, u.port, "GET", u.path, options)
  1467. insert_cache(state, response);
  1468. end
  1469. u = parse_redirect(host, port, path, response)
  1470. if ( not(u) ) then
  1471. break
  1472. end
  1473. location = location or {}
  1474. table.insert(location, response.header.location)
  1475. until( not(redir_check(u)) )
  1476. response.location = location
  1477. return response
  1478. end
  1479. ---Parses a URL and calls <code>http.get</code> with the result. The URL can contain
  1480. -- all the standard fields, protocol://host:port/path
  1481. --
  1482. -- @param u The URL of the host.
  1483. -- @param options [optional] A table that lets the caller control socket timeouts, HTTP headers, and other parameters. For full documentation, see the module documentation (above).
  1484. -- @return A response table, see module documentation for description.
  1485. -- @see http.get
  1486. function get_url( u, options )
  1487. if(not(validate_options(options))) then
  1488. return http_error("Options failed to validate.")
  1489. end
  1490. local parsed = url.parse( u )
  1491. local port = {}
  1492. port.service = parsed.scheme
  1493. port.number = parsed.port
  1494. if not port.number then
  1495. if parsed.scheme == 'https' then
  1496. port.number = 443
  1497. else
  1498. port.number = 80
  1499. end
  1500. end
  1501. local path = parsed.path or "/"
  1502. if parsed.query then
  1503. path = path .. "?" .. parsed.query
  1504. end
  1505. return get( parsed.host, port, path, options )
  1506. end
  1507. ---Fetches a resource with a HEAD request.
  1508. --
  1509. -- Like <code>get</code>, this is a simple wrapper around
  1510. -- <code>generic_request</code> with response caching. This function also has
  1511. -- support for HTTP redirects. Redirects are followed only if they pass all the
  1512. -- validation rules of the redirect_ok function. This function may be
  1513. -- overridden by supplying a custom function in the <code>redirect_ok</code>
  1514. -- field of the options array. The default function redirects the request if
  1515. -- the destination is:
  1516. -- * Within the same host or domain
  1517. -- * Has the same port number
  1518. -- * Stays within the current scheme
  1519. -- * Does not exceed <code>MAX_REDIRECT_COUNT</code> count of redirects
  1520. --
  1521. -- Caching and redirects can be controlled in the <code>options</code> array,
  1522. -- see module documentation for more information.
  1523. --
  1524. -- @param host The host to connect to.
  1525. -- @param port The port to connect to.
  1526. -- @param path The path to retrieve.
  1527. -- @param options [optional] A table that lets the caller control socket
  1528. -- timeouts, HTTP headers, and other parameters. For full
  1529. -- documentation, see the module documentation (above).
  1530. -- @return A response table, see module documentation for description.
  1531. -- @see http.generic_request
  1532. function head(host, port, path, options)
  1533. if(not(validate_options(options))) then
  1534. return http_error("Options failed to validate.")
  1535. end
  1536. local redir_check = get_redirect_ok(host, port, options)
  1537. local response, state, location
  1538. local u = { host = host, port = port, path = path }
  1539. repeat
  1540. response, state = lookup_cache("HEAD", u.host, u.port, u.path, options);
  1541. if response == nil then
  1542. response = generic_request(u.host, u.port, "HEAD", u.path, options)
  1543. insert_cache(state, response);
  1544. end
  1545. u = parse_redirect(host, port, path, response)
  1546. if ( not(u) ) then
  1547. break
  1548. end
  1549. location = location or {}
  1550. table.insert(location, response.header.location)
  1551. until( not(redir_check(u)) )
  1552. response.location = location
  1553. return response
  1554. end
  1555. ---Fetches a resource with a POST request.
  1556. --
  1557. -- Like <code>get</code>, this is a simple wrapper around
  1558. -- <code>generic_request</code> except that postdata is handled properly.
  1559. --
  1560. -- @param host The host to connect to.
  1561. -- @param port The port to connect to.
  1562. -- @param path The path to retrieve.
  1563. -- @param options [optional] A table that lets the caller control socket
  1564. -- timeouts, HTTP headers, and other parameters. For full
  1565. -- documentation, see the module documentation (above).
  1566. -- @param ignored Ignored for backwards compatibility.
  1567. -- @param postdata A string or a table of data to be posted. If a table, the
  1568. -- keys and values must be strings, and they will be encoded
  1569. -- into an application/x-www-form-encoded form submission.
  1570. -- @return A response table, see module documentation for description.
  1571. -- @see http.generic_request
  1572. function post( host, port, path, options, ignored, postdata )
  1573. if(not(validate_options(options))) then
  1574. return http_error("Options failed to validate.")
  1575. end
  1576. local mod_options = {
  1577. content = postdata,
  1578. }
  1579. table_augment(mod_options, options or {})
  1580. return generic_request(host, port, "POST", path, mod_options)
  1581. end
  1582. -- Deprecated pipeline functions
  1583. function pGet( host, port, path, options, ignored, allReqs )
  1584. stdnse.debug1("WARNING: pGet() is deprecated. Use pipeline_add() instead.")
  1585. return pipeline_add(path, options, allReqs, 'GET')
  1586. end
  1587. function pHead( host, port, path, options, ignored, allReqs )
  1588. stdnse.debug1("WARNING: pHead() is deprecated. Use pipeline_add instead.")
  1589. return pipeline_add(path, options, allReqs, 'HEAD')
  1590. end
  1591. function addPipeline(host, port, path, options, ignored, allReqs, method)
  1592. stdnse.debug1("WARNING: addPipeline() is deprecated! Use pipeline_add instead.")
  1593. return pipeline_add(path, options, allReqs, method)
  1594. end
  1595. function pipeline(host, port, allReqs)
  1596. stdnse.debug1("WARNING: pipeline() is deprecated. Use pipeline_go() instead.")
  1597. return pipeline_go(host, port, allReqs)
  1598. end
  1599. ---Adds a pending request to the HTTP pipeline.
  1600. --
  1601. -- The HTTP pipeline is a set of requests that will all be sent at the same
  1602. -- time, or as close as the server allows. This allows more efficient code,
  1603. -- since requests are automatically buffered and sent simultaneously.
  1604. --
  1605. -- The <code>all_requests</code> argument contains the current list of queued
  1606. -- requests (if this is the first time calling <code>pipeline_add</code>, it
  1607. -- should be <code>nil</code>). After adding the request to end of the queue,
  1608. -- the queue is returned and can be passed to the next
  1609. -- <code>pipeline_add</code> call.
  1610. --
  1611. -- When all requests have been queued, call <code>pipeline_go</code> with the
  1612. -- all_requests table that has been built.
  1613. --
  1614. -- @param path The path to retrieve.
  1615. -- @param options [optional] A table that lets the caller control socket
  1616. -- timeouts, HTTP headers, and other parameters. For full
  1617. -- documentation, see the module documentation (above).
  1618. -- @param all_requests [optional] The current pipeline queue (returned from a
  1619. -- previous <code>add_pipeline</code> call), or nil if it's
  1620. -- the first call.
  1621. -- @param method [optional] The HTTP method ('GET', 'HEAD', 'POST', etc).
  1622. -- Default: 'GET'.
  1623. -- @return Table with the pipeline get requests (plus this new one)
  1624. -- @see http.pipeline_go
  1625. function pipeline_add(path, options, all_requests, method)
  1626. if(not(validate_options(options))) then
  1627. return nil
  1628. end
  1629. method = method or 'GET'
  1630. all_requests = all_requests or {}
  1631. local mod_options = {
  1632. header = {
  1633. ["Connection"] = "keep-alive"
  1634. }
  1635. }
  1636. table_augment(mod_options, options or {})
  1637. local object = { method=method, path=path, options=mod_options }
  1638. table.insert(all_requests, object)
  1639. return all_requests
  1640. end
  1641. ---Performs all queued requests in the all_requests variable (created by the
  1642. -- <code>pipeline_add</code> function).
  1643. --
  1644. -- Returns an array of responses, each of which is a table as defined in the
  1645. -- module documentation above.
  1646. --
  1647. -- @param host The host to connect to.
  1648. -- @param port The port to connect to.
  1649. -- @param all_requests A table with all the previously built pipeline requests
  1650. -- @return A list of responses, in the same order as the requests were queued.
  1651. -- Each response is a table as described in the module documentation.
  1652. function pipeline_go(host, port, all_requests)
  1653. stdnse.debug1("Total number of pipelined requests: " .. #all_requests)
  1654. local responses
  1655. local response
  1656. local partial
  1657. responses = {}
  1658. -- Check for an empty request
  1659. if (#all_requests == 0) then
  1660. stdnse.debug1("Warning: empty set of requests passed to http.pipeline()")
  1661. return responses
  1662. end
  1663. local socket, bopt
  1664. -- We'll try a first request with keep-alive, just to check if the server
  1665. -- supports and how many requests we can send into one socket!
  1666. local request = build_request(host, port, all_requests[1].method, all_requests[1].path, all_requests[1].options)
  1667. socket, partial, bopt = comm.tryssl(host, port, request, {recv_before=false})
  1668. if not socket then
  1669. return nil
  1670. end
  1671. response, partial = next_response(socket, all_requests[1].method, partial)
  1672. if not response then
  1673. return nil
  1674. end
  1675. table.insert(responses, response)
  1676. local limit = getPipelineMax(response) -- how many requests to send on one connection
  1677. limit = limit > #all_requests and #all_requests or limit
  1678. local max_pipeline = stdnse.get_script_args("http.max-pipeline") or limit -- how many requests should be pipelined
  1679. local count = 1
  1680. stdnse.debug1("Number of requests allowed by pipeline: " .. limit)
  1681. while #responses < #all_requests do
  1682. local j, batch_end
  1683. -- we build a table with many requests, upper limited by the var "limit"
  1684. local requests = {}
  1685. if #responses + limit < #all_requests then
  1686. batch_end = #responses + limit
  1687. else
  1688. batch_end = #all_requests
  1689. end
  1690. j = #responses + 1
  1691. while j <= batch_end do
  1692. if j == batch_end then
  1693. all_requests[j].options.header["Connection"] = "close"
  1694. end
  1695. if j~= batch_end and all_requests[j].options.header["Connection"] ~= 'keep-alive' then
  1696. all_requests[j].options.header["Connection"] = 'keep-alive'
  1697. end
  1698. table.insert(requests, build_request(host, port, all_requests[j].method, all_requests[j].path, all_requests[j].options))
  1699. -- to avoid calling build_request more than one time on the same request,
  1700. -- we might want to build all the requests once, above the main while loop
  1701. j = j + 1
  1702. end
  1703. if count >= limit or not socket:get_info() then
  1704. socket:connect(host, port, bopt)
  1705. partial = ""
  1706. count = 0
  1707. end
  1708. socket:set_timeout(10000)
  1709. local start = 1
  1710. local len = #requests
  1711. local req_sent = 0
  1712. -- start sending the requests and pipeline them in batches of max_pipeline elements
  1713. while start <= len do
  1714. stdnse.debug2("HTTP pipeline: number of requests in current batch: %d, already sent: %d, responses from current batch: %d, all responses received: %d",len,start-1,count,#responses)
  1715. local req = {}
  1716. if max_pipeline == limit then
  1717. req = requests
  1718. else
  1719. for i=start,start+max_pipeline-1,1 do
  1720. table.insert(req, requests[i])
  1721. end
  1722. end
  1723. local num_req = #req
  1724. req = table.concat(req, "")
  1725. start = start + max_pipeline
  1726. socket:send(req)
  1727. req_sent = req_sent + num_req
  1728. local inner_count = 0
  1729. local fail = false
  1730. -- collect responses for the last batch
  1731. while inner_count < num_req and #responses < #all_requests do
  1732. response, partial = next_response(socket, all_requests[#responses + 1].method, partial)
  1733. if not response then
  1734. stdnse.debug1("HTTP pipeline: there was a problem while receiving responses.")
  1735. stdnse.debug3("The request was:\n%s",req)
  1736. fail = true
  1737. break
  1738. end
  1739. count = count + 1
  1740. inner_count = inner_count + 1
  1741. responses[#responses + 1] = response
  1742. end
  1743. if fail then break end
  1744. end
  1745. socket:close()
  1746. if count == 0 then
  1747. stdnse.debug1("Received 0 of %d expected responses.\nGiving up on pipeline.", limit);
  1748. break
  1749. elseif count < req_sent then
  1750. stdnse.debug1("Received only %d of %d expected responses.\nDecreasing max pipelined requests to %d.", count, req_sent, count)
  1751. limit = count
  1752. end
  1753. end
  1754. stdnse.debug1("Number of received responses: " .. #responses)
  1755. return responses
  1756. end
  1757. -- Parsing of specific headers. skip_space and the read_* functions return the
  1758. -- byte index following whatever they have just read, or nil on error.
  1759. -- Skip whitespace (that has already been folded from LWS). See RFC 2616,
  1760. -- section 2.2, definition of LWS.
  1761. local function skip_space(s, pos)
  1762. local _
  1763. _, pos = string.find(s, "^[ \t]*", pos)
  1764. return pos + 1
  1765. end
  1766. -- See RFC 2616, section 2.2.
  1767. local function read_token(s, pos)
  1768. local _, token
  1769. pos = skip_space(s, pos)
  1770. -- 1*<any CHAR except CTLs or separators>. CHAR is only byte values 0-127.
  1771. _, pos, token = string.find(s, "^([^\0\001-\031()<>@,;:\\\"/?={} \t%[%]\127-\255]+)", pos)
  1772. if token then
  1773. return pos + 1, token
  1774. else
  1775. return nil
  1776. end
  1777. end
  1778. -- See RFC 2616, section 2.2. Here we relax the restriction that TEXT may not
  1779. -- contain CTLs.
  1780. local function read_quoted_string(s, pos)
  1781. local chars = {}
  1782. if string.sub(s, pos, pos) ~= "\"" then
  1783. return nil
  1784. end
  1785. pos = pos + 1
  1786. pos = skip_space(s, pos)
  1787. while pos <= #s and string.sub(s, pos, pos) ~= "\"" do
  1788. local c
  1789. c = string.sub(s, pos, pos)
  1790. if c == "\\" then
  1791. if pos < #s then
  1792. pos = pos + 1
  1793. c = string.sub(s, pos, pos)
  1794. else
  1795. return nil
  1796. end
  1797. end
  1798. chars[#chars + 1] = c
  1799. pos = pos + 1
  1800. end
  1801. if pos > #s or string.sub(s, pos, pos) ~= "\"" then
  1802. return nil
  1803. end
  1804. return pos + 1, table.concat(chars)
  1805. end
  1806. local function read_token_or_quoted_string(s, pos)
  1807. pos = skip_space(s, pos)
  1808. if string.sub(s, pos, pos) == "\"" then
  1809. return read_quoted_string(s, pos)
  1810. else
  1811. return read_token(s, pos)
  1812. end
  1813. end
  1814. --- Create a pattern to find a tag
  1815. --
  1816. -- Case-insensitive search for tags
  1817. -- @param tag The name of the tag to find
  1818. -- @param endtag Boolean true if you are looking for an end tag, otherwise it will look for a start tag
  1819. -- @return A pattern to find the tag
  1820. function tag_pattern(tag, endtag)
  1821. local patt = {}
  1822. if endtag then
  1823. patt[1] = "</%s*"
  1824. else
  1825. patt[1] = "<%s*"
  1826. end
  1827. local up, down = tag:upper(), tag:lower()
  1828. for i = 1, #tag do
  1829. patt[#patt+1] = string.format("[%s%s]", up:sub(i,i), down:sub(i,i))
  1830. end
  1831. if endtag then
  1832. patt[#patt+1] = "%f[%s>].->"
  1833. else
  1834. patt[#patt+1] = "%f[%s/>].->"
  1835. end
  1836. return table.concat(patt)
  1837. end
  1838. ---
  1839. -- Finds forms in html code
  1840. --
  1841. -- returns table of found forms, in plaintext.
  1842. -- @param body A <code>response.body</code> in which to search for forms
  1843. -- @return A list of forms.
  1844. function grab_forms(body)
  1845. local forms = {}
  1846. if not body then return forms end
  1847. local form_start_expr = tag_pattern("form")
  1848. local form_end_expr = tag_pattern("form", true)
  1849. local form_opening = string.find(body, form_start_expr)
  1850. local forms = {}
  1851. while form_opening do
  1852. local form_closing = string.find(body, form_end_expr, form_opening+1)
  1853. if form_closing == nil then --html code contains errors
  1854. break
  1855. end
  1856. forms[#forms+1] = string.sub(body, form_opening, form_closing-1)
  1857. if form_closing+1 <= #body then
  1858. form_opening = string.find(body, form_start_expr, form_closing+1)
  1859. else
  1860. break
  1861. end
  1862. end
  1863. return forms
  1864. end
  1865. local function get_attr (html, name)
  1866. local lhtml = html:lower()
  1867. local lname = name:lower()
  1868. -- try the attribute-value syntax first
  1869. local _, pos = lhtml:find('%s' .. lname .. '%s*=%s*[^%s]')
  1870. if not pos then
  1871. -- try the empty attribute syntax and, if found,
  1872. -- return zero-length string as its value; nil otherwise
  1873. return lhtml:match('[^%s=]%s+' .. lname .. '[%s/>]') and "" or nil
  1874. end
  1875. local value
  1876. _, value = html:match('^([\'"])(.-)%1', pos)
  1877. if not value then
  1878. value = html:match('^[^%s<>=\'"`]+', pos)
  1879. end
  1880. return value
  1881. end
  1882. ---
  1883. -- Parses a form, that is, finds its action and fields.
  1884. -- @param form A plaintext representation of form
  1885. -- @return A dictionary with keys: <code>action</code>,
  1886. -- <code>method</code> if one is specified, <code>fields</code>
  1887. -- which is a list of fields found in the form each of which has a
  1888. -- <code>name</code> attribute and <code>type</code> if specified.
  1889. function parse_form(form)
  1890. local parsed = {}
  1891. local fields = {}
  1892. local form_action = get_attr(form, "action")
  1893. if form_action then
  1894. parsed["action"] = form_action
  1895. end
  1896. -- determine if the form is using get or post
  1897. local form_method = get_attr(form, "method")
  1898. if form_method then
  1899. parsed["method"] = string.lower(form_method)
  1900. end
  1901. -- get the id of the form
  1902. local form_id = get_attr(form, "id")
  1903. if form_id then
  1904. parsed["id"] = string.lower(form_id)
  1905. end
  1906. -- now identify the fields
  1907. local input_type
  1908. local input_name
  1909. local input_value
  1910. -- first find regular inputs
  1911. for f in string.gmatch(form, tag_pattern("input")) do
  1912. input_type = get_attr(f, "type")
  1913. input_name = get_attr(f, "name")
  1914. input_value = get_attr(f, "value")
  1915. local next_field_index = #fields+1
  1916. if input_name then
  1917. fields[next_field_index] = {}
  1918. fields[next_field_index]["name"] = input_name
  1919. if input_type then
  1920. fields[next_field_index]["type"] = string.lower(input_type)
  1921. end
  1922. if input_value then
  1923. fields[next_field_index]["value"] = input_value
  1924. end
  1925. end
  1926. end
  1927. -- now search for textareas
  1928. for f in string.gmatch(form, tag_pattern("textarea")) do
  1929. input_name = get_attr(f, "name")
  1930. local next_field_index = #fields+1
  1931. if input_name then
  1932. fields[next_field_index] = {}
  1933. fields[next_field_index]["name"] = input_name
  1934. fields[next_field_index]["type"] = "textarea"
  1935. end
  1936. end
  1937. parsed["fields"] = fields
  1938. return parsed
  1939. end
  1940. local MONTH_MAP = {
  1941. Jan = 1, Feb = 2, Mar = 3, Apr = 4, May = 5, Jun = 6,
  1942. Jul = 7, Aug = 8, Sep = 9, Oct = 10, Nov = 11, Dec = 12
  1943. }
  1944. --- Parses an HTTP date string
  1945. --
  1946. -- Supports any of the following formats from section 3.3.1 of RFC 2616:
  1947. -- * Sun, 06 Nov 1994 08:49:37 GMT (RFC 822, updated by RFC 1123)
  1948. -- * Sunday, 06-Nov-94 08:49:37 GMT (RFC 850, obsoleted by RFC 1036)
  1949. -- * Sun Nov 6 08:49:37 1994 (ANSI C's <code>asctime()</code> format)
  1950. -- @param s the date string.
  1951. -- @return a table with keys <code>year</code>, <code>month</code>,
  1952. -- <code>day</code>, <code>hour</code>, <code>min</code>, <code>sec</code>, and
  1953. -- <code>isdst</code>, relative to GMT, suitable for input to
  1954. -- <code>os.time</code>.
  1955. function parse_date(s)
  1956. local day, month, year, hour, min, sec, tz, month_name
  1957. -- Handle RFC 1123 and 1036 at once.
  1958. day, month_name, year, hour, min, sec, tz = s:match("^%w+, (%d+)[- ](%w+)[- ](%d+) (%d+):(%d+):(%d+) (%w+)$")
  1959. if not day then
  1960. month_name, day, hour, min, sec, year = s:match("%w+ (%w+) ?(%d+) (%d+):(%d+):(%d+) (%d+)")
  1961. tz = "GMT"
  1962. end
  1963. if not day then
  1964. stdnse.debug1("http.parse_date: can't parse date \"%s\": unknown format.", s)
  1965. return nil
  1966. end
  1967. -- Look up the numeric code for month.
  1968. month = MONTH_MAP[month_name]
  1969. if not month then
  1970. stdnse.debug1("http.parse_date: unknown month name \"%s\".", month_name)
  1971. return nil
  1972. end
  1973. if tz ~= "GMT" then
  1974. stdnse.debug1("http.parse_date: don't know time zone \"%s\", only \"GMT\".", tz)
  1975. return nil
  1976. end
  1977. day = tonumber(day)
  1978. year = tonumber(year)
  1979. hour = tonumber(hour)
  1980. min = tonumber(min)
  1981. sec = tonumber(sec)
  1982. if year < 100 then
  1983. -- Two-digit year. Make a guess.
  1984. if year < 70 then
  1985. year = year + 2000
  1986. else
  1987. year = year + 1900
  1988. end
  1989. end
  1990. return { year = year, month = month, day = day, hour = hour, min = min, sec = sec, isdst = false }
  1991. end
  1992. -- See RFC 2617, section 1.2. This function returns a table with keys "scheme"
  1993. -- and "params".
  1994. local function read_auth_challenge(s, pos)
  1995. local _, scheme, params
  1996. pos, scheme = read_token(s, pos)
  1997. if not scheme then
  1998. return nil
  1999. end
  2000. params = {}
  2001. pos = skip_space(s, pos)
  2002. while pos < #s do
  2003. local name, val
  2004. local tmp_pos
  2005. -- We need to peek ahead at this point. It's possible that we've hit the
  2006. -- end of one challenge and the beginning of another. Section 14.33 says
  2007. -- that the header value can be 1#challenge, in other words several
  2008. -- challenges separated by commas. Because the auth-params are also
  2009. -- separated by commas, the only way we can tell is if we find a token not
  2010. -- followed by an equals sign.
  2011. tmp_pos = pos
  2012. tmp_pos, name = read_token(s, tmp_pos)
  2013. if not name then
  2014. pos = skip_space(s, pos + 1)
  2015. return pos, { scheme = scheme, params = nil }
  2016. end
  2017. tmp_pos = skip_space(s, tmp_pos)
  2018. if string.sub(s, tmp_pos, tmp_pos) ~= "=" then
  2019. -- No equals sign, must be the beginning of another challenge.
  2020. break
  2021. end
  2022. tmp_pos = tmp_pos + 1
  2023. pos = tmp_pos
  2024. pos, val = read_token_or_quoted_string(s, pos)
  2025. if not val then
  2026. return nil
  2027. end
  2028. if params[name] then
  2029. return nil
  2030. end
  2031. params[name] = val
  2032. pos = skip_space(s, pos)
  2033. if string.sub(s, pos, pos) == "," then
  2034. pos = skip_space(s, pos + 1)
  2035. if pos > #s then
  2036. return nil
  2037. end
  2038. end
  2039. end
  2040. return pos, { scheme = scheme, params = params }
  2041. end
  2042. ---Parses the WWW-Authenticate header as described in RFC 2616, section 14.47
  2043. -- and RFC 2617, section 1.2.
  2044. --
  2045. -- The return value is an array of challenges. Each challenge is a table with
  2046. -- the keys <code>scheme</code> and <code>params</code>.
  2047. -- @param s The header value text.
  2048. -- @return An array of challenges, or <code>nil</code> on error.
  2049. function parse_www_authenticate(s)
  2050. local challenges = {}
  2051. local pos
  2052. pos = 1
  2053. while pos <= #s do
  2054. local challenge
  2055. pos, challenge = read_auth_challenge(s, pos)
  2056. if not challenge then
  2057. return nil
  2058. end
  2059. challenges[#challenges + 1] = challenge
  2060. end
  2061. return challenges
  2062. end
  2063. ---Take the data returned from a HTTP request and return the status string.
  2064. -- Useful for <code>stdnse.debug</code> messages and even advanced output.
  2065. --
  2066. -- @param data The response table from any HTTP request
  2067. -- @return The best status string we could find: either the actual status string, the status code, or <code>"<unknown status>"</code>.
  2068. function get_status_string(data)
  2069. -- Make sure we have valid data
  2070. if(data == nil) then
  2071. return "<unknown status>"
  2072. elseif(data['status-line'] == nil) then
  2073. if(data['status'] ~= nil) then
  2074. return data['status']
  2075. end
  2076. return "<unknown status>"
  2077. end
  2078. -- We basically want everything after the space
  2079. local space = string.find(data['status-line'], ' ')
  2080. if(space == nil) then
  2081. return data['status-line']
  2082. else
  2083. return (string.sub(data['status-line'], space + 1)):gsub('\r?\n', '')
  2084. end
  2085. end
  2086. ---Determine whether or not the server supports HEAD.
  2087. --
  2088. -- Tests by requesting / and verifying that it returns 200, and doesn't return
  2089. -- data. We implement the check like this because can't always rely on OPTIONS
  2090. -- to tell the truth.
  2091. --
  2092. -- Note: If <code>identify_404</code> returns a 200 status, HEAD requests
  2093. -- should be disabled. Sometimes, servers use a 200 status code with a message
  2094. -- explaining that the page wasn't found. In this case, to actually identify
  2095. -- a 404 page, we need the full body that a HEAD request doesn't supply.
  2096. -- This is determined automatically if the <code>result_404</code> field is
  2097. -- set.
  2098. --
  2099. -- @param host The host object.
  2100. -- @param port The port to use.
  2101. -- @param result_404 [optional] The result when an unknown page is requested.
  2102. -- This is returned by <code>identify_404</code>. If the 404
  2103. -- page returns a 200 code, then we disable HEAD requests.
  2104. -- @param path The path to request; by default, / is used.
  2105. -- @return A boolean value: true if HEAD is usable, false otherwise.
  2106. -- @return If HEAD is usable, the result of the HEAD request is returned (so
  2107. -- potentially, a script can avoid an extra call to HEAD)
  2108. function can_use_head(host, port, result_404, path)
  2109. -- If the 404 result is 200, don't use HEAD.
  2110. if(result_404 == 200) then
  2111. return false
  2112. end
  2113. -- Default path
  2114. if(path == nil) then
  2115. path = '/'
  2116. end
  2117. -- Perform a HEAD request and see what happens.
  2118. local data = head( host, port, path )
  2119. if data then
  2120. if data.status and data.status == 302 and data.header and data.header.location then
  2121. stdnse.debug1("HTTP: Warning: Host returned 302 and not 200 when performing HEAD.")
  2122. return false
  2123. end
  2124. if data.status and data.status == 200 and data.header then
  2125. -- check that a body wasn't returned
  2126. if #data.body > 0 then
  2127. stdnse.debug1("HTTP: Warning: Host returned data when performing HEAD.")
  2128. return false
  2129. end
  2130. stdnse.debug1("HTTP: Host supports HEAD.")
  2131. return true, data
  2132. end
  2133. stdnse.debug1("HTTP: Didn't receive expected response to HEAD request (got %s).", get_status_string(data))
  2134. return false
  2135. end
  2136. stdnse.debug1("HTTP: HEAD request completely failed.")
  2137. return false
  2138. end
  2139. --- Try to remove anything that might change within a 404.
  2140. --
  2141. -- For example:
  2142. -- * A file path (includes URI)
  2143. -- * A time
  2144. -- * A date
  2145. -- * An execution time (numbers in general, really)
  2146. --
  2147. -- The intention is that two 404 pages from different URIs and taken hours
  2148. -- apart should, whenever possible, look the same.
  2149. --
  2150. -- During this function, we're likely going to over-trim things. This is fine
  2151. -- -- we want enough to match on that it'll a) be unique, and b) have the best
  2152. -- chance of not changing. Even if we remove bits and pieces from the file, as
  2153. -- long as it isn't a significant amount, it'll remain unique.
  2154. --
  2155. -- One case this doesn't cover is if the server generates a random haiku for
  2156. -- the user.
  2157. --
  2158. -- @param body The body of the page.
  2159. function clean_404(body)
  2160. if ( not(body) ) then
  2161. return
  2162. end
  2163. -- Remove anything that looks like time
  2164. body = string.gsub(body, '%d?%d:%d%d:%d%d', "")
  2165. body = string.gsub(body, '%d%d:%d%d', "")
  2166. body = string.gsub(body, 'AM', "")
  2167. body = string.gsub(body, 'am', "")
  2168. body = string.gsub(body, 'PM', "")
  2169. body = string.gsub(body, 'pm', "")
  2170. -- Remove anything that looks like a date (this includes 6 and 8 digit numbers)
  2171. -- (this is probably unnecessary, but it's getting pretty close to 11:59 right now, so you never know!)
  2172. body = string.gsub(body, '%d%d%d%d%d%d%d%d', "") -- 4-digit year (has to go first, because it overlaps 2-digit year)
  2173. body = string.gsub(body, '%d%d%d%d%-%d%d%-%d%d', "")
  2174. body = string.gsub(body, '%d%d%d%d/%d%d/%d%d', "")
  2175. body = string.gsub(body, '%d%d%-%d%d%-%d%d%d%d', "")
  2176. body = string.gsub(body, '%d%d%/%d%d%/%d%d%d%d', "")
  2177. body = string.gsub(body, '%d%d%d%d%d%d', "") -- 2-digit year
  2178. body = string.gsub(body, '%d%d%-%d%d%-%d%d', "")
  2179. body = string.gsub(body, '%d%d%/%d%d%/%d%d', "")
  2180. -- Remove anything that looks like a path (note: this will get the URI too) (note2: this interferes with the date removal above, so it can't be moved up)
  2181. body = string.gsub(body, "/[^ ]+", "") -- Unix - remove everything from a slash till the next space
  2182. body = string.gsub(body, "[a-zA-Z]:\\[^ ]+", "") -- Windows - remove everything from a "x:\" pattern till the next space
  2183. -- If we have SSL available, save us a lot of memory by hashing the page (if SSL isn't available, this will work fine, but
  2184. -- take up more memory). If we're debugging, don't hash (it makes things far harder to debug).
  2185. if(have_ssl and nmap.debugging() == 0) then
  2186. return openssl.md5(body)
  2187. end
  2188. return body
  2189. end
  2190. ---Try requesting a non-existent file to determine how the server responds to
  2191. -- unknown pages ("404 pages")
  2192. --
  2193. -- This tells us
  2194. -- * what to expect when a non-existent page is requested, and
  2195. -- * if the server will be impossible to scan.
  2196. --
  2197. -- If the server responds with a 404 status code, as it is supposed to, then
  2198. -- this function simply returns 404. If it contains one of a series of common
  2199. -- status codes, including unauthorized, moved, and others, it is returned like
  2200. -- a 404.
  2201. --
  2202. -- I (Ron Bowes) have observed one host that responds differently for three
  2203. -- scenarios:
  2204. -- * A non-existent page, all lowercase (a login page)
  2205. -- * A non-existent page, with uppercase (a weird error page that says,
  2206. -- "Filesystem is corrupt.")
  2207. -- * A page in a non-existent directory (a login page with different font
  2208. -- colours)
  2209. --
  2210. -- As a result, I've devised three different 404 tests, one to check each of
  2211. -- these conditions. They all have to match, the tests can proceed; if any of
  2212. -- them are different, we can't check 404s properly.
  2213. --
  2214. -- @param host The host object.
  2215. -- @param port The port to which we are establishing the connection.
  2216. -- @return status Did we succeed?
  2217. -- @return result If status is false, result is an error message. Otherwise,
  2218. -- it's the code to expect (typically, but not necessarily,
  2219. -- '404').
  2220. -- @return body Body is a hash of the cleaned-up body that can be used when
  2221. -- detecting a 404 page that doesn't return a 404 error code.
  2222. function identify_404(host, port)
  2223. local data
  2224. local bad_responses = { 301, 302, 400, 401, 403, 499, 501, 503 }
  2225. -- The URLs used to check 404s
  2226. local URL_404_1 = '/nmaplowercheck' .. os.time(os.date('*t'))
  2227. local URL_404_2 = '/NmapUpperCheck' .. os.time(os.date('*t'))
  2228. local URL_404_3 = '/Nmap/folder/check' .. os.time(os.date('*t'))
  2229. data = get(host, port, URL_404_1)
  2230. if(data == nil) then
  2231. stdnse.debug1("HTTP: Failed while testing for 404 status code")
  2232. return false, "Failed while testing for 404 error message"
  2233. end
  2234. if(data.status and data.status == 404) then
  2235. stdnse.debug1("HTTP: Host returns proper 404 result.")
  2236. return true, 404
  2237. end
  2238. if(data.status and data.status == 200) then
  2239. stdnse.debug1("HTTP: Host returns 200 instead of 404.")
  2240. -- Clean up the body (for example, remove the URI). This makes it easier to validate later
  2241. if(data.body) then
  2242. -- Obtain a couple more 404 pages to test different conditions
  2243. local data2 = get(host, port, URL_404_2)
  2244. local data3 = get(host, port, URL_404_3)
  2245. if(data2 == nil or data3 == nil) then
  2246. stdnse.debug1("HTTP: Failed while testing for extra 404 error messages")
  2247. return false, "Failed while testing for extra 404 error messages"
  2248. end
  2249. -- Check if the return code became something other than 200.
  2250. -- Status code: -1 represents unknown.
  2251. -- If the status is nil or the string "unknown" we switch to -1.
  2252. if(data2.status ~= 200) then
  2253. if(type(data2.status) ~= "number") then
  2254. data2.status = -1
  2255. end
  2256. stdnse.debug1("HTTP: HTTP 404 status changed for second request (became %d).", data2.status)
  2257. return false, string.format("HTTP 404 status changed for second request (became %d).", data2.status)
  2258. end
  2259. -- Check if the return code became something other than 200
  2260. if(data3.status ~= 200) then
  2261. if(type(data3.status) ~= "number") then
  2262. data3.status = -1
  2263. end
  2264. stdnse.debug1("HTTP: HTTP 404 status changed for third request (became %d).", data3.status)
  2265. return false, string.format("HTTP 404 status changed for third request (became %d).", data3.status)
  2266. end
  2267. -- Check if the returned bodies (once cleaned up) matches the first returned body
  2268. local clean_body = clean_404(data.body)
  2269. local clean_body2 = clean_404(data2.body)
  2270. local clean_body3 = clean_404(data3.body)
  2271. if(clean_body ~= clean_body2) then
  2272. stdnse.debug1("HTTP: Two known 404 pages returned valid and different pages; unable to identify valid response.")
  2273. stdnse.debug1("HTTP: If you investigate the server and it's possible to clean up the pages, please post to nmap-dev mailing list.")
  2274. return false, string.format("Two known 404 pages returned valid and different pages; unable to identify valid response.")
  2275. end
  2276. if(clean_body ~= clean_body3) then
  2277. stdnse.debug1("HTTP: Two known 404 pages returned valid and different pages; unable to identify valid response (happened when checking a folder).")
  2278. stdnse.debug1("HTTP: If you investigate the server and it's possible to clean up the pages, please post to nmap-dev mailing list.")
  2279. return false, string.format("Two known 404 pages returned valid and different pages; unable to identify valid response (happened when checking a folder).")
  2280. end
  2281. return true, 200, clean_body
  2282. end
  2283. stdnse.debug1("HTTP: The 200 response didn't contain a body.")
  2284. return true, 200
  2285. end
  2286. -- Loop through any expected error codes
  2287. for _,code in pairs(bad_responses) do
  2288. if(data.status and data.status == code) then
  2289. stdnse.debug1("HTTP: Host returns %s instead of 404 File Not Found.", get_status_string(data))
  2290. return true, code
  2291. end
  2292. end
  2293. stdnse.debug1("Unexpected response returned for 404 check: %s", get_status_string(data))
  2294. return true, data.status
  2295. end
  2296. --- Determine whether or not the page that was returned is a 404 page.
  2297. --
  2298. -- This is actually a pretty simple function, but it's best to keep this logic
  2299. -- close to <code>identify_404</code>, since they will generally be used
  2300. -- together.
  2301. --
  2302. -- @param data The data returned by the HTTP request
  2303. -- @param result_404 The status code to expect for non-existent pages. This is
  2304. -- returned by <code>identify_404</code>.
  2305. -- @param known_404 The 404 page itself, if <code>result_404</code> is 200. If
  2306. -- <code>result_404</code> is something else, this parameter
  2307. -- is ignored and can be set to <code>nil</code>. This is
  2308. -- returned by <code>identify_404</code>.
  2309. -- @param page The page being requested (used in error messages).
  2310. -- @param displayall [optional] If set to true, don't exclude non-404 errors
  2311. -- (such as 500).
  2312. -- @return A boolean value: true if the page appears to exist, and false if it
  2313. -- does not.
  2314. function page_exists(data, result_404, known_404, page, displayall)
  2315. if(data and data.status) then
  2316. -- Handle the most complicated case first: the "200 Ok" response
  2317. if(data.status == 200) then
  2318. if(result_404 == 200) then
  2319. -- If the 404 response is also "200", deal with it (check if the body matches)
  2320. if(#data.body == 0) then
  2321. -- I observed one server that returned a blank string instead of an error, on some occasions
  2322. stdnse.debug1("HTTP: Page returned a totally empty body; page likely doesn't exist")
  2323. return false
  2324. elseif(clean_404(data.body) ~= known_404) then
  2325. stdnse.debug1("HTTP: Page returned a body that doesn't match known 404 body, therefore it exists (%s)", page)
  2326. return true
  2327. else
  2328. return false
  2329. end
  2330. else
  2331. -- If 404s return something other than 200, and we got a 200, we're good to go
  2332. stdnse.debug1("HTTP: Page was '%s', it exists! (%s)", get_status_string(data), page)
  2333. return true
  2334. end
  2335. else
  2336. -- If the result isn't a 200, check if it's a 404 or returns the same code as a 404 returned
  2337. if(data.status ~= 404 and data.status ~= result_404) then
  2338. -- If this check succeeded, then the page isn't a standard 404 -- it could be a redirect, authentication request, etc. Unless the user
  2339. -- asks for everything (with a script argument), only display 401 Authentication Required here.
  2340. stdnse.debug1("HTTP: Page didn't match the 404 response (%s) (%s)", get_status_string(data), page)
  2341. if(data.status == 401) then -- "Authentication Required"
  2342. return true
  2343. elseif(displayall) then
  2344. return true
  2345. end
  2346. return false
  2347. else
  2348. -- Page was a 404, or looked like a 404
  2349. return false
  2350. end
  2351. end
  2352. else
  2353. stdnse.debug1("HTTP: HTTP request failed (is the host still up?)")
  2354. return false
  2355. end
  2356. end
  2357. ---Check if the response variable contains the given text.
  2358. --
  2359. -- Response variable could be a return from a http.get, http.post,
  2360. -- http.pipeline, etc. The text can be:
  2361. -- * Part of a header ('content-type', 'text/html', '200 OK', etc)
  2362. -- * An entire header ('Content-type: text/html', 'Content-length: 123', etc)
  2363. -- * Part of the body
  2364. --
  2365. -- The search text is treated as a Lua pattern.
  2366. --
  2367. --@param response The full response table from a HTTP request.
  2368. --@param pattern The pattern we're searching for. Don't forget to escape '-',
  2369. -- for example, 'Content%-type'. The pattern can also contain
  2370. -- captures, like 'abc(.*)def', which will be returned if
  2371. -- successful.
  2372. --@param case_sensitive [optional] Set to <code>true</code> for case-sensitive
  2373. -- searches. Default: not case sensitive.
  2374. --@return result True if the string matched, false otherwise
  2375. --@return matches An array of captures from the match, if any
  2376. function response_contains(response, pattern, case_sensitive)
  2377. local result, _
  2378. local m = {}
  2379. -- If they're searching for the empty string or nil, it's true
  2380. if(pattern == '' or pattern == nil) then
  2381. return true
  2382. end
  2383. -- Create a function that either lowercases everything or doesn't, depending on case sensitivity
  2384. local case = function(pattern) return string.lower(pattern or '') end
  2385. if(case_sensitive == true) then
  2386. case = function(pattern) return (pattern or '') end
  2387. end
  2388. -- Set the case of the pattern
  2389. pattern = case(pattern)
  2390. -- Check the status line (eg, 'HTTP/1.1 200 OK')
  2391. m = {string.match(case(response['status-line']), pattern)};
  2392. if(m and #m > 0) then
  2393. return true, m
  2394. end
  2395. -- Check the headers
  2396. for _, header in pairs(response['rawheader']) do
  2397. m = {string.match(case(header), pattern)}
  2398. if(m and #m > 0) then
  2399. return true, m
  2400. end
  2401. end
  2402. -- Check the body
  2403. m = {string.match(case(response['body']), pattern)}
  2404. if(m and #m > 0) then
  2405. return true, m
  2406. end
  2407. return false
  2408. end
  2409. ---Take a URI or URL in any form and convert it to its component parts.
  2410. --
  2411. -- The URL can optionally have a protocol definition ('http://'), a server
  2412. -- ('scanme.insecure.org'), a port (':80'), a URI ('/test/file.php'), and a
  2413. -- query string ('?username=ron&password=turtle'). At the minimum, a path or
  2414. -- protocol and url are required.
  2415. --
  2416. --@param url The incoming URL to parse
  2417. --@return A table containing the result, which can have the following fields:
  2418. -- * protocol
  2419. -- * hostname
  2420. -- * port
  2421. -- * uri
  2422. -- * querystring
  2423. -- All fields are strings except querystring, which is a table
  2424. -- containing name=value pairs.
  2425. function parse_url(url)
  2426. local result = {}
  2427. -- Save the original URL
  2428. result['original'] = url
  2429. -- Split the protocol off, if it exists
  2430. local colonslashslash = string.find(url, '://')
  2431. if(colonslashslash) then
  2432. result['protocol'] = string.sub(url, 1, colonslashslash - 1)
  2433. url = string.sub(url, colonslashslash + 3)
  2434. end
  2435. -- Split the host:port from the path
  2436. local slash, host_port
  2437. slash = string.find(url, '/')
  2438. if(slash) then
  2439. host_port = string.sub(url, 1, slash - 1)
  2440. result['path_query'] = string.sub(url, slash)
  2441. else
  2442. -- If there's no slash, then it's just a URL (if it has a http://) or a path (if it doesn't)
  2443. if(result['protocol']) then
  2444. result['host_port'] = url
  2445. else
  2446. result['path_query'] = url
  2447. end
  2448. end
  2449. if(host_port == '') then
  2450. host_port = nil
  2451. end
  2452. -- Split the host and port apart, if possible
  2453. if(host_port) then
  2454. local colon = string.find(host_port, ':')
  2455. if(colon) then
  2456. result['host'] = string.sub(host_port, 1, colon - 1)
  2457. result['port'] = tonumber(string.sub(host_port, colon + 1))
  2458. else
  2459. result['host'] = host_port
  2460. end
  2461. end
  2462. -- Split the path and querystring apart
  2463. if(result['path_query']) then
  2464. local question = string.find(result['path_query'], '?')
  2465. if(question) then
  2466. result['path'] = string.sub(result['path_query'], 1, question - 1)
  2467. result['raw_querystring'] = string.sub(result['path_query'], question + 1)
  2468. else
  2469. result['path'] = result['path_query']
  2470. end
  2471. -- Split up the query, if necessary
  2472. if(result['raw_querystring']) then
  2473. result['querystring'] = {}
  2474. local values = stdnse.strsplit('&', result['raw_querystring'])
  2475. for i, v in ipairs(values) do
  2476. local name, value = table.unpack(stdnse.strsplit('=', v))
  2477. result['querystring'][name] = value
  2478. end
  2479. end
  2480. -- Get the extension of the file, if any, or set that it's a folder
  2481. if(string.match(result['path'], "/$")) then
  2482. result['is_folder'] = true
  2483. else
  2484. result['is_folder'] = false
  2485. local split_str = stdnse.strsplit('%.', result['path'])
  2486. if(split_str and #split_str > 1) then
  2487. result['extension'] = split_str[#split_str]
  2488. end
  2489. end
  2490. end
  2491. return result
  2492. end
  2493. ---This function should be called whenever a valid path (a path that doesn't
  2494. -- contain a known 404 page) is discovered.
  2495. --
  2496. -- It will add the path to the registry in several ways, allowing other scripts
  2497. -- to take advantage of it in interesting ways.
  2498. --
  2499. --@param host The host the path was discovered on (not necessarily the host
  2500. -- being scanned).
  2501. --@param port The port the path was discovered on (not necessarily the port
  2502. -- being scanned).
  2503. --@param path The path discovered. Calling this more than once with the same
  2504. -- path is okay; it'll update the data as much as possible instead
  2505. -- of adding a duplicate entry
  2506. --@param status [optional] The status code (200, 404, 500, etc). This can be
  2507. -- left off if it isn't known.
  2508. --@param links_to [optional] A table of paths that this page links to.
  2509. --@param linked_from [optional] A table of paths that link to this page.
  2510. --@param contenttype [optional] The content-type value for the path, if it's known.
  2511. function save_path(host, port, path, status, links_to, linked_from, contenttype)
  2512. -- Make sure we have a proper hostname and port
  2513. host = stdnse.get_hostname(host)
  2514. if(type(port) == 'table') then
  2515. port = port.number
  2516. end
  2517. -- Parse the path
  2518. local parsed = parse_url(path)
  2519. -- Add to the 'all_pages' key
  2520. stdnse.registry_add_array({parsed['host'] or host, 'www', parsed['port'] or port, 'all_pages'}, parsed['path'])
  2521. -- Add the URL with querystring to all_pages_full_query
  2522. stdnse.registry_add_array({parsed['host'] or host, 'www', parsed['port'] or port, 'all_pages_full_query'}, parsed['path_query'])
  2523. -- Add the URL to a key matching the response code
  2524. if(status) then
  2525. stdnse.registry_add_array({parsed['host'] or host, 'www', parsed['port'] or port, 'status_codes', status}, parsed['path'])
  2526. end
  2527. -- If it's a directory, add it to the directories list; otherwise, add it to the files list
  2528. if(parsed['is_folder']) then
  2529. stdnse.registry_add_array({parsed['host'] or host, 'www', parsed['port'] or port, 'directories'}, parsed['path'])
  2530. else
  2531. stdnse.registry_add_array({parsed['host'] or host, 'www', parsed['port'] or port, 'files'}, parsed['path'])
  2532. end
  2533. -- If we have an extension, add it to the extensions key
  2534. if(parsed['extension']) then
  2535. stdnse.registry_add_array({parsed['host'] or host, 'www', parsed['port'] or port, 'extensions', parsed['extension']}, parsed['path'])
  2536. end
  2537. -- Add an entry for the page and its arguments
  2538. if(parsed['querystring']) then
  2539. -- Add all scripts with a querystring to the 'cgi' and 'cgi_full_query' keys
  2540. stdnse.registry_add_array({parsed['host'] or host, 'www', parsed['port'] or port, 'cgi'}, parsed['path'])
  2541. stdnse.registry_add_array({parsed['host'] or host, 'www', parsed['port'] or port, 'cgi_full_query'}, parsed['path_query'])
  2542. -- Add the query string alone to the registry (probably not necessary)
  2543. stdnse.registry_add_array({parsed['host'] or host, 'www', parsed['port'] or port, 'cgi_querystring', parsed['path'] }, parsed['raw_querystring'])
  2544. -- Add the individual arguments for the page, along with their values
  2545. for key, value in pairs(parsed['querystring']) do
  2546. stdnse.registry_add_array({parsed['host'] or host, 'www', parsed['port'] or port, 'cgi_args', parsed['path']}, parsed['querystring'])
  2547. end
  2548. end
  2549. -- Save the pages it links to
  2550. if(links_to) then
  2551. if(type(links_to) == 'string') then
  2552. links_to = {links_to}
  2553. end
  2554. for _, v in ipairs(links_to) do
  2555. stdnse.registry_add_array({parsed['host'] or host, 'www', parsed['port'] or port, 'links_to', parsed['path_query']}, v)
  2556. end
  2557. end
  2558. -- Save the pages it's linked from (we save these in the 'links_to' key, reversed)
  2559. if(linked_from) then
  2560. if(type(linked_from) == 'string') then
  2561. linked_from = {linked_from}
  2562. end
  2563. for _, v in ipairs(linked_from) do
  2564. stdnse.registry_add_array({parsed['host'] or host, 'www', parsed['port'] or port, 'links_to', v}, parsed['path_query'])
  2565. end
  2566. end
  2567. -- Save it as a content-type, if we have one
  2568. if(contenttype) then
  2569. stdnse.registry_add_array({parsed['host'] or host, 'www', parsed['port'] or port, 'content-type', contenttype}, parsed['path_query'])
  2570. end
  2571. end
  2572. return _ENV;