Intercept.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #ifdef USE_GNU_SOURCE
  28. #define _GNU_SOURCE
  29. #endif
  30. /* Name used in err msgs */
  31. char *progname = "";
  32. #include <unistd.h>
  33. #include <stdint.h>
  34. #include <stdio.h>
  35. #include <dlfcn.h>
  36. #include <strings.h>
  37. #include <netinet/in.h>
  38. #include <sys/time.h>
  39. #include <pwd.h>
  40. #include <errno.h>
  41. #include <linux/errno.h>
  42. #include <stdarg.h>
  43. #include <netdb.h>
  44. #include <string.h>
  45. #include <sys/syscall.h>
  46. #include <sys/types.h>
  47. #include <sys/socket.h>
  48. #include <sys/poll.h>
  49. #include <sys/un.h>
  50. #include <arpa/inet.h>
  51. #include "Intercept.h"
  52. #include "Common.c"
  53. #ifdef CHECKS
  54. #include <sys/resource.h>
  55. #include <linux/net.h> /* for NPROTO */
  56. #define SOCK_MAX (SOCK_PACKET + 1)
  57. #define SOCK_TYPE_MASK 0xf
  58. #endif
  59. /* Global Declarations */
  60. #ifdef USE_SOCKS_DNS
  61. static int (*realresinit)(void);
  62. #endif
  63. static int (*realconnect)(CONNECT_SIG);
  64. static int (*realselect)(SELECT_SIG);
  65. static int (*realbind)(BIND_SIG);
  66. static int (*realaccept)(ACCEPT_SIG);
  67. static int (*reallisten)(LISTEN_SIG);
  68. static int (*realsocket)(SOCKET_SIG);
  69. static int (*realsetsockopt)(SETSOCKOPT_SIG);
  70. static int (*realgetsockopt)(GETSOCKOPT_SIG);
  71. static int (*realaccept4)(ACCEPT4_SIG);
  72. static long (*realsyscall)(SYSCALL_SIG);
  73. static int (*realclose)(CLOSE_SIG);
  74. static int (*realclone)(CLONE_SIG);
  75. /* static int (*realpoll)(POLL_SIG); */
  76. static int (*realdup2)(DUP2_SIG);
  77. static int (*realdup3)(DUP3_SIG);
  78. /* Exported Function Prototypes */
  79. void my_init(void);
  80. int connect(CONNECT_SIG);
  81. int select(SELECT_SIG);
  82. int bind(BIND_SIG);
  83. int accept(ACCEPT_SIG);
  84. int listen(LISTEN_SIG);
  85. int socket(SOCKET_SIG);
  86. int setsockopt(SETSOCKOPT_SIG);
  87. int getsockopt(GETSOCKOPT_SIG);
  88. int accept4(ACCEPT4_SIG);
  89. long syscall(SYSCALL_SIG);
  90. int close(CLOSE_SIG);
  91. int clone(CLONE_SIG);
  92. /* int poll(POLL_SIG); */
  93. int dup2(DUP2_SIG);
  94. int dup3(DUP3_SIG);
  95. #ifdef USE_SOCKS_DNS
  96. int res_init(void);
  97. #endif
  98. int connect_to_service(void);
  99. int init_service_connection();
  100. void load_symbols(void);
  101. void set_up_intercept();
  102. int checkpid();
  103. #define SERVICE_CONNECT_ATTEMPTS 30
  104. #define RPC_FD 1023
  105. ssize_t sock_fd_read(int sock, void *buf, ssize_t bufsize, int *fd);
  106. /* threading */
  107. pthread_mutex_t lock;
  108. pthread_mutex_t loglock;
  109. void handle_error(char *name, char *info, int err)
  110. {
  111. #ifdef ERRORS_ARE_FATAL
  112. if(err < 0) {
  113. dwr(MSG_DEBUG,"handle_error(%s)=%d: FATAL: %s\n", name, err, info);
  114. exit(-1);
  115. }
  116. #endif
  117. #ifdef VERBOSE
  118. dwr(MSG_DEBUG,"%s()=%d\n", name, err);
  119. #endif
  120. }
  121. static unsigned long rpc_count = 0;
  122. /*------------------------------------------------------------------------------
  123. ------------------- Intercept<--->Service Comm mechanisms-----------------------
  124. ------------------------------------------------------------------------------*/
  125. static int is_initialized = 0;
  126. static int fdret_sock; // used for fd-transfers
  127. static int newfd; // used for "this_end" socket
  128. static int thispid;
  129. static char* af_sock_name = "/tmp/.ztnc_e5cd7a9e1c5311ab";
  130. static int instance_count = 0;
  131. /*
  132. * Check for forking
  133. */
  134. int checkpid() {
  135. if(thispid != getpid()) {
  136. printf("clone/fork detected. re-initializing this instance.\n");
  137. set_up_intercept();
  138. fdret_sock = init_service_connection();
  139. thispid = getpid();
  140. }
  141. return 0;
  142. }
  143. /*
  144. * Sends an RPC command to the service
  145. */
  146. int send_command(int rpc_fd, char *cmd)
  147. {
  148. char metabuf[BUF_SZ]; // portion of buffer which contains RPC metadata for debugging
  149. #ifdef VERBOSE
  150. /*
  151. #define IDX_PID 0
  152. #define IDX_TID sizeof(pid_t)
  153. #define IDX_COUNT IDX_TID + sizeof(pid_t)
  154. #define IDX_TIME IDX_COUNT + sizeof(int)
  155. #define IDX_CMD IDX_TIME + 20 // 20 being the length of the timestamp string
  156. #define IDX_PAYLOAD IDX_TIME + sizeof(char)
  157. */
  158. /* [pid_t] [pid_t] [rpc_count] [int] [...] */
  159. memset(metabuf, '\0', BUF_SZ);
  160. pid_t pid = syscall(SYS_getpid);
  161. pid_t tid = syscall(SYS_gettid);
  162. rpc_count++;
  163. char timestring[20];
  164. time_t timestamp;
  165. timestamp = time(NULL);
  166. strftime(timestring, sizeof(timestring), "%H:%M:%S", localtime(&timestamp));
  167. memcpy(&metabuf[IDX_PID], &pid, sizeof(pid_t) ); /* pid */
  168. memcpy(&metabuf[IDX_TID], &tid, sizeof(pid_t) ); /* tid */
  169. memcpy(&metabuf[IDX_COUNT], &rpc_count, sizeof(rpc_count) ); /* rpc_count */
  170. memcpy(&metabuf[IDX_TIME], &timestring, 20 ); /* timestamp */
  171. #endif
  172. /* Combine command flag+payload with RPC metadata */
  173. memcpy(&metabuf[IDX_PAYLOAD], cmd, PAYLOAD_SZ);
  174. int n_write = write(rpc_fd, &metabuf, BUF_SZ);
  175. if(n_write < 0){
  176. dwr(MSG_DEBUG,"Error writing command to service (CMD = %d)\n", cmd[0]);
  177. errno = 0;
  178. return -1;
  179. }
  180. return 0;
  181. }
  182. /*
  183. * Reads a return value from the service and sets errno (if applicable)
  184. */
  185. int get_retval()
  186. {
  187. dwr(MSG_DEBUG,"get_retval()\n");
  188. if(fdret_sock >= 0) {
  189. int retval;
  190. int sz = sizeof(char) + sizeof(retval) + sizeof(errno);
  191. char retbuf[BUF_SZ];
  192. memset(&retbuf, '\0', sz);
  193. int n_read = read(fdret_sock, &retbuf, sz);
  194. if(n_read > 0) {
  195. memcpy(&retval, &retbuf[1], sizeof(retval));
  196. memcpy(&errno, &retbuf[1+sizeof(retval)], sizeof(errno));
  197. return retval;
  198. }
  199. }
  200. dwr(MSG_DEBUG,"unable to read return value\n");
  201. return -1;
  202. }
  203. /* Reads a new file descriptor from the service */
  204. int get_new_fd(int oversock)
  205. {
  206. char buf[BUF_SZ];
  207. int newfd;
  208. ssize_t size = sock_fd_read(oversock, buf, sizeof(buf), &newfd);
  209. if(size > 0){
  210. dwr(MSG_DEBUG, "get_new_fd(): RX: fd = (%d) over (%d)\n", newfd, oversock);
  211. return newfd;
  212. }
  213. dwr(MSG_ERROR, "get_new_fd(): ERROR: unable to read fd over (%d)\n", oversock);
  214. return -1;
  215. }
  216. /* Check whether the socket is mapped to the service or not. We
  217. need to know if this is a regular AF_LOCAL socket or an end of a socketpair
  218. that the service uses. We don't want to keep state in the intercept, so
  219. we simply ask the service via an RPC */
  220. int is_mapped_to_service(int sockfd)
  221. {
  222. dwr(MSG_DEBUG,"is_mapped_to_service()\n");
  223. char cmd[BUF_SZ];
  224. memset(cmd, '\0', BUF_SZ);
  225. cmd[0] = RPC_MAP_REQ;
  226. memcpy(&cmd[1], &sockfd, sizeof(sockfd));
  227. pthread_mutex_lock(&lock);
  228. if(send_command(fdret_sock, cmd) < 0)
  229. return -1;
  230. int err = get_retval();
  231. pthread_mutex_unlock(&lock);
  232. return err;
  233. }
  234. /*------------------------------------------------------------------------------
  235. ---------- Unix-domain socket lazy initializer (for fd-transfers)--------------
  236. ------------------------------------------------------------------------------*/
  237. /* Sets up the connection pipes and sockets to the service */
  238. int init_service_connection()
  239. {
  240. instance_count++;
  241. dwr(MSG_DEBUG,"init_service_connection()\n");
  242. struct sockaddr_un addr;
  243. int tfd = -1, attempts = 0, conn_err = -1;
  244. memset(&addr, 0, sizeof(addr));
  245. addr.sun_family = AF_UNIX;
  246. strncpy(addr.sun_path, af_sock_name, sizeof(addr.sun_path)-1);
  247. dwr(MSG_DEBUG, "init(): pre-realsocket\n");
  248. if ( (tfd = realsocket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
  249. perror("socket error");
  250. exit(-1);
  251. }
  252. dwr(MSG_DEBUG, "init(): post-realsocket, conn_err = %d, attempts = %d\n", conn_err, attempts);
  253. while(conn_err < 0 && attempts < SERVICE_CONNECT_ATTEMPTS) {
  254. dwr(MSG_DEBUG, "init(): Attempting!\n");
  255. conn_err = realconnect(tfd, (struct sockaddr*)&addr, sizeof(addr));
  256. dwr(MSG_DEBUG, "init(): post-realconnect\n");
  257. if(conn_err < 0) {
  258. dwr(MSG_DEBUG,"re-attempting connection in %ds\n", 1+attempts);
  259. sleep(1);
  260. }
  261. else {
  262. dwr(MSG_DEBUG,"AF_UNIX connection established: %d\n", tfd);
  263. is_initialized = 1;
  264. int newtfd = realdup2(tfd, RPC_FD-instance_count);
  265. dwr(MSG_DEBUG,"dup'd to rpc_fd = %d\n", newtfd);
  266. close(tfd);
  267. return newtfd;
  268. }
  269. attempts++;
  270. }
  271. return -1;
  272. }
  273. /*------------------------------------------------------------------------------
  274. ------------------------ ctors and dtors (and friends)-------------------------
  275. ------------------------------------------------------------------------------*/
  276. void my_dest(void) __attribute__ ((destructor));
  277. void my_dest(void) {
  278. dwr(MSG_DEBUG,"closing connections to service...\n");
  279. close(fdret_sock);
  280. pthread_mutex_destroy(&lock);
  281. }
  282. void load_symbols(void)
  283. {
  284. #ifdef USE_OLD_DLSYM
  285. void *lib;
  286. #endif
  287. /* possibly add check to beginning of each method to avoid needing to cll the constructor */
  288. if(thispid == getpid()) {
  289. dwr(MSG_DEBUG,"detected duplicate call to global ctor (pid=%d).\n", thispid);
  290. }
  291. thispid = getpid();
  292. #ifndef USE_OLD_DLSYM
  293. realconnect = dlsym(RTLD_NEXT, "connect");
  294. realbind = dlsym(RTLD_NEXT, "bind");
  295. realaccept = dlsym(RTLD_NEXT, "accept");
  296. reallisten = dlsym(RTLD_NEXT, "listen");
  297. realsocket = dlsym(RTLD_NEXT, "socket");
  298. realbind = dlsym(RTLD_NEXT, "bind");
  299. realselect = dlsym(RTLD_NEXT, "select");
  300. realsetsockopt = dlsym(RTLD_NEXT, "setsockopt");
  301. realgetsockopt = dlsym(RTLD_NEXT, "getsockopt");
  302. realaccept4 = dlsym(RTLD_NEXT, "accept4");
  303. realclone = dlsym(RTLD_NEXT, "clone");
  304. realclose = dlsym(RTLD_NEXT, "close");
  305. realsyscall = dlsym(RTLD_NEXT, "syscall");
  306. /* realsyscall = dlsym(RTLD_NEXT, "poll"); */
  307. realdup2 = dlsym(RTLD_NEXT, "dup2");
  308. realdup3 = dlsym(RTLD_NEXT, "dup3");
  309. #ifdef USE_SOCKS_DNS
  310. realresinit = dlsym(RTLD_NEXT, "res_init");
  311. #endif
  312. #else
  313. lib = dlopen(LIBCONNECT, RTLD_LAZY);
  314. realconnect = dlsym(lib, "connect");
  315. realbind = dlsym(lib, "bind");
  316. realaccept = dlsym(lib, "accept");
  317. reallisten = dlsym(lib, "listen");
  318. realsocket = dlsym(lib, "socket");
  319. realselect = dlsym(lib, "select");
  320. realsetsockopt = dlsym(lib, "setsockopt");
  321. realgetsockopt = dlsym(lib, "getsockopt");
  322. realaccept4 = dlsym(lib), "accept4");
  323. realclone = dlsym(lib, "clone");
  324. realclose = dlsym(lib, "close");
  325. realsyscall = dlsym(lib, "syscall");
  326. /* realsyscall = dlsym(lib, "poll"); */
  327. realdup2 = dlsym(RTLD_NEXT, "dup2");
  328. realdup3 = dlsym(RTLD_NEXT, "dup3");
  329. #ifdef USE_SOCKS_DNS
  330. realresinit = dlsym(lib, "res_init");
  331. #endif
  332. dlclose(lib);
  333. lib = dlopen(LIBC, RTLD_LAZY);
  334. dlclose(lib);
  335. #endif
  336. }
  337. /* Private Function Prototypes */
  338. void _init(void) __attribute__ ((constructor));
  339. void _init(void) {
  340. set_up_intercept();
  341. }
  342. /* get symbols and initialize mutexes */
  343. void set_up_intercept()
  344. {
  345. load_symbols();
  346. if(pthread_mutex_init(&lock, NULL) != 0) {
  347. dwr(MSG_ERROR, "error while initializing service call mutex\n");
  348. }
  349. if(pthread_mutex_init(&loglock, NULL) != 0) {
  350. dwr(MSG_ERROR, "error while initializing log mutex mutex\n");
  351. }
  352. }
  353. /*------------------------------------------------------------------------------
  354. --------------------------------- setsockopt() ---------------------------------
  355. ------------------------------------------------------------------------------*/
  356. /* int socket, int level, int option_name, const void *option_value, socklen_t option_len */
  357. int setsockopt(SETSOCKOPT_SIG)
  358. {
  359. if(realsetsockopt == NULL){
  360. dwr(MSG_ERROR, "setsockopt(): SYMBOL NOT FOUND.\n");
  361. return -1;
  362. }
  363. dwr(MSG_DEBUG,"\nsetsockopt(%d)\n", socket);
  364. /*
  365. if(is_mapped_to_service(socket) < 0) { // First, check if the service manages this
  366. return realsetsockopt(socket, level, option_name, option_value, option_len);
  367. }
  368. */
  369. /* return(realsetsockopt(socket, level, option_name, option_value, option_len)); */
  370. if(level == SOL_IPV6 && option_name == IPV6_V6ONLY)
  371. return 0;
  372. if(level == SOL_IP && option_name == IP_TTL)
  373. return 0;
  374. if(level == IPPROTO_TCP || (level == SOL_SOCKET && option_name == SO_KEEPALIVE))
  375. return 0;
  376. /* make sure we don't touch any standard outputs */
  377. if(socket == STDIN_FILENO || socket == STDOUT_FILENO || socket == STDERR_FILENO)
  378. return(realsetsockopt(socket, level, option_name, option_value, option_len));
  379. int err = realsetsockopt(socket, level, option_name, option_value, option_len);
  380. if(err < 0){
  381. perror("setsockopt():\n");
  382. }
  383. return 0;
  384. }
  385. /*------------------------------------------------------------------------------
  386. --------------------------------- getsockopt() ---------------------------------
  387. ------------------------------------------------------------------------------*/
  388. /* int sockfd, int level, int optname, void *optval, socklen_t *optlen */
  389. int getsockopt(GETSOCKOPT_SIG)
  390. {
  391. if(realgetsockopt == NULL){
  392. dwr(MSG_ERROR, "getsockopt(): SYMBOL NOT FOUND.\n");
  393. return -1;
  394. }
  395. dwr(MSG_DEBUG,"\ngetsockopt(%d)\n", sockfd);
  396. /*
  397. if(is_mapped_to_service(sockfd) < 0) { // First, check if the service manages this
  398. return realgetsockopt(sockfd, level, optname, optval, optlen);
  399. }
  400. */
  401. int err = realgetsockopt(sockfd, level, optname, optval, optlen);
  402. /* TODO: this condition will need a little more intelligence later on
  403. -- we will need to know if this fd is a local we are spoofing, or a true local */
  404. if(optname == SO_TYPE)
  405. {
  406. int* val = (int*)optval;
  407. *val = 2;
  408. optval = (void*)val;
  409. }
  410. if(err < 0){
  411. perror("setsockopt():\n");
  412. }
  413. return 0;
  414. }
  415. /*------------------------------------------------------------------------------
  416. ----------------------------------- socket() -----------------------------------
  417. ------------------------------------------------------------------------------*/
  418. /* int socket_family, int socket_type, int protocol
  419. socket() intercept function */
  420. int socket(SOCKET_SIG)
  421. {
  422. if(realsocket == NULL){
  423. dwr(MSG_ERROR, "socket(): SYMBOL NOT FOUND.\n");
  424. return -1;
  425. }
  426. dwr(MSG_DEBUG,"\nsocket():\n");
  427. int err;
  428. #ifdef CHECKS
  429. /* Check that type makes sense */
  430. int flags = socket_type & ~SOCK_TYPE_MASK;
  431. if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) {
  432. errno = EINVAL;
  433. handle_error("socket1", "", -1);
  434. return -1;
  435. }
  436. socket_type &= SOCK_TYPE_MASK;
  437. /* Check protocol is in range */
  438. if (socket_family < 0 || socket_family >= NPROTO){
  439. errno = EAFNOSUPPORT;
  440. handle_error("socket2", "", -1);
  441. return -1;
  442. }
  443. if (socket_type < 0 || socket_type >= SOCK_MAX) {
  444. errno = EINVAL;
  445. handle_error("socket3", "", -1);
  446. return -1;
  447. }
  448. /* Check that we haven't hit the soft-limit file descriptors allowed */
  449. /* FIXME: Find number of open fds
  450. struct rlimit rl;
  451. getrlimit(RLIMIT_NOFILE, &rl);
  452. if(sockfd >= rl.rlim_cur){
  453. errno = EMFILE;
  454. return -1;
  455. }
  456. */
  457. /* TODO: detect ENFILE condition */
  458. #endif
  459. char cmd[BUF_SZ];
  460. fdret_sock = !is_initialized ? init_service_connection() : fdret_sock;
  461. if(fdret_sock < 0) {
  462. dwr(MSG_DEBUG,"BAD service connection. exiting.\n");
  463. handle_error("socket4", "", -1);
  464. exit(-1);
  465. }
  466. if(socket_family == AF_LOCAL
  467. || socket_family == AF_NETLINK
  468. || socket_family == AF_UNIX) {
  469. int err = realsocket(socket_family, socket_type, protocol);
  470. dwr(MSG_DEBUG,"realsocket, err = %d\n", err);
  471. handle_error("socket5", "", err);
  472. return err;
  473. }
  474. /* Assemble and send RPC */
  475. struct socket_st rpc_st;
  476. rpc_st.socket_family = socket_family;
  477. rpc_st.socket_type = socket_type;
  478. rpc_st.protocol = protocol;
  479. rpc_st.__tid = syscall(SYS_gettid);
  480. memset(cmd, '\0', BUF_SZ);
  481. cmd[0] = RPC_SOCKET;
  482. memcpy(&cmd[1], &rpc_st, sizeof(struct socket_st));
  483. pthread_mutex_lock(&lock);
  484. send_command(fdret_sock, cmd);
  485. /* get new fd */
  486. newfd = get_new_fd(fdret_sock);
  487. if(newfd > 0)
  488. {
  489. dwr(MSG_DEBUG,"sending fd = %d to Service over (%d)\n", newfd, fdret_sock);
  490. /* send our local-fd number back to service so
  491. it can complete its mapping table entry */
  492. memset(cmd, '\0', BUF_SZ);
  493. cmd[0] = RPC_MAP;
  494. memcpy(&cmd[1], &newfd, sizeof(newfd));
  495. if(newfd > -1) {
  496. send_command(fdret_sock, cmd);
  497. pthread_mutex_unlock(&lock);
  498. errno = ERR_OK; /* OK */
  499. handle_error("socket6", "", newfd);
  500. return newfd;
  501. }
  502. else { /* Try to read retval+errno since we RXed a bad fd */
  503. dwr(MSG_DEBUG,"Error, service sent bad fd.\n");
  504. err = get_retval();
  505. pthread_mutex_unlock(&lock);
  506. handle_error("socket7", "", -1);
  507. return err;
  508. }
  509. }
  510. else {
  511. dwr(MSG_DEBUG,"Error while receiving new FD.\n");
  512. err = get_retval();
  513. pthread_mutex_unlock(&lock);
  514. handle_error("socket8", "", -1);
  515. return err;
  516. }
  517. }
  518. /*------------------------------------------------------------------------------
  519. ---------------------------------- connect() -----------------------------------
  520. ------------------------------------------------------------------------------*/
  521. /* int __fd, const struct sockaddr * __addr, socklen_t __len
  522. connect() intercept function */
  523. int connect(CONNECT_SIG)
  524. {
  525. if(realconnect == NULL){
  526. dwr(MSG_ERROR, "connect(): SYMBOL NOT FOUND.\n");
  527. return -1;
  528. }
  529. dwr(MSG_DEBUG,"\nconnect(%d):\n", __fd);
  530. /* print_addr(__addr); */
  531. struct sockaddr_in *connaddr;
  532. connaddr = (struct sockaddr_in *) __addr;
  533. #ifdef CHECKS
  534. /* Check that this is a valid fd */
  535. if(fcntl(__fd, F_GETFD) < 0) {
  536. errno = EBADF;
  537. handle_error("connect", "EBADF", -1);
  538. return -1;
  539. }
  540. /* Check that it is a socket */
  541. int sock_type;
  542. socklen_t sock_type_len = sizeof(sock_type);
  543. if(getsockopt(__fd, SOL_SOCKET, SO_TYPE, (void *) &sock_type, &sock_type_len) < 0) {
  544. errno = ENOTSOCK;
  545. handle_error("connect", "ENOTSOCK", -1);
  546. return -1;
  547. }
  548. /* Check family */
  549. if (connaddr->sin_family < 0 || connaddr->sin_family >= NPROTO){
  550. errno = EAFNOSUPPORT;
  551. handle_error("connect", "EAFNOSUPPORT", -1);
  552. return -1;
  553. }
  554. /* FIXME: Check that address is in user space, return EFAULT ? */
  555. #endif
  556. /* make sure we don't touch any standard outputs */
  557. if(__fd == STDIN_FILENO || __fd == STDOUT_FILENO || __fd == STDERR_FILENO){
  558. if (realconnect == NULL) {
  559. handle_error("connect", "Unresolved symbol [connect]", -1);
  560. exit(-1);
  561. }
  562. return(realconnect(__fd, __addr, __len));
  563. }
  564. if(__addr != NULL && (connaddr->sin_family == AF_LOCAL
  565. || connaddr->sin_family == PF_NETLINK
  566. || connaddr->sin_family == AF_NETLINK
  567. || connaddr->sin_family == AF_UNIX)) {
  568. int err = realconnect(__fd, __addr, __len);
  569. perror("connect():");
  570. /* handle_error("connect", "Cannot connect to local socket", err); */
  571. return err;
  572. }
  573. /* Assemble and send RPC */
  574. int err;
  575. char cmd[BUF_SZ];
  576. memset(cmd, '\0', BUF_SZ);
  577. struct connect_st rpc_st;
  578. rpc_st.__tid = syscall(SYS_gettid);
  579. rpc_st.__fd = __fd;
  580. memcpy(&rpc_st.__addr, __addr, sizeof(struct sockaddr));
  581. memcpy(&rpc_st.__len, &__len, sizeof(socklen_t));
  582. cmd[0] = RPC_CONNECT;
  583. memcpy(&cmd[1], &rpc_st, sizeof(struct connect_st));
  584. pthread_mutex_lock(&lock);
  585. send_command(fdret_sock, cmd);
  586. /*
  587. if(sock_type && O_NONBLOCK) {
  588. pthread_mutex_unlock(&lock);
  589. return EINPROGRESS;
  590. }
  591. */
  592. err = get_retval();
  593. pthread_mutex_unlock(&lock);
  594. /* handle_error("connect", "", err); */
  595. return err;
  596. }
  597. /*------------------------------------------------------------------------------
  598. ---------------------------------- select() ------------------------------------
  599. ------------------------------------------------------------------------------*/
  600. /* int n, fd_set *readfds, fd_set *writefds,
  601. fd_set *exceptfds, struct timeval *timeout */
  602. int select(SELECT_SIG)
  603. {
  604. if(realselect == NULL){
  605. dwr(MSG_ERROR, "select(): SYMBOL NOT FOUND.\n");
  606. return -1;
  607. }
  608. /* dwr(MSG_DEBUG,"select():\n"); */
  609. return realselect(n, readfds, writefds, exceptfds, timeout);
  610. }
  611. /*------------------------------------------------------------------------------
  612. ------------------------------------ bind() ------------------------------------
  613. ------------------------------------------------------------------------------*/
  614. /* int sockfd, const struct sockaddr *addr, socklen_t addrlen
  615. bind() intercept function */
  616. int bind(BIND_SIG)
  617. {
  618. if(realbind == NULL){
  619. dwr(MSG_ERROR, "bind(): SYMBOL NOT FOUND.\n");
  620. return -1;
  621. }
  622. dwr(MSG_DEBUG,"\nbind(%d):\n", sockfd);
  623. /* print_addr(addr); */
  624. #ifdef CHECKS
  625. /* Check that this is a valid fd */
  626. if(fcntl(sockfd, F_GETFD) < 0) {
  627. errno = EBADF;
  628. handle_error("bind", "EBADF", -1);
  629. return -1;
  630. }
  631. /* Check that it is a socket */
  632. int opt = -1;
  633. socklen_t opt_len;
  634. if(getsockopt(sockfd, SOL_SOCKET, SO_TYPE, (void *) &opt, &opt_len) < 0) {
  635. errno = ENOTSOCK;
  636. handle_error("bind", "ENOTSOCK", -1);
  637. return -1;
  638. }
  639. #endif
  640. int err;
  641. /* make sure we don't touch any standard outputs */
  642. if(sockfd == STDIN_FILENO || sockfd == STDOUT_FILENO || sockfd == STDERR_FILENO)
  643. return(realbind(sockfd, addr, addrlen));
  644. /* If local, just use normal syscall */
  645. struct sockaddr_in *connaddr;
  646. connaddr = (struct sockaddr_in *)addr;
  647. if(connaddr->sin_family == AF_LOCAL
  648. || connaddr->sin_family == AF_NETLINK
  649. || connaddr->sin_family == AF_UNIX) {
  650. int err = realbind(sockfd, addr, addrlen);
  651. dwr(MSG_DEBUG,"realbind, err = %d\n", err);
  652. return err;
  653. }
  654. /* Assemble and send RPC */
  655. char cmd[BUF_SZ];
  656. struct bind_st rpc_st;
  657. rpc_st.sockfd = sockfd;
  658. rpc_st.__tid = syscall(SYS_gettid);
  659. memcpy(&rpc_st.addr, addr, sizeof(struct sockaddr));
  660. memcpy(&rpc_st.addrlen, &addrlen, sizeof(socklen_t));
  661. cmd[0]=RPC_BIND;
  662. memcpy(&cmd[1], &rpc_st, sizeof(struct bind_st));
  663. pthread_mutex_lock(&lock);
  664. send_command(fdret_sock, cmd);
  665. err = get_retval();
  666. pthread_mutex_unlock(&lock);
  667. errno = ERR_OK;
  668. handle_error("bind", "", err);
  669. return err;
  670. }
  671. /*------------------------------------------------------------------------------
  672. ----------------------------------- accept4() ----------------------------------
  673. ------------------------------------------------------------------------------*/
  674. /* int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags */
  675. int accept4(ACCEPT4_SIG)
  676. {
  677. if(realaccept4 == NULL){
  678. dwr(MSG_ERROR, "accept4(): SYMBOL NOT FOUND.\n");
  679. return -1;
  680. }
  681. dwr(MSG_DEBUG,"\naccept4(%d):\n", sockfd);
  682. #ifdef CHECKS
  683. if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) {
  684. errno = EINVAL;
  685. return -1;
  686. }
  687. #endif
  688. int newfd = accept(sockfd, addr, addrlen);
  689. if(newfd > 0) {
  690. if(flags & SOCK_CLOEXEC)
  691. fcntl(newfd, F_SETFL, FD_CLOEXEC);
  692. if(flags & SOCK_NONBLOCK)
  693. fcntl(newfd, F_SETFL, O_NONBLOCK);
  694. }
  695. handle_error("accept4", "", newfd);
  696. return newfd;
  697. }
  698. /*------------------------------------------------------------------------------
  699. ----------------------------------- accept() -----------------------------------
  700. ------------------------------------------------------------------------------*/
  701. /* int sockfd struct sockaddr *addr, socklen_t *addrlen
  702. accept() intercept function */
  703. int accept(ACCEPT_SIG)
  704. {
  705. if(realaccept == NULL){
  706. dwr(MSG_ERROR, "accept(): SYMBOL NOT FOUND.\n");
  707. return -1;
  708. }
  709. dwr(MSG_DEBUG,"\naccept(%d):\n", sockfd);
  710. #ifdef CHECKS
  711. /* Check that this is a valid fd */
  712. if(fcntl(sockfd, F_GETFD) < 0) {
  713. return -1;
  714. errno = EBADF;
  715. dwr(MSG_DEBUG,"EBADF\n");
  716. handle_error("accept", "EBADF", -1);
  717. return -1;
  718. }
  719. /* Check that it is a socket */
  720. int opt;
  721. socklen_t opt_len;
  722. if(getsockopt(sockfd, SOL_SOCKET, SO_TYPE, (void *) &opt, &opt_len) < 0) {
  723. errno = ENOTSOCK;
  724. dwr(MSG_DEBUG,"ENOTSOCK\n");
  725. handle_error("accept", "ENOTSOCK", -1);
  726. return -1;
  727. }
  728. /* Check that this socket supports accept() */
  729. if(!(opt && (SOCK_STREAM | SOCK_SEQPACKET))) {
  730. errno = EOPNOTSUPP;
  731. dwr(MSG_DEBUG,"EOPNOTSUPP\n");
  732. handle_error("accept", "EOPNOTSUPP", -1);
  733. return -1;
  734. }
  735. /* Check that we haven't hit the soft-limit file descriptors allowed */
  736. struct rlimit rl;
  737. getrlimit(RLIMIT_NOFILE, &rl);
  738. if(sockfd >= rl.rlim_cur){
  739. errno = EMFILE;
  740. dwr(MSG_DEBUG,"EMFILE\n");
  741. handle_error("accept", "EMFILE", -1);
  742. return -1;
  743. }
  744. /* Check address length */
  745. if(addrlen < 0) {
  746. errno = EINVAL;
  747. dwr(MSG_DEBUG,"EINVAL\n");
  748. handle_error("accept", "EINVAL", -1);
  749. return -1;
  750. }
  751. #endif
  752. /* redirect calls for standard I/O descriptors to kernel */
  753. if(sockfd == STDIN_FILENO || sockfd == STDOUT_FILENO || sockfd == STDERR_FILENO){
  754. dwr(MSG_DEBUG,"realaccept():\n");
  755. return(realaccept(sockfd, addr, addrlen));
  756. }
  757. if(addr)
  758. addr->sa_family = AF_INET;
  759. /* TODO: also get address info */
  760. char cmd[BUF_SZ];
  761. if(realaccept == NULL) {
  762. handle_error("accept", "Unresolved symbol [accept]", -1);
  763. return -1;
  764. }
  765. // if(opt & O_NONBLOCK)
  766. fcntl(sockfd, F_SETFL, O_NONBLOCK); /* required by libuv in nodejs */
  767. char c[1];
  768. int new_conn_socket;
  769. int n = read(sockfd, c, sizeof(c)); /* Read signal byte */
  770. if(n > 0)
  771. {
  772. new_conn_socket = get_new_fd(fdret_sock);
  773. dwr(MSG_DEBUG, " accept(): RX: fd = (%d) over (%d)\n", new_conn_socket, fdret_sock);
  774. if(new_conn_socket > 0) {
  775. /* Send our local-fd number back to service so it can complete its mapping table */
  776. memset(cmd, '\0', BUF_SZ);
  777. cmd[0] = RPC_MAP;
  778. memcpy(&cmd[1], &new_conn_socket, sizeof(new_conn_socket));
  779. pthread_mutex_lock(&lock);
  780. dwr(MSG_DEBUG, "accept(): sending perceived fd (%d) to service.\n", new_conn_socket);
  781. int n_write = send_command(fdret_sock, cmd);
  782. if(n_write < 0) {
  783. errno = ECONNABORTED; /* TODO: Closest match, service unreachable */
  784. handle_error("accept", "ECONNABORTED - Error sending perceived FD to service", -1);
  785. return -1;
  786. }
  787. pthread_mutex_unlock(&lock);
  788. errno = ERR_OK;
  789. dwr(MSG_DEBUG,"*accept()=%d\n", new_conn_socket);
  790. handle_error("accept", "", new_conn_socket);
  791. return new_conn_socket; /* OK */
  792. }
  793. else {
  794. errno = ECONNABORTED; /* TODO: Closest match, service unreachable */
  795. handle_error("accept", "ECONNABORTED - Error receiving new FD from service", -1);
  796. return -1;
  797. }
  798. }
  799. errno = EAGAIN; /* necessary? */
  800. handle_error("accept", "EAGAIN - Error reading signal byte from service", -1);
  801. return -EAGAIN;
  802. /* Prevents libuv in nodejs from accepting properly (it looks for a -EAGAIN) */
  803. /*
  804. errno = EBADF;
  805. handle_error("accept", "EBADF - Error reading signal byte from service", -1);
  806. return -1;
  807. */
  808. }
  809. /*------------------------------------------------------------------------------
  810. ------------------------------------- listen()----------------------------------
  811. ------------------------------------------------------------------------------*/
  812. /* int sockfd, int backlog
  813. listen() intercept function */
  814. int listen(LISTEN_SIG)
  815. {
  816. if(reallisten == NULL){
  817. dwr(MSG_ERROR, "listen(): SYMBOL NOT FOUND.\n");
  818. return -1;
  819. }
  820. dwr(MSG_DEBUG,"\nlisten(%d):\n", sockfd);
  821. int sock_type;
  822. socklen_t sock_type_len = sizeof(sock_type);
  823. #ifdef CHECKS
  824. /* Check that this is a valid fd */
  825. if(fcntl(sockfd, F_GETFD) < 0) {
  826. errno = EBADF;
  827. handle_error("listen", "EBADF", -1);
  828. return -1;
  829. }
  830. /* Check that it is a socket */
  831. if(getsockopt(sockfd, SOL_SOCKET, SO_TYPE, (void *) &sock_type, &sock_type_len) < 0) {
  832. errno = ENOTSOCK;
  833. handle_error("listen", "ENOTSOCK", -1);
  834. return -1;
  835. }
  836. /* Check that this socket supports accept() */
  837. if(!(sock_type && (SOCK_STREAM | SOCK_SEQPACKET))) {
  838. errno = EOPNOTSUPP;
  839. handle_error("listen", "EOPNOTSUPP", -1);
  840. return -1;
  841. }
  842. #endif
  843. /* make sure we don't touch any standard outputs */
  844. if(sockfd == STDIN_FILENO || sockfd == STDOUT_FILENO || sockfd == STDERR_FILENO)
  845. return(reallisten(sockfd, backlog));
  846. if(is_mapped_to_service(sockfd) < 0) {
  847. /* We now know this socket is not one of our socketpairs */
  848. int err = reallisten(sockfd, backlog);
  849. dwr(MSG_DEBUG,"reallisten()=%d\n", err);
  850. return err;
  851. }
  852. /* Assemble and send RPC */
  853. char cmd[BUF_SZ];
  854. memset(cmd, '\0', BUF_SZ);
  855. struct listen_st rpc_st;
  856. rpc_st.sockfd = sockfd;
  857. rpc_st.backlog = backlog;
  858. rpc_st.__tid = syscall(SYS_gettid);
  859. cmd[0] = RPC_LISTEN;
  860. memcpy(&cmd[1], &rpc_st, sizeof(struct listen_st));
  861. pthread_mutex_lock(&lock);
  862. send_command(fdret_sock, cmd);
  863. get_retval();
  864. pthread_mutex_unlock(&lock);
  865. handle_error("listen", "", ERR_OK);
  866. return ERR_OK;
  867. }
  868. /*------------------------------------------------------------------------------
  869. -------------------------------------- clone()----------------------------------
  870. ------------------------------------------------------------------------------*/
  871. /* int (*fn)(void *), void *child_stack, int flags, void *arg, ... */
  872. int clone(CLONE_SIG)
  873. {
  874. if(realclone == NULL){
  875. dwr(MSG_ERROR, "clone(): SYMBOL NOT FOUND.\n");
  876. return -1;
  877. }
  878. dwr(MSG_DEBUG,"clone()\n");
  879. int err = realclone(fn, child_stack, flags, arg);
  880. checkpid();
  881. return err;
  882. }
  883. /*------------------------------------------------------------------------------
  884. -------------------------------------- poll()-----------------------------------
  885. ------------------------------------------------------------------------------*/
  886. /* struct pollfd *fds, nfds_t nfds, int timeout */
  887. /*
  888. int poll(POLL_SIG)
  889. {
  890. dwr(MSG_DEBUG,"poll()\n");
  891. return realpoll(fds, nfds, timeout);
  892. }
  893. */
  894. /*------------------------------------------------------------------------------
  895. -------------------------------------- close()-----------------------------------
  896. ------------------------------------------------------------------------------*/
  897. /* int fd */
  898. int close(CLOSE_SIG)
  899. {
  900. /* checkpid(); // Required for httpd-2.4.17-3.x86_64 -- After clone, some symbols aren't initialized yet */
  901. if(realclose == NULL){
  902. dwr(MSG_ERROR, "close(): SYMBOL NOT FOUND.\n");
  903. return -1;
  904. }
  905. dwr(MSG_DEBUG,"close(%d)\n", fd);
  906. if(fd == fdret_sock)
  907. return -1; /* TODO: Ignore request to shut down our rpc fd, this is *almost always* safe */
  908. if(fd != STDIN_FILENO && fd != STDOUT_FILENO && fd != STDERR_FILENO)
  909. return realclose(fd);
  910. return -1;
  911. }
  912. /*------------------------------------------------------------------------------
  913. -------------------------------------- dup2()-----------------------------------
  914. ------------------------------------------------------------------------------*/
  915. /* int oldfd, int newfd */
  916. int dup2(DUP2_SIG)
  917. {
  918. if(realdup2 == NULL){
  919. dwr(MSG_ERROR, "dup2(): SYMBOL NOT FOUND.\n");
  920. return -1;
  921. }
  922. dwr(MSG_DEBUG,"dup2(%d, %d)\n", oldfd, newfd);
  923. if(oldfd == fdret_sock) {
  924. dwr(MSG_DEBUG,"client application attempted to dup2 RPC socket (%d). This is not allowed.\n", oldfd);
  925. errno = EBADF;
  926. return -1;
  927. }
  928. if(oldfd != STDIN_FILENO && oldfd != STDOUT_FILENO && oldfd != STDERR_FILENO)
  929. if(newfd != STDIN_FILENO && newfd != STDOUT_FILENO && newfd != STDERR_FILENO)
  930. return realdup2(oldfd, newfd);
  931. return -1;
  932. }
  933. /*------------------------------------------------------------------------------
  934. -------------------------------------- dup3()-----------------------------------
  935. ------------------------------------------------------------------------------*/
  936. /* int oldfd, int newfd, int flags */
  937. int dup3(DUP3_SIG)
  938. {
  939. if(realdup3 == NULL){
  940. dwr(MSG_ERROR, "dup3(): SYMBOL NOT FOUND.\n");
  941. return -1;
  942. }
  943. dwr(MSG_DEBUG,"dup3(%d, %d, %d)\n", oldfd, newfd, flags);
  944. #ifdef DEBUG
  945. /* Only do this check if we want to debug the intercept, otherwise, dont mess with
  946. the client application's logging methods */
  947. if(newfd == STDIN_FILENO || newfd == STDOUT_FILENO || newfd == STDERR_FILENO)
  948. return newfd; /* FIXME: This is to prevent httpd from dup'ing over our stderr
  949. and preventing us from debugging */
  950. else
  951. #endif
  952. return realdup3(oldfd, newfd, flags);
  953. }
  954. /*------------------------------------------------------------------------------
  955. ------------------------------------ syscall()----------------------------------
  956. ------------------------------------------------------------------------------*/
  957. long syscall(SYSCALL_SIG){
  958. if(realsyscall == NULL){
  959. dwr(MSG_ERROR, "syscall(): SYMBOL NOT FOUND.\n");
  960. return -1;
  961. }
  962. dwr(MSG_DEBUG_EXTRA,"syscall(%u, ...):\n", number);
  963. va_list ap;
  964. uintptr_t a,b,c,d,e,f;
  965. va_start(ap, number);
  966. a=va_arg(ap, uintptr_t);
  967. b=va_arg(ap, uintptr_t);
  968. c=va_arg(ap, uintptr_t);
  969. d=va_arg(ap, uintptr_t);
  970. e=va_arg(ap, uintptr_t);
  971. f=va_arg(ap, uintptr_t);
  972. va_end(ap);
  973. #if defined(__i386__)
  974. /* TODO: Implement for 32-bit systems: syscall(__NR_socketcall, 18, args);
  975. args[0] = (unsigned long) fd;
  976. args[1] = (unsigned long) addr;
  977. args[2] = (unsigned long) addrlen;
  978. args[3] = (unsigned long) flags;
  979. */
  980. #else
  981. if(number == __NR_accept4) {
  982. int sockfd = a;
  983. struct sockaddr * addr = (struct sockaddr*)b;
  984. socklen_t * addrlen = (socklen_t*)c;
  985. int flags = d;
  986. int old_errno = errno;
  987. int err = accept4(sockfd, addr, addrlen, flags);
  988. errno = old_errno;
  989. if(err == -EBADF)
  990. err = -EAGAIN;
  991. return err;
  992. }
  993. #endif
  994. return realsyscall(number,a,b,c,d,e,f);
  995. }