PageRenderTime 44ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/service_scan.cc

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