PageRenderTime 52ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/nse_nsock.cc

https://gitlab.com/g10h4ck/nmap-gsoc2015
C++ | 1121 lines | 1088 code | 27 blank | 6 comment | 11 complexity | 097e06c91704e3553b8d1501c48b78db MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, Apache-2.0, LGPL-2.0, LGPL-2.1, MIT
  1. #include "nsock.h"
  2. #include "nmap_error.h"
  3. #include "NmapOps.h"
  4. #include "tcpip.h"
  5. #include "protocols.h"
  6. #include "libnetutil/netutil.h"
  7. #include "nse_nsock.h"
  8. #include "nse_main.h"
  9. #include "nse_utility.h"
  10. #include "nse_ssl_cert.h"
  11. #if HAVE_OPENSSL
  12. /* See the comments in service_scan.cc for the reason for _WINSOCKAPI_. */
  13. # define _WINSOCKAPI_
  14. # include <openssl/ssl.h>
  15. #endif
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <errno.h>
  19. #include <sstream>
  20. #include <iomanip>
  21. #define DEFAULT_TIMEOUT 30000
  22. /* Upvalues for library variables */
  23. enum {
  24. NSOCK_POOL = lua_upvalueindex(1),
  25. NSOCK_SOCKET = lua_upvalueindex(2), /* nsock socket metatable */
  26. PCAP_SOCKET = lua_upvalueindex(3), /* pcap socket metatable */
  27. THREAD_SOCKETS = lua_upvalueindex(4), /* <Thread, Table of Sockets (keys)> */
  28. CONNECT_WAITING = lua_upvalueindex(5), /* Threads waiting to lock */
  29. KEY_PCAP = lua_upvalueindex(6) /* Keys to pcap sockets */
  30. };
  31. /* Integer keys in the Nsock userdata environments */
  32. #define THREAD_I 1 /* The thread that yielded */
  33. #define BUFFER_I 2 /* Location of Userdata Buffer */
  34. extern NmapOps o;
  35. typedef struct nse_nsock_udata
  36. {
  37. nsock_iod nsiod;
  38. unsigned timeout;
  39. lua_State *thread;
  40. int proto;
  41. int af;
  42. const char *direction;
  43. const char *action;
  44. void *ssl_session;
  45. struct sockaddr_storage source_addr;
  46. size_t source_addrlen;
  47. /* PCAP */
  48. int is_pcap;
  49. nsock_event_id nseid;
  50. struct timeval recvtime; /* Time packet was received, if r_success is true */
  51. } nse_nsock_udata;
  52. static int gc_pool (lua_State *L)
  53. {
  54. nsock_pool *nsp = (nsock_pool *) lua_touserdata(L, 1);
  55. assert(*nsp != NULL);
  56. nsock_pool_delete(*nsp);
  57. *nsp = NULL;
  58. return 0;
  59. }
  60. static nsock_pool new_pool (lua_State *L)
  61. {
  62. nsock_pool nsp = nsock_pool_new(NULL);
  63. nsock_pool *nspp;
  64. /* configure logging */
  65. nsock_set_log_function(nmap_nsock_stderr_logger);
  66. nmap_adjust_loglevel(o.scriptTrace());
  67. nsock_pool_set_device(nsp, o.device);
  68. if (o.proxy_chain)
  69. nsock_pool_set_proxychain(nsp, o.proxy_chain);
  70. nsock_pool_set_broadcast(nsp, true);
  71. nspp = (nsock_pool *) lua_newuserdata(L, sizeof(nsock_pool));
  72. *nspp = nsp;
  73. lua_newtable(L);
  74. lua_pushcfunction(L, gc_pool);
  75. lua_setfield(L, -2, "__gc");
  76. lua_setmetatable(L, -2);
  77. return nsp;
  78. }
  79. static nsock_pool get_pool (lua_State *L)
  80. {
  81. nsock_pool *nspp;
  82. nspp = (nsock_pool *) lua_touserdata(L, NSOCK_POOL);
  83. assert(nspp != NULL);
  84. assert(*nspp != NULL);
  85. return *nspp;
  86. }
  87. static std::string hexify (const unsigned char *str, size_t len)
  88. {
  89. size_t num = 0;
  90. std::ostringstream ret;
  91. // If more than 95% of the chars are printable, we escape unprintable chars
  92. for (size_t i = 0; i < len; i++)
  93. if (isprint((int) str[i]))
  94. num++;
  95. if ((double) num / (double) len >= 0.95)
  96. {
  97. for (size_t i = 0; i < len; i++)
  98. {
  99. if (isprint((int) str[i]) || isspace((int) str[i]))
  100. ret << str[i];
  101. else
  102. ret << std::setw(3) << "\\" << (unsigned int) (unsigned char) str[i];
  103. }
  104. return ret.str();
  105. }
  106. ret << std::setbase(16) << std::setfill('0');
  107. for (size_t i = 0; i < len; i += 16)
  108. {
  109. ret << std::setw(8) << i << ": ";
  110. for (size_t j = i; j < i + 16; j++)
  111. if (j < len)
  112. ret << std::setw(2) << (unsigned int) (unsigned char) str[j] << " ";
  113. else
  114. ret << " ";
  115. for (size_t j = i; j < i + 16 && j < len; j++)
  116. ret.put(isgraph((int) str[j]) ? (unsigned char) str[j] : ' ');
  117. ret << std::endl;
  118. }
  119. return ret.str();
  120. }
  121. /* Some constants used for enforcing a limit on the number of open sockets
  122. * in use by threads. The maximum value between MAX_PARALLELISM and
  123. * o.max_parallelism is the max # of threads that can have connected sockets
  124. * (open).
  125. *
  126. * THREAD_SOCKETS is a weak keyed table of <Thread, Socket Table> pairs.
  127. * A socket table is a weak keyed table (socket keys with garbage values) of
  128. * sockets the Thread has allocated but not necessarily open). You may
  129. * test for an open socket by checking whether its nsiod field in the
  130. * socket userdata structure is not NULL.
  131. *
  132. * CONNECT_WAITING is a weak keyed table of <Thread, Garbage Value> pairs.
  133. * The table contains threads waiting to make a socket connection.
  134. */
  135. #define MAX_PARALLELISM 20
  136. /* int socket_lock (lua_State *L)
  137. *
  138. * This function is called by l_connect to get a "lock" on a socket.
  139. * When connect calls this function, it expects socket_lock to yield forcing
  140. * connect to be restarted when resumed or it succeeds returning normally.
  141. */
  142. static int socket_lock (lua_State *L, int idx)
  143. {
  144. unsigned p = o.max_parallelism == 0 ? MAX_PARALLELISM : o.max_parallelism;
  145. int top = lua_gettop(L);
  146. nse_base(L);
  147. lua_rawget(L, THREAD_SOCKETS);
  148. if (lua_istable(L, -1))
  149. {
  150. /* Thread already has a "lock" with open sockets. Place the new socket
  151. * in its sockets table */
  152. lua_pushvalue(L, idx);
  153. lua_pushboolean(L, true);
  154. lua_rawset(L, -3);
  155. } else if (nseU_tablen(L, THREAD_SOCKETS) <= p)
  156. {
  157. /* There is room for this thread to open sockets */
  158. nse_base(L);
  159. nseU_weaktable(L, 0, 0, "k"); /* weak socket references */
  160. lua_pushvalue(L, idx); /* socket */
  161. lua_pushboolean(L, true);
  162. lua_rawset(L, -3); /* add to sockets table */
  163. lua_rawset(L, THREAD_SOCKETS); /* add new <Thread, Sockets Table> Pair
  164. * to THREAD_SOCKETS */
  165. } else
  166. {
  167. nse_base(L);
  168. lua_pushboolean(L, true);
  169. lua_rawset(L, CONNECT_WAITING);
  170. lua_settop(L, top); /* restore stack to original condition for l_connect */
  171. return 0;
  172. }
  173. lua_settop(L, top); /* restore stack to original condition for l_connect */
  174. return 1;
  175. }
  176. static void socket_unlock (lua_State *L)
  177. {
  178. int top = lua_gettop(L);
  179. lua_gc(L, LUA_GCSTOP, 0); /* don't collect threads during iteration */
  180. for (lua_pushnil(L); lua_next(L, THREAD_SOCKETS); lua_pop(L, 1))
  181. {
  182. unsigned open = 0;
  183. if (lua_status(lua_tothread(L, -2)) == LUA_YIELD)
  184. {
  185. for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) /* for each socket */
  186. {
  187. if (((nse_nsock_udata *) lua_touserdata(L, -2))->nsiod != NULL)
  188. open++;
  189. }
  190. }
  191. if (open == 0) /* thread has no open sockets? */
  192. {
  193. /* close all of its sockets */
  194. for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) /* for each socket */
  195. {
  196. lua_getfield(L, -2, "close");
  197. lua_pushvalue(L, -3);
  198. lua_call(L, 1, 0);
  199. }
  200. lua_pushvalue(L, -2); /* thread key */
  201. lua_pushnil(L);
  202. lua_rawset(L, THREAD_SOCKETS);
  203. for (lua_pushnil(L); lua_next(L, CONNECT_WAITING); lua_pop(L, 1))
  204. {
  205. nse_restore(lua_tothread(L, -2), 0);
  206. lua_pushvalue(L, -2);
  207. lua_pushnil(L);
  208. lua_rawset(L, CONNECT_WAITING);
  209. }
  210. }
  211. }
  212. lua_gc(L, LUA_GCRESTART, 0);
  213. lua_settop(L, top);
  214. }
  215. static const char *inet_ntop_both (int af, const void *v_addr, char *ipstring)
  216. {
  217. if (af == AF_INET)
  218. {
  219. inet_ntop(AF_INET, &((struct sockaddr_in *) v_addr)->sin_addr,
  220. ipstring, INET6_ADDRSTRLEN);
  221. return ipstring;
  222. }
  223. #ifdef HAVE_IPV6
  224. else if (af == AF_INET6)
  225. {
  226. inet_ntop(AF_INET6, &((struct sockaddr_in6 *) v_addr)->sin6_addr,
  227. ipstring, INET6_ADDRSTRLEN);
  228. return ipstring;
  229. }
  230. #endif
  231. else
  232. return "unknown protocol";
  233. }
  234. static unsigned short inet_port_both (int af, const void *v_addr)
  235. {
  236. int port;
  237. if (af == AF_INET)
  238. port = ((struct sockaddr_in *) v_addr)->sin_port;
  239. #ifdef HAVE_IPV6
  240. else if (af == AF_INET6)
  241. port = ((struct sockaddr_in6 *) v_addr)->sin6_port;
  242. #endif
  243. else
  244. port = 0;
  245. return ntohs(port);
  246. }
  247. #define TO ">"
  248. #define FROM "<"
  249. static void trace (nsock_iod nsiod, const char *message, const char *dir)
  250. {
  251. if (o.scriptTrace())
  252. {
  253. if (!nsock_iod_is_pcap(nsiod))
  254. {
  255. int protocol;
  256. int af;
  257. char ipstring_local[INET6_ADDRSTRLEN];
  258. char ipstring_remote[INET6_ADDRSTRLEN];
  259. struct sockaddr_storage local;
  260. struct sockaddr_storage remote;
  261. nsock_iod_get_communication_info(nsiod, &protocol, &af,
  262. (sockaddr *) &local, (sockaddr *) &remote, sizeof(sockaddr_storage));
  263. log_write(LOG_STDOUT, "%s: %s %s:%d %s %s:%d | %s\n",
  264. SCRIPT_ENGINE,
  265. IPPROTO2STR_UC(protocol),
  266. inet_ntop_both(af, &local, ipstring_local),
  267. inet_port_both(af, &local),
  268. dir,
  269. inet_ntop_both(af, &remote, ipstring_remote),
  270. inet_port_both(af, &remote), message);
  271. } else {
  272. log_write(LOG_STDOUT, "%s: %s | %s\n", SCRIPT_ENGINE, dir, message);
  273. }
  274. }
  275. }
  276. static void status (lua_State *L, enum nse_status status)
  277. {
  278. switch (status)
  279. {
  280. case NSE_STATUS_SUCCESS:
  281. lua_pushboolean(L, true);
  282. nse_restore(L, 1);
  283. break;
  284. case NSE_STATUS_KILL:
  285. case NSE_STATUS_CANCELLED:
  286. return; /* do nothing! */
  287. case NSE_STATUS_EOF:
  288. case NSE_STATUS_ERROR:
  289. case NSE_STATUS_TIMEOUT:
  290. case NSE_STATUS_PROXYERROR:
  291. lua_pushnil(L);
  292. lua_pushstring(L, nse_status2str(status));
  293. nse_restore(L, 2);
  294. break;
  295. case NSE_STATUS_NONE:
  296. default:
  297. assert(0);
  298. break;
  299. }
  300. }
  301. static void callback (nsock_pool nsp, nsock_event nse, void *ud)
  302. {
  303. nse_nsock_udata *nu = (nse_nsock_udata *) ud;
  304. lua_State *L = nu->thread;
  305. assert(lua_status(L) == LUA_YIELD);
  306. trace(nse_iod(nse), nu->action, nu->direction);
  307. status(L, nse_status(nse));
  308. }
  309. static int yield (lua_State *L, nse_nsock_udata *nu, const char *action,
  310. const char *direction, int ctx, lua_CFunction k)
  311. {
  312. lua_getuservalue(L, 1);
  313. lua_pushthread(L);
  314. lua_rawseti(L, -2, THREAD_I);
  315. lua_pop(L, 1); /* nsock udata environment */
  316. nu->thread = L;
  317. nu->action = action;
  318. nu->direction = direction;
  319. return nse_yield(L, ctx, k);
  320. }
  321. /* In the case of unconnected UDP sockets, this function will call
  322. nsock_setup_udp on your behalf before returning true. */
  323. static nse_nsock_udata *check_nsock_udata (lua_State *L, int idx, bool open)
  324. {
  325. nse_nsock_udata *nu = (nse_nsock_udata *) nseU_checkudata(L, idx, NSOCK_SOCKET, "nsock");
  326. if (open && nu->nsiod == NULL) {
  327. /* The socket hasn't been connected or setup yet. Try doing a setup, or
  328. throw an error if that's not possible. */
  329. if (nu->proto == IPPROTO_UDP) {
  330. nsock_pool nsp;
  331. nsp = get_pool(L);
  332. nu->nsiod = nsock_iod_new(nsp, NULL);
  333. if (nu->source_addr.ss_family != AF_UNSPEC) {
  334. nsock_iod_set_localaddr(nu->nsiod, &nu->source_addr, nu->source_addrlen);
  335. } else if (o.spoofsource) {
  336. struct sockaddr_storage ss;
  337. size_t sslen;
  338. o.SourceSockAddr(&ss, &sslen);
  339. nsock_iod_set_localaddr(nu->nsiod, &ss, sslen);
  340. }
  341. if (o.ipoptionslen)
  342. nsock_iod_set_ipoptions(nu->nsiod, o.ipoptions, o.ipoptionslen);
  343. if (nsock_setup_udp(nsp, nu->nsiod, nu->af) == -1) {
  344. luaL_error(L, "Error in setup of iod with proto %d and af %d: %s (%d)",
  345. nu->proto, nu->af, socket_strerror(socket_errno()), socket_errno());
  346. }
  347. }
  348. }
  349. return nu;
  350. }
  351. /* If the socket udata nu is not open, return from the enclosing function with
  352. an error. */
  353. #define NSOCK_UDATA_ENSURE_OPEN(L, nu) \
  354. do { \
  355. if (nu->nsiod == NULL) \
  356. return nseU_safeerror(L, "socket must be connected"); \
  357. } while (0)
  358. static int l_loop (lua_State *L)
  359. {
  360. nsock_pool nsp = get_pool(L);
  361. int tout = luaL_checkint(L, 1);
  362. socket_unlock(L); /* clean up old socket locks */
  363. nmap_adjust_loglevel(o.scriptTrace());
  364. if (nsock_loop(nsp, tout) == NSOCK_LOOP_ERROR)
  365. return luaL_error(L, "a fatal error occurred in nsock_loop");
  366. return 0;
  367. }
  368. static int l_reconnect_ssl (lua_State *L)
  369. {
  370. nsock_pool nsp = get_pool(L);
  371. nse_nsock_udata *nu = check_nsock_udata(L, 1, true);
  372. NSOCK_UDATA_ENSURE_OPEN(L, nu);
  373. #ifndef HAVE_OPENSSL
  374. return nseU_safeerror(L, "sorry, you don't have OpenSSL");
  375. #endif
  376. nsock_reconnect_ssl(nsp, nu->nsiod, callback, nu->timeout,
  377. nu, nu->ssl_session);
  378. return yield(L, nu, "SSL RECONNECT", TO, 0, NULL);
  379. }
  380. static void close_internal (lua_State *L, nse_nsock_udata *nu);
  381. static int l_connect (lua_State *L)
  382. {
  383. enum type {TCP, UDP, SSL};
  384. static const char * const op[] = {"tcp", "udp", "ssl", NULL};
  385. nsock_pool nsp = get_pool(L);
  386. nse_nsock_udata *nu = check_nsock_udata(L, 1, false);
  387. const char *addr, *targetname; nseU_checktarget(L, 2, &addr, &targetname);
  388. const char *default_proto = NULL;
  389. unsigned short port = nseU_checkport(L, 3, &default_proto);
  390. if (default_proto == NULL) {
  391. switch (nu->proto) {
  392. case IPPROTO_TCP:
  393. default_proto = "tcp";
  394. break;
  395. case IPPROTO_UDP:
  396. default_proto = "udp";
  397. break;
  398. default:
  399. default_proto = "tcp";
  400. break;
  401. }
  402. }
  403. int what = luaL_checkoption(L, 4, default_proto, op);
  404. struct addrinfo *dest;
  405. int error_id;
  406. if (!socket_lock(L, 1)) /* we cannot get a socket lock */
  407. return nse_yield(L, 0, l_connect); /* restart on continuation */
  408. #ifndef HAVE_OPENSSL
  409. if (what == SSL)
  410. return nseU_safeerror(L, "sorry, you don't have OpenSSL");
  411. #endif
  412. /* If we're connecting by name, we should use the same AF as our scan */
  413. struct addrinfo hints = {0};
  414. /* First check if it's a numeric address */
  415. hints.ai_flags = AI_NUMERICHOST;
  416. error_id = getaddrinfo(addr, NULL, &hints, &dest);
  417. if (error_id == EAI_NONAME) {
  418. /* Nope, let's resolve it for the proper AF */
  419. hints.ai_flags = 0;
  420. hints.ai_family = o.af();
  421. error_id = getaddrinfo(addr, NULL, &hints, &dest);
  422. }
  423. if (error_id)
  424. return nseU_safeerror(L, gai_strerror(error_id));
  425. if (dest == NULL)
  426. return nseU_safeerror(L, "getaddrinfo returned success but no addresses");
  427. if (nu->nsiod != NULL)
  428. close_internal(L, nu);
  429. nu->nsiod = nsock_iod_new(nsp, NULL);
  430. if (nu->source_addr.ss_family != AF_UNSPEC) {
  431. nsock_iod_set_localaddr(nu->nsiod, &nu->source_addr, nu->source_addrlen);
  432. } else if (o.spoofsource) {
  433. struct sockaddr_storage ss;
  434. size_t sslen;
  435. o.SourceSockAddr(&ss, &sslen);
  436. nsock_iod_set_localaddr(nu->nsiod, &ss, sslen);
  437. }
  438. if (o.ipoptionslen)
  439. nsock_iod_set_ipoptions(nu->nsiod, o.ipoptions, o.ipoptionslen);
  440. if (targetname != NULL) {
  441. if (nsock_iod_set_hostname(nu->nsiod, targetname) == -1)
  442. fatal("nsock_iod_set_hostname(\"%s\" failed in %s()", targetname, __func__);
  443. }
  444. nu->af = dest->ai_addr->sa_family;
  445. switch (what)
  446. {
  447. case TCP:
  448. nu->proto = IPPROTO_TCP;
  449. nsock_connect_tcp(nsp, nu->nsiod, callback, nu->timeout, nu,
  450. dest->ai_addr, dest->ai_addrlen, port);
  451. break;
  452. case UDP:
  453. nu->proto = IPPROTO_UDP;
  454. nsock_connect_udp(nsp, nu->nsiod, callback, nu, dest->ai_addr,
  455. dest->ai_addrlen, port);
  456. break;
  457. case SSL:
  458. nu->proto = IPPROTO_TCP;
  459. nsock_connect_ssl(nsp, nu->nsiod, callback, nu->timeout, nu,
  460. dest->ai_addr, dest->ai_addrlen, IPPROTO_TCP, port, nu->ssl_session);
  461. break;
  462. }
  463. if (dest != NULL)
  464. freeaddrinfo(dest);
  465. return yield(L, nu, "CONNECT", TO, 0, NULL);
  466. }
  467. static int l_send (lua_State *L)
  468. {
  469. nsock_pool nsp = get_pool(L);
  470. nse_nsock_udata *nu = check_nsock_udata(L, 1, true);
  471. NSOCK_UDATA_ENSURE_OPEN(L, nu);
  472. size_t size;
  473. const char *string = luaL_checklstring(L, 2, &size);
  474. trace(nu->nsiod, hexify((unsigned char *) string, size).c_str(), TO);
  475. nsock_write(nsp, nu->nsiod, callback, nu->timeout, nu, string, size);
  476. return yield(L, nu, "SEND", TO, 0, NULL);
  477. }
  478. static int l_sendto (lua_State *L)
  479. {
  480. nsock_pool nsp = get_pool(L);
  481. nse_nsock_udata *nu = check_nsock_udata(L, 1, true);
  482. NSOCK_UDATA_ENSURE_OPEN(L, nu);
  483. size_t size;
  484. const char *addr, *targetname; nseU_checktarget(L, 2, &addr, &targetname);
  485. const char *default_proto = NULL;
  486. unsigned short port = nseU_checkport(L, 3, &default_proto);
  487. const char *string = luaL_checklstring(L, 4, &size);
  488. int error_id;
  489. struct addrinfo *dest;
  490. error_id = getaddrinfo(addr, NULL, NULL, &dest);
  491. if (error_id)
  492. return nseU_safeerror(L, gai_strerror(error_id));
  493. if (dest == NULL)
  494. return nseU_safeerror(L, "getaddrinfo returned success but no addresses");
  495. nsock_sendto(nsp, nu->nsiod, callback, nu->timeout, nu, dest->ai_addr, dest->ai_addrlen, port, string, size);
  496. trace(nu->nsiod, hexify((unsigned char *) string, size).c_str(), TO);
  497. freeaddrinfo(dest);
  498. return yield(L, nu, "SEND", TO, 0, NULL);
  499. }
  500. static void receive_callback (nsock_pool nsp, nsock_event nse, void *udata)
  501. {
  502. nse_nsock_udata *nu = (nse_nsock_udata *) udata;
  503. lua_State *L = nu->thread;
  504. assert(lua_status(L) == LUA_YIELD);
  505. if (nse_status(nse) == NSE_STATUS_SUCCESS)
  506. {
  507. int len;
  508. const char *str = nse_readbuf(nse, &len);
  509. trace(nse_iod(nse), hexify((const unsigned char *) str, len).c_str(), FROM);
  510. lua_pushboolean(L, true);
  511. lua_pushlstring(L, str, len);
  512. nse_restore(L, 2);
  513. }
  514. else
  515. status(L, nse_status(nse)); /* will also restore the thread */
  516. }
  517. static int l_receive (lua_State *L)
  518. {
  519. nsock_pool nsp = get_pool(L);
  520. nse_nsock_udata *nu = check_nsock_udata(L, 1, true);
  521. NSOCK_UDATA_ENSURE_OPEN(L, nu);
  522. nsock_read(nsp, nu->nsiod, receive_callback, nu->timeout, nu);
  523. return yield(L, nu, "RECEIVE", FROM, 0, NULL);
  524. }
  525. static int l_receive_lines (lua_State *L)
  526. {
  527. nsock_pool nsp = get_pool(L);
  528. nse_nsock_udata *nu = check_nsock_udata(L, 1, true);
  529. NSOCK_UDATA_ENSURE_OPEN(L, nu);
  530. nsock_readlines(nsp, nu->nsiod, receive_callback, nu->timeout, nu,
  531. luaL_checkint(L, 2));
  532. return yield(L, nu, "RECEIVE LINES", FROM, 0, NULL);
  533. }
  534. static int l_receive_bytes (lua_State *L)
  535. {
  536. nsock_pool nsp = get_pool(L);
  537. nse_nsock_udata *nu = check_nsock_udata(L, 1, true);
  538. NSOCK_UDATA_ENSURE_OPEN(L, nu);
  539. nsock_readbytes(nsp, nu->nsiod, receive_callback, nu->timeout, nu,
  540. luaL_checkint(L, 2));
  541. return yield(L, nu, "RECEIVE BYTES", FROM, 0, NULL);
  542. }
  543. static int l_receive_buf (lua_State *L)
  544. {
  545. nsock_pool nsp = get_pool(L);
  546. nse_nsock_udata *nu = check_nsock_udata(L, 1, true);
  547. NSOCK_UDATA_ENSURE_OPEN(L, nu);
  548. if (!(lua_type(L, 2) == LUA_TFUNCTION || lua_type(L, 2) == LUA_TSTRING))
  549. nseU_typeerror(L, 2, "function/string");
  550. luaL_checktype(L, 3, LUA_TBOOLEAN); /* 3 */
  551. if (lua_getctx(L, NULL) == LUA_OK)
  552. {
  553. lua_settop(L, 3); /* clear top */
  554. lua_getuservalue(L, 1); /* 4 */
  555. lua_rawgeti(L, 4, BUFFER_I); /* 5 */
  556. }
  557. else
  558. {
  559. /* Here we are returning from nsock_read below.
  560. * We have two extra values on the stack pushed by receive_callback.
  561. */
  562. assert(lua_gettop(L) == 7);
  563. if (lua_toboolean(L, 6)) /* success? */
  564. {
  565. lua_replace(L, 6); /* remove boolean */
  566. lua_concat(L, 2); /* concat BUFFER_I with received data */
  567. }
  568. else /* receive_callback encountered an error */
  569. return 2;
  570. }
  571. if (lua_isfunction(L, 2))
  572. {
  573. lua_pushvalue(L, 2);
  574. lua_pushvalue(L, 5);
  575. lua_call(L, 1, 2); /* we do not allow yields */
  576. }
  577. else /* string */
  578. {
  579. lua_getglobal(L, "string");
  580. lua_getfield(L, -1, "find");
  581. lua_replace(L, -2);
  582. lua_pushvalue(L, 5);
  583. lua_pushvalue(L, 2);
  584. lua_call(L, 2, 2); /* we do not allow yields */
  585. }
  586. if (lua_isnumber(L, -2) && lua_isnumber(L, -1)) /* found end? */
  587. {
  588. lua_Integer l = lua_tointeger(L, -2), r = lua_tointeger(L, -1);
  589. if (l > r || r > (lua_Integer) lua_rawlen(L, 5))
  590. return luaL_error(L, "invalid indices for match");
  591. lua_pushboolean(L, 1);
  592. if (lua_toboolean(L, 3))
  593. lua_pushlstring(L, lua_tostring(L, 5), r);
  594. else
  595. lua_pushlstring(L, lua_tostring(L, 5), l-1);
  596. lua_pushlstring(L, lua_tostring(L, 5)+r, lua_rawlen(L, 5)-r);
  597. lua_rawseti(L, 4, BUFFER_I);
  598. return 2;
  599. }
  600. else
  601. {
  602. lua_pop(L, 2); /* pop 2 results */
  603. nsock_read(nsp, nu->nsiod, receive_callback, nu->timeout, nu);
  604. return yield(L, nu, "RECEIVE BUF", FROM, 0, l_receive_buf);
  605. }
  606. }
  607. static int l_get_info (lua_State *L)
  608. {
  609. nse_nsock_udata *nu = check_nsock_udata(L, 1, true);
  610. NSOCK_UDATA_ENSURE_OPEN(L, nu);
  611. int protocol; // tcp or udp
  612. int af; // address family
  613. struct sockaddr_storage local;
  614. struct sockaddr_storage remote;
  615. char *ipstring_local = (char *) lua_newuserdata(L, sizeof(char) * INET6_ADDRSTRLEN);
  616. char *ipstring_remote = (char *) lua_newuserdata(L, sizeof(char) * INET6_ADDRSTRLEN);
  617. nsock_iod_get_communication_info(nu->nsiod, &protocol, &af,
  618. (struct sockaddr*)&local, (struct sockaddr*)&remote,
  619. sizeof(struct sockaddr_storage));
  620. lua_pushboolean(L, true);
  621. lua_pushstring(L, inet_ntop_both(af, &local, ipstring_local));
  622. lua_pushnumber(L, inet_port_both(af, &local));
  623. lua_pushstring(L, inet_ntop_both(af, &remote, ipstring_remote));
  624. lua_pushnumber(L, inet_port_both(af, &remote));
  625. return 5;
  626. }
  627. static int l_set_timeout (lua_State *L)
  628. {
  629. nse_nsock_udata *nu = check_nsock_udata(L, 1, false);
  630. nu->timeout = luaL_checkint(L, 2);
  631. if ((int) nu->timeout < -1) /* -1 is no timeout */
  632. return luaL_error(L, "Negative timeout: %d", nu->timeout);
  633. return nseU_success(L);
  634. }
  635. static int sleep_destructor (lua_State *L)
  636. {
  637. nsock_pool nsp = get_pool(L);
  638. nsock_event_id *neidp = (nsock_event_id *) lua_touserdata(L, 2);
  639. if (o.debugging >= 2)
  640. log_write(LOG_STDERR, "Destroying sleep callback.\n");
  641. assert(neidp);
  642. int success = nsock_event_cancel(nsp, *neidp, 0);
  643. if (success)
  644. return nseU_success(L);
  645. else
  646. return nseU_safeerror(L, "could not cancel event");
  647. }
  648. static void sleep_callback (nsock_pool nsp, nsock_event nse, void *ud)
  649. {
  650. lua_State *L = (lua_State *) ud;
  651. assert(lua_status(L) == LUA_YIELD);
  652. assert(nse_status(nse) == NSE_STATUS_SUCCESS);
  653. nse_restore(L, 0);
  654. }
  655. static int l_sleep (lua_State *L)
  656. {
  657. nsock_pool nsp = get_pool(L);
  658. double secs = luaL_checknumber(L, 1);
  659. int msecs;
  660. if (secs < 0)
  661. luaL_error(L, "argument to sleep (%f) must not be negative\n", secs);
  662. /* Convert to milliseconds for nsock_timer_create. */
  663. msecs = (int) (secs * 1000 + 0.5);
  664. nsock_event_id *neidp = (nsock_event_id *) lua_newuserdata(L, sizeof(nsock_event_id *));
  665. *neidp = nsock_timer_create(nsp, sleep_callback, msecs, L);
  666. lua_pushvalue(L, NSOCK_POOL);
  667. lua_pushcclosure(L, sleep_destructor, 1);
  668. nse_destructor(L, 'a');
  669. return nse_yield(L, 0, NULL);
  670. }
  671. #if HAVE_OPENSSL
  672. SSL *nse_nsock_get_ssl (lua_State *L)
  673. {
  674. nse_nsock_udata *nu = check_nsock_udata(L, 1, false);
  675. if (nu->nsiod == NULL || !nsock_iod_check_ssl(nu->nsiod))
  676. luaL_argerror(L, 1, "not a SSL socket");
  677. return (SSL *) nsock_iod_get_ssl(nu->nsiod);
  678. }
  679. #else
  680. /* If HAVE_OPENSSL is defined, these come from nse_ssl_cert.cc. */
  681. int l_get_ssl_certificate (lua_State *L)
  682. {
  683. return luaL_error(L, "SSL is not available");
  684. }
  685. int l_parse_ssl_certificate(lua_State *L)
  686. {
  687. return luaL_error(L, "SSL is not available");
  688. }
  689. #endif
  690. /* Set the local address for socket operations. The two optional parameters
  691. after the first (which is the socket object) are a string representing a
  692. numeric address, and a port number. If either optional parameter is omitted
  693. or nil, that part of the address will be left unspecified. */
  694. static int l_bind (lua_State *L)
  695. {
  696. nse_nsock_udata *nu = check_nsock_udata(L, 1, false);
  697. struct addrinfo hints = { 0 };
  698. struct addrinfo *results;
  699. const char *addr_str = luaL_optstring(L, 2, NULL);
  700. luaL_checkint(L, 3);
  701. const char *port_str = lua_tostring(L, 3); /* automatic conversion */
  702. int rc;
  703. /* If we don't have a string to work with, set our configured address family
  704. to get the proper unspecified address (0.0.0.0 or ::). Otherwise infer the
  705. family from the string. */
  706. if (addr_str == NULL)
  707. hints.ai_family = o.af();
  708. else
  709. hints.ai_family = AF_UNSPEC;
  710. /* AI_NUMERICHOST: don't use DNS to resolve names.
  711. AI_PASSIVE: set an unspecified address if addr_str is NULL. */
  712. hints.ai_flags = AI_NUMERICHOST | AI_PASSIVE;
  713. rc = getaddrinfo(addr_str, port_str, &hints, &results);
  714. if (rc != 0)
  715. return nseU_safeerror(L, gai_strerror(rc));
  716. if (results == NULL)
  717. return nseU_safeerror(L, "getaddrinfo: no results found");
  718. if (results->ai_addrlen > sizeof(nu->source_addr)) {
  719. freeaddrinfo(results);
  720. return nseU_safeerror(L, "getaddrinfo: result is too big");
  721. }
  722. /* We ignore any results after the first. */
  723. /* We would just call nsock_iod_set_localaddr here, but nu->nsiod is not
  724. * created until connect. So store the address in the userdatum. */
  725. nu->source_addrlen = results->ai_addrlen;
  726. memcpy(&nu->source_addr, results->ai_addr, nu->source_addrlen);
  727. freeaddrinfo(results);
  728. return nseU_success(L);
  729. }
  730. static const char *default_af_string(int af)
  731. {
  732. if (af == AF_INET)
  733. return "inet";
  734. else
  735. return "inet6";
  736. }
  737. static void initialize (lua_State *L, int idx, nse_nsock_udata *nu,
  738. int proto, int af)
  739. {
  740. lua_createtable(L, 2, 0); /* room for thread in array */
  741. lua_pushliteral(L, "");
  742. lua_rawseti(L, -2, BUFFER_I);
  743. lua_setuservalue(L, idx);
  744. nu->nsiod = NULL;
  745. nu->proto = proto;
  746. nu->af = af;
  747. nu->ssl_session = NULL;
  748. nu->source_addr.ss_family = AF_UNSPEC;
  749. nu->source_addrlen = sizeof(nu->source_addr);
  750. nu->timeout = DEFAULT_TIMEOUT;
  751. nu->is_pcap = 0;
  752. nu->thread = NULL;
  753. nu->direction = nu->action = NULL;
  754. }
  755. static int l_new (lua_State *L)
  756. {
  757. static const char *proto_strings[] = { "tcp", "udp", NULL };
  758. int proto_map[] = { IPPROTO_TCP, IPPROTO_UDP };
  759. static const char *af_strings[] = { "inet", "inet6", NULL };
  760. int af_map[] = { AF_INET, AF_INET6 };
  761. int proto, af;
  762. nse_nsock_udata *nu;
  763. proto = proto_map[luaL_checkoption(L, 1, "tcp", proto_strings)];
  764. af = af_map[luaL_checkoption(L, 2, default_af_string(o.af()), af_strings)];
  765. lua_settop(L, 0);
  766. nu = (nse_nsock_udata *) lua_newuserdata(L, sizeof(nse_nsock_udata));
  767. lua_pushvalue(L, NSOCK_SOCKET);
  768. lua_setmetatable(L, -2);
  769. initialize(L, 1, nu, proto, af);
  770. return 1;
  771. }
  772. /* Common subfunction to l_close and l_connect. l_connect calls this when a
  773. second attempt is made to connect a socket that has already had a connection
  774. attempt. */
  775. static void close_internal (lua_State *L, nse_nsock_udata *nu)
  776. {
  777. trace(nu->nsiod, "CLOSE", TO);
  778. #ifdef HAVE_OPENSSL
  779. if (nu->ssl_session)
  780. SSL_SESSION_free((SSL_SESSION *) nu->ssl_session);
  781. #endif
  782. if (!nu->is_pcap) { /* pcap sockets are closed by pcap_gc */
  783. nsock_iod_delete(nu->nsiod, NSOCK_PENDING_NOTIFY);
  784. nu->nsiod = NULL;
  785. }
  786. }
  787. static int l_close (lua_State *L)
  788. {
  789. nse_nsock_udata *nu = check_nsock_udata(L, 1, false);
  790. if (nu->nsiod == NULL)
  791. return nseU_safeerror(L, "socket already closed");
  792. close_internal(L, nu);
  793. initialize(L, 1, nu, nu->proto, nu->af);
  794. return nseU_success(L);
  795. }
  796. static int nsock_gc (lua_State *L)
  797. {
  798. nse_nsock_udata *nu = check_nsock_udata(L, 1, false);
  799. if (nu->nsiod)
  800. return l_close(L);
  801. return 0;
  802. }
  803. /****************** PCAP_SOCKET ***********************************************/
  804. static void dnet_to_pcap_device_name (lua_State *L, const char *device)
  805. {
  806. if (strcmp(device, "any") == 0)
  807. lua_pushliteral(L, "any");
  808. else
  809. #ifdef WIN32
  810. {
  811. char pcapdev[4096];
  812. /* Nmap normally uses device names obtained through dnet for interfaces,
  813. but Pcap has its own naming system. So the conversion is done here */
  814. if (!DnetName2PcapName(device, pcapdev, sizeof(pcapdev)))
  815. lua_pushstring(L, device);
  816. else
  817. lua_pushstring(L, pcapdev);
  818. }
  819. #else
  820. lua_pushstring(L, device);
  821. #endif
  822. }
  823. static int pcap_gc (lua_State *L)
  824. {
  825. nsock_iod *nsiod = (nsock_iod *) lua_touserdata(L, 1);
  826. nsock_iod_delete(*nsiod, NSOCK_PENDING_NOTIFY);
  827. *nsiod = NULL;
  828. return 0;
  829. }
  830. static int l_pcap_open (lua_State *L)
  831. {
  832. nsock_pool nsp = get_pool(L);
  833. nse_nsock_udata *nu = check_nsock_udata(L, 1, false);
  834. const char *device = luaL_checkstring(L, 2);
  835. int snaplen = luaL_checkint(L, 3);
  836. luaL_checktype(L, 4, LUA_TBOOLEAN); /* promiscuous */
  837. const char *bpf = luaL_checkstring(L, 5);
  838. lua_settop(L, 5);
  839. dnet_to_pcap_device_name(L, device); /* 6 */
  840. lua_pushfstring(L, "%s|%d|%d|%s", lua_tostring(L, 6), snaplen,
  841. lua_toboolean(L, 4), lua_tostring(L, 5)); /* 7, the pcap socket key */
  842. if (nu->nsiod)
  843. luaL_argerror(L, 1, "socket is already open");
  844. if (lua_rawlen(L, 6) == 0)
  845. luaL_argerror(L, 2, "bad device name");
  846. lua_pushvalue(L, 7);
  847. lua_rawget(L, KEY_PCAP);
  848. nsock_iod *nsiod = (nsock_iod *) lua_touserdata(L, -1);
  849. if (nsiod == NULL) /* does not exist */
  850. {
  851. int rc;
  852. lua_pop(L, 1); /* the nonexistant socket */
  853. nsiod = (nsock_iod *) lua_newuserdata(L, sizeof(nsock_iod));
  854. lua_pushvalue(L, PCAP_SOCKET);
  855. lua_setmetatable(L, -2);
  856. *nsiod = nsock_iod_new(nsp, nu);
  857. lua_pushvalue(L, 7); /* the pcap socket key */
  858. lua_pushvalue(L, -2); /* the pcap socket nsiod */
  859. lua_rawset(L, KEY_PCAP); /* KEY_PCAP["dev|snap|promis|bpf"] = pcap_nsiod */
  860. rc = nsock_pcap_open(nsp, *nsiod, lua_tostring(L, 6), snaplen,
  861. lua_toboolean(L, 4), bpf);
  862. if (rc)
  863. luaL_error(L, "can't open pcap reader on %s", device);
  864. }
  865. lua_getuservalue(L, 1); /* the socket user value */
  866. lua_pushvalue(L, -2); /* the pcap socket nsiod */
  867. lua_pushboolean(L, 1); /* dummy variable */
  868. lua_rawset(L, -3);
  869. nu->nsiod = *nsiod;
  870. nu->is_pcap = 1;
  871. return 0;
  872. }
  873. static void pcap_receive_handler (nsock_pool nsp, nsock_event nse, void *ud)
  874. {
  875. nse_nsock_udata *nu = (nse_nsock_udata *) ud;
  876. lua_State *L = nu->thread;
  877. assert(lua_status(L) == LUA_YIELD);
  878. if (nse_status(nse) == NSE_STATUS_SUCCESS)
  879. {
  880. const unsigned char *l2_data, *l3_data;
  881. size_t l2_len, l3_len, packet_len;
  882. struct timeval tv;
  883. nse_readpcap(nse, &l2_data, &l2_len, &l3_data, &l3_len, &packet_len, &tv);
  884. lua_pushboolean(L, 1);
  885. lua_pushinteger(L, packet_len);
  886. lua_pushlstring(L, (const char *) l2_data, l2_len);
  887. lua_pushlstring(L, (const char *) l3_data, l3_len);
  888. lua_pushnumber(L, TIMEVAL_SECS(tv));
  889. nse_restore(L, 5);
  890. }
  891. else
  892. status(L, nse_status(nse)); /* will also restore the thread */
  893. }
  894. static int l_pcap_receive (lua_State *L)
  895. {
  896. nsock_pool nsp = get_pool(L);
  897. nse_nsock_udata *nu = check_nsock_udata(L, 1, true);
  898. NSOCK_UDATA_ENSURE_OPEN(L, nu);
  899. nu->nseid = nsock_pcap_read_packet(nsp, nu->nsiod, pcap_receive_handler,
  900. nu->timeout, nu);
  901. return yield(L, nu, "PCAP RECEIVE", FROM, 0, NULL);
  902. }
  903. LUALIB_API int luaopen_nsock (lua_State *L)
  904. {
  905. static const luaL_Reg metatable_index[] = {
  906. {"bind", l_bind},
  907. {"close", l_close},
  908. {"connect", l_connect},
  909. {"get_info", l_get_info},
  910. {"get_ssl_certificate", l_get_ssl_certificate},
  911. {"pcap_open", l_pcap_open},
  912. {"pcap_close", l_close},
  913. {"pcap_receive", l_pcap_receive},
  914. {"send", l_send},
  915. {"sendto", l_sendto},
  916. {"receive", l_receive},
  917. {"receive_buf", l_receive_buf},
  918. {"receive_bytes", l_receive_bytes},
  919. {"receive_lines", l_receive_lines},
  920. {"reconnect_ssl", l_reconnect_ssl},
  921. {"set_timeout", l_set_timeout},
  922. {NULL, NULL}
  923. };
  924. static const luaL_Reg l_nsock[] = {
  925. {"loop", l_loop},
  926. {"new", l_new},
  927. {"sleep", l_sleep},
  928. {"parse_ssl_certificate", l_parse_ssl_certificate},
  929. {NULL, NULL}
  930. };
  931. /* Set up an environment for all nsock C functions to share.
  932. * This table particularly contains the THREAD_SOCKETS and
  933. * CONNECT_WAITING tables.
  934. * These values are accessed at the Lua pseudo-index LUA_ENVIRONINDEX.
  935. */
  936. int i;
  937. int top = lua_gettop(L);
  938. /* library upvalues */
  939. nsock_pool nsp = new_pool(L); /* NSOCK_POOL */
  940. lua_newtable(L); /* NSOCK_SOCKET */
  941. lua_newtable(L); /* PCAP_SOCKET */
  942. nseU_weaktable(L, 0, MAX_PARALLELISM, "k"); /* THREAD_SOCKETS */
  943. nseU_weaktable(L, 0, 1000, "k"); /* CONNECT_WAITING */
  944. nseU_weaktable(L, 0, 0, "v"); /* KEY_PCAP */
  945. /* Create the nsock metatable for sockets */
  946. lua_pushvalue(L, top+2); /* NSOCK_SOCKET */
  947. luaL_newlibtable(L, metatable_index);
  948. for (i = top+1; i < top+1+6; i++) lua_pushvalue(L, i);
  949. luaL_setfuncs(L, metatable_index, 6);
  950. lua_setfield(L, -2, "__index");
  951. for (i = top+1; i < top+1+6; i++) lua_pushvalue(L, i);
  952. lua_pushcclosure(L, nsock_gc, 6);
  953. lua_setfield(L, -2, "__gc");
  954. lua_newtable(L);
  955. lua_setfield(L, -2, "__metatable"); /* protect metatable */
  956. lua_pop(L, 1); /* NSOCK_SOCKET */
  957. /* Create the nsock pcap metatable */
  958. lua_pushvalue(L, top+3); /* PCAP_SOCKET */
  959. for (i = top+1; i < top+1+6; i++) lua_pushvalue(L, i);
  960. lua_pushcclosure(L, pcap_gc, 6);
  961. lua_setfield(L, top+3, "__gc");
  962. lua_pop(L, 1); /* PCAP_SOCKET */
  963. #if HAVE_OPENSSL
  964. /* Set up the SSL certificate userdata code in nse_ssl_cert.cc. */
  965. nse_nsock_init_ssl_cert(L);
  966. #endif
  967. #if HAVE_OPENSSL
  968. /* Value speed over security in SSL connections. */
  969. nsock_pool_ssl_init(nsp, NSOCK_SSL_MAX_SPEED);
  970. #endif
  971. luaL_newlibtable(L, l_nsock);
  972. for (i = top+1; i < top+1+6; i++) lua_pushvalue(L, i);
  973. luaL_setfuncs(L, l_nsock, 6);
  974. return 1;
  975. }