root/src/modules-lua/noit/module/http.lua

Revision 353258a7cab6bd5c7069ab335642da33a6c67a2a, 23.2 kB (checked in by Philip Maddox <pmaddox@circonus.com>, 2 years ago)

Added improved SSL certificate validation to IMAP and TCP checks (use the default-ca-chain.crt file if none is provided by the user, allow users to pass a header_Host to the check to verify the CN of the certificate). Tweaked the HTTP check to not throw a certificate name mismatch error if no header_Host field is provided

  • Property mode set to 100644
Line 
1 -- Copyright (c) 2008, OmniTI Computer Consulting, Inc.
2 -- All rights reserved.
3 --
4 -- Redistribution and use in source and binary forms, with or without
5 -- modification, are permitted provided that the following conditions are
6 -- met:
7 --
8 --     * Redistributions of source code must retain the above copyright
9 --       notice, this list of conditions and the following disclaimer.
10 --     * Redistributions in binary form must reproduce the above
11 --       copyright notice, this list of conditions and the following
12 --       disclaimer in the documentation and/or other materials provided
13 --       with the distribution.
14 --     * Neither the name OmniTI Computer Consulting, Inc. nor the names
15 --       of its contributors may be used to endorse or promote products
16 --       derived from this software without specific prior written
17 --       permission.
18 --
19 -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 -- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 module(..., package.seeall)
32
33 function onload(image)
34   image.xml_description([=[
35 <module>
36   <name>http</name>
37   <description><para>The http module performs GET requests over either HTTP or HTTPS and checks the return code and optionally the body.</para>
38   </description>
39   <loader>lua</loader>
40   <object>noit.module.http</object>
41   <checkconfig>
42     <parameter name="url"
43                required="required"
44                allowed=".+">The URL including schema and hostname (as you would type into a browser's location bar).</parameter>
45     <parameter name="header_(\S+)"
46                required="optional"
47                allowed=".+">Allows the setting of arbitrary HTTP headers in the request.</parameter>
48     <parameter name="method"
49                required="optional"
50                allowed="\S+"
51                default="GET">The HTTP method to use.</parameter>
52     <parameter name="payload"
53                required="optional"
54                allowed=".*">The information transferred as the payload of an HTTP request.</parameter>
55     <parameter name="auth_method"
56                required="optional"
57                allowed="^(?:Basic|Digest|Auto)$">HTTP Authentication method to use.</parameter>
58     <parameter name="auth_user"
59                required="optional"
60                allowed="[^:]*">The user to authenticate as.</parameter>
61     <parameter name="auth_password"
62                required="optional"
63                allowed=".*">The password to use during authentication.</parameter>
64     <parameter name="ca_chain"
65                required="optional"
66                allowed=".+">A path to a file containing all the certificate authorities that should be loaded to validate the remote certificate (for SSL checks).</parameter>
67     <parameter name="certificate_file"
68                required="optional"
69                allowed=".+">A path to a file containing the client certificate that will be presented to the remote server (for SSL checks).</parameter>
70     <parameter name="key_file"
71                required="optional"
72                allowed=".+">A path to a file containing key to be used in conjunction with the cilent certificate (for SSL checks).</parameter>
73     <parameter name="ciphers"
74                required="optional"
75                allowed=".+">A list of ciphers to be used in the SSL protocol (for SSL checks).</parameter>
76     <parameter name="code"
77                required="optional"
78                default="^200$"
79                allowed=".+">The HTTP code that is expected.  If the code received does not match this regular expression, the check is marked as "bad."</parameter>
80     <parameter name="redirects"
81                required="optional"
82                default="0"
83                allowed="\d+">The maximum number of Location header redirects to follow.</parameter>
84     <parameter name="body"
85                required="optional"
86                allowed=".+">This regular expression is matched against the body of the response. If a match is not found, the check will be marked as "bad."</parameter>
87     <parameter name="body_match_*"
88                required="optional"
89                allowed=".+">This regular expression is matched against the body of the response. If a match is found it is captured and added as a metric. For example, if setting is named 'body_match_foo_bar' and a match is found new metric called 'foo_bar' will be added.</parameter>
90     <parameter name="extract"
91                required="optional"
92                allowed=".+">This regular expression is matched against the body of the response globally.  The first capturing match is the key and the second capturing match is the value.  Each key/value extracted is registered as a metric for the check.</parameter>
93     <parameter name="pcre_match_limit"
94                required="optional"
95                default="10000"
96                allowed="\d+">This sets the PCRE internal match limit (see pcreapi documentation).</parameter>
97     <parameter name="include_body"
98                required="optional"
99                allowed="^(?:true|false|on|off)$"
100                default="false">Include whole response body as a metric with the key 'body'.</parameter>
101     <parameter name="read_limit"
102                required="optional"
103                default="0"
104                allowed="\d+">Sets an approximate limit on the data read (0 means no limit).</parameter>
105   </checkconfig>
106   <examples>
107     <example>
108       <title>Checking an HTTP and HTTPS URL.</title>
109       <para>This example checks the OmniTI Labs website over both HTTP and HTTPS.</para>
110       <programlisting><![CDATA[
111       <noit>
112         <modules>
113           <loader image="lua" name="lua">
114             <config><directory>/opt/reconnoiter/libexec/modules-lua/?.lua</directory></config>
115           </loader>
116           <module loader="lua" name="http" object="noit.module.http" />
117         </modules>
118         <checks>
119           <labs target="8.8.38.5" module="http">
120             <check uuid="fe3e984c-7895-11dd-90c1-c74c31b431f0" name="http">
121               <config><url>http://labs.omniti.com/</url></config>
122             </check>
123             <check uuid="1ecd887a-7896-11dd-b28d-0b4216877f83" name="https">
124               <config><url>https://labs.omniti.com/</url></config>
125             </check>
126           </labs>
127         </checks>
128       </noit>
129     ]]></programlisting>
130     </example>
131   </examples>
132 </module>
133 ]=]);
134   return 0
135 end
136
137 function init(module)
138   return 0
139 end
140
141 function config(module, options)
142   return 0
143 end
144
145 local HttpClient = require 'noit.HttpClient'
146
147 local BODY_MATCHES_PREFIX = 'body_match_'
148
149 function elapsed(check, name, starttime, endtime)
150     local elapsedtime = endtime - starttime
151     local seconds = string.format('%.3f', noit.timeval.seconds(elapsedtime))
152     check.metric_uint32(name, math.floor(seconds * 1000 + 0.5))
153     return seconds
154 end
155
156 function populate_cookie_jar(cookies, host, hdr)
157     local path = nil
158     if hdr ~= nil then
159         local name, value, trailer =
160             string.match(hdr, "([^=]+)=([^;]+);?%s*(.*)")
161         if name ~= nil then
162             local jar = { }
163             local fields = noit.extras.split(trailer, ";")
164             if fields ~= nil then
165                 for k, v in pairs(fields) do
166                     local pair = noit.extras.split(v, "=", 1);
167                     if pair ~= nil and pair[1] ~= nil and pair[2] ~= nil then
168                         local name = (string.gsub(pair[1], "^%s*(.-)%s*$", "%1"));
169                         local setting = (string.gsub(pair[2], "^%s*(.-)%s*$", "%1"));
170                         if name == "path" then
171                             path = setting
172                         end
173                     end
174                 end
175             end
176             if string.sub(name, 1, 1) ~= ";" and string.sub(value, 1, 1) ~= ";" then
177                 if path == nil then path = "/" end
178                 if cookies[host] == nil then cookies[host] = { } end
179                 if cookies[host][path] == nil then cookies[host][path] = { } end
180                 jar.name = name
181                 jar.value = value
182                 table.insert(cookies[host][path], jar)
183             end
184         end
185     end
186 end
187
188 function has_host(pat, host)
189     if pat == host then return true end
190     if pat:sub(1,1) ~= "." then return false end
191     local revpat = pat:sub(2):reverse()
192     local revhost = host:reverse()
193     if revpat == revhost then return true end
194     if revpat == revhost:sub(1, revpat:len()) then
195         if revhost:sub(pat:len(), pat:len()) == "." then return true end
196     end
197     return false
198 end
199
200 function apply_cookies(headers, cookies, host, uri)
201     local use_cookies = { }
202     for h, paths in pairs(cookies) do
203         if has_host(h, host) then
204             local split_uri = noit.extras.split(uri, "/")
205             if split_uri ~= nil then
206                 local path = ""
207                 for i, val in pairs(split_uri) do
208                     local append = true
209                     if val == nil then val = "" end
210                     if #split_uri == i and string.find(val, "%.") ~= nil then append = false end
211                     if append == true then
212                         path = path .. "/" .. val
213                         if string.len(path) >= 2 and string.sub(path, 1, 2) == "//" then
214                             path = string.sub(path, 2)
215                         end
216                     end
217                     if path == "" then path = "/" end
218                     local rindex = string.match(path, '.*()'..'%?')
219                     if rindex ~= nil then
220                         path = string.sub(path, 1, rindex-1)
221                     end
222                     if path ~= "/" then
223                         while string.find(path, "/", -1) ~= nil do
224                             path = string.sub(path, 1, -2)
225                         end
226                     end
227                     if paths[path] ~= nil then
228                         local jars = paths[path]
229                         for index, jar in ipairs(jars) do
230                             use_cookies[jar.name] = jar.value
231                         end
232                     end
233                 end
234             end
235         end
236     end
237     for name, value in pairs(use_cookies) do
238         if headers["Cookie"] == nil then
239             headers["Cookie"] = name .. "=" .. value
240         else
241             headers["Cookie"] = headers["Cookie"] .. "; " .. name .. "=" .. value
242         end
243     end
244 end
245
246 function get_new_uri(old_uri, new_uri)
247     if new_uri == nil then return "/" end
248     if new_uri == "/" then return new_uri end
249     local toReturn = old_uri
250     while string.find(toReturn, "/", -1) ~= nil do
251         toReturn = string.sub(toReturn, 1, -2)
252     end
253     if string.sub(new_uri, 1, 1) == '?' then
254         local rindex = string.match(toReturn, '.*()'.."/")
255         toReturn = string.sub(toReturn, 1, rindex-1)
256         toReturn = toReturn .. new_uri
257     elseif string.sub(new_uri, 1, 1) ~= "." then
258         toReturn = new_uri
259     else
260         toReturn = string.gsub(toReturn, "%/%?", "?")
261         while string.sub(new_uri, 1, 1) == "." do
262             if string.find(new_uri, "%./") == 1 then
263                 new_uri = string.gsub("%./", "", 1)
264             elseif string.find(new_uri, "%.%./") == 1 then
265                 --strip out last bit from toReturn
266                 local rindex = string.match(toReturn, '.*()'.."/")
267                 toReturn = string.sub(toReturn, 1, rindex-1)
268                 new_uri = string.gsub(new_uri, "../", "", 1)
269             else
270                 -- bad URI... just return /
271                 return "/"
272             end
273         end
274         toReturn = toReturn .. "/" .. new_uri
275     end
276     return toReturn
277 end
278
279 function get_absolute_path(uri)
280     if uri == nil then return "/" end
281     local toReturn = uri
282     local go_back = string.find(toReturn, "%.%./")
283     while go_back ~= nil do
284         local tojoin = go_back + 3
285         go_back = go_back - 2
286         local back_substring = string.sub(toReturn, 1, go_back)
287         local forward_substring = string.sub(toReturn, tojoin)
288         local rindex = string.match(back_substring, '.*()' .. "/")
289         if rindex ~= nil then
290             toReturn = string.sub(toReturn, 1, rindex) .. forward_substring
291         end
292         go_back = string.find(toReturn, "%.%./")
293     end
294     toReturn = string.gsub(toReturn, "%./", "")
295     return toReturn
296 end
297
298 function initiate(module, check)
299     local url = check.config.url or 'http:///'
300     local schema, host, port, uri = string.match(url, "^(https?)://([^:/]*):?([0-9]*)(/?.*)$");
301     local use_ssl = false
302     local codere = noit.pcre(check.config.code or '^200$')
303     local good = false
304     local starttime = noit.timeval.now()
305     local method = check.config.method or "GET"
306     local max_len = 80
307     local pcre_match_limit = check.config.pcre_match_limit or 10000
308     local redirects = check.config.redirects or 0
309     local include_body = false
310     local read_limit = tonumber(check.config.read_limit) or nil
311     local host_header = check.config.header_Host or ''
312
313     -- expect the worst
314     check.bad()
315     check.unavailable()
316
317     if host == nil then host = check.target end
318     if schema == nil then
319         schema = 'http'
320         uri = '/'
321     end
322     if uri == '' then
323         uri = '/'
324     end
325     if port == '' or port == nil then
326         if schema == 'http' then
327             port = check.config.port or 80
328         elseif schema == 'https' then
329             port = check.config.port or 443
330         else
331             error(schema .. " not supported")
332         end
333     end
334     if schema == 'https' then
335         use_ssl = true
336     end
337
338     -- Include body as a metric
339     if check.config.include_body == "true" or check.config.include_body == "on" then
340         include_body = true
341     end
342
343     local output = ''
344     local connecttime, firstbytetime
345     local next_location
346     local cookies = { }
347     local setfirstbyte = 1
348
349     -- callbacks from the HttpClient
350     local callbacks = { }
351     callbacks.consume = function (str)
352         if setfirstbyte == 1 then
353             firstbytetime = noit.timeval.now()
354             setfirstbyte = 0
355         end
356         output = output .. (str or '')
357     end
358     callbacks.headers = function (hdrs, setcookies)
359         next_location = hdrs.location
360         for key, value in pairs(setcookies) do
361             populate_cookie_jar(cookies, host, value)
362         end
363     end
364
365     callbacks.connected = function () connecttime = noit.timeval.now() end
366
367     -- setup SSL info
368     local default_ca_chain =
369         noit.conf_get_string("/noit/eventer/config/default_ca_chain")
370     callbacks.certfile = function () return check.config.certificate_file end
371     callbacks.keyfile = function () return check.config.key_file end
372     callbacks.cachain = function ()
373         return check.config.ca_chain and check.config.ca_chain
374                                       or default_ca_chain
375     end
376     callbacks.ciphers = function () return check.config.ciphers end
377
378     -- set the stage
379     local headers = {}
380     headers.Host = host
381     for header, value in pairs(check.config) do
382         hdr = string.match(header, '^header_(.+)$')
383         if hdr ~= nil then
384           headers[hdr] = value
385         end
386     end
387     if check.config.auth_method == "Basic" then
388         local user = check.config.auth_user or ''
389         local password = check.config.auth_password or ''
390         local encoded = noit.base64_encode(user .. ':' .. password)
391         headers["Authorization"] = "Basic " .. encoded
392     elseif check.config.auth_method == "Digest" or
393            check.config.auth_method == "Auto" then
394         -- this is handled later as we need our challenge.
395         local client = HttpClient:new()
396         local rv, err = client:connect(check.target_ip, port, use_ssl)
397         if rv ~= 0 then
398             check.status(err or "unknown error")
399             return
400         end
401         local headers_firstpass = {}
402         for k,v in pairs(headers) do
403             headers_firstpass[k] = v
404         end
405         client:do_request(method, uri, headers_firstpass)
406         client:get_response(read_limit)
407         if client.code ~= 401 or
408            client.headers["www-authenticate"] == nil then
409             check.status("expected digest challenge, got " .. client.code)
410             return
411         end
412         local user = check.config.auth_user or ''
413         local password = check.config.auth_password or ''
414         local ameth, challenge =
415             string.match(client.headers["www-authenticate"], '^(%S+)%s+(.+)$')
416         if check.config.auth_method == "Auto" and ameth == "Basic" then
417             local encoded = noit.base64_encode(user .. ':' .. password)
418             headers["Authorization"] = "Basic " .. encoded
419         elseif ameth == "Digest" then
420             headers["Authorization"] =
421                 "Digest " .. client:auth_digest(method, uri,
422                                          user, password, challenge)
423         else
424             check.status("Unexpected auth '" .. ameth .. "' in challenge")
425             return
426         end
427     elseif check.config.auth_method ~= nil then
428       check.status("Unknown auth method: " .. check.config.auth_method)
429       return
430     end
431
432     -- perform the request
433     local client
434     local dns = noit.dns()
435     local target = check.target_ip
436     local payload = check.config.payload
437     -- artificially increase redirects as the initial request counts
438     redirects = redirects + 1
439     starttime = noit.timeval.now()
440     repeat
441         local optclient = HttpClient:new(callbacks)
442         local rv, err = optclient:connect(target, port, use_ssl)
443
444         if rv ~= 0 then
445             check.status(err or "unknown error")
446             return
447         end
448         optclient:do_request(method, uri, headers, payload)
449         optclient:get_response(read_limit)
450         setfirstbyte = 1
451
452         redirects = redirects - 1
453         client = optclient
454
455         if next_location ~= nil then
456             -- reset some stuff for the redirect
457             local prev_port = port
458             local prev_host = host
459             local prev_uri = uri
460             method = 'GET'
461             payload = nil
462             schema, host, port, uri =
463                 string.match(next_location,
464                              "^(https?)://([^:/]*):?([0-9]*)(/?.*)$")
465             if schema == nil then
466                 port = prev_port
467                 host = prev_host
468                 uri = get_new_uri(prev_uri, next_location)
469             elseif schema == 'http' then
470                 use_ssl = false
471                 if port == "" then port = 80 end
472             elseif schema == 'https' then
473                 use_ssl = true
474                 if port == "" then port = 443 end
475             end
476             uri = get_absolute_path(uri)
477             if host ~= nil then
478                 headers.Host = host
479                 local r = dns:lookup(host)
480                 if not r or r.a == nil then
481                     check.status("failed to resolve " .. host)
482                     return
483                 end
484                 target = r.a
485             end
486             while string.find(host, "/", -1) ~= nil do
487                 host = string.sub(host, 1, -2)
488             end
489             headers["Cookie"] = check.config["header_Cookie"]
490             apply_cookies(headers, cookies, host, uri)
491         end
492     until redirects <= 0 or next_location == nil
493
494     local endtime = noit.timeval.now()
495     check.available()
496
497     local status = ''
498     -- setup the code
499     check.metric_string("code", client.code)
500     status = status .. 'code=' .. client.code
501     if codere ~= nil and codere(client.code) then
502       good = true
503     end
504
505     -- truncated response
506     check.metric_uint32("truncated", client.truncated and 1 or 0)
507
508     -- turnaround time
509     local seconds = elapsed(check, "duration", starttime, endtime)
510     status = status .. ',rt=' .. seconds .. 's'
511     elapsed(check, "tt_connect", starttime, connecttime)
512
513     if firstbytetime ~= nil then
514       elapsed(check, "tt_firstbyte", starttime, firstbytetime)
515     end
516
517     -- size
518     status = status .. ',bytes=' .. client.content_bytes
519     check.metric_int32("bytes", client.content_bytes)
520
521     if check.config.extract ~= nil then
522       local exre = noit.pcre(check.config.extract)
523       local rv = true
524       local m = nil
525       while rv and m ~= '' do
526         rv, m, key, value = exre(output or '', { limit = pcre_match_limit })
527         if rv and key ~= nil then
528           check.metric(key, value)
529         end
530       end
531     end
532
533     -- check body
534     if check.config.body ~= nil then
535       local bodyre = noit.pcre(check.config.body)
536       local rv, m, m1 = bodyre(output or '')
537       if rv then
538         m = m1 or m or output
539         if string.len(m) > max_len then
540           m = string.sub(m,1,max_len)
541         end
542         status = status .. ',body=matched'
543         check.metric_string('body_match', m)
544       else
545         status = status .. ',body=failed'
546         check.metric_string('body_match', nil)
547         good = false
548       end
549     end
550
551     -- check body matches
552     local matches = 0
553     has_body_matches = false
554     for key, value in pairs(check.config) do
555       m = string.find(key, BODY_MATCHES_PREFIX)
556
557       if m == 1 then
558         has_body_matches = true
559         key = string.gsub(key, BODY_MATCHES_PREFIX, '')
560
561         local bodyre = noit.pcre(value)
562         local rv, m, m1 = bodyre(output or '')
563
564         if rv then
565           matches = matches + 1
566           m = m1 or m or output
567           if string.len(m) > max_len then
568             m = string.sub(m,1,max_len)
569           end
570           check.metric_string('body_match_' .. key, m)
571         else
572           check.metric_string('body_match_' .. key, nil)
573         end
574       end
575     end
576
577     if has_body_matches then
578       status = status .. ',body_matches=' .. tostring(matches) .. ' matches'
579     end
580
581     -- Include body
582     if include_body then
583         check.metric_string('body', output or '')
584     end
585
586     -- ssl ctx
587     local ssl_ctx = client:ssl_ctx()
588     if ssl_ctx ~= nil then
589       local header_match_error = nil
590       if host_header ~= '' then
591         header_match_error = noit.extras.check_host_header_against_certificate(host_header, ssl_ctx.subject, ssl_ctx.san_list)
592       end
593       if ssl_ctx.error ~= nil then status = status .. ',sslerror' end
594       if header_match_error == nil then
595         check.metric_string("cert_error", ssl_ctx.error)
596       elseif ssl_ctx.error == nil then
597         check.metric_string("cert_error", header_match_error)
598       else
599         check.metric_string("cert_error", ssl_ctx.error .. ', ' .. header_match_error)
600       end
601       check.metric_string("cert_issuer", ssl_ctx.issuer)
602       check.metric_string("cert_subject", ssl_ctx.subject)
603       if ssl_ctx.san_list ~= nil then
604         check.metric_string("cert_subject_alternative_names", ssl_ctx.san_list)
605       end
606       check.metric_uint32("cert_start", ssl_ctx.start_time)
607       check.metric_uint32("cert_end", ssl_ctx.end_time)
608       check.metric_int32("cert_end_in", ssl_ctx.end_time - os.time())
609       if noit.timeval.seconds(starttime) > ssl_ctx.end_time then
610         good = false
611         status = status .. ',ssl=expired'
612       end
613     end
614
615     if good then check.good() else check.bad() end
616     check.status(status)
617 end
618
Note: See TracBrowser for help on using the browser.