PageRenderTime 69ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/service_scan.cc

https://github.com/prakashgamit/nmap
C++ | 2762 lines | 2181 code | 202 blank | 379 comment | 446 complexity | f7a696193f9f59efe543f5a3d3ba30bb MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, LGPL-2.0, LGPL-2.1
  1. /***************************************************************************
  2. * service_scan.cc -- Routines used for service fingerprinting to determine *
  3. * what application-level protocol is listening on a given port *
  4. * (e.g. snmp, http, ftp, smtp, etc.) *
  5. * *
  6. ***********************IMPORTANT NMAP LICENSE TERMS************************
  7. * *
  8. * The Nmap Security Scanner is (C) 1996-2013 Insecure.Com LLC. Nmap is *
  9. * also a registered trademark of Insecure.Com LLC. This program is free *
  10. * software; you may redistribute and/or modify it under the terms of the *
  11. * GNU General Public License as published by the Free Software *
  12. * Foundation; Version 2 ("GPL"), BUT ONLY WITH ALL OF THE CLARIFICATIONS *
  13. * AND EXCEPTIONS DESCRIBED HEREIN. This guarantees your right to use, *
  14. * modify, and redistribute this software under certain conditions. If *
  15. * you wish to embed Nmap technology into proprietary software, we sell *
  16. * alternative licenses (contact sales@nmap.com). Dozens of software *
  17. * vendors already license Nmap technology such as host discovery, port *
  18. * scanning, OS detection, version detection, and the Nmap Scripting *
  19. * Engine. *
  20. * *
  21. * Note that the GPL places important restrictions on "derivative works", *
  22. * yet it does not provide a detailed definition of that term. To avoid *
  23. * misunderstandings, we interpret that term as broadly as copyright law *
  24. * allows. For example, we consider an application to constitute a *
  25. * derivative work for the purpose of this license if it does any of the *
  26. * following with any software or content covered by this license *
  27. * ("Covered Software"): *
  28. * *
  29. * o Integrates source code from Covered Software. *
  30. * *
  31. * o Reads or includes copyrighted data files, such as Nmap's nmap-os-db *
  32. * or nmap-service-probes. *
  33. * *
  34. * o Is designed specifically to execute Covered Software and parse the *
  35. * results (as opposed to typical shell or execution-menu apps, which will *
  36. * execute anything you tell them to). *
  37. * *
  38. * o Includes Covered Software in a proprietary executable installer. The *
  39. * installers produced by InstallShield are an example of this. Including *
  40. * Nmap with other software in compressed or archival form does not *
  41. * trigger this provision, provided appropriate open source decompression *
  42. * or de-archiving software is widely available for no charge. For the *
  43. * purposes of this license, an installer is considered to include Covered *
  44. * Software even if it actually retrieves a copy of Covered Software from *
  45. * another source during runtime (such as by downloading it from the *
  46. * Internet). *
  47. * *
  48. * o Links (statically or dynamically) to a library which does any of the *
  49. * above. *
  50. * *
  51. * o Executes a helper program, module, or script to do any of the above. *
  52. * *
  53. * This list is not exclusive, but is meant to clarify our interpretation *
  54. * of derived works with some common examples. Other people may interpret *
  55. * the plain GPL differently, so we consider this a special exception to *
  56. * the GPL that we apply to Covered Software. Works which meet any of *
  57. * these conditions must conform to all of the terms of this license, *
  58. * particularly including the GPL Section 3 requirements of providing *
  59. * source code and allowing free redistribution of the work as a whole. *
  60. * *
  61. * As another special exception to the GPL terms, Insecure.Com LLC grants *
  62. * permission to link the code of this program with any version of the *
  63. * OpenSSL library which is distributed under a license identical to that *
  64. * listed in the included docs/licenses/OpenSSL.txt file, and distribute *
  65. * linked combinations including the two. *
  66. * *
  67. * Any redistribution of Covered Software, including any derived works, *
  68. * must obey and carry forward all of the terms of this license, including *
  69. * obeying all GPL rules and restrictions. For example, source code of *
  70. * the whole work must be provided and free redistribution must be *
  71. * allowed. All GPL references to "this License", are to be treated as *
  72. * including the terms and conditions of this license text as well. *
  73. * *
  74. * Because this license imposes special exceptions to the GPL, Covered *
  75. * Work may not be combined (even as part of a larger work) with plain GPL *
  76. * software. The terms, conditions, and exceptions of this license must *
  77. * be included as well. This license is incompatible with some other open *
  78. * source licenses as well. In some cases we can relicense portions of *
  79. * Nmap or grant special permissions to use it in other open source *
  80. * software. Please contact fyodor@nmap.org with any such requests. *
  81. * Similarly, we don't incorporate incompatible open source software into *
  82. * Covered Software without special permission from the copyright holders. *
  83. * *
  84. * If you have any questions about the licensing restrictions on using *
  85. * Nmap in other works, are happy to help. As mentioned above, we also *
  86. * offer alternative license to integrate Nmap into proprietary *
  87. * applications and appliances. These contracts have been sold to dozens *
  88. * of software vendors, and generally include a perpetual license as well *
  89. * as providing for priority support and updates. They also fund the *
  90. * continued development of Nmap. Please email sales@nmap.com for further *
  91. * information. *
  92. * *
  93. * If you have received a written license agreement or contract for *
  94. * Covered Software stating terms other than these, you may choose to use *
  95. * and redistribute Covered Software under those terms instead of these. *
  96. * *
  97. * Source is provided to this software because we believe users have a *
  98. * right to know exactly what a program is going to do before they run it. *
  99. * This also allows you to audit the software for security holes (none *
  100. * have been found so far). *
  101. * *
  102. * Source code also allows you to port Nmap to new platforms, fix bugs, *
  103. * and add new features. You are highly encouraged to send your changes *
  104. * to the dev@nmap.org mailing list for possible incorporation into the *
  105. * main distribution. By sending these changes to Fyodor or one of the *
  106. * Insecure.Org development mailing lists, or checking them into the Nmap *
  107. * source code repository, it is understood (unless you specify otherwise) *
  108. * that you are offering the Nmap Project (Insecure.Com LLC) the *
  109. * unlimited, non-exclusive right to reuse, modify, and relicense the *
  110. * code. Nmap will always be available Open Source, but this is important *
  111. * because the inability to relicense code has caused devastating problems *
  112. * for other Free Software projects (such as KDE and NASM). We also *
  113. * occasionally relicense the code to third parties as discussed above. *
  114. * If you wish to specify special license conditions of your *
  115. * contributions, just say so when you send them. *
  116. * *
  117. * This program is distributed in the hope that it will be useful, but *
  118. * WITHOUT ANY WARRANTY; without even the implied warranty of *
  119. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Nmap *
  120. * license file for more details (it's in a COPYING file included with *
  121. * Nmap, and also available from https://svn.nmap.org/nmap/COPYING *
  122. * *
  123. ***************************************************************************/
  124. /* $Id$ */
  125. #include "service_scan.h"
  126. #include "timing.h"
  127. #include "NmapOps.h"
  128. #include "nsock.h"
  129. #include "Target.h"
  130. #include "utils.h"
  131. #include "protocols.h"
  132. #include "nmap_tty.h"
  133. #if HAVE_OPENSSL
  134. /* OpenSSL 1.0.0 needs _WINSOCKAPI_ to be defined, otherwise it loads
  135. <windows.h> (through openssl/dtls1.h), which is incompatible with the
  136. <winsock2.h> that we use. (It creates errors with the redefinition of struct
  137. timeval, for example.) _WINSOCKAPI_ should be defined by our inclusion of
  138. <winsock2.h>, but it appears to be undefined somewhere, possibly in
  139. libpcap. */
  140. #define _WINSOCKAPI_
  141. #include <openssl/ssl.h>
  142. #endif
  143. #if TIME_WITH_SYS_TIME
  144. # include <sys/time.h>
  145. # include <time.h>
  146. #else
  147. # if HAVE_SYS_TIME_H
  148. # include <sys/time.h>
  149. # else
  150. # include <time.h>
  151. # endif
  152. #endif
  153. #include <algorithm>
  154. #include <list>
  155. extern NmapOps o;
  156. // Details on a particular service (open port) we are trying to match
  157. class ServiceNFO {
  158. public:
  159. ServiceNFO(AllProbes *AP);
  160. ~ServiceNFO();
  161. // If a service response to a given probeName, this function adds
  162. // the response the the fingerprint for that service. The
  163. // fingerprint can be printed when nothing matches the service. You
  164. // can obtain the fingerprint (if any) via getServiceFingerprint();
  165. void addToServiceFingerprint(const char *probeName, const u8 *resp,
  166. int resplen);
  167. // Get the service fingerprint. It is NULL if there is none, such
  168. // as if there was a match before any other probes were finished (or
  169. // if no probes gave back data). Note that this is plain
  170. // NUL-terminated ASCII data, although the length is optionally
  171. // available anyway. This function terminates the service fingerprint
  172. // with a semi-colon
  173. const char *getServiceFingerprint(int *flen);
  174. // Note that the next 2 members are for convenience and are not destroyed w/the ServiceNFO
  175. Target *target; // the port belongs to this target host
  176. // if a match is found, it is placed here. Otherwise NULL
  177. const char *probe_matched;
  178. // If a match is found, any product/version/info/hostname/ostype/devicetype
  179. // is placed in these 6 strings. Otherwise the string will be 0 length.
  180. char product_matched[80];
  181. char version_matched[80];
  182. char extrainfo_matched[256];
  183. char hostname_matched[80];
  184. char ostype_matched[32];
  185. char devicetype_matched[32];
  186. char cpe_a_matched[80];
  187. char cpe_h_matched[80];
  188. char cpe_o_matched[80];
  189. enum service_tunnel_type tunnel; /* SERVICE_TUNNEL_NONE, SERVICE_TUNNEL_SSL */
  190. // This stores our SSL session id, which will help speed up subsequent
  191. // SSL connections. It's overwritten each time. void* is used so we don't
  192. // need to #ifdef HAVE_OPENSSL all over. We'll cast later as needed.
  193. void *ssl_session;
  194. // if a match was found (see above), this tells whether it was a "soft"
  195. // or hard match. It is always false if no match has been found.
  196. bool softMatchFound;
  197. // most recent probe executed (or in progress). If there has been a match
  198. // (probe_matched != NULL), this will be the corresponding ServiceProbe.
  199. ServiceProbe *currentProbe();
  200. // computes the next probe to test, and ALSO CHANGES currentProbe() to
  201. // that! If newresp is true, the old response info will be lost and
  202. // invalidated. Otherwise it remains as if it had been received by
  203. // the current probe (useful after a NULL probe).
  204. ServiceProbe *nextProbe(bool newresp);
  205. // Resets the probes back to the first one. One case where this is useful is
  206. // when SSL is detected -- we redo all probes through SSL. If freeFP, any
  207. // service fingerprint is freed too.
  208. void resetProbes(bool freefp);
  209. // Number of milliseconds left to complete the present probe, or 0 if
  210. // the probe is already expired. Timeval can omitted, it is just there
  211. // as an optimization in case you have it handy.
  212. int probe_timemsleft(const ServiceProbe *probe, const struct timeval *now = NULL);
  213. enum serviceprobestate probe_state; // defined in portlist.h
  214. nsock_iod niod; // The IO Descriptor being used in this probe (or NULL)
  215. u16 portno; // in host byte order
  216. u8 proto; // IPPROTO_TCP or IPPROTO_UDP
  217. // The time that the current probe was executed (meaning TCP connection
  218. // made or first UDP packet sent
  219. struct timeval currentprobe_exec_time;
  220. // Append newly-received data to the current response string (if any)
  221. void appendtocurrentproberesponse(const u8 *respstr, int respstrlen);
  222. // Get the full current response string. Note that this pointer is
  223. // INVALIDATED if you call appendtocurrentproberesponse() or nextProbe()
  224. u8 *getcurrentproberesponse(int *respstrlen);
  225. AllProbes *AP;
  226. private:
  227. // Adds a character to servicefp. Takes care of word wrapping if
  228. // necessary at the given (wrapat) column. Chars will only be
  229. // written if there is enough space. Otherwise it exits.
  230. void addServiceChar(char c, int wrapat);
  231. // Like addServiceChar, but for a whole zero-terminated string
  232. void addServiceString(const char *s, int wrapat);
  233. std::vector<ServiceProbe *>::iterator current_probe;
  234. u8 *currentresp;
  235. int currentresplen;
  236. char *servicefp;
  237. int servicefplen;
  238. int servicefpalloc;
  239. };
  240. // This holds the service information for a group of Targets being service scanned.
  241. class ServiceGroup {
  242. public:
  243. ServiceGroup(std::vector<Target *> &Targets, AllProbes *AP);
  244. ~ServiceGroup();
  245. std::list<ServiceNFO *> services_finished; // Services finished (discovered or not)
  246. std::list<ServiceNFO *> services_in_progress; // Services currently being probed
  247. std::list<ServiceNFO *> services_remaining; // Probes not started yet
  248. unsigned int ideal_parallelism; // Max (and desired) number of probes out at once.
  249. ScanProgressMeter *SPM;
  250. int num_hosts_timedout; // # of hosts timed out during (or before) scan
  251. };
  252. #define SUBSTARGS_MAX_ARGS 5
  253. #define SUBSTARGS_STRLEN 128
  254. #define SUBSTARGS_ARGTYPE_NONE 0
  255. #define SUBSTARGS_ARGTYPE_STRING 1
  256. #define SUBSTARGS_ARGTYPE_INT 2
  257. struct substargs {
  258. int num_args; // Total number of arguments found
  259. char str_args[SUBSTARGS_MAX_ARGS][SUBSTARGS_STRLEN];
  260. // This is the length of each string arg, since they can contain zeros.
  261. // The str_args[] are zero-terminated for convenience in the cases where
  262. // you know they won't contain zero.
  263. int str_args_len[SUBSTARGS_MAX_ARGS];
  264. int int_args[SUBSTARGS_MAX_ARGS];
  265. // The type of each argument -- see #define's above.
  266. int arg_types[SUBSTARGS_MAX_ARGS];
  267. };
  268. /******************** PROTOTYPES *******************/
  269. static void servicescan_read_handler(nsock_pool nsp, nsock_event nse, void *mydata);
  270. static void servicescan_write_handler(nsock_pool nsp, nsock_event nse, void *mydata);
  271. static void servicescan_connect_handler(nsock_pool nsp, nsock_event nse, void *mydata);
  272. static void end_svcprobe(nsock_pool nsp, enum serviceprobestate probe_state, ServiceGroup *SG, ServiceNFO *svc, nsock_iod nsi);
  273. ServiceProbeMatch::ServiceProbeMatch() {
  274. deflineno = -1;
  275. servicename = NULL;
  276. matchstr = NULL;
  277. product_template = version_template = info_template = NULL;
  278. hostname_template = ostype_template = devicetype_template = NULL;
  279. regex_compiled = NULL;
  280. regex_extra = NULL;
  281. isInitialized = false;
  282. matchops_ignorecase = false;
  283. matchops_dotall = false;
  284. isSoft = false;
  285. }
  286. ServiceProbeMatch::~ServiceProbeMatch() {
  287. std::vector<char *>::iterator it;
  288. if (!isInitialized) return;
  289. if (servicename) free(servicename);
  290. if (matchstr) free(matchstr);
  291. if (product_template) free(product_template);
  292. if (version_template) free(version_template);
  293. if (info_template) free(info_template);
  294. if (hostname_template) free(hostname_template);
  295. if (ostype_template) free(ostype_template);
  296. if (devicetype_template) free(devicetype_template);
  297. for (it = cpe_templates.begin(); it != cpe_templates.end(); it++)
  298. free(*it);
  299. matchstrlen = 0;
  300. if (regex_compiled) pcre_free(regex_compiled);
  301. if (regex_extra) pcre_free(regex_extra);
  302. isInitialized = false;
  303. matchops_anchor = -1;
  304. }
  305. /* Realloc a malloc-allocated string and put a given prefix at the front. */
  306. static char *string_prefix(char *string, const char *prefix)
  307. {
  308. size_t slen, plen;
  309. slen = strlen(string);
  310. plen = strlen(prefix);
  311. string = (char *) safe_realloc(string, plen + slen + 1);
  312. memmove(string + plen, string, slen + 1);
  313. memmove(string, prefix, plen);
  314. return string;
  315. }
  316. /* Read the next tmplt from *matchtext and update *matchtext. Return true iff
  317. a template was read. For example, after
  318. matchtext = "p/123/ d/456/";
  319. next_template(&matchtext, &modestr, &flags, &tmplt);
  320. then
  321. matchtext == " d/456/"
  322. modestr == "p"
  323. tmplt == "123"
  324. flags == ""
  325. *modestr and *tmplt must be freed if the return value is true. */
  326. static bool next_template(const char **matchtext, char **modestr, char **tmplt,
  327. char **flags, int lineno) {
  328. const char *p, *q;
  329. char delimchar;
  330. p = *matchtext;
  331. while(isspace((int) (unsigned char) *p))
  332. p++;
  333. if (*p == '\0')
  334. return false;
  335. q = p;
  336. while (isalpha(*q) || *q == ':')
  337. q++;
  338. if (*q == '\0' || isspace(*q))
  339. fatal("%s: parse error on line %d of nmap-service-probes", __func__, lineno);
  340. *modestr = mkstr(p, q);
  341. delimchar = *q;
  342. p = q + 1;
  343. q = strchr(p, delimchar);
  344. if (q == NULL)
  345. fatal("%s: parse error on line %d of nmap-service-probes", __func__, lineno);
  346. *tmplt = mkstr(p, q);
  347. p = q + 1;
  348. q = p;
  349. while (isalpha(*q))
  350. q++;
  351. *flags = mkstr(p, q);
  352. /* Update pointer for caller. */
  353. *matchtext = q;
  354. return true;
  355. }
  356. // match text from the nmap-service-probes file. This must be called
  357. // before you try and do anything with this match. This function
  358. // should be passed the whole line starting with "match" or
  359. // "softmatch" in nmap-service-probes. The line number that the text
  360. // is provided so that it can be reported in error messages. This
  361. // function will abort the program if there is a syntax problem.
  362. void ServiceProbeMatch::InitMatch(const char *matchtext, int lineno) {
  363. const char *p;
  364. char *modestr, *tmptemplate, *flags;
  365. int pcre_compile_ops = 0;
  366. const char *pcre_errptr = NULL;
  367. int pcre_erroffset = 0;
  368. char **curr_tmp = NULL;
  369. if (isInitialized) fatal("Sorry ... %s does not yet support reinitializion", __func__);
  370. if (!matchtext || !*matchtext)
  371. fatal("%s: no matchtext passed in (line %d of nmap-service-probes)", __func__, lineno);
  372. isInitialized = true;
  373. deflineno = lineno;
  374. while(isspace((int) (unsigned char) *matchtext)) matchtext++;
  375. // first we find whether this is a "soft" or normal match
  376. if (strncmp(matchtext, "softmatch ", 10) == 0) {
  377. isSoft = true;
  378. matchtext += 10;
  379. } else if (strncmp(matchtext, "match ", 6) == 0) {
  380. isSoft = false;
  381. matchtext += 6;
  382. } else
  383. fatal("%s: parse error on line %d of nmap-service-probes - must begin with \"match\" or \"softmatch\"", __func__, lineno);
  384. // next comes the service name
  385. p = strchr(matchtext, ' ');
  386. if (!p) fatal("%s: parse error on line %d of nmap-service-probes: could not find service name", __func__, lineno);
  387. servicename = (char *) safe_malloc(p - matchtext + 1);
  388. memcpy(servicename, matchtext, p - matchtext);
  389. servicename[p - matchtext] = '\0';
  390. // The next part is a perl style regular expression specifier, like:
  391. // m/^220 .*smtp/i Where 'm' means a normal regular expressions is
  392. // used, the char after m can be anything (within reason, slash in
  393. // this case) and tells us what delieates the end of the regex.
  394. // After the delineating character are any single-character
  395. // options. ('i' means "case insensitive", 's' means that . matches
  396. // newlines (both are just as in perl)
  397. matchtext = p;
  398. if (!next_template(&matchtext, &modestr, &matchstr, &flags, lineno))
  399. fatal("%s: parse error on line %d of nmap-service-probes", __func__, lineno);
  400. if (strcmp(modestr, "m") != 0)
  401. fatal("%s: parse error on line %d of nmap-service-probes: matchtext must begin with 'm'", __func__, lineno);
  402. matchtype = SERVICEMATCH_REGEX;
  403. // any options?
  404. for (p = flags; *p != '\0'; p++) {
  405. if (*p == 'i')
  406. matchops_ignorecase = true;
  407. else if (*p == 's')
  408. matchops_dotall = true;
  409. else
  410. fatal("%s: illegal regexp option on line %d of nmap-service-probes", __func__, lineno);
  411. }
  412. // Next we compile and study the regular expression to match
  413. if (matchops_ignorecase)
  414. pcre_compile_ops |= PCRE_CASELESS;
  415. if (matchops_dotall)
  416. pcre_compile_ops |= PCRE_DOTALL;
  417. regex_compiled = pcre_compile(matchstr, pcre_compile_ops, &pcre_errptr,
  418. &pcre_erroffset, NULL);
  419. if (regex_compiled == NULL)
  420. fatal("%s: illegal regexp on line %d of nmap-service-probes (at regexp offset %d): %s\n", __func__, lineno, pcre_erroffset, pcre_errptr);
  421. // Now study the regexp for greater efficiency
  422. regex_extra = pcre_study(regex_compiled, 0, &pcre_errptr);
  423. if (pcre_errptr != NULL)
  424. fatal("%s: failed to pcre_study regexp on line %d of nmap-service-probes: %s\n", __func__, lineno, pcre_errptr);
  425. free(modestr);
  426. free(flags);
  427. /* OK! Now we look for any templates of the form ?/.../
  428. * where ? is either p, v, i, h, o, or d. / is any
  429. * delimiter character and ... is a template */
  430. while (next_template(&matchtext, &modestr, &tmptemplate, &flags, lineno)) {
  431. if (strcmp(modestr, "p") == 0)
  432. curr_tmp = &product_template;
  433. else if (strcmp(modestr, "v") == 0)
  434. curr_tmp = &version_template;
  435. else if (strcmp(modestr, "i") == 0)
  436. curr_tmp = &info_template;
  437. else if (strcmp(modestr, "h") == 0)
  438. curr_tmp = &hostname_template;
  439. else if (strcmp(modestr, "o") == 0)
  440. curr_tmp = &ostype_template;
  441. else if (strcmp(modestr, "d") == 0)
  442. curr_tmp = &devicetype_template;
  443. else if (strcmp(modestr, "cpe:") == 0) {
  444. tmptemplate = string_prefix(tmptemplate, "cpe:/");
  445. cpe_templates.push_back(NULL);
  446. curr_tmp = &cpe_templates.back();
  447. } else
  448. fatal("%s: Unknown template specifier '%s' on line %d of nmap-service-probes", __func__, modestr, lineno);
  449. /* This one already defined? */
  450. if (*curr_tmp) {
  451. if (o.debugging) {
  452. error("WARNING: Template \"%s/%s/\" replaced with \"%s/%s/\" on line %d of nmap-service-probes",
  453. modestr, *curr_tmp, modestr, tmptemplate, lineno);
  454. }
  455. free(*curr_tmp);
  456. }
  457. *curr_tmp = tmptemplate;
  458. free(modestr);
  459. free(flags);
  460. }
  461. isInitialized = 1;
  462. }
  463. // If the buf (of length buflen) match the regex in this
  464. // ServiceProbeMatch, returns the details of the match (service
  465. // name, version number if applicable, and whether this is a "soft"
  466. // match. If the buf doesn't match, the serviceName field in the
  467. // structure will be NULL. The MatchDetails sructure returned is
  468. // only valid until the next time this function is called. The only
  469. // exception is that the serviceName field can be saved throughought
  470. // program execution. If no version matched, that field will be
  471. // NULL.
  472. const struct MatchDetails *ServiceProbeMatch::testMatch(const u8 *buf, int buflen) {
  473. int rc;
  474. static char product[80];
  475. static char version[80];
  476. static char info[256]; /* We will truncate with ... later */
  477. static char hostname[80];
  478. static char ostype[32];
  479. static char devicetype[32];
  480. static char cpe_a[80], cpe_h[80], cpe_o[80];
  481. char *bufc = (char *) buf;
  482. int ovector[150]; // allows 50 substring matches (including the overall match)
  483. assert(isInitialized);
  484. assert (matchtype == SERVICEMATCH_REGEX);
  485. // Clear out the output struct
  486. memset(&MD_return, 0, sizeof(MD_return));
  487. MD_return.isSoft = isSoft;
  488. rc = pcre_exec(regex_compiled, regex_extra, bufc, buflen, 0, 0, ovector, sizeof(ovector) / sizeof(*ovector));
  489. if (rc < 0) {
  490. #ifdef PCRE_ERROR_MATCHLIMIT // earlier PCRE versions lack this
  491. if (rc == PCRE_ERROR_MATCHLIMIT) {
  492. if (o.debugging || o.verbose > 1)
  493. error("Warning: Hit PCRE_ERROR_MATCHLIMIT when probing for service %s with the regex '%s'", servicename, matchstr);
  494. } else
  495. #endif // PCRE_ERROR_MATCHLIMIT
  496. if (rc != PCRE_ERROR_NOMATCH) {
  497. fatal("Unexpected PCRE error (%d) when probing for service %s with the regex '%s'", rc, servicename, matchstr);
  498. }
  499. } else {
  500. // Yeah! Match apparently succeeded.
  501. // Now lets get the version number if available
  502. getVersionStr(buf, buflen, ovector, rc, product, sizeof(product), version, sizeof(version), info, sizeof(info),
  503. hostname, sizeof(hostname), ostype, sizeof(ostype), devicetype, sizeof(devicetype),
  504. cpe_a, sizeof(cpe_a), cpe_h, sizeof(cpe_h), cpe_o, sizeof(cpe_o));
  505. if (*product) MD_return.product = product;
  506. if (*version) MD_return.version = version;
  507. if (*info) MD_return.info = info;
  508. if (*hostname) MD_return.hostname = hostname;
  509. if (*ostype) MD_return.ostype = ostype;
  510. if (*devicetype) MD_return.devicetype = devicetype;
  511. if (*cpe_a) MD_return.cpe_a = cpe_a;
  512. if (*cpe_h) MD_return.cpe_h = cpe_h;
  513. if (*cpe_o) MD_return.cpe_o = cpe_o;
  514. MD_return.serviceName = servicename;
  515. MD_return.lineno = getLineNo();
  516. }
  517. return &MD_return;
  518. }
  519. // This simple function parses arguments out of a string. The string
  520. // starts with the first argument. Each argument can be a string or
  521. // an integer. Strings must be enclosed in double quotes (""). Most
  522. // standard C-style escapes are supported. If this is successful, the
  523. // number of args found is returned, args is filled appropriately, and
  524. // args_end (if non-null) is set to the character after the closing
  525. // ')'. Otherwise we return -1 and the values of args and args_end
  526. // are undefined.
  527. static int getsubstcommandargs(struct substargs *args, char *args_start,
  528. char **args_end) {
  529. char *p;
  530. unsigned int len;
  531. if (!args || !args_start) return -1;
  532. memset(args, 0, sizeof(*args));
  533. while(*args_start && *args_start != ')') {
  534. // Find the next argument.
  535. while(isspace((int) (unsigned char) *args_start)) args_start++;
  536. if (*args_start == ')')
  537. break;
  538. else if (*args_start == '"') {
  539. // OK - it is a string
  540. // Do we have space for another arg?
  541. if (args->num_args == SUBSTARGS_MAX_ARGS)
  542. return -1;
  543. do {
  544. args_start++;
  545. if (*args_start == '"' && (*(args_start - 1) != '\\' || *(args_start - 2) == '\\'))
  546. break;
  547. len = args->str_args_len[args->num_args];
  548. if (len >= SUBSTARGS_STRLEN - 1)
  549. return -1;
  550. args->str_args[args->num_args][len] = *args_start;
  551. args->str_args_len[args->num_args]++;
  552. } while(*args_start);
  553. len = args->str_args_len[args->num_args];
  554. args->str_args[args->num_args][len] = '\0';
  555. // Now handle escaped characters and such
  556. if (!cstring_unescape(args->str_args[args->num_args], &len))
  557. return -1;
  558. args->str_args_len[args->num_args] = len;
  559. args->arg_types[args->num_args] = SUBSTARGS_ARGTYPE_STRING;
  560. args->num_args++;
  561. args_start++;
  562. args_start = strpbrk(args_start, ",)");
  563. if (!args_start) return -1;
  564. if (*args_start == ',') args_start++;
  565. } else {
  566. // Must be an integer argument
  567. args->int_args[args->num_args] = (int) strtol(args_start, &p, 0);
  568. if (p <= args_start) return -1;
  569. args_start = p;
  570. args->arg_types[args->num_args] = SUBSTARGS_ARGTYPE_INT;
  571. args->num_args++;
  572. args_start = strpbrk(args_start, ",)");
  573. if (!args_start) return -1;
  574. if (*args_start == ',') args_start++;
  575. }
  576. }
  577. if (*args_start == ')') args_start++;
  578. if (args_end) *args_end = args_start;
  579. return args->num_args;
  580. }
  581. /* These three functions manage a growing string buffer, appended to at the end.
  582. Begin with strbuf_init, follow with any number of strbuf_append, and end with
  583. strbuf_finish. */
  584. static void strbuf_init(char **buf, size_t *n, size_t *len) {
  585. *buf = NULL;
  586. *n = 0;
  587. *len = 0;
  588. }
  589. static void strbuf_append(char **buf, size_t *n, size_t *len,
  590. const char *from, size_t fromlen) {
  591. /* Double the size of the buffer if necessary. */
  592. if (*len == 0 || *len + fromlen > *n) {
  593. *n = (*len + fromlen) * 2;
  594. *buf = (char *) safe_realloc(*buf, *n + 1);
  595. }
  596. memcpy(*buf + *len, from, fromlen);
  597. *len += fromlen;
  598. }
  599. /* Trim to length. (Also does initial allocation when *buf is empty.) */
  600. static void strbuf_finish(char **buf, size_t *n, size_t *len) {
  601. *buf = (char *) safe_realloc(*buf, *len + 1);
  602. (*buf)[*len] = '\0';
  603. }
  604. /* Transform a string so that it is safe to insert into the middle of a CPE URL. */
  605. static char *transform_cpe(const char *s) {
  606. char *result;
  607. size_t n, len, repllen;
  608. const char *p;
  609. strbuf_init(&result, &n, &len);
  610. for (p = s; *p != '\0'; p++) {
  611. const char *repl;
  612. char buf[32];
  613. /* Section 5.4 of the CPE specification lists these characters to be
  614. escaped. */
  615. if (strchr(":/?#[]@!$&'()*+,;=%<>\"", *p) != NULL) {
  616. Snprintf(buf, sizeof(buf), "%%%02X", *p);
  617. repl = buf;
  618. /* Replacing spaces with underscores is also a convention. */
  619. } else if (*p == ' ') {
  620. repl = "_";
  621. /* Otherwise just make lower-case. */
  622. } else {
  623. buf[0] = tolower(*p);
  624. buf[1] = '\0';
  625. repl = buf;
  626. }
  627. repllen = strlen(repl);
  628. strbuf_append(&result, &n, &len, repl, repllen);
  629. }
  630. strbuf_finish(&result, &n, &len);
  631. return result;
  632. }
  633. // This function does the substitution of a placeholder like $2 or $P(4). It
  634. // returns a newly allocated string, or NULL if it fails. tmplvar is a template
  635. // variable, such as "$P(2)". We set *tmplvarend to the character after the
  636. // variable. subject, subjectlen, ovector, and nummatches mean the same as in
  637. // dotmplsubst().
  638. static char *substvar(char *tmplvar, char **tmplvarend,
  639. const u8 *subject, int subjectlen, int *ovector,
  640. int nummatches) {
  641. char substcommand[16];
  642. char *p = NULL;
  643. char *p_end;
  644. int subnum = 0;
  645. int offstart, offend;
  646. int rc;
  647. int i;
  648. struct substargs command_args;
  649. char *result;
  650. size_t n, len;
  651. // skip the '$'
  652. if (*tmplvar != '$') return NULL;
  653. tmplvar++;
  654. if (!isdigit((int) (unsigned char) *tmplvar)) {
  655. int commandlen;
  656. /* This is a command like $P(1). */
  657. p = strchr(tmplvar, '(');
  658. if (!p) return NULL;
  659. commandlen = p - tmplvar;
  660. if (!commandlen || commandlen >= (int) sizeof(substcommand))
  661. return NULL;
  662. memcpy(substcommand, tmplvar, commandlen);
  663. substcommand[commandlen] = '\0';
  664. tmplvar = p+1;
  665. // Now we grab the arguments.
  666. rc = getsubstcommandargs(&command_args, tmplvar, &p_end);
  667. if (rc <= 0) return NULL;
  668. tmplvar = p_end;
  669. } else {
  670. /* This is a placeholder like $2. */
  671. substcommand[0] = '\0';
  672. subnum = *tmplvar - '0';
  673. tmplvar++;
  674. }
  675. if (tmplvarend) *tmplvarend = tmplvar;
  676. strbuf_init(&result, &n, &len);
  677. if (!*substcommand) {
  678. /* Handler for a placeholder like $2. */
  679. if (subnum > 9 || subnum <= 0) return NULL;
  680. if (subnum >= nummatches) return NULL;
  681. offstart = ovector[subnum * 2];
  682. offend = ovector[subnum * 2 + 1];
  683. assert(offstart >= 0 && offstart < subjectlen);
  684. assert(offend >= 0 && offend <= subjectlen);
  685. // A plain-jane copy
  686. strbuf_append(&result, &n, &len, (const char *) subject + offstart, offend - offstart);
  687. } else if (strcmp(substcommand, "P") == 0) {
  688. if (command_args.num_args != 1 ||
  689. command_args.arg_types[0] != SUBSTARGS_ARGTYPE_INT) {
  690. return NULL;
  691. }
  692. subnum = command_args.int_args[0];
  693. if (subnum > 9 || subnum <= 0) return NULL;
  694. if (subnum >= nummatches) return NULL;
  695. offstart = ovector[subnum * 2];
  696. offend = ovector[subnum * 2 + 1];
  697. assert(offstart >= 0 && offstart < subjectlen);
  698. assert(offend >= 0 && offend <= subjectlen);
  699. // This filter only includes printable characters. It is particularly
  700. // useful for collapsing unicode text that looks like
  701. // "W\0O\0R\0K\0G\0R\0O\0U\0P\0"
  702. for(i=offstart; i < offend; i++) {
  703. if (isprint((int) subject[i]))
  704. strbuf_append(&result, &n, &len, (const char *) subject + i, 1);
  705. }
  706. } else if (strcmp(substcommand, "SUBST") == 0) {
  707. char *findstr, *replstr;
  708. int findstrlen, replstrlen;
  709. if (command_args.num_args != 3 ||
  710. command_args.arg_types[0] != SUBSTARGS_ARGTYPE_INT ||
  711. command_args.arg_types[1] != SUBSTARGS_ARGTYPE_STRING ||
  712. command_args.arg_types[2] != SUBSTARGS_ARGTYPE_STRING) {
  713. return NULL;
  714. }
  715. subnum = command_args.int_args[0];
  716. if (subnum > 9 || subnum <= 0) return NULL;
  717. if (subnum >= nummatches) return NULL;
  718. offstart = ovector[subnum * 2];
  719. offend = ovector[subnum * 2 + 1];
  720. assert(offstart >= 0 && offstart < subjectlen);
  721. assert(offend >= 0 && offend <= subjectlen);
  722. findstr = command_args.str_args[1];
  723. findstrlen = command_args.str_args_len[1];
  724. replstr = command_args.str_args[2];
  725. replstrlen = command_args.str_args_len[2];
  726. for(i=offstart; i < offend; ) {
  727. if (memcmp(subject + i, findstr, findstrlen) != 0) {
  728. strbuf_append(&result, &n, &len, (const char *) subject + i, 1); // no match
  729. i++;
  730. } else {
  731. // The find string was found, copy it to newstring
  732. strbuf_append(&result, &n, &len, replstr, replstrlen);
  733. i += findstrlen;
  734. }
  735. }
  736. } else return NULL; // Unknown command
  737. strbuf_finish(&result, &n, &len);
  738. return result;
  739. }
  740. // This function takes a template string (tmpl) which can have
  741. // placeholders in it such as $1 for substring matches in a regexp
  742. // that was run against subject, and subjectlen, with the 'nummatches'
  743. // matches in ovector. The NUL-terminated newly composted string is
  744. // placed into 'newstr', as long as it doesn't exceed 'newstrlen'
  745. // bytes. Trailing whitespace and commas are removed. Returns zero for success
  746. //
  747. // The transform argument is a function pointer. If not NULL, the given
  748. // function is applied to all substitutions before they are inserted
  749. // into the result string.
  750. static int dotmplsubst(const u8 *subject, int subjectlen,
  751. int *ovector, int nummatches, char *tmpl, char *newstr,
  752. int newstrlen,
  753. char *(*transform)(const char *) = NULL) {
  754. int newlen;
  755. char *srcstart=tmpl, *srcend;
  756. char *dst = newstr;
  757. char *newstrend = newstr + newstrlen; // Right after the final char
  758. char *subst;
  759. if (!newstr || !tmpl) return -1;
  760. if (newstrlen < 3) return -1; // fuck this!
  761. while(*srcstart) {
  762. // First do any literal text before '$'
  763. srcend = strchr(srcstart, '$');
  764. if (!srcend) {
  765. // Only literal text remain!
  766. while(*srcstart) {
  767. if (dst >= newstrend - 1)
  768. return -1;
  769. *dst++ = *srcstart++;
  770. }
  771. *dst = '\0';
  772. while (--dst >= newstr) {
  773. if (isspace((int) (unsigned char) *dst) || *dst == ',')
  774. *dst = '\0';
  775. else break;
  776. }
  777. return 0;
  778. } else {
  779. // Copy the literal text up to the '$', then do the substitution
  780. newlen = srcend - srcstart;
  781. if (newlen > 0) {
  782. if (newstrend - dst <= newlen - 1)
  783. return -1;
  784. memcpy(dst, srcstart, newlen);
  785. dst += newlen;
  786. }
  787. srcstart = srcend;
  788. subst = substvar(srcstart, &srcend, subject, subjectlen, ovector, nummatches);
  789. if (subst == NULL)
  790. return -1;
  791. /* Apply transformation if requested. */
  792. if (transform != NULL) {
  793. char *tmp = subst;
  794. subst = transform(subst);
  795. free(tmp);
  796. if (subst == NULL)
  797. return -1;
  798. }
  799. newlen = strlen(subst);
  800. if (dst + newlen >= newstrend - 1) {
  801. free(subst);
  802. return -1;
  803. }
  804. memcpy(dst, subst, newlen);
  805. free(subst);
  806. dst += newlen;
  807. srcstart = srcend;
  808. }
  809. }
  810. if (dst >= newstrend - 1)
  811. return -1;
  812. *dst = '\0';
  813. while (--dst >= newstr) {
  814. if (isspace((int) (unsigned char) *dst) || *dst == ',')
  815. *dst = '\0';
  816. else break;
  817. }
  818. return 0;
  819. }
  820. // Use the version templates and the match data included here
  821. // to put the version info into the given strings, (as long as the sizes
  822. // are sufficient). Returns zero for success. If no template is available
  823. // for a string, that string will have zero length after the function
  824. // call (assuming the corresponding length passed in is at least 1)
  825. int ServiceProbeMatch::getVersionStr(const u8 *subject, int subjectlen,
  826. int *ovector, int nummatches, char *product, int productlen,
  827. char *version, int versionlen, char *info, int infolen,
  828. char *hostname, int hostnamelen, char *ostype, int ostypelen,
  829. char *devicetype, int devicetypelen,
  830. char *cpe_a, int cpe_alen,
  831. char *cpe_h, int cpe_hlen,
  832. char *cpe_o, int cpe_olen) {
  833. int rc;
  834. assert(productlen >= 0 && versionlen >= 0 && infolen >= 0 &&
  835. hostnamelen >= 0 && ostypelen >= 0 && devicetypelen >= 0);
  836. if (productlen > 0) *product = '\0';
  837. if (versionlen > 0) *version = '\0';
  838. if (infolen > 0) *info = '\0';
  839. if (hostnamelen > 0) *hostname = '\0';
  840. if (ostypelen > 0) *ostype = '\0';
  841. if (devicetypelen > 0) *devicetype = '\0';
  842. if (cpe_alen > 0) *cpe_a = '\0';
  843. if (cpe_hlen > 0) *cpe_h = '\0';
  844. if (cpe_olen > 0) *cpe_o = '\0';
  845. int retval = 0;
  846. // Now lets get this started! We begin with the product name
  847. if (product_template) {
  848. rc = dotmplsubst(subject, subjectlen, ovector, nummatches, product_template, product, productlen);
  849. if (rc != 0) {
  850. error("Warning: Servicescan failed to fill product_template (subjectlen: %d, productlen: %d). Capture exceeds length? Match string was line %d: p/%s/%s/%s", subjectlen, productlen, deflineno,
  851. (product_template)? product_template : "",
  852. (version_template)? version_template : "",
  853. (info_template)? info_template : "");
  854. if (productlen > 0) *product = '\0';
  855. retval = -1;
  856. }
  857. }
  858. if (version_template) {
  859. rc = dotmplsubst(subject, subjectlen, ovector, nummatches, version_template, version, versionlen);
  860. if (rc != 0) {
  861. error("Warning: Servicescan failed to fill version_template (subjectlen: %d, versionlen: %d). Capture exceeds length? Match string was line %d: v/%s/%s/%s", subjectlen, versionlen, deflineno,
  862. (product_template)? product_template : "",
  863. (version_template)? version_template : "",
  864. (info_template)? info_template : "");
  865. if (versionlen > 0) *version = '\0';
  866. retval = -1;
  867. }
  868. }
  869. if (info_template) {
  870. rc = dotmplsubst(subject, subjectlen, ovector, nummatches, info_template, info, infolen);
  871. if (rc != 0) {
  872. error("Warning: Servicescan failed to fill info_template (subjectlen: %d, infolen: %d). Capture exceeds length? Match string was line %d: i/%s/%s/%s", subjectlen, infolen, deflineno,
  873. (product_template)? product_template : "",
  874. (version_template)? version_template : "",
  875. (info_template)? info_template : "");
  876. if (infolen > 0) *info = '\0';
  877. retval = -1;
  878. }
  879. }
  880. if (hostname_template) {
  881. rc = dotmplsubst(subject, subjectlen, ovector, nummatches, hostname_template, hostname, hostnamelen);
  882. if (rc != 0) {
  883. error("Warning: Servicescan failed to fill hostname_template (subjectlen: %d, hostnamelen: %d). Capture exceeds length? Match string was line %d: h/%s/", subjectlen, hostnamelen, deflineno,
  884. (hostname_template)? hostname_template : "");
  885. if (hostnamelen > 0) *hostname = '\0';
  886. retval = -1;
  887. }
  888. }
  889. if (ostype_template) {
  890. rc = dotmplsubst(subject, subjectlen, ovector, nummatches, ostype_template, ostype, ostypelen);
  891. if (rc != 0) {
  892. error("Warning: Servicescan failed to fill ostype_template (subjectlen: %d, ostypelen: %d). Capture exceeds length? Match string was line %d: o/%s/", subjectlen, ostypelen, deflineno,
  893. (ostype_template)? ostype_template : "");
  894. if (ostypelen > 0) *ostype = '\0';
  895. retval = -1;
  896. }
  897. }
  898. if (devicetype_template) {
  899. rc = dotmplsubst(subject, subjectlen, ovector, nummatches, devicetype_template, devicetype, devicetypelen);
  900. if (rc != 0) {
  901. error("Warning: Servicescan failed to fill devicetype_template (subjectlen: %d, devicetypelen: %d). Too long? Match string was line %d: d/%s/", subjectlen, devicetypelen, deflineno,
  902. (devicetype_template)? devicetype_template : "");
  903. if (devicetypelen > 0) *devicetype = '\0';
  904. retval = -1;
  905. }
  906. }
  907. /* There may be multiple cpe templates. We peek at the first character and
  908. store in cpe_a, cpe_h, or cpe_o as appropriate. */
  909. for (unsigned int i = 0; i < cpe_templates.size(); i++) {
  910. char *cpe;
  911. int cpelen;
  912. int part;
  913. part = cpe_get_part(cpe_templates[i]);
  914. switch (part) {
  915. case 'a':
  916. cpe = cpe_a;
  917. cpelen = cpe_alen;
  918. break;
  919. case 'h':
  920. cpe = cpe_h;
  921. cpelen = cpe_hlen;
  922. break;
  923. case 'o':
  924. cpe = cpe_o;
  925. cpelen = cpe_olen;
  926. break;
  927. default:
  928. error("Warning: ignoring cpe:// template with unknown part '%c' (0x%02X)",
  929. isprint(part) ? part : '.', part);
  930. continue;
  931. break;
  932. }
  933. rc = dotmplsubst(subject, subjectlen, ovector, nummatches, cpe_templates[i], cpe, cpelen, transform_cpe);
  934. if (rc != 0) {
  935. error("Warning: Servicescan failed to fill cpe_%c (subjectlen: %d, devicetypelen: %d). Too long? Match string was line %d: d/%s/", part, subjectlen, devicetypelen, deflineno,
  936. (devicetype_template)? devicetype_template : "");
  937. if (devicetypelen > 0) *devicetype = '\0';
  938. retval = -1;
  939. }
  940. }
  941. return retval;
  942. }
  943. ServiceProbe::ServiceProbe() {
  944. int i;
  945. probename = NULL;
  946. probestring = NULL;
  947. totalwaitms = DEFAULT_SERVICEWAITMS;
  948. probestringlen = 0; probeprotocol = -1;
  949. // The default rarity level for a probe without a rarity
  950. // directive - should almost never have to be relied upon.
  951. rarity = 5;
  952. fallbackStr = NULL;
  953. for (i=0; i<MAXFALLBACKS+1; i++) fallbacks[i] = NULL;
  954. }
  955. ServiceProbe::~ServiceProbe() {
  956. std::vector<ServiceProbeMatch *>::iterator vi;
  957. if (probename) free(probename);
  958. if (probestring) free(probestring);
  959. for(vi = matches.begin(); vi != matches.end(); vi++) {
  960. delete *vi;
  961. }
  962. if (fallbackStr) free(fallbackStr);
  963. }
  964. // Parses the "probe " line in the nmap-service-probes file. Pass the rest of the line
  965. // after "probe ". The format better be:
  966. // [TCP|UDP] [probename] q|probetext|
  967. // Note that the delimiter (|) of the probetext can be anything (within reason)
  968. // the lineno is requested because this function will bail with an error
  969. // (giving the line number) if it fails to parse the string.
  970. void ServiceProbe::setProbeDetails(char *pd, int lineno) {
  971. char *p;
  972. unsigned int len;
  973. char delimiter;
  974. if (!pd || !*pd)
  975. fatal("Parse error on line %d of nmap-service-probes: no arguments found!", lineno);
  976. // First the protocol
  977. if (strncmp(pd, "TCP ", 4) == 0)
  978. probeprotocol = IPPROTO_TCP;
  979. else if (strncmp(pd, "UDP ", 4) == 0)
  980. probeprotocol = IPPROTO_UDP;
  981. else fatal("Parse error on line %d of nmap-service-probes: invalid protocol", lineno);
  982. pd += 4;
  983. // Next the service name
  984. if (!isalnum((int) (unsigned char) *pd)) fatal("Parse error on line %d of nmap-service-probes - bad probe name", lineno);
  985. p = strchr(pd, ' ');
  986. if (!p) fatal("Parse error on line %d of nmap-service-probes - nothing after probe name", lineno);
  987. len = p - pd;
  988. probename = (char *) safe_malloc(len + 1);
  989. memcpy(probename, pd, len);
  990. probename[len] = '\0';
  991. // Now for the probe itself
  992. pd = p+1;
  993. if (*pd != 'q') fatal("Parse error on line %d of nmap-service-probes - probe string must begin with 'q'", lineno);
  994. delimiter = *(++pd);
  995. p = strchr(++pd, delimiter);
  996. if (!p) fatal("Parse error on line %d of nmap-service-probes -- no ending delimiter for probe string", lineno);
  997. *p = '\0';
  998. if (!cstring_unescape(pd, &len)) {
  999. fatal("Parse error on line %d of nmap-service-probes: bad probe string escaping", lineno);
  1000. }
  1001. setProbeString((const u8 *)pd, len);
  1002. }
  1003. void ServiceProbe::setProbeString(const u8 *ps, int stringlen) {
  1004. if (probestringlen) free(probestring);
  1005. probestringlen = stringlen;
  1006. if (stringlen > 0) {
  1007. probestring = (u8 *) safe_malloc(stringlen + 1);
  1008. memcpy(probestring, ps, stringlen);
  1009. probestring[stringlen] = '\0'; // but note that other \0 may be in string
  1010. } else probestring = NULL;
  1011. }
  1012. void ServiceProbe::setPortVector(std::vector<u16> *portv, const char *portstr,
  1013. int lineno) {
  1014. const char *current_range;
  1015. char *endptr;
  1016. long int rangestart = 0, rangeend = 0;
  1017. current_range = portstr;
  1018. do {
  1019. while(*current_range && isspace((int) (unsigned char) *current_range)) current_range++;
  1020. if (isdigit((int) (unsigned char) *current_range)) {
  1021. rangestart = strtol(current_range, &endptr, 10);
  1022. if (rangestart < 0 || rangestart > 65535) {
  1023. fatal("Parse error on line %d of nmap-service-probes: Ports must be between 0 and 65535 inclusive", lineno);
  1024. }
  1025. current_range = endptr;
  1026. while(isspace((int) (unsigned char) *current_range)) current_range++;
  1027. } else {
  1028. fatal("Parse error on line %d of nmap-service-probes: An example of proper portlist form is \"21-25,53,80\"", lineno);
  1029. }
  1030. /* Now I have a rangestart, time to go after rangeend */
  1031. if (!*current_range || *current_range == ',') {
  1032. /* Single port specification */
  1033. rangeend = rangestart;
  1034. } else if (*current_range == '-') {
  1035. current_range++;
  1036. if (isdigit((int) (unsigned char) *current_range)) {
  1037. rangeend = strtol(current_range, &endptr, 10);
  1038. if (rangeend < 0 || rangeend > 65535 || rangeend < rangestart) {
  1039. fatal("Parse error on line %d of nmap-service-probes: Ports must be between 0 and 65535 inclusive", lineno);
  1040. }
  1041. current_range = endptr;
  1042. } else {
  1043. fatal("Parse error on line %d of nmap-service-probes: An example of proper portlist form is \"21-25,53,80\"", lineno);
  1044. }
  1045. } else {
  1046. fatal("Parse error on line %d of nmap-service-probes: An example of proper portlist form is \"21-25,53,80\"", lineno);
  1047. }
  1048. /* Now I have a rangestart and a rangeend, so I can add these ports */
  1049. while(rangestart <= rangeend) {
  1050. portv->push_back(rangestart);
  1051. rangestart++;
  1052. }
  1053. /* Find the next range */
  1054. while(isspace((int) (unsigned char) *current_range)) current_range++;
  1055. if (*current_range && *current_range != ',') {
  1056. fatal("Parse error on line %d of nmap-service-probes: An example of proper portlist form is \"21-25,53,80\"", lineno);
  1057. }
  1058. if (*current_range == ',')
  1059. current_range++;
  1060. } while(current_range && *current_range);
  1061. }
  1062. // Takes a string as given in the 'ports '/'sslports ' line of
  1063. // nmap-service-probes. Pass in the list from the appropriate
  1064. // line. For 'sslports', tunnel should be specified as
  1065. // SERVICE_TUNNEL_SSL. Otherwise use SERVICE_TUNNEL_NONE. The line
  1066. // number is requested because this function will bail with an error
  1067. // (giving the line number) if it fails to parse the string. Ports
  1068. // are a comma separated list of ports and ranges
  1069. // (e.g. 53,80,6000-6010).
  1070. void ServiceProbe::setProbablePorts(enum service_tunnel_type tunnel,
  1071. const char *portstr, int lineno) {
  1072. if (tunnel == SERVICE_TUNNEL_NONE)
  1073. setPortVector(&probableports, portstr, lineno);
  1074. else {
  1075. assert(tunnel == SERVICE_TUNNEL_SSL);
  1076. setPortVector(&probablesslports, portstr, lineno);
  1077. }
  1078. }
  1079. /* Returns true if the passed in port is on the list of probable
  1080. ports for this probe and tunnel type. Use a tunnel of
  1081. SERVICE_TUNNEL_SSL or SERVICE_TUNNEL_NONE as appropriate */
  1082. bool ServiceProbe::portIsProbable(enum service_tunnel_type tunnel, u16 portno) {
  1083. std::vector<u16> *portv;
  1084. portv = (tunnel == SERVICE_TUNNEL_SSL)? &probablesslports : &probableports;
  1085. if (find(portv->begin(), portv->end(), portno) == portv->end())
  1086. return false;
  1087. return true;
  1088. }
  1089. // Returns true if the passed in service name is among those that can
  1090. // be detected by the matches in this probe;
  1091. bool ServiceProbe::serviceIsPossible(const char *sname) {
  1092. std::vector<const char *>::iterator vi;
  1093. for(vi = detectedServices.begin(); vi != detectedServices.end(); vi++) {
  1094. if (strcmp(*vi, sname) == 0)
  1095. return true;
  1096. }
  1097. return false;
  1098. }
  1099. // Takes a string following a Rarity directive in the probes file.
  1100. // The string should contain a single integer between 1 and 9. The
  1101. // default rarity is 5. This function will bail if the string is invalid.
  1102. void ServiceProbe::setRarity(const char *portstr, int lineno) {
  1103. int tp;
  1104. tp = atoi(portstr);
  1105. if (tp < 1 || tp > 9)
  1106. fatal("%s: Rarity directive on line %d of nmap-service-probes must be between 1 and 9", __func__, lineno);
  1107. rarity = tp;
  1108. }
  1109. // Takes a match line in a probe description and adds it to the
  1110. // list of matches for this probe. This function should be passed
  1111. // the whole line starting with "match" or "softmatch" in
  1112. // nmap-service-probes. The line number is requested because this
  1113. // function will bail with an error (giving the line number) if it
  1114. // fails to parse the string.
  1115. void ServiceProbe::addMatch(const char *match, int lineno) {
  1116. const char *sname;
  1117. ServiceProbeMatch *newmatch = new ServiceProbeMatch();
  1118. newmatch->InitMatch(match, lineno);
  1119. sname = newmatch->getName();
  1120. if (!serviceIsPossible(sname))
  1121. detectedServices.push_back(sname);
  1122. matches.push_back(newmatch);
  1123. }
  1124. /* Parses the given nmap-service-probes file into the AP class Must
  1125. NOT be made static because I have external maintenance tools
  1126. (servicematch) which use this */
  1127. void parse_nmap_service_probe_file(AllProbes *AP, char *filename) {
  1128. ServiceProbe *newProbe = NULL;
  1129. char line[2048];
  1130. int lineno = 0;
  1131. FILE *fp;
  1132. // We better start by opening the file
  1133. fp = fopen(filename, "r");
  1134. if (!fp)
  1135. fatal("Failed to open nmap-service-probes file %s for reading", filename);
  1136. while(fgets(line, sizeof(line), fp)) {
  1137. lineno++;
  1138. if (*line == '\n' || *line == '#')
  1139. continue;
  1140. if (strncmp(line, "Exclude ", 8) == 0) {
  1141. if (AP->excluded_seen)
  1142. fatal("Only 1 Exclude directive is allowed in the nmap-service-probes file");
  1143. getpts(line+8, &AP->excludedports);
  1144. AP->excluded_seen = true;
  1145. continue;
  1146. }
  1147. anotherprobe:
  1148. if (strncmp(line, "Probe ", 6) != 0)
  1149. fatal("Parse error on line %d of nmap-service-probes file: %s -- line was expected to begin with \"Probe \" or \"Exclude \"", lineno, filename);
  1150. newProbe = new ServiceProbe();
  1151. newProbe->setProbeDetails(line + 6, lineno);
  1152. // Now we read the rest of the probe info
  1153. while(fgets(line, sizeof(line), fp)) {
  1154. lineno++;
  1155. if (*line == '\n' || *line == '#')
  1156. continue;
  1157. if (strncmp(line, "Probe ", 6) == 0) {
  1158. if (newProbe->isNullProbe()) {
  1159. assert(!AP->nullProbe);
  1160. AP->nullProbe = newProbe;
  1161. } else {
  1162. AP->probes.push_back(newProbe);
  1163. }
  1164. goto anotherprobe;
  1165. } else if (strncmp(line, "ports ", 6) == 0) {
  1166. newProbe->setProbablePorts(SERVICE_TUNNEL_NONE, line + 6, lineno);
  1167. } else if (strncmp(line, "sslports ", 9) == 0) {
  1168. newProbe->setProbablePorts(SERVICE_TUNNEL_SSL, line + 9, lineno);
  1169. } else if (strncmp(line, "rarity ", 7) == 0) {
  1170. newProbe->setRarity(line + 7, lineno);
  1171. } else if (strncmp(line, "fallback ", 9) == 0) {
  1172. newProbe->fallbackStr = strdup(line + 9);
  1173. } else if (strncmp(line, "totalwaitms ", 12) == 0) {
  1174. long waitms = strtol(line + 12, NULL, 10);
  1175. if (waitms < 100 || waitms > 300000)
  1176. fatal("Error on line %d of nmap-service-probes file (%s): bad totalwaitms value. Must be between 100 and 300000 milliseconds", lineno, filename);
  1177. newProbe->totalwaitms = waitms;
  1178. } else if (strncmp(line, "match ", 6) == 0 || strncmp(line, "softmatch ", 10) == 0) {
  1179. newProbe->addMatch(line, lineno);
  1180. } else if (strncmp(line, "Exclude ", 8) == 0) {
  1181. fatal("The Exclude directive must precede all Probes in nmap-service-probes");
  1182. } else fatal("Parse error on line %d of nmap-service-probes file: %s -- unknown directive", lineno, filename);
  1183. }
  1184. }
  1185. if (newProbe != NULL) {
  1186. if (newProbe->isNullProbe()) {
  1187. assert(!AP->nullProbe);
  1188. AP->nullProbe = newProbe;
  1189. } else {
  1190. AP->probes.push_back(newProbe);
  1191. }
  1192. }
  1193. fclose(fp);
  1194. AP->compileFallbacks();
  1195. }
  1196. // Parses the nmap-service-probes file, and adds each probe to
  1197. // the already-created 'probes' vector.
  1198. static void parse_nmap_service_probes(AllProbes *AP) {
  1199. char filename[256];
  1200. if (nmap_fetchfile(filename, sizeof(filename), "nmap-service-probes") != 1){
  1201. fatal("Service scan requested but I cannot find nmap-service-probes file. It should be in %s, ~/.nmap/ or .", NMAPDATADIR);
  1202. }
  1203. parse_nmap_service_probe_file(AP, filename);
  1204. /* Record where this data file was found. */
  1205. o.loaded_data_files["nmap-service-probes"] = filename;
  1206. }
  1207. AllProbes *AllProbes::global_AP;
  1208. AllProbes *AllProbes::service_scan_init(void)
  1209. {
  1210. if(global_AP)
  1211. return global_AP;
  1212. global_AP = new AllProbes();
  1213. parse_nmap_service_probes(global_AP);
  1214. return global_AP;
  1215. }
  1216. void AllProbes::service_scan_free(void)
  1217. {
  1218. if(global_AP){
  1219. delete global_AP;
  1220. global_AP = NULL;
  1221. }
  1222. }
  1223. // Function that calls isExcluded() function to check if the port
  1224. // is in the excludedports list.
  1225. int AllProbes::check_excluded_port(unsigned short portno, int proto)
  1226. {
  1227. int excluded;
  1228. // Check if the -sV version scan option was specified
  1229. // or if the --allports option was used
  1230. if (!o.servicescan || o.override_excludeports)
  1231. return 0;
  1232. if (global_AP == NULL)
  1233. fatal("Failed to check the list of excluded ports: %s", __func__);
  1234. if ((excluded = global_AP->isExcluded(portno, proto))) {
  1235. if (o.debugging)
  1236. log_write(LOG_PLAIN, "EXCLUDING %d/%s\n",
  1237. portno, IPPROTO2STR(proto));
  1238. }
  1239. return excluded;
  1240. }
  1241. // If the buf (of length buflen) matches one of the regexes in this
  1242. // ServiceProbe, returns the details of nth match (service name,
  1243. // version number if applicable, and whether this is a "soft" match.
  1244. // If the buf doesn't match, the serviceName field in the structure
  1245. // will be NULL. The MatchDetails returned is only valid until the
  1246. // next time this function is called. The only exception is that the
  1247. // serviceName field can be saved throughought program execution. If
  1248. // no version matched, that field will be NULL. This function may
  1249. // return NULL if there are no match lines at all in this probe.
  1250. const struct MatchDetails *ServiceProbe::testMatch(const u8 *buf, int buflen, int n = 0) {
  1251. std::vector<ServiceProbeMatch *>::iterator vi;
  1252. const struct MatchDetails *MD;
  1253. for(vi = matches.begin(); vi != matches.end(); vi++) {
  1254. MD = (*vi)->testMatch(buf, buflen);
  1255. if (MD->serviceName) {
  1256. if (n == 0)
  1257. return MD;
  1258. n--;
  1259. }
  1260. }
  1261. return NULL;
  1262. }
  1263. AllProbes::AllProbes() {
  1264. nullProbe = NULL;
  1265. excluded_seen = false;
  1266. memset(&excludedports, 0, sizeof(excludedports));
  1267. }
  1268. AllProbes::~AllProbes() {
  1269. std::vector<ServiceProbe *>::iterator vi;
  1270. // Delete all the ServiceProbe's inside the probes vector
  1271. for(vi = probes.begin(); vi != probes.end(); vi++) {
  1272. delete *vi;
  1273. }
  1274. if(nullProbe)
  1275. delete nullProbe;
  1276. free_scan_lists(&excludedports);
  1277. }
  1278. // Tries to find the probe in this AllProbes class which have the
  1279. // given name and protocol. It can return the NULL probe.
  1280. ServiceProbe *AllProbes::getProbeByName(const char *name, int proto) {
  1281. std::vector<ServiceProbe *>::iterator vi;
  1282. if (proto == IPPROTO_TCP && nullProbe && strcmp(nullProbe->getName(), name) == 0)
  1283. return nullProbe;
  1284. for(vi = probes.begin(); vi != probes.end(); vi++) {
  1285. if ((*vi)->getProbeProtocol() == proto &&
  1286. strcmp(name, (*vi)->getName()) == 0)
  1287. return *vi;
  1288. }
  1289. return NULL;
  1290. }
  1291. // Returns nonzero if port was specified in the excludeports
  1292. // directive in nmap-service-probes. Zero otherwise.
  1293. // Proto should be IPPROTO_TCP for TCP and IPPROTO_UDP for UDP
  1294. // Note that although getpts() can set protocols (for protocol
  1295. // scanning), this is ignored here because you can't version
  1296. // scan protocols.
  1297. int AllProbes::isExcluded(unsigned short port, int proto) {
  1298. unsigned short *p=NULL;
  1299. int count=-1,i;
  1300. if (!excluded_seen) return 0;
  1301. if (proto == IPPROTO_TCP) {
  1302. p = excludedports.tcp_ports;
  1303. count = excludedports.tcp_count;
  1304. } else if (proto == IPPROTO_UDP) {
  1305. p = excludedports.udp_ports;
  1306. count = excludedports.udp_count;
  1307. } else if (proto == IPPROTO_SCTP) {
  1308. p = excludedports.sctp_ports;
  1309. count = excludedports.sctp_count;
  1310. } else {
  1311. fatal("Bad proto number (%d) specified in %s", proto, __func__);
  1312. }
  1313. for (i=0; i<count; i++)
  1314. if (p[i] == port)
  1315. return 1;
  1316. return 0;
  1317. }
  1318. // Before this function is called, the fallbacks exist as unparsed
  1319. // comma-separated strings in the fallbackStr field of each probe.
  1320. // This function fills out the fallbacks array in each probe with
  1321. // an ordered list of pointers to which probes to try. This is both for
  1322. // efficiency and to deal with odd cases like the NULL probe and falling
  1323. // back to probes later in the file. This function also free()s all the
  1324. // fallbackStrs.
  1325. void AllProbes::compileFallbacks() {
  1326. std::vector<ServiceProbe *>::iterator curr;
  1327. char *tp;
  1328. int i;
  1329. curr = probes.begin();
  1330. // The NULL probe is a special case:
  1331. if (nullProbe != NULL)
  1332. nullProbe->fallbacks[0] = nullProbe;
  1333. while (curr != probes.end()) {
  1334. if ((*curr)->fallbackStr == NULL) {
  1335. // A non-NULL probe without a fallback directive. We
  1336. // just use "Itself,NULL" unless it's UDP, then just "Itself".
  1337. (*curr)->fallbacks[0] = *curr;
  1338. if ((*curr)->getProbeProtocol() == IPPROTO_TCP)
  1339. (*curr)->fallbacks[1] = nullProbe;
  1340. } else {
  1341. // A non-NULL probe *with* a fallback directive. We use:
  1342. // TCP: "Itself,<directive1>,...,<directiveN>,NULL"
  1343. // UDP: "Itself,<directive1>,...,<directiveN>"
  1344. (*curr)->fallbacks[0] = *curr;
  1345. i = 1;
  1346. tp = strtok((*curr)->fallbackStr, ",\r\n\t "); // \r and \n because string will be terminated with them
  1347. while (tp != NULL && i<(MAXFALLBACKS-1)) {
  1348. (*curr)->fallbacks[i] = getProbeByName(tp, (*curr)->getProbeProtocol());
  1349. if ((*curr)->fallbacks[i] == NULL)
  1350. fatal("%s: Unknown fallback specified in Probe %s: '%s'", __func__, (*curr)->getName(), tp);
  1351. i++;
  1352. tp = strtok(NULL, ",\r\n\t ");
  1353. }
  1354. if (i == MAXFALLBACKS-1)
  1355. fatal("%s: MAXFALLBACKS exceeded on probe '%s'", __func__, (*curr)->getName());
  1356. if ((*curr)->getProbeProtocol() == IPPROTO_TCP)
  1357. (*curr)->fallbacks[i] = nullProbe;
  1358. }
  1359. if ((*curr)->fallbackStr) free((*curr)->fallbackStr);
  1360. (*curr)->fallbackStr = NULL;
  1361. curr++;
  1362. }
  1363. }
  1364. ServiceNFO::ServiceNFO(AllProbes *newAP) {
  1365. target = NULL;
  1366. probe_matched = NULL;
  1367. niod = NULL;
  1368. probe_state = PROBESTATE_INITIAL;
  1369. portno = proto = 0;
  1370. AP = newAP;
  1371. currentresp = NULL;
  1372. currentresplen = 0;
  1373. product_matched[0] = version_matched[0] = extrainfo_matched[0] = '\0';
  1374. hostname_matched[0] = ostype_matched[0] = devicetype_matched[0] = '\0';
  1375. cpe_a_matched[0] = cpe_h_matched[0] = cpe_o_matched[0] = '\0';
  1376. tunnel = SERVICE_TUNNEL_NONE;
  1377. ssl_session = NULL;
  1378. softMatchFound = false;
  1379. servicefplen = servicefpalloc = 0;
  1380. servicefp = NULL;
  1381. memset(&currentprobe_exec_time, 0, sizeof(currentprobe_exec_time));
  1382. }
  1383. ServiceNFO::~ServiceNFO() {
  1384. if (currentresp) free(currentresp);
  1385. if (servicefp) free(servicefp);
  1386. servicefp = NULL;
  1387. servicefpalloc = servicefplen = 0;
  1388. #if HAVE_OPENSSL
  1389. if (ssl_session)
  1390. SSL_SESSION_free((SSL_SESSION*)ssl_session);
  1391. ssl_session=NULL;
  1392. #endif
  1393. }
  1394. // Adds a character to servicefp. Takes care of word wrapping if
  1395. // necessary at the given (wrapat) column. Chars will only be
  1396. // written if there is enough space. Otherwise it exits.
  1397. void ServiceNFO::addServiceChar(const char c, int wrapat) {
  1398. if (servicefpalloc - servicefplen < 6)
  1399. fatal("%s - out of space for servicefp", __func__);
  1400. if (servicefplen % (wrapat+1) == wrapat) {
  1401. // we need to start a new line
  1402. memcpy(servicefp + servicefplen, "\nSF:", 4);
  1403. servicefplen += 4;
  1404. }
  1405. servicefp[servicefplen++] = c;
  1406. }
  1407. // Like addServiceChar, but for a whole zero-terminated string
  1408. void ServiceNFO::addServiceString(const char *s, int wrapat) {
  1409. while(*s)
  1410. addServiceChar(*s++, wrapat);
  1411. }
  1412. // If a service responds to a given probeName, this function adds the
  1413. // response to the fingerprint for that service. The fingerprint can
  1414. // be printed when nothing matches the service. You can obtain the
  1415. // fingerprint (if any) via getServiceFingerprint();
  1416. void ServiceNFO::addToServiceFingerprint(const char *probeName, const u8 *resp,
  1417. int resplen) {
  1418. int spaceleft = servicefpalloc - servicefplen;
  1419. int servicewrap=74; // Wrap after 74 chars / line
  1420. int respused = MIN(resplen, (o.debugging)? 1300 : 900); // truncate to reasonable size
  1421. // every char could require \xHH escape, plus there is the matter of
  1422. // "\nSF:" for each line, plus "%r(probename,probelen,"") Oh, and
  1423. // the SF-PortXXXX-TCP stuff, etc
  1424. int spaceneeded = respused * 5 + strlen(probeName) + 128;
  1425. int srcidx;
  1426. struct tm *ltime;
  1427. time_t timep;
  1428. char buf[128];
  1429. assert(resplen);
  1430. assert(probeName);
  1431. if (servicefplen > (o.debugging? 10000 : 2200))
  1432. return; // it is large enough.
  1433. if (spaceneeded >= spaceleft) {
  1434. spaceneeded = MAX(spaceneeded, 512); // No point in tiny allocations
  1435. spaceneeded += servicefpalloc;
  1436. servicefp = (char *) safe_realloc(servicefp, spaceneeded);
  1437. servicefpalloc = spaceneeded;
  1438. }
  1439. spaceleft = servicefpalloc - servicefplen;
  1440. if (servicefplen == 0) {
  1441. timep = time(NULL);
  1442. ltime = localtime(&timep);
  1443. Snprintf(buf, sizeof(buf), "SF-Port%hu-%s:V=%s%s%%I=%d%%D=%d/%d%%Time=%X%%P=%s", portno, proto2ascii_uppercase(proto), NMAP_VERSION, (tunnel == SERVICE_TUNNEL_SSL)? "%T=SSL" : "", o.version_intensity, ltime->tm_mon + 1, ltime->tm_mday, (int) timep, NMAP_PLATFORM);
  1444. addServiceString(buf, servicewrap);
  1445. }
  1446. // Note that we give the total length of the response, even though we
  1447. // may truncate
  1448. Snprintf(buf, sizeof(buf), "%%r(%s,%X,\"", probeName, resplen);
  1449. addServiceString(buf, servicewrap);
  1450. // Now for the probe response itself ...
  1451. for(srcidx=0; srcidx < respused; srcidx++) {
  1452. // A run of this can take up to 8 chars: "\n \x20"
  1453. assert( servicefpalloc - servicefplen > 8);
  1454. if (isalnum((int)resp[srcidx]))
  1455. addServiceChar((char) resp[srcidx], servicewrap);
  1456. else if (resp[srcidx] == '\0') {
  1457. /* We need to be careful with this, because if it is followed by
  1458. an ASCII number, PCRE will treat it differently. */
  1459. if (srcidx + 1 >= respused || !isdigit((int) resp[srcidx + 1]))
  1460. addServiceString("\\0", servicewrap);
  1461. else addServiceString("\\x00", servicewrap);
  1462. } else if (strchr("\\?\"[]().*+$^|", resp[srcidx])) {
  1463. addServiceChar('\\', servicewrap);
  1464. addServiceChar(resp[srcidx], servicewrap);
  1465. } else if (ispunct((int)resp[srcidx])) {
  1466. addServiceChar((char) resp[srcidx], servicewrap);
  1467. } else if (resp[srcidx] == '\r') {
  1468. addServiceString("\\r", servicewrap);
  1469. } else if (resp[srcidx] == '\n') {
  1470. addServiceString("\\n", servicewrap);
  1471. } else if (resp[srcidx] == '\t') {
  1472. addServiceString("\\t", servicewrap);
  1473. } else {
  1474. addServiceChar('\\', servicewrap);
  1475. addServiceChar('x', servicewrap);
  1476. Snprintf(buf, sizeof(buf), "%02x", resp[srcidx]);
  1477. addServiceChar(*buf, servicewrap);
  1478. addServiceChar(*(buf+1), servicewrap);
  1479. }
  1480. }
  1481. addServiceChar('"', servicewrap);
  1482. addServiceChar(')', servicewrap);
  1483. assert(servicefpalloc - servicefplen > 1);
  1484. servicefp[servicefplen] = '\0';
  1485. }
  1486. // Get the service fingerprint. It is NULL if there is none, such
  1487. // as if there was a match before any other probes were finished (or
  1488. // if no probes gave back data). Note that this is plain
  1489. // NUL-terminated ASCII data, although the length is optionally
  1490. // available anyway. This function terminates the service fingerprint
  1491. // with a semi-colon
  1492. const char *ServiceNFO::getServiceFingerprint(int *flen) {
  1493. if (servicefplen == 0) {
  1494. if (flen) *flen = 0;
  1495. return NULL;
  1496. }
  1497. // Ensure we have enough space for the terminating semi-colon and \0
  1498. if (servicefplen + 2 > servicefpalloc) {
  1499. servicefpalloc = servicefplen + 20;
  1500. servicefp = (char *) safe_realloc(servicefp, servicefpalloc);
  1501. }
  1502. if (flen) *flen = servicefplen + 1;
  1503. // We terminate with a semi-colon, which is never wrapped.
  1504. servicefp[servicefplen] = ';';
  1505. servicefp[servicefplen + 1] = '\0';
  1506. return servicefp;
  1507. }
  1508. ServiceProbe *ServiceNFO::currentProbe() {
  1509. if (probe_state == PROBESTATE_INITIAL) {
  1510. return nextProbe(true);
  1511. } else if (probe_state == PROBESTATE_NULLPROBE) {
  1512. assert(AP->nullProbe);
  1513. return AP->nullProbe;
  1514. } else if (probe_state == PROBESTATE_MATCHINGPROBES ||
  1515. probe_state == PROBESTATE_NONMATCHINGPROBES) {
  1516. return *current_probe;
  1517. }
  1518. return NULL;
  1519. }
  1520. // computes the next probe to test, and ALSO CHANGES currentProbe() to
  1521. // that! If newresp is true, the old response info will be lost and
  1522. // invalidated. Otherwise it remains as if it had been received by
  1523. // the current probe (useful after a NULL probe).
  1524. ServiceProbe *ServiceNFO::nextProbe(bool newresp) {
  1525. bool dropdown = false;
  1526. // This invalidates the probe response string if any
  1527. if (newresp) {
  1528. if (currentresp) free(currentresp);
  1529. currentresp = NULL; currentresplen = 0;
  1530. }
  1531. if (probe_state == PROBESTATE_INITIAL) {
  1532. probe_state = PROBESTATE_NULLPROBE;
  1533. // This is the very first probe -- so we try to use the NULL probe
  1534. // but obviously NULL probe only works with TCP
  1535. if (proto == IPPROTO_TCP && AP->nullProbe)
  1536. return AP->nullProbe;
  1537. // No valid NULL probe -- we'll drop to the next state
  1538. }
  1539. if (probe_state == PROBESTATE_NULLPROBE) {
  1540. // There can only be one (or zero) NULL probe. So now we go through the
  1541. // list looking for matching probes
  1542. probe_state = PROBESTATE_MATCHINGPROBES;
  1543. dropdown = true;
  1544. current_probe = AP->probes.begin();
  1545. }
  1546. if (probe_state == PROBESTATE_MATCHINGPROBES) {
  1547. if (!dropdown && current_probe != AP->probes.end()) current_probe++;
  1548. while (current_probe != AP->probes.end()) {
  1549. // For the first run, we only do probes that match this port number
  1550. if ((proto == (*current_probe)->getProbeProtocol()) &&
  1551. (*current_probe)->portIsProbable(tunnel, portno)) {
  1552. // This appears to be a valid probe. Let's do it!
  1553. return *current_probe;
  1554. }
  1555. current_probe++;
  1556. }
  1557. // Tried all MATCHINGPROBES -- now we must move to nonmatching
  1558. probe_state = PROBESTATE_NONMATCHINGPROBES;
  1559. dropdown = true;
  1560. current_probe = AP->probes.begin();
  1561. }
  1562. if (probe_state == PROBESTATE_NONMATCHINGPROBES) {
  1563. if (!dropdown && current_probe != AP->probes.end()) current_probe++;
  1564. while (current_probe != AP->probes.end()) {
  1565. // The protocol must be right, it must be a nonmatching port ('cause we did those),
  1566. // and we better either have no soft match yet, or the soft service match must
  1567. // be available via this probe. Also, the Probe's rarity must be <= to our
  1568. // version detection intensity level.
  1569. if ((proto == (*current_probe)->getProbeProtocol()) &&
  1570. !(*current_probe)->portIsProbable(tunnel, portno) &&
  1571. (*current_probe)->getRarity() <= o.version_intensity &&
  1572. (!softMatchFound || (*current_probe)->serviceIsPossible(probe_matched))) {
  1573. // Valid, probe. Let's do it!
  1574. return *current_probe;
  1575. }
  1576. current_probe++;
  1577. }
  1578. // Tried all NONMATCHINGPROBES -- we're finished
  1579. probe_state = (softMatchFound)? PROBESTATE_FINISHED_SOFTMATCHED : PROBESTATE_FINISHED_NOMATCH;
  1580. return NULL;
  1581. }
  1582. fatal("%s called for probe in state (%d)", __func__, (int) probe_state);
  1583. return NULL;
  1584. }
  1585. // Resets the probes back to the first one. One case where this is useful is
  1586. // when SSL is detected -- we redo all probes through SSL. If freeFP, any
  1587. // service fingerprint is freed too.
  1588. void ServiceNFO::resetProbes(bool freefp) {
  1589. if (currentresp) free(currentresp);
  1590. if (freefp) {
  1591. if (servicefp) { free(servicefp); servicefp = NULL; }
  1592. servicefplen = servicefpalloc = 0;
  1593. }
  1594. currentresp = NULL; currentresplen = 0;
  1595. probe_state = PROBESTATE_INITIAL;
  1596. }
  1597. int ServiceNFO::probe_timemsleft(const ServiceProbe *probe, const struct timeval *now) {
  1598. int timeused, timeleft;
  1599. if (now)
  1600. timeused = TIMEVAL_MSEC_SUBTRACT(*now, currentprobe_exec_time);
  1601. else {
  1602. struct timeval tv;
  1603. gettimeofday(&tv, NULL);
  1604. timeused = TIMEVAL_MSEC_SUBTRACT(tv, currentprobe_exec_time);
  1605. }
  1606. // Historically this function was always called with the assumption that
  1607. // probe == currentProbe(). Check that this remains the case.
  1608. assert(probe == currentProbe());
  1609. timeleft = probe->totalwaitms - timeused;
  1610. return (timeleft < 0)? 0 : timeleft;
  1611. }
  1612. void ServiceNFO::appendtocurrentproberesponse(const u8 *respstr, int respstrlen) {
  1613. currentresp = (u8 *) safe_realloc(currentresp, currentresplen + respstrlen);
  1614. memcpy(currentresp + currentresplen, respstr, respstrlen);
  1615. currentresplen += respstrlen;
  1616. }
  1617. // Get the full current response string. Note that this pointer is
  1618. // INVALIDATED if you call appendtocurrentproberesponse() or nextProbe()
  1619. u8 *ServiceNFO::getcurrentproberesponse(int *respstrlen) {
  1620. *respstrlen = currentresplen;
  1621. return currentresp;
  1622. }
  1623. ServiceGroup::ServiceGroup(std::vector<Target *> &Targets, AllProbes *AP) {
  1624. unsigned int targetno;
  1625. ServiceNFO *svc;
  1626. Port *nxtport;
  1627. Port port;
  1628. int desired_par;
  1629. struct timeval now;
  1630. num_hosts_timedout = 0;
  1631. gettimeofday(&now, NULL);
  1632. for(targetno = 0 ; targetno < Targets.size(); targetno++) {
  1633. nxtport = NULL;
  1634. if (Targets[targetno]->timedOut(&now)) {
  1635. num_hosts_timedout++;
  1636. continue;
  1637. }
  1638. while((nxtport = Targets[targetno]->ports.nextPort(nxtport, &port, TCPANDUDPANDSCTP, PORT_OPEN))) {
  1639. svc = new ServiceNFO(AP);
  1640. svc->target = Targets[targetno];
  1641. svc->portno = nxtport->portno;
  1642. svc->proto = nxtport->proto;
  1643. services_remaining.push_back(svc);
  1644. }
  1645. }
  1646. /* Use a whole new loop for PORT_OPENFILTERED so that we try all the
  1647. known open ports first before bothering with this speculative
  1648. stuff */
  1649. for(targetno = 0 ; targetno < Targets.size(); targetno++) {
  1650. nxtport = NULL;
  1651. if (Targets[targetno]->timedOut(&now)) {
  1652. continue;
  1653. }
  1654. while((nxtport = Targets[targetno]->ports.nextPort(nxtport, &port, TCPANDUDPANDSCTP, PORT_OPENFILTERED))) {
  1655. svc = new ServiceNFO(AP);
  1656. svc->target = Targets[targetno];
  1657. svc->portno = nxtport->portno;
  1658. svc->proto = nxtport->proto;
  1659. services_remaining.push_back(svc);
  1660. }
  1661. }
  1662. SPM = new ScanProgressMeter("Service scan");
  1663. desired_par = 1;
  1664. if (o.timing_level == 3) desired_par = 20;
  1665. if (o.timing_level == 4) desired_par = 30;
  1666. if (o.timing_level >= 5) desired_par = 40;
  1667. // TODO: Come up with better ways to determine ideal_parallelism
  1668. int min_par, max_par;
  1669. min_par = o.min_parallelism;
  1670. max_par = MAX(min_par, o.max_parallelism ? o.max_parallelism : 100);
  1671. ideal_parallelism = box(min_par, max_par, desired_par);
  1672. }
  1673. ServiceGroup::~ServiceGroup() {
  1674. std::list<ServiceNFO *>::iterator i;
  1675. for(i = services_finished.begin(); i != services_finished.end(); i++)
  1676. delete *i;
  1677. for(i = services_in_progress.begin(); i != services_in_progress.end(); i++)
  1678. delete *i;
  1679. for(i = services_remaining.begin(); i != services_remaining.end(); i++)
  1680. delete *i;
  1681. delete SPM;
  1682. }
  1683. /* Called if data is read for a service or a TCP connection made. Sets the port
  1684. state to PORT_OPEN. */
  1685. static void adjustPortStateIfNecessary(ServiceNFO *svc) {
  1686. int oldstate;
  1687. char host[128];
  1688. oldstate = svc->target->ports.getPortState(svc->portno, svc->proto);
  1689. if (oldstate != PORT_OPEN) {
  1690. svc->target->ports.setPortState(svc->portno, svc->proto, PORT_OPEN);
  1691. if (svc->proto == IPPROTO_TCP)
  1692. svc->target->ports.setStateReason(svc->portno, svc->proto, ER_TCPRESPONSE, 0, NULL);
  1693. if (svc->proto == IPPROTO_UDP)
  1694. svc->target->ports.setStateReason(svc->portno, svc->proto, ER_UDPRESPONSE, 0, NULL);
  1695. if (o.verbose || o.debugging > 1) {
  1696. svc->target->NameIP(host, sizeof(host));
  1697. log_write(LOG_STDOUT, "Discovered %s port %hu/%s on %s is actually open\n",
  1698. statenum2str(oldstate), svc->portno, proto2ascii_lowercase(svc->proto), host);
  1699. log_flush(LOG_STDOUT);
  1700. }
  1701. }
  1702. return;
  1703. }
  1704. // Sends probe text to an open connection. In the case of a NULL probe, there
  1705. // may be no probe text
  1706. static int send_probe_text(nsock_pool nsp, nsock_iod nsi, ServiceNFO *svc,
  1707. ServiceProbe *probe) {
  1708. const u8 *probestring;
  1709. int probestringlen;
  1710. // Report data as probes are sent if --version-trace has been requested
  1711. if (o.debugging > 1 || o.versionTrace()) {
  1712. log_write(LOG_PLAIN, "Service scan sending probe %s to %s:%hu (%s)\n", probe->getName(), svc->target->targetipstr(), svc->portno, proto2ascii_lowercase(svc->proto));
  1713. }
  1714. assert(probe);
  1715. if (probe->isNullProbe())
  1716. return 0; // No need to send anything for a NULL probe;
  1717. probestring = probe->getProbeString(&probestringlen);
  1718. assert(probestringlen > 0);
  1719. // Now we write the string to the IOD
  1720. nsock_write(nsp, nsi, servicescan_write_handler, svc->probe_timemsleft(probe), svc,
  1721. (const char *) probestring, probestringlen);
  1722. return 0;
  1723. }
  1724. // This simple helper function is used to start the next probe. If
  1725. // the probe exists, execution begins (and the previous one is cleaned
  1726. // up if necessary) . Otherwise, the service is listed as finished
  1727. // and moved to the finished list. If you pass 'true' for alwaysrestart, a
  1728. // new connection will be made even if the previous probe was the NULL probe.
  1729. // You would do this, for example, if the other side has closed the connection.
  1730. static void startNextProbe(nsock_pool nsp, nsock_iod nsi, ServiceGroup *SG,
  1731. ServiceNFO *svc, bool alwaysrestart) {
  1732. bool isInitial = svc->probe_state == PROBESTATE_INITIAL;
  1733. ServiceProbe *probe = svc->currentProbe();
  1734. struct sockaddr_storage ss;
  1735. size_t ss_len;
  1736. if (!alwaysrestart && probe->isNullProbe()) {
  1737. // The difference here is that we can reuse the same (TCP) connection
  1738. // if the last probe was the NULL probe.
  1739. probe = svc->nextProbe(false);
  1740. if (probe) {
  1741. svc->currentprobe_exec_time = *nsock_gettimeofday();
  1742. send_probe_text(nsp, nsi, svc, probe);
  1743. nsock_read(nsp, nsi, servicescan_read_handler,
  1744. svc->probe_timemsleft(probe, nsock_gettimeofday()), svc);
  1745. } else {
  1746. // Should only happen if someone has a highly perverse nmap-service-probes
  1747. // file. Null scan should generally never be the only probe.
  1748. end_svcprobe(nsp, (svc->softMatchFound)? PROBESTATE_FINISHED_SOFTMATCHED : PROBESTATE_FINISHED_NOMATCH, SG, svc, NULL);
  1749. }
  1750. } else {
  1751. // The finisehd probe was not a NULL probe. So we close the
  1752. // connection, and if further probes are available, we launch the
  1753. // next one.
  1754. if (!isInitial)
  1755. probe = svc->nextProbe(true); // if was initial, currentProbe() returned the right one to execute.
  1756. if (probe) {
  1757. // For a TCP probe, we start by requesting a new connection to the target
  1758. if (svc->proto == IPPROTO_TCP) {
  1759. nsi_delete(nsi, NSOCK_PENDING_SILENT);
  1760. if ((svc->niod = nsi_new(nsp, svc)) == NULL) {
  1761. fatal("Failed to allocate Nsock I/O descriptor in %s()", __func__);
  1762. }
  1763. if (o.spoofsource) {
  1764. o.SourceSockAddr(&ss, &ss_len);
  1765. nsi_set_localaddr(svc->niod, &ss, ss_len);
  1766. }
  1767. if (o.ipoptionslen)
  1768. nsi_set_ipoptions(svc->niod, o.ipoptions, o.ipoptionslen);
  1769. if (svc->target->TargetName()) {
  1770. if (nsi_set_hostname(svc->niod, svc->target->TargetName()) == -1)
  1771. fatal("nsi_set_hostname(\"%s\" failed in %s()", svc->target->TargetName(), __func__);
  1772. }
  1773. svc->target->TargetSockAddr(&ss, &ss_len);
  1774. if (svc->tunnel == SERVICE_TUNNEL_NONE) {
  1775. nsock_connect_tcp(nsp, svc->niod, servicescan_connect_handler,
  1776. DEFAULT_CONNECT_TIMEOUT, svc,
  1777. (struct sockaddr *) &ss, ss_len,
  1778. svc->portno);
  1779. } else {
  1780. assert(svc->tunnel == SERVICE_TUNNEL_SSL);
  1781. nsock_connect_ssl(nsp, svc->niod, servicescan_connect_handler,
  1782. DEFAULT_CONNECT_SSL_TIMEOUT, svc,
  1783. (struct sockaddr *) &ss,
  1784. ss_len, svc->proto, svc->portno, svc->ssl_session);
  1785. }
  1786. } else {
  1787. assert(svc->proto == IPPROTO_UDP);
  1788. /* Can maintain the same UDP "connection" */
  1789. svc->currentprobe_exec_time = *nsock_gettimeofday();
  1790. send_probe_text(nsp, nsi, svc, probe);
  1791. // Now let us read any results
  1792. nsock_read(nsp, nsi, servicescan_read_handler,
  1793. svc->probe_timemsleft(probe, nsock_gettimeofday()), svc);
  1794. }
  1795. } else {
  1796. // No more probes remaining! Failed to match
  1797. nsi_delete(nsi, NSOCK_PENDING_SILENT);
  1798. end_svcprobe(nsp, (svc->softMatchFound)? PROBESTATE_FINISHED_SOFTMATCHED : PROBESTATE_FINISHED_NOMATCH, SG, svc, NULL);
  1799. }
  1800. }
  1801. return;
  1802. }
  1803. /* Sometimes the normal service scan will detect a
  1804. tunneling/encryption protocol such as SSL. Instead of just
  1805. reporting "ssl", we can make an SSL connection and try to determine
  1806. the service that is really sitting behind the SSL. This function
  1807. will take a service that has just been detected (hard match only),
  1808. and see if we can dig deeper through tunneling. Nonzero is
  1809. returned if we can do more. Otherwise 0 is returned and the caller
  1810. should end the service with its successful match. If the tunnel
  1811. results can be determined with no more effort, 0 is also returned.
  1812. For example, a service that already matched as "ssl/ldap" will be
  1813. chaned to "ldap" with the tunnel being SSL and 0 will be returned.
  1814. That is a special case.
  1815. */
  1816. static int scanThroughTunnel(nsock_pool nsp, nsock_iod nsi, ServiceGroup *SG,
  1817. ServiceNFO *svc) {
  1818. if (svc->probe_matched && strncmp(svc->probe_matched, "ssl/", 4) == 0) {
  1819. /* The service has been detected without having to make an SSL connection */
  1820. svc->tunnel = SERVICE_TUNNEL_SSL;
  1821. svc->probe_matched += 4;
  1822. return 0;
  1823. }
  1824. #ifdef HAVE_OPENSSL
  1825. if (svc->tunnel != SERVICE_TUNNEL_NONE) {
  1826. // Another tunnel type has already been tried. Let's not go recursive.
  1827. return 0;
  1828. }
  1829. if (svc->proto != IPPROTO_TCP ||
  1830. !svc->probe_matched || strcmp(svc->probe_matched, "ssl") != 0)
  1831. return 0; // Not SSL
  1832. // Alright! We are going to start the tests over using SSL
  1833. // printf("DBG: Found SSL service on %s:%hu - starting SSL scan\n", svc->target->NameIP(), svc->portno);
  1834. svc->tunnel = SERVICE_TUNNEL_SSL;
  1835. svc->probe_matched = NULL;
  1836. svc->product_matched[0] = svc->version_matched[0] = svc->extrainfo_matched[0] = '\0';
  1837. svc->hostname_matched[0] = svc->ostype_matched[0] = svc->devicetype_matched[0] = '\0';
  1838. svc->cpe_a_matched[0] = svc->cpe_h_matched[0] = svc->cpe_o_matched[0] = '\0';
  1839. svc->softMatchFound = false;
  1840. svc->resetProbes(true);
  1841. startNextProbe(nsp, nsi, SG, svc, true);
  1842. return 1;
  1843. #else
  1844. return 0;
  1845. #endif
  1846. }
  1847. /* Prints completion estimates and the like when appropriate */
  1848. static void considerPrintingStats(nsock_pool nsp, ServiceGroup *SG) {
  1849. /* Check for status requests */
  1850. if (keyWasPressed()) {
  1851. nmap_adjust_loglevel(nsp, o.versionTrace());
  1852. SG->SPM->printStats(SG->services_finished.size() /
  1853. ((double)SG->services_remaining.size() + SG->services_in_progress.size() +
  1854. SG->services_finished.size()), nsock_gettimeofday());
  1855. }
  1856. /* Perhaps this should be made more complex, but I suppose it should be
  1857. good enough for now. */
  1858. if (SG->SPM->mayBePrinted(nsock_gettimeofday())) {
  1859. SG->SPM->printStatsIfNecessary(SG->services_finished.size() / ((double)SG->services_remaining.size() + SG->services_in_progress.size() + SG->services_finished.size()), nsock_gettimeofday());
  1860. }
  1861. }
  1862. /* Check if target is done (no more probes remaining for it in service group),
  1863. and responds appropriately if so */
  1864. static void handleHostIfDone(ServiceGroup *SG, Target *target) {
  1865. std::list<ServiceNFO *>::iterator svcI;
  1866. bool found = false;
  1867. for(svcI = SG->services_in_progress.begin();
  1868. svcI != SG->services_in_progress.end(); svcI++) {
  1869. if ((*svcI)->target == target) {
  1870. found = true;
  1871. break;
  1872. }
  1873. }
  1874. for(svcI = SG->services_remaining.begin();
  1875. !found && svcI != SG->services_remaining.end(); svcI++) {
  1876. if ((*svcI)->target == target) {
  1877. found = true;
  1878. break;
  1879. }
  1880. }
  1881. if (!found) {
  1882. target->stopTimeOutClock(nsock_gettimeofday());
  1883. if (target->timedOut(NULL)) {
  1884. SG->num_hosts_timedout++;
  1885. }
  1886. }
  1887. }
  1888. // A simple helper function to cancel further work on a service and
  1889. // set it to the given probe_state pass NULL for nsi if you don't want
  1890. // it to be deleted (for example, if you already have done so).
  1891. static void end_svcprobe(nsock_pool nsp, enum serviceprobestate probe_state, ServiceGroup *SG, ServiceNFO *svc, nsock_iod nsi) {
  1892. std::list<ServiceNFO *>::iterator member;
  1893. Target *target = svc->target;
  1894. svc->probe_state = probe_state;
  1895. member = find(SG->services_in_progress.begin(), SG->services_in_progress.end(),
  1896. svc);
  1897. if (member != SG->services_in_progress.end()) {
  1898. assert(*member == svc);
  1899. SG->services_in_progress.erase(member);
  1900. } else {
  1901. /* A probe can finish from services_remaining if the host times out before the
  1902. probe has even started */
  1903. member = find(SG->services_remaining.begin(), SG->services_remaining.end(),
  1904. svc);
  1905. assert(member != SG->services_remaining.end());
  1906. assert(*member == svc);
  1907. SG->services_remaining.erase(member);
  1908. }
  1909. SG->services_finished.push_back(svc);
  1910. considerPrintingStats(nsp, SG);
  1911. if (nsi) {
  1912. nsi_delete(nsi, NSOCK_PENDING_SILENT);
  1913. }
  1914. handleHostIfDone(SG, target);
  1915. return;
  1916. }
  1917. // This function consults the ServiceGroup to determine whether any
  1918. // more probes can be launched at this time. If so, it determines the
  1919. // appropriate ones and then starts them up.
  1920. static int launchSomeServiceProbes(nsock_pool nsp, ServiceGroup *SG) {
  1921. ServiceNFO *svc;
  1922. ServiceProbe *nextprobe;
  1923. struct sockaddr_storage ss;
  1924. size_t ss_len;
  1925. static int warn_no_scanning=1;
  1926. while (SG->services_in_progress.size() < SG->ideal_parallelism &&
  1927. !SG->services_remaining.empty()) {
  1928. // Start executing a probe from the new list and move it to in_progress
  1929. svc = SG->services_remaining.front();
  1930. if (svc->target->timedOut(nsock_gettimeofday())) {
  1931. end_svcprobe(nsp, PROBESTATE_INCOMPLETE, SG, svc, NULL);
  1932. continue;
  1933. }
  1934. nextprobe = svc->nextProbe(true);
  1935. if (nextprobe == NULL) {
  1936. if (warn_no_scanning && o.debugging) {
  1937. log_write(LOG_PLAIN, "Service scan: Not probing some ports due to low intensity\n");
  1938. warn_no_scanning=0;
  1939. }
  1940. end_svcprobe(nsp, PROBESTATE_FINISHED_NOMATCH, SG, svc, NULL);
  1941. continue;
  1942. }
  1943. // We start by requesting a connection to the target
  1944. if ((svc->niod = nsi_new(nsp, svc)) == NULL) {
  1945. fatal("Failed to allocate Nsock I/O descriptor in %s()", __func__);
  1946. }
  1947. if (o.debugging > 1) {
  1948. log_write(LOG_PLAIN, "Starting probes against new service: %s:%hu (%s)\n", svc->target->targetipstr(), svc->portno, proto2ascii_lowercase(svc->proto));
  1949. }
  1950. if (o.spoofsource) {
  1951. o.SourceSockAddr(&ss, &ss_len);
  1952. nsi_set_localaddr(svc->niod, &ss, ss_len);
  1953. }
  1954. if (o.ipoptionslen)
  1955. nsi_set_ipoptions(svc->niod, o.ipoptions, o.ipoptionslen);
  1956. svc->target->TargetSockAddr(&ss, &ss_len);
  1957. if (svc->proto == IPPROTO_TCP)
  1958. nsock_connect_tcp(nsp, svc->niod, servicescan_connect_handler,
  1959. DEFAULT_CONNECT_TIMEOUT, svc,
  1960. (struct sockaddr *)&ss, ss_len,
  1961. svc->portno);
  1962. else {
  1963. assert(svc->proto == IPPROTO_UDP);
  1964. nsock_connect_udp(nsp, svc->niod, servicescan_connect_handler,
  1965. svc, (struct sockaddr *) &ss, ss_len,
  1966. svc->portno);
  1967. }
  1968. // Now remove it from the remaining service list
  1969. SG->services_remaining.pop_front();
  1970. // And add it to the in progress list
  1971. SG->services_in_progress.push_back(svc);
  1972. }
  1973. return 0;
  1974. }
  1975. static void servicescan_connect_handler(nsock_pool nsp, nsock_event nse, void *mydata) {
  1976. nsock_iod nsi = nse_iod(nse);
  1977. enum nse_status status = nse_status(nse);
  1978. enum nse_type type = nse_type(nse);
  1979. ServiceNFO *svc = (ServiceNFO *) mydata;
  1980. ServiceProbe *probe = svc->currentProbe();
  1981. ServiceGroup *SG = (ServiceGroup *) nsp_getud(nsp);
  1982. assert(type == NSE_TYPE_CONNECT || type == NSE_TYPE_CONNECT_SSL);
  1983. if (svc->target->timedOut(nsock_gettimeofday())) {
  1984. end_svcprobe(nsp, PROBESTATE_INCOMPLETE, SG, svc, nsi);
  1985. } else if (status == NSE_STATUS_SUCCESS) {
  1986. #if HAVE_OPENSSL
  1987. // Snag our SSL_SESSION from the nsi for use in subsequent connections.
  1988. if (nsi_checkssl(nsi)) {
  1989. if ( svc->ssl_session ) {
  1990. if (svc->ssl_session == (SSL_SESSION *)(nsi_get0_ssl_session(nsi))) {
  1991. //nada
  1992. } else {
  1993. SSL_SESSION_free((SSL_SESSION*)svc->ssl_session);
  1994. svc->ssl_session = (SSL_SESSION *)(nsi_get1_ssl_session(nsi));
  1995. }
  1996. } else {
  1997. svc->ssl_session = (SSL_SESSION *)(nsi_get1_ssl_session(nsi));
  1998. }
  1999. }
  2000. #endif
  2001. /* If the port is TCP, it is now known to be open rather than openfiltered */
  2002. if (svc->proto == IPPROTO_TCP)
  2003. adjustPortStateIfNecessary(svc);
  2004. // Yeah! Connection made to the port. Send the appropriate probe
  2005. // text (if any is needed -- might be NULL probe)
  2006. svc->currentprobe_exec_time = *nsock_gettimeofday();
  2007. send_probe_text(nsp, nsi, svc, probe);
  2008. // Now let us read any results
  2009. nsock_read(nsp, nsi, servicescan_read_handler, svc->probe_timemsleft(probe, nsock_gettimeofday()), svc);
  2010. } else {
  2011. switch(status) {
  2012. case NSE_STATUS_TIMEOUT:
  2013. case NSE_STATUS_ERROR:
  2014. case NSE_STATUS_PROXYERROR:
  2015. // This is not good. The connect() really shouldn't generally
  2016. // be timing out like that. We'll mark this svc as incomplete
  2017. // and move it to the finished bin.
  2018. if (o.debugging)
  2019. error("Got nsock CONNECT response with status %s - aborting this service", nse_status2str(status));
  2020. end_svcprobe(nsp, PROBESTATE_INCOMPLETE, SG, svc, nsi);
  2021. break;
  2022. case NSE_STATUS_KILL:
  2023. /* User probablby specified host_timeout and so the service scan is
  2024. * shutting down */
  2025. end_svcprobe(nsp, PROBESTATE_INCOMPLETE, SG, svc, nsi);
  2026. return;
  2027. default:
  2028. fatal("Unexpected nsock status (%d) returned for connection attempt", (int)status);
  2029. }
  2030. }
  2031. // We may have room for more pr0bes!
  2032. launchSomeServiceProbes(nsp, SG);
  2033. return;
  2034. }
  2035. static void servicescan_write_handler(nsock_pool nsp, nsock_event nse, void *mydata) {
  2036. enum nse_status status = nse_status(nse);
  2037. nsock_iod nsi;
  2038. ServiceNFO *svc = (ServiceNFO *)mydata;
  2039. ServiceGroup *SG;
  2040. int err;
  2041. SG = (ServiceGroup *) nsp_getud(nsp);
  2042. nsi = nse_iod(nse);
  2043. // Check if a status message was requested
  2044. if (keyWasPressed()) {
  2045. SG->SPM->printStats(SG->services_finished.size() /
  2046. ((double)SG->services_remaining.size() + SG->services_in_progress.size() +
  2047. SG->services_finished.size()), nsock_gettimeofday());
  2048. }
  2049. if (svc->target->timedOut(nsock_gettimeofday())) {
  2050. end_svcprobe(nsp, PROBESTATE_INCOMPLETE, SG, svc, nsi);
  2051. return;
  2052. }
  2053. if (status == NSE_STATUS_SUCCESS)
  2054. return;
  2055. if (status == NSE_STATUS_KILL) {
  2056. /* User probablby specified host_timeout and so the service scan is
  2057. shutting down */
  2058. end_svcprobe(nsp, PROBESTATE_INCOMPLETE, SG, svc, nsi);
  2059. return;
  2060. }
  2061. if (status == NSE_STATUS_ERROR || status == NSE_STATUS_PROXYERROR) {
  2062. err = nse_errorcode(nse);
  2063. error("Got nsock WRITE error #%d (%s)", err, strerror(err));
  2064. }
  2065. // Uh-oh. Some sort of write failure ... maybe the connection closed
  2066. // on us unexpectedly?
  2067. if (o.debugging)
  2068. error("Got nsock WRITE response with status %s - aborting this service", nse_status2str(status));
  2069. end_svcprobe(nsp, PROBESTATE_INCOMPLETE, SG, svc, nsi);
  2070. // We may have room for more pr0bes!
  2071. launchSomeServiceProbes(nsp, SG);
  2072. return;
  2073. }
  2074. static void servicescan_read_handler(nsock_pool nsp, nsock_event nse, void *mydata) {
  2075. nsock_iod nsi = nse_iod(nse);
  2076. enum nse_status status = nse_status(nse);
  2077. enum nse_type type = nse_type(nse);
  2078. ServiceNFO *svc = (ServiceNFO *) mydata;
  2079. ServiceProbe *probe = svc->currentProbe();
  2080. ServiceGroup *SG = (ServiceGroup *) nsp_getud(nsp);
  2081. const u8 *readstr;
  2082. int readstrlen;
  2083. const struct MatchDetails *MD;
  2084. int fallbackDepth=0;
  2085. assert(type == NSE_TYPE_READ);
  2086. if (svc->target->timedOut(nsock_gettimeofday())) {
  2087. end_svcprobe(nsp, PROBESTATE_INCOMPLETE, SG, svc, nsi);
  2088. } else if (status == NSE_STATUS_SUCCESS) {
  2089. // w00p, w00p, we read something back from the port.
  2090. readstr = (u8 *) nse_readbuf(nse, &readstrlen);
  2091. adjustPortStateIfNecessary(svc); /* A response means PORT_OPENFILTERED is really PORT_OPEN */
  2092. svc->appendtocurrentproberesponse(readstr, readstrlen);
  2093. // now get the full version
  2094. readstr = svc->getcurrentproberesponse(&readstrlen);
  2095. for (MD = NULL; probe->fallbacks[fallbackDepth] != NULL; fallbackDepth++) {
  2096. MD = (probe->fallbacks[fallbackDepth])->testMatch(readstr, readstrlen);
  2097. if (MD && MD->serviceName) break; // Found one!
  2098. }
  2099. if (MD && MD->serviceName) {
  2100. // WOO HOO!!!!!! MATCHED! But might be soft
  2101. if (MD->isSoft && svc->probe_matched) {
  2102. if (strcmp(svc->probe_matched, MD->serviceName) != 0)
  2103. error("WARNING: Service %s:%hu had already soft-matched %s, but now soft-matched %s; ignoring second value", svc->target->targetipstr(), svc->portno, svc->probe_matched, MD->serviceName);
  2104. // No error if its the same - that happens frequently. For
  2105. // example, if we read more data for the same probe response
  2106. // it will probably still match.
  2107. } else {
  2108. if (o.debugging > 1 || o.versionTrace()) {
  2109. if (MD->product || MD->version || MD->info)
  2110. log_write(LOG_PLAIN, "Service scan match (Probe %s matched with %s line %d): %s:%hu is %s%s. Version: |%s|%s|%s|\n",
  2111. probe->getName(), (*probe->fallbacks[fallbackDepth]).getName(),
  2112. MD->lineno,
  2113. svc->target->targetipstr(), svc->portno, (svc->tunnel == SERVICE_TUNNEL_SSL)? "SSL/" : "",
  2114. MD->serviceName, (MD->product)? MD->product : "", (MD->version)? MD->version : "",
  2115. (MD->info)? MD->info : "");
  2116. else
  2117. log_write(LOG_PLAIN, "Service scan %s match (Probe %s matched with %s line %d): %s:%hu is %s%s\n",
  2118. (MD->isSoft)? "soft" : "hard",
  2119. probe->getName(), (*probe->fallbacks[fallbackDepth]).getName(),
  2120. MD->lineno,
  2121. svc->target->targetipstr(), svc->portno, (svc->tunnel == SERVICE_TUNNEL_SSL)? "SSL/" : "", MD->serviceName);
  2122. }
  2123. svc->probe_matched = MD->serviceName;
  2124. if (MD->product)
  2125. Strncpy(svc->product_matched, MD->product, sizeof(svc->product_matched));
  2126. if (MD->version)
  2127. Strncpy(svc->version_matched, MD->version, sizeof(svc->version_matched));
  2128. if (MD->info)
  2129. Strncpy(svc->extrainfo_matched, MD->info, sizeof(svc->extrainfo_matched));
  2130. if (MD->hostname)
  2131. Strncpy(svc->hostname_matched, MD->hostname, sizeof(svc->hostname_matched));
  2132. if (MD->ostype)
  2133. Strncpy(svc->ostype_matched, MD->ostype, sizeof(svc->ostype_matched));
  2134. if (MD->devicetype)
  2135. Strncpy(svc->devicetype_matched, MD->devicetype, sizeof(svc->devicetype_matched));
  2136. if (MD->cpe_a)
  2137. Strncpy(svc->cpe_a_matched, MD->cpe_a, sizeof(svc->cpe_a_matched));
  2138. if (MD->cpe_h)
  2139. Strncpy(svc->cpe_h_matched, MD->cpe_h, sizeof(svc->cpe_h_matched));
  2140. if (MD->cpe_o)
  2141. Strncpy(svc->cpe_o_matched, MD->cpe_o, sizeof(svc->cpe_o_matched));
  2142. svc->softMatchFound = MD->isSoft;
  2143. if (!svc->softMatchFound) {
  2144. // We might be able to continue scan through a tunnel protocol
  2145. // like SSL
  2146. if (scanThroughTunnel(nsp, nsi, SG, svc) == 0)
  2147. end_svcprobe(nsp, PROBESTATE_FINISHED_HARDMATCHED, SG, svc, nsi);
  2148. }
  2149. }
  2150. }
  2151. if (!MD || !MD->serviceName || MD->isSoft) {
  2152. // Didn't match... maybe reading more until timeout will help
  2153. // TODO: For efficiency I should be able to test if enough data
  2154. // has been received rather than always waiting for the reading
  2155. // to timeout. For now I'll limit it to 4096 bytes just to
  2156. // avoid reading megs from services like chargen. But better
  2157. // approach is needed.
  2158. if (svc->probe_timemsleft(probe) > 0 && readstrlen < 4096) {
  2159. nsock_read(nsp, nsi, servicescan_read_handler, svc->probe_timemsleft(probe), svc);
  2160. } else {
  2161. // Failed -- lets go to the next probe.
  2162. if (readstrlen > 0)
  2163. svc->addToServiceFingerprint(probe->getName(), readstr, readstrlen);
  2164. startNextProbe(nsp, nsi, SG, svc, false);
  2165. }
  2166. }
  2167. } else if (status == NSE_STATUS_TIMEOUT) {
  2168. // Failed to read enough to make a match in the given amount of time. So we
  2169. // move on to the next probe. If this was a NULL probe, we can simply
  2170. // send the new probe text immediately. Otherwise we make a new connection.
  2171. readstr = svc->getcurrentproberesponse(&readstrlen);
  2172. if (readstrlen > 0)
  2173. svc->addToServiceFingerprint(svc->currentProbe()->getName(), readstr,
  2174. readstrlen);
  2175. startNextProbe(nsp, nsi, SG, svc, false);
  2176. } else if (status == NSE_STATUS_EOF) {
  2177. // The jerk closed on us during read request!
  2178. // If this was during the NULL probe, let's (for now) assume
  2179. // the port is TCP wrapped. Otherwise, we'll treat it as a nomatch
  2180. readstr = svc->getcurrentproberesponse(&readstrlen);
  2181. if (readstrlen > 0)
  2182. svc->addToServiceFingerprint(svc->currentProbe()->getName(), readstr,
  2183. readstrlen);
  2184. if (probe->isNullProbe() && readstrlen == 0) {
  2185. // TODO: Perhaps should do further verification before making this assumption
  2186. end_svcprobe(nsp, PROBESTATE_FINISHED_TCPWRAPPED, SG, svc, nsi);
  2187. } else {
  2188. // Perhaps this service didn't like the particular probe text.
  2189. // We'll try the next one
  2190. startNextProbe(nsp, nsi, SG, svc, true);
  2191. }
  2192. } else if (status == NSE_STATUS_ERROR) {
  2193. // Errors might happen in some cases ... I'll worry about later
  2194. int err = nse_errorcode(nse);
  2195. switch(err) {
  2196. case ECONNRESET:
  2197. case ECONNREFUSED: // weird to get this on a connected socket (shrug) but
  2198. // BSD sometimes gives it
  2199. case ECONNABORTED:
  2200. // Jerk hung up on us. Probably didn't like our probe. We treat it as with EOF above.
  2201. if (probe->isNullProbe()) {
  2202. // TODO: Perhaps should do further verification before making this assumption
  2203. end_svcprobe(nsp, PROBESTATE_FINISHED_TCPWRAPPED, SG, svc, nsi);
  2204. } else {
  2205. // Perhaps this service didn't like the particular probe text. We'll try the
  2206. // next one
  2207. startNextProbe(nsp, nsi, SG, svc, true);
  2208. }
  2209. break;
  2210. case EHOSTUNREACH:
  2211. // That is funny. The port scanner listed the port as open. Maybe it got unplugged, or firewalled us, or did
  2212. // something else nasty during the scan. Shrug. I'll give up on this port
  2213. end_svcprobe(nsp, PROBESTATE_INCOMPLETE, SG, svc, nsi);
  2214. break;
  2215. #ifndef WIN32
  2216. case EPIPE:
  2217. case ENETRESET:
  2218. //This error (same as WSAENETRESET according to nbase_winunix) is Microsoft only error, where the connected host crashes and then resets during the communication
  2219. //More information can be found at http://www.sockets.com/err_lst1.htm#WSAENETRESET.
  2220. //I assume that we shouldn't bother doing anything beyond catching it, and then going on to the next probe.
  2221. #endif
  2222. #ifdef EPROTO
  2223. case EPROTO:
  2224. // EPROTO is suspected to be caused by an active IDS/IPS that forges ICMP
  2225. // type-12 errors ("Parameter problem"). It's been seen in response to the
  2226. // Sqlping probe.
  2227. #endif
  2228. case EIO:
  2229. // Usually an SSL error of some sort (those are presently
  2230. // hardcoded to EIO). I'll just try the next probe.
  2231. startNextProbe(nsp, nsi, SG, svc, true);
  2232. break;
  2233. default:
  2234. fatal("Unexpected error in NSE_TYPE_READ callback. Error code: %d (%s)", err,
  2235. socket_strerror(err));
  2236. }
  2237. } else if (status == NSE_STATUS_KILL) {
  2238. /* User probablby specified host_timeout and so the service scan is
  2239. shutting down */
  2240. end_svcprobe(nsp, PROBESTATE_INCOMPLETE, SG, svc, nsi);
  2241. return;
  2242. } else {
  2243. fatal("Unexpected status (%d) in NSE_TYPE_READ callback.", (int) status);
  2244. }
  2245. // We may have room for more pr0bes!
  2246. launchSomeServiceProbes(nsp, SG);
  2247. return;
  2248. }
  2249. // This is used in processResults to determine whether a FP
  2250. // should be printed based on type of match, version intensity, etc.
  2251. static int shouldWePrintFingerprint(ServiceNFO *svc) {
  2252. // Never print FP if hardmatched
  2253. if (svc->probe_state == PROBESTATE_FINISHED_HARDMATCHED)
  2254. return 0;
  2255. // If we were called with a version_intensity less than
  2256. // the default, don't bother printing.
  2257. if (o.version_intensity < 7) return 0;
  2258. return 1;
  2259. }
  2260. // This is passed a completed ServiceGroup which contains the scanning results for every service.
  2261. // The function iterates through each finished service and adds the results to Target structure for
  2262. // Nmap to output later.
  2263. static void processResults(ServiceGroup *SG) {
  2264. std::list<ServiceNFO *>::iterator svc;
  2265. for(svc = SG->services_finished.begin(); svc != SG->services_finished.end(); svc++) {
  2266. if ((*svc)->probe_state != PROBESTATE_FINISHED_NOMATCH) {
  2267. std::vector<const char *> cpe;
  2268. if (*(*svc)->cpe_a_matched)
  2269. cpe.push_back((*svc)->cpe_a_matched);
  2270. if (*(*svc)->cpe_h_matched)
  2271. cpe.push_back((*svc)->cpe_h_matched);
  2272. if (*(*svc)->cpe_o_matched)
  2273. cpe.push_back((*svc)->cpe_o_matched);
  2274. (*svc)->target->ports.setServiceProbeResults((*svc)->portno, (*svc)->proto,
  2275. (*svc)->probe_state,
  2276. (*svc)->probe_matched,
  2277. (*svc)->tunnel,
  2278. *(*svc)->product_matched? (*svc)->product_matched : NULL,
  2279. *(*svc)->version_matched? (*svc)->version_matched : NULL,
  2280. *(*svc)->extrainfo_matched? (*svc)->extrainfo_matched : NULL,
  2281. *(*svc)->hostname_matched? (*svc)->hostname_matched : NULL,
  2282. *(*svc)->ostype_matched? (*svc)->ostype_matched : NULL,
  2283. *(*svc)->devicetype_matched? (*svc)->devicetype_matched : NULL,
  2284. (cpe.size() > 0) ? &cpe : NULL,
  2285. shouldWePrintFingerprint(*svc) ? (*svc)->getServiceFingerprint(NULL) : NULL);
  2286. } else {
  2287. (*svc)->target->ports.setServiceProbeResults((*svc)->portno, (*svc)->proto,
  2288. (*svc)->probe_state, NULL,
  2289. (*svc)->tunnel, NULL, NULL, NULL, NULL, NULL, NULL,
  2290. NULL,
  2291. (*svc)->getServiceFingerprint(NULL));
  2292. }
  2293. }
  2294. }
  2295. /* Start the timeout clocks of any targets that have probes. Assumes
  2296. that this is called before any probes have been launched (so they
  2297. are all in services_remaining */
  2298. static void startTimeOutClocks(ServiceGroup *SG) {
  2299. std::list<ServiceNFO *>::iterator svcI;
  2300. Target *target = NULL;
  2301. struct timeval tv;
  2302. gettimeofday(&tv, NULL);
  2303. for(svcI = SG->services_remaining.begin();
  2304. svcI != SG->services_remaining.end(); svcI++) {
  2305. target = (*svcI)->target;
  2306. if (!target->timeOutClockRunning())
  2307. target->startTimeOutClock(&tv);
  2308. }
  2309. }
  2310. // We iterate through SG->services_remaining and remove any with port/protocol
  2311. // pairs that are excluded. We use AP->isExcluded() to determine which ports
  2312. // are excluded.
  2313. static void remove_excluded_ports(AllProbes *AP, ServiceGroup *SG) {
  2314. std::list<ServiceNFO *>::iterator i, nxt;
  2315. ServiceNFO *svc;
  2316. for(i = SG->services_remaining.begin(); i != SG->services_remaining.end(); i=nxt) {
  2317. nxt = i;
  2318. nxt++;
  2319. svc = *i;
  2320. if (AP->isExcluded(svc->portno, svc->proto)) {
  2321. if (o.debugging) log_write(LOG_PLAIN, "EXCLUDING %d/%s\n", svc->portno,
  2322. IPPROTO2STR(svc->proto));
  2323. svc->target->ports.setServiceProbeResults(svc->portno, svc->proto,
  2324. PROBESTATE_EXCLUDED, NULL,
  2325. SERVICE_TUNNEL_NONE,
  2326. "Excluded from version scan", NULL,
  2327. NULL, NULL, NULL, NULL, NULL, NULL);
  2328. SG->services_remaining.erase(i);
  2329. SG->services_finished.push_back(svc);
  2330. }
  2331. }
  2332. }
  2333. /* Execute a service fingerprinting scan against all open ports of the
  2334. Targets specified. */
  2335. int service_scan(std::vector<Target *> &Targets) {
  2336. // int service_scan(Target *targets[], int num_targets)
  2337. AllProbes *AP;
  2338. ServiceGroup *SG;
  2339. nsock_pool nsp;
  2340. struct timeval now;
  2341. int timeout;
  2342. enum nsock_loopstatus looprc;
  2343. struct timeval starttv;
  2344. if (Targets.size() == 0)
  2345. return 1;
  2346. AP = AllProbes::service_scan_init();
  2347. // Now I convert the targets into a new ServiceGroup
  2348. SG = new ServiceGroup(Targets, AP);
  2349. if (o.override_excludeports) {
  2350. if (o.debugging || o.verbose) log_write(LOG_PLAIN, "Overriding exclude ports option! Some undesirable ports may be version scanned!\n");
  2351. } else {
  2352. remove_excluded_ports(AP, SG);
  2353. }
  2354. startTimeOutClocks(SG);
  2355. if (SG->services_remaining.size() == 0) {
  2356. delete SG;
  2357. return 1;
  2358. }
  2359. gettimeofday(&starttv, NULL);
  2360. if (o.verbose) {
  2361. char targetstr[128];
  2362. bool plural = (Targets.size() != 1);
  2363. if (!plural) {
  2364. (*(Targets.begin()))->NameIP(targetstr, sizeof(targetstr));
  2365. } else Snprintf(targetstr, sizeof(targetstr), "%u hosts", (unsigned) Targets.size());
  2366. log_write(LOG_STDOUT, "Scanning %u %s on %s\n",
  2367. (unsigned) SG->services_remaining.size(),
  2368. (SG->services_remaining.size() == 1)? "service" : "services",
  2369. targetstr);
  2370. }
  2371. // Lets create a nsock pool for managing all the concurrent probes
  2372. // Store the servicegroup in there for availability in callbacks
  2373. if ((nsp = nsp_new(SG)) == NULL) {
  2374. fatal("%s() failed to create new nsock pool.", __func__);
  2375. }
  2376. nsock_set_log_function(nsp, nmap_nsock_stderr_logger);
  2377. nmap_adjust_loglevel(nsp, o.versionTrace());
  2378. nsp_setdevice(nsp, o.device);
  2379. if (o.proxy_chain) {
  2380. nsp_set_proxychain(nsp, o.proxy_chain);
  2381. }
  2382. #if HAVE_OPENSSL
  2383. /* We don't care about connection security in version detection. */
  2384. nsp_ssl_init_max_speed(nsp);
  2385. #endif
  2386. launchSomeServiceProbes(nsp, SG);
  2387. // How long do we have before timing out?
  2388. gettimeofday(&now, NULL);
  2389. timeout = -1;
  2390. // OK! Lets start our main loop!
  2391. looprc = nsock_loop(nsp, timeout);
  2392. if (looprc == NSOCK_LOOP_ERROR) {
  2393. int err = nsp_geterrorcode(nsp);
  2394. fatal("Unexpected nsock_loop error. Error code %d (%s)", err, socket_strerror(err));
  2395. }
  2396. nsp_delete(nsp);
  2397. if (o.verbose) {
  2398. char additional_info[128];
  2399. if (SG->num_hosts_timedout == 0)
  2400. Snprintf(additional_info, sizeof(additional_info), "%u %s on %u %s",
  2401. (unsigned) SG->services_finished.size(),
  2402. (SG->services_finished.size() == 1)? "service" : "services",
  2403. (unsigned) Targets.size(), (Targets.size() == 1)? "host" : "hosts");
  2404. else Snprintf(additional_info, sizeof(additional_info), "%u %s timed out",
  2405. SG->num_hosts_timedout,
  2406. (SG->num_hosts_timedout == 1)? "host" : "hosts");
  2407. SG->SPM->endTask(NULL, additional_info);
  2408. }
  2409. // Yeah - done with the service scan. Now I go through the results
  2410. // discovered, store the important info away, and free up everything
  2411. // else.
  2412. processResults(SG);
  2413. delete SG;
  2414. return 0;
  2415. }