Intercept.c 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  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. if ( (tfd = realsocket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
  248. perror("socket error");
  249. exit(-1);
  250. }
  251. while(conn_err < 0 && attempts < SERVICE_CONNECT_ATTEMPTS) {
  252. conn_err = realconnect(tfd, (struct sockaddr*)&addr, sizeof(addr));
  253. if(conn_err < 0) {
  254. dwr(MSG_DEBUG,"re-attempting connection in %ds\n", 1+attempts);
  255. sleep(1);
  256. }
  257. else {
  258. dwr(MSG_DEBUG,"AF_UNIX connection established: %d\n", tfd);
  259. is_initialized = 1;
  260. int newtfd = realdup2(tfd, RPC_FD-instance_count);
  261. dwr(MSG_DEBUG,"dup'd to rpc_fd = %d\n", newtfd);
  262. close(tfd);
  263. return newtfd;
  264. }
  265. attempts++;
  266. }
  267. return -1;
  268. }
  269. /*------------------------------------------------------------------------------
  270. ------------------------ ctors and dtors (and friends)-------------------------
  271. ------------------------------------------------------------------------------*/
  272. void my_dest(void) __attribute__ ((destructor));
  273. void my_dest(void) {
  274. dwr(MSG_DEBUG,"closing connections to service...\n");
  275. close(fdret_sock);
  276. pthread_mutex_destroy(&lock);
  277. }
  278. void load_symbols(void)
  279. {
  280. #ifdef USE_OLD_DLSYM
  281. void *lib;
  282. #endif
  283. /* possibly add check to beginning of each method to avoid needing to cll the constructor */
  284. if(thispid == getpid()) {
  285. dwr(MSG_DEBUG,"detected duplicate call to global ctor (pid=%d).\n", thispid);
  286. }
  287. thispid = getpid();
  288. #ifndef USE_OLD_DLSYM
  289. realconnect = dlsym(RTLD_NEXT, "connect");
  290. realbind = dlsym(RTLD_NEXT, "bind");
  291. realaccept = dlsym(RTLD_NEXT, "accept");
  292. reallisten = dlsym(RTLD_NEXT, "listen");
  293. realsocket = dlsym(RTLD_NEXT, "socket");
  294. realbind = dlsym(RTLD_NEXT, "bind");
  295. realselect = dlsym(RTLD_NEXT, "select");
  296. realsetsockopt = dlsym(RTLD_NEXT, "setsockopt");
  297. realgetsockopt = dlsym(RTLD_NEXT, "getsockopt");
  298. realaccept4 = dlsym(RTLD_NEXT, "accept4");
  299. realclone = dlsym(RTLD_NEXT, "clone");
  300. realclose = dlsym(RTLD_NEXT, "close");
  301. realsyscall = dlsym(RTLD_NEXT, "syscall");
  302. /* realsyscall = dlsym(RTLD_NEXT, "poll"); */
  303. realdup2 = dlsym(RTLD_NEXT, "dup2");
  304. realdup3 = dlsym(RTLD_NEXT, "dup3");
  305. #ifdef USE_SOCKS_DNS
  306. realresinit = dlsym(RTLD_NEXT, "res_init");
  307. #endif
  308. #else
  309. lib = dlopen(LIBCONNECT, RTLD_LAZY);
  310. realconnect = dlsym(lib, "connect");
  311. realbind = dlsym(lib, "bind");
  312. realaccept = dlsym(lib, "accept");
  313. reallisten = dlsym(lib, "listen");
  314. realsocket = dlsym(lib, "socket");
  315. realselect = dlsym(lib, "select");
  316. realsetsockopt = dlsym(lib, "setsockopt");
  317. realgetsockopt = dlsym(lib, "getsockopt");
  318. realaccept4 = dlsym(lib), "accept4");
  319. realclone = dlsym(lib, "clone");
  320. realclose = dlsym(lib, "close");
  321. realsyscall = dlsym(lib, "syscall");
  322. /* realsyscall = dlsym(lib, "poll"); */
  323. realdup2 = dlsym(RTLD_NEXT, "dup2");
  324. realdup3 = dlsym(RTLD_NEXT, "dup3");
  325. #ifdef USE_SOCKS_DNS
  326. realresinit = dlsym(lib, "res_init");
  327. #endif
  328. dlclose(lib);
  329. lib = dlopen(LIBC, RTLD_LAZY);
  330. dlclose(lib);
  331. #endif
  332. }
  333. /* Private Function Prototypes */
  334. void _init(void) __attribute__ ((constructor));
  335. void _init(void) {
  336. set_up_intercept();
  337. }
  338. /* get symbols and initialize mutexes */
  339. void set_up_intercept()
  340. {
  341. load_symbols();
  342. if(pthread_mutex_init(&lock, NULL) != 0) {
  343. dwr(MSG_ERROR, "error while initializing service call mutex\n");
  344. }
  345. if(pthread_mutex_init(&loglock, NULL) != 0) {
  346. dwr(MSG_ERROR, "error while initializing log mutex mutex\n");
  347. }
  348. }
  349. /*------------------------------------------------------------------------------
  350. --------------------------------- setsockopt() ---------------------------------
  351. ------------------------------------------------------------------------------*/
  352. /* int socket, int level, int option_name, const void *option_value, socklen_t option_len */
  353. int setsockopt(SETSOCKOPT_SIG)
  354. {
  355. if(realsetsockopt == NULL){
  356. dwr(MSG_ERROR, "setsockopt(): SYMBOL NOT FOUND.\n");
  357. return -1;
  358. }
  359. dwr(MSG_DEBUG,"setsockopt(%d)\n", socket);
  360. /*
  361. if(is_mapped_to_service(socket) < 0) { // First, check if the service manages this
  362. return realsetsockopt(socket, level, option_name, option_value, option_len);
  363. }
  364. */
  365. /* return(realsetsockopt(socket, level, option_name, option_value, option_len)); */
  366. if(level == SOL_IPV6 && option_name == IPV6_V6ONLY)
  367. return 0;
  368. if(level == SOL_IP && option_name == IP_TTL)
  369. return 0;
  370. if(level == IPPROTO_TCP || (level == SOL_SOCKET && option_name == SO_KEEPALIVE))
  371. return 0;
  372. /* make sure we don't touch any standard outputs */
  373. if(socket == STDIN_FILENO || socket == STDOUT_FILENO || socket == STDERR_FILENO)
  374. return(realsetsockopt(socket, level, option_name, option_value, option_len));
  375. int err = realsetsockopt(socket, level, option_name, option_value, option_len);
  376. if(err < 0){
  377. perror("setsockopt():\n");
  378. }
  379. return 0;
  380. }
  381. /*------------------------------------------------------------------------------
  382. --------------------------------- getsockopt() ---------------------------------
  383. ------------------------------------------------------------------------------*/
  384. /* int sockfd, int level, int optname, void *optval, socklen_t *optlen */
  385. int getsockopt(GETSOCKOPT_SIG)
  386. {
  387. if(realgetsockopt == NULL){
  388. dwr(MSG_ERROR, "getsockopt(): SYMBOL NOT FOUND.\n");
  389. return -1;
  390. }
  391. dwr(MSG_DEBUG,"getsockopt(%d)\n", sockfd);
  392. /*
  393. if(is_mapped_to_service(sockfd) < 0) { // First, check if the service manages this
  394. return realgetsockopt(sockfd, level, optname, optval, optlen);
  395. }
  396. */
  397. int err = realgetsockopt(sockfd, level, optname, optval, optlen);
  398. /* TODO: this condition will need a little more intelligence later on
  399. -- we will need to know if this fd is a local we are spoofing, or a true local */
  400. if(optname == SO_TYPE)
  401. {
  402. int* val = (int*)optval;
  403. *val = 2;
  404. optval = (void*)val;
  405. }
  406. if(err < 0){
  407. perror("setsockopt():\n");
  408. }
  409. return 0;
  410. }
  411. /*------------------------------------------------------------------------------
  412. ----------------------------------- socket() -----------------------------------
  413. ------------------------------------------------------------------------------*/
  414. /* int socket_family, int socket_type, int protocol
  415. socket() intercept function */
  416. int socket(SOCKET_SIG)
  417. {
  418. if(realsocket == NULL){
  419. dwr(MSG_ERROR, "socket(): SYMBOL NOT FOUND.\n");
  420. return -1;
  421. }
  422. dwr(MSG_DEBUG,"socket():\n");
  423. int err;
  424. #ifdef CHECKS
  425. /* Check that type makes sense */
  426. int flags = socket_type & ~SOCK_TYPE_MASK;
  427. if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) {
  428. errno = EINVAL;
  429. handle_error("socket", "", -1);
  430. return -1;
  431. }
  432. socket_type &= SOCK_TYPE_MASK;
  433. /* Check protocol is in range */
  434. if (socket_family < 0 || socket_family >= NPROTO){
  435. errno = EAFNOSUPPORT;
  436. handle_error("socket", "", -1);
  437. return -1;
  438. }
  439. if (socket_type < 0 || socket_type >= SOCK_MAX) {
  440. errno = EINVAL;
  441. handle_error("socket", "", -1);
  442. return -1;
  443. }
  444. /* Check that we haven't hit the soft-limit file descriptors allowed */
  445. /* FIXME: Find number of open fds
  446. struct rlimit rl;
  447. getrlimit(RLIMIT_NOFILE, &rl);
  448. if(sockfd >= rl.rlim_cur){
  449. errno = EMFILE;
  450. return -1;
  451. }
  452. */
  453. /* TODO: detect ENFILE condition */
  454. #endif
  455. char cmd[BUF_SZ];
  456. fdret_sock = !is_initialized ? init_service_connection() : fdret_sock;
  457. if(fdret_sock < 0) {
  458. dwr(MSG_DEBUG,"BAD service connection. exiting.\n");
  459. handle_error("socket", "", -1);
  460. exit(-1);
  461. }
  462. if(socket_family == AF_LOCAL
  463. || socket_family == AF_NETLINK
  464. || socket_family == AF_UNIX) {
  465. int err = realsocket(socket_family, socket_type, protocol);
  466. dwr(MSG_DEBUG,"realsocket, err = %d\n", err);
  467. handle_error("socket", "", err);
  468. return err;
  469. }
  470. /* Assemble and send RPC */
  471. struct socket_st rpc_st;
  472. rpc_st.socket_family = socket_family;
  473. rpc_st.socket_type = socket_type;
  474. rpc_st.protocol = protocol;
  475. rpc_st.__tid = syscall(SYS_gettid);
  476. memset(cmd, '\0', BUF_SZ);
  477. cmd[0] = RPC_SOCKET;
  478. memcpy(&cmd[1], &rpc_st, sizeof(struct socket_st));
  479. pthread_mutex_lock(&lock);
  480. send_command(fdret_sock, cmd);
  481. /* get new fd */
  482. newfd = get_new_fd(fdret_sock);
  483. if(newfd > 0)
  484. {
  485. dwr(MSG_DEBUG,"sending fd = %d to Service over (%d)\n", newfd, fdret_sock);
  486. /* send our local-fd number back to service so
  487. it can complete its mapping table entry */
  488. memset(cmd, '\0', BUF_SZ);
  489. cmd[0] = RPC_MAP;
  490. memcpy(&cmd[1], &newfd, sizeof(newfd));
  491. if(newfd > -1) {
  492. send_command(fdret_sock, cmd);
  493. pthread_mutex_unlock(&lock);
  494. errno = ERR_OK; /* OK */
  495. handle_error("socket", "", newfd);
  496. return newfd;
  497. }
  498. else { /* Try to read retval+errno since we RXed a bad fd */
  499. dwr(MSG_DEBUG,"Error, service sent bad fd.\n");
  500. err = get_retval();
  501. pthread_mutex_unlock(&lock);
  502. handle_error("socket", "", -1);
  503. return err;
  504. }
  505. }
  506. else {
  507. dwr(MSG_DEBUG,"Error while receiving new FD.\n");
  508. err = get_retval();
  509. pthread_mutex_unlock(&lock);
  510. handle_error("socket", "", -1);
  511. return err;
  512. }
  513. }
  514. /*------------------------------------------------------------------------------
  515. ---------------------------------- connect() -----------------------------------
  516. ------------------------------------------------------------------------------*/
  517. /* int __fd, const struct sockaddr * __addr, socklen_t __len
  518. connect() intercept function */
  519. int connect(CONNECT_SIG)
  520. {
  521. if(realconnect == NULL){
  522. dwr(MSG_ERROR, "connect(): SYMBOL NOT FOUND.\n");
  523. return -1;
  524. }
  525. dwr(MSG_DEBUG,"connect(%d):\n", __fd);
  526. /* print_addr(__addr); */
  527. struct sockaddr_in *connaddr;
  528. connaddr = (struct sockaddr_in *) __addr;
  529. #ifdef CHECKS
  530. /* Check that this is a valid fd */
  531. if(fcntl(__fd, F_GETFD) < 0) {
  532. errno = EBADF;
  533. handle_error("connect", "EBADF", -1);
  534. return -1;
  535. }
  536. /* Check that it is a socket */
  537. int sock_type;
  538. socklen_t sock_type_len = sizeof(sock_type);
  539. if(getsockopt(__fd, SOL_SOCKET, SO_TYPE, (void *) &sock_type, &sock_type_len) < 0) {
  540. errno = ENOTSOCK;
  541. handle_error("connect", "ENOTSOCK", -1);
  542. return -1;
  543. }
  544. /* Check family */
  545. if (connaddr->sin_family < 0 || connaddr->sin_family >= NPROTO){
  546. errno = EAFNOSUPPORT;
  547. handle_error("connect", "EAFNOSUPPORT", -1);
  548. return -1;
  549. }
  550. /* FIXME: Check that address is in user space, return EFAULT ? */
  551. #endif
  552. /* make sure we don't touch any standard outputs */
  553. if(__fd == STDIN_FILENO || __fd == STDOUT_FILENO || __fd == STDERR_FILENO){
  554. if (realconnect == NULL) {
  555. handle_error("connect", "Unresolved symbol [connect]", -1);
  556. exit(-1);
  557. }
  558. return(realconnect(__fd, __addr, __len));
  559. }
  560. if(__addr != NULL && (connaddr->sin_family == AF_LOCAL
  561. || connaddr->sin_family == PF_NETLINK
  562. || connaddr->sin_family == AF_NETLINK
  563. || connaddr->sin_family == AF_UNIX)) {
  564. int err = realconnect(__fd, __addr, __len);
  565. perror("connect():");
  566. /* handle_error("connect", "Cannot connect to local socket", err); */
  567. return err;
  568. }
  569. /* Assemble and send RPC */
  570. int err;
  571. char cmd[BUF_SZ];
  572. memset(cmd, '\0', BUF_SZ);
  573. struct connect_st rpc_st;
  574. rpc_st.__tid = syscall(SYS_gettid);
  575. rpc_st.__fd = __fd;
  576. memcpy(&rpc_st.__addr, __addr, sizeof(struct sockaddr));
  577. memcpy(&rpc_st.__len, &__len, sizeof(socklen_t));
  578. cmd[0] = RPC_CONNECT;
  579. memcpy(&cmd[1], &rpc_st, sizeof(struct connect_st));
  580. pthread_mutex_lock(&lock);
  581. send_command(fdret_sock, cmd);
  582. /*
  583. if(sock_type && O_NONBLOCK) {
  584. pthread_mutex_unlock(&lock);
  585. return EINPROGRESS;
  586. }
  587. */
  588. err = get_retval();
  589. pthread_mutex_unlock(&lock);
  590. /* handle_error("connect", "", err); */
  591. return err;
  592. }
  593. /*------------------------------------------------------------------------------
  594. ---------------------------------- select() ------------------------------------
  595. ------------------------------------------------------------------------------*/
  596. /* int n, fd_set *readfds, fd_set *writefds,
  597. fd_set *exceptfds, struct timeval *timeout */
  598. int select(SELECT_SIG)
  599. {
  600. if(realselect == NULL){
  601. dwr(MSG_ERROR, "select(): SYMBOL NOT FOUND.\n");
  602. return -1;
  603. }
  604. /* dwr(MSG_DEBUG,"select():\n"); */
  605. return realselect(n, readfds, writefds, exceptfds, timeout);
  606. }
  607. /*------------------------------------------------------------------------------
  608. ------------------------------------ bind() ------------------------------------
  609. ------------------------------------------------------------------------------*/
  610. /* int sockfd, const struct sockaddr *addr, socklen_t addrlen
  611. bind() intercept function */
  612. int bind(BIND_SIG)
  613. {
  614. if(realbind == NULL){
  615. dwr(MSG_ERROR, "bind(): SYMBOL NOT FOUND.\n");
  616. return -1;
  617. }
  618. dwr(MSG_DEBUG,"bind(%d):\n", sockfd);
  619. /* print_addr(addr); */
  620. #ifdef CHECKS
  621. /* Check that this is a valid fd */
  622. if(fcntl(sockfd, F_GETFD) < 0) {
  623. errno = EBADF;
  624. handle_error("bind", "EBADF", -1);
  625. return -1;
  626. }
  627. /* Check that it is a socket */
  628. int opt = -1;
  629. socklen_t opt_len;
  630. if(getsockopt(sockfd, SOL_SOCKET, SO_TYPE, (void *) &opt, &opt_len) < 0) {
  631. errno = ENOTSOCK;
  632. handle_error("bind", "ENOTSOCK", -1);
  633. return -1;
  634. }
  635. #endif
  636. int err;
  637. /* make sure we don't touch any standard outputs */
  638. if(sockfd == STDIN_FILENO || sockfd == STDOUT_FILENO || sockfd == STDERR_FILENO)
  639. return(realbind(sockfd, addr, addrlen));
  640. /* If local, just use normal syscall */
  641. struct sockaddr_in *connaddr;
  642. connaddr = (struct sockaddr_in *)addr;
  643. if(connaddr->sin_family == AF_LOCAL
  644. || connaddr->sin_family == AF_NETLINK
  645. || connaddr->sin_family == AF_UNIX) {
  646. int err = realbind(sockfd, addr, addrlen);
  647. dwr(MSG_DEBUG,"realbind, err = %d\n", err);
  648. return err;
  649. }
  650. /* Assemble and send RPC */
  651. char cmd[BUF_SZ];
  652. struct bind_st rpc_st;
  653. rpc_st.sockfd = sockfd;
  654. rpc_st.__tid = syscall(SYS_gettid);
  655. memcpy(&rpc_st.addr, addr, sizeof(struct sockaddr));
  656. memcpy(&rpc_st.addrlen, &addrlen, sizeof(socklen_t));
  657. cmd[0]=RPC_BIND;
  658. memcpy(&cmd[1], &rpc_st, sizeof(struct bind_st));
  659. pthread_mutex_lock(&lock);
  660. send_command(fdret_sock, cmd);
  661. err = get_retval();
  662. pthread_mutex_unlock(&lock);
  663. errno = ERR_OK;
  664. handle_error("bind", "", err);
  665. return err;
  666. }
  667. /*------------------------------------------------------------------------------
  668. ----------------------------------- accept4() ----------------------------------
  669. ------------------------------------------------------------------------------*/
  670. /* int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags */
  671. int accept4(ACCEPT4_SIG)
  672. {
  673. if(realaccept4 == NULL){
  674. dwr(MSG_ERROR, "accept4(): SYMBOL NOT FOUND.\n");
  675. return -1;
  676. }
  677. dwr(MSG_DEBUG,"accept4(%d):\n", sockfd);
  678. #ifdef CHECKS
  679. if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) {
  680. errno = EINVAL;
  681. return -1;
  682. }
  683. #endif
  684. int newfd = accept(sockfd, addr, addrlen);
  685. if(newfd > 0) {
  686. if(flags & SOCK_CLOEXEC)
  687. fcntl(newfd, F_SETFL, FD_CLOEXEC);
  688. if(flags & SOCK_NONBLOCK)
  689. fcntl(newfd, F_SETFL, O_NONBLOCK);
  690. }
  691. handle_error("accept4", "", newfd);
  692. return newfd;
  693. }
  694. /*------------------------------------------------------------------------------
  695. ----------------------------------- accept() -----------------------------------
  696. ------------------------------------------------------------------------------*/
  697. /* int sockfd struct sockaddr *addr, socklen_t *addrlen
  698. accept() intercept function */
  699. int accept(ACCEPT_SIG)
  700. {
  701. if(realaccept == NULL){
  702. dwr(MSG_ERROR, "accept(): SYMBOL NOT FOUND.\n");
  703. return -1;
  704. }
  705. dwr(MSG_DEBUG,"accept(%d):\n", sockfd);
  706. #ifdef CHECKS
  707. /* Check that this is a valid fd */
  708. if(fcntl(sockfd, F_GETFD) < 0) {
  709. return -1;
  710. errno = EBADF;
  711. dwr(MSG_DEBUG,"EBADF\n");
  712. handle_error("accept", "EBADF", -1);
  713. return -1;
  714. }
  715. /* Check that it is a socket */
  716. int opt;
  717. socklen_t opt_len;
  718. if(getsockopt(sockfd, SOL_SOCKET, SO_TYPE, (void *) &opt, &opt_len) < 0) {
  719. errno = ENOTSOCK;
  720. dwr(MSG_DEBUG,"ENOTSOCK\n");
  721. handle_error("accept", "ENOTSOCK", -1);
  722. return -1;
  723. }
  724. /* Check that this socket supports accept() */
  725. if(!(opt && (SOCK_STREAM | SOCK_SEQPACKET))) {
  726. errno = EOPNOTSUPP;
  727. dwr(MSG_DEBUG,"EOPNOTSUPP\n");
  728. handle_error("accept", "EOPNOTSUPP", -1);
  729. return -1;
  730. }
  731. /* Check that we haven't hit the soft-limit file descriptors allowed */
  732. struct rlimit rl;
  733. getrlimit(RLIMIT_NOFILE, &rl);
  734. if(sockfd >= rl.rlim_cur){
  735. errno = EMFILE;
  736. dwr(MSG_DEBUG,"EMFILE\n");
  737. handle_error("accept", "EMFILE", -1);
  738. return -1;
  739. }
  740. /* Check address length */
  741. if(addrlen < 0) {
  742. errno = EINVAL;
  743. dwr(MSG_DEBUG,"EINVAL\n");
  744. handle_error("accept", "EINVAL", -1);
  745. return -1;
  746. }
  747. #endif
  748. /* redirect calls for standard I/O descriptors to kernel */
  749. if(sockfd == STDIN_FILENO || sockfd == STDOUT_FILENO || sockfd == STDERR_FILENO){
  750. dwr(MSG_DEBUG,"realaccept():\n");
  751. return(realaccept(sockfd, addr, addrlen));
  752. }
  753. if(addr)
  754. addr->sa_family = AF_INET;
  755. /* TODO: also get address info */
  756. char cmd[BUF_SZ];
  757. if(realaccept == NULL) {
  758. handle_error("accept", "Unresolved symbol [accept]", -1);
  759. return -1;
  760. }
  761. // if(opt & O_NONBLOCK)
  762. fcntl(sockfd, F_SETFL, O_NONBLOCK); /* required by libuv in nodejs */
  763. char c[1];
  764. int new_conn_socket;
  765. int n = read(sockfd, c, sizeof(c)); /* Read signal byte */
  766. if(n > 0)
  767. {
  768. new_conn_socket = get_new_fd(fdret_sock);
  769. dwr(MSG_DEBUG, " accept(): RX: fd = (%d) over (%d)\n", new_conn_socket, fdret_sock);
  770. if(new_conn_socket > 0) {
  771. /* Send our local-fd number back to service so it can complete its mapping table */
  772. memset(cmd, '\0', BUF_SZ);
  773. cmd[0] = RPC_MAP;
  774. memcpy(&cmd[1], &new_conn_socket, sizeof(new_conn_socket));
  775. pthread_mutex_lock(&lock);
  776. dwr(MSG_DEBUG, "accept(): sending perceived fd (%d) to service.\n", new_conn_socket);
  777. int n_write = send_command(fdret_sock, cmd);
  778. if(n_write < 0) {
  779. errno = ECONNABORTED; /* TODO: Closest match, service unreachable */
  780. handle_error("accept", "ECONNABORTED - Error sending perceived FD to service", -1);
  781. return -1;
  782. }
  783. pthread_mutex_unlock(&lock);
  784. errno = ERR_OK;
  785. dwr(MSG_DEBUG,"*accept()=%d\n", new_conn_socket);
  786. handle_error("accept", "", new_conn_socket);
  787. return new_conn_socket; /* OK */
  788. }
  789. else {
  790. errno = ECONNABORTED; /* TODO: Closest match, service unreachable */
  791. handle_error("accept", "ECONNABORTED - Error receiving new FD from service", -1);
  792. return -1;
  793. }
  794. }
  795. errno = EAGAIN; /* necessary? */
  796. handle_error("accept", "EAGAIN - Error reading signal byte from service", -1);
  797. return -EAGAIN;
  798. /* Prevents libuv in nodejs from accepting properly (it looks for a -EAGAIN) */
  799. /*
  800. errno = EBADF;
  801. handle_error("accept", "EBADF - Error reading signal byte from service", -1);
  802. return -1;
  803. */
  804. }
  805. /*------------------------------------------------------------------------------
  806. ------------------------------------- listen()----------------------------------
  807. ------------------------------------------------------------------------------*/
  808. /* int sockfd, int backlog
  809. listen() intercept function */
  810. int listen(LISTEN_SIG)
  811. {
  812. if(reallisten == NULL){
  813. dwr(MSG_ERROR, "listen(): SYMBOL NOT FOUND.\n");
  814. return -1;
  815. }
  816. dwr(MSG_DEBUG,"listen(%d):\n", sockfd);
  817. int sock_type;
  818. socklen_t sock_type_len = sizeof(sock_type);
  819. #ifdef CHECKS
  820. /* Check that this is a valid fd */
  821. if(fcntl(sockfd, F_GETFD) < 0) {
  822. errno = EBADF;
  823. handle_error("listen", "EBADF", -1);
  824. return -1;
  825. }
  826. /* Check that it is a socket */
  827. if(getsockopt(sockfd, SOL_SOCKET, SO_TYPE, (void *) &sock_type, &sock_type_len) < 0) {
  828. errno = ENOTSOCK;
  829. handle_error("listen", "ENOTSOCK", -1);
  830. return -1;
  831. }
  832. /* Check that this socket supports accept() */
  833. if(!(sock_type && (SOCK_STREAM | SOCK_SEQPACKET))) {
  834. errno = EOPNOTSUPP;
  835. handle_error("listen", "EOPNOTSUPP", -1);
  836. return -1;
  837. }
  838. #endif
  839. /* make sure we don't touch any standard outputs */
  840. if(sockfd == STDIN_FILENO || sockfd == STDOUT_FILENO || sockfd == STDERR_FILENO)
  841. return(reallisten(sockfd, backlog));
  842. if(is_mapped_to_service(sockfd) < 0) {
  843. /* We now know this socket is not one of our socketpairs */
  844. int err = reallisten(sockfd, backlog);
  845. dwr(MSG_DEBUG,"reallisten()=%d\n", err);
  846. return err;
  847. }
  848. /* Assemble and send RPC */
  849. char cmd[BUF_SZ];
  850. memset(cmd, '\0', BUF_SZ);
  851. struct listen_st rpc_st;
  852. rpc_st.sockfd = sockfd;
  853. rpc_st.backlog = backlog;
  854. rpc_st.__tid = syscall(SYS_gettid);
  855. cmd[0] = RPC_LISTEN;
  856. memcpy(&cmd[1], &rpc_st, sizeof(struct listen_st));
  857. pthread_mutex_lock(&lock);
  858. send_command(fdret_sock, cmd);
  859. get_retval();
  860. pthread_mutex_unlock(&lock);
  861. handle_error("listen", "", ERR_OK);
  862. return ERR_OK;
  863. }
  864. /*------------------------------------------------------------------------------
  865. -------------------------------------- clone()----------------------------------
  866. ------------------------------------------------------------------------------*/
  867. /* int (*fn)(void *), void *child_stack, int flags, void *arg, ... */
  868. int clone(CLONE_SIG)
  869. {
  870. if(realclone == NULL){
  871. dwr(MSG_ERROR, "clone(): SYMBOL NOT FOUND.\n");
  872. return -1;
  873. }
  874. dwr(MSG_DEBUG,"clone()\n");
  875. int err = realclone(fn, child_stack, flags, arg);
  876. checkpid();
  877. return err;
  878. }
  879. /*------------------------------------------------------------------------------
  880. -------------------------------------- poll()-----------------------------------
  881. ------------------------------------------------------------------------------*/
  882. /* struct pollfd *fds, nfds_t nfds, int timeout */
  883. /*
  884. int poll(POLL_SIG)
  885. {
  886. dwr(MSG_DEBUG,"poll()\n");
  887. return realpoll(fds, nfds, timeout);
  888. }
  889. */
  890. /*------------------------------------------------------------------------------
  891. -------------------------------------- close()-----------------------------------
  892. ------------------------------------------------------------------------------*/
  893. /* int fd */
  894. int close(CLOSE_SIG)
  895. {
  896. /* checkpid(); // Required for httpd-2.4.17-3.x86_64 -- After clone, some symbols aren't initialized yet */
  897. if(realclose == NULL){
  898. dwr(MSG_ERROR, "close(): SYMBOL NOT FOUND.\n");
  899. return -1;
  900. }
  901. /* dwr(MSG_DEBUG,"close(%d)\n", fd); */
  902. if(fd == fdret_sock)
  903. return -1; /* TODO: Ignore request to shut down our rpc fd, this is *almost always* safe */
  904. if(fd != STDIN_FILENO && fd != STDOUT_FILENO && fd != STDERR_FILENO)
  905. return realclose(fd);
  906. return -1;
  907. }
  908. /*------------------------------------------------------------------------------
  909. -------------------------------------- dup2()-----------------------------------
  910. ------------------------------------------------------------------------------*/
  911. /* int oldfd, int newfd */
  912. int dup2(DUP2_SIG)
  913. {
  914. if(realdup2 == NULL){
  915. dwr(MSG_ERROR, "dup2(): SYMBOL NOT FOUND.\n");
  916. return -1;
  917. }
  918. dwr(MSG_DEBUG,"dup2(%d, %d)\n", oldfd, newfd);
  919. if(oldfd == fdret_sock) {
  920. dwr(MSG_DEBUG,"client application attempted to dup2 RPC socket (%d). This is not allowed.\n", oldfd);
  921. errno = EBADF;
  922. return -1;
  923. }
  924. if(oldfd != STDIN_FILENO && oldfd != STDOUT_FILENO && oldfd != STDERR_FILENO)
  925. if(newfd != STDIN_FILENO && newfd != STDOUT_FILENO && newfd != STDERR_FILENO)
  926. return realdup2(oldfd, newfd);
  927. return -1;
  928. }
  929. /*------------------------------------------------------------------------------
  930. -------------------------------------- dup3()-----------------------------------
  931. ------------------------------------------------------------------------------*/
  932. /* int oldfd, int newfd, int flags */
  933. int dup3(DUP3_SIG)
  934. {
  935. if(realdup3 == NULL){
  936. dwr(MSG_ERROR, "dup3(): SYMBOL NOT FOUND.\n");
  937. return -1;
  938. }
  939. dwr(MSG_DEBUG,"dup3(%d, %d, %d)\n", oldfd, newfd, flags);
  940. #ifdef DEBUG
  941. /* Only do this check if we want to debug the intercept, otherwise, dont mess with
  942. the client application's logging methods */
  943. if(newfd == STDIN_FILENO || newfd == STDOUT_FILENO || newfd == STDERR_FILENO)
  944. return newfd; /* FIXME: This is to prevent httpd from dup'ing over our stderr
  945. and preventing us from debugging */
  946. else
  947. #endif
  948. return realdup3(oldfd, newfd, flags);
  949. }
  950. /*------------------------------------------------------------------------------
  951. ------------------------------------ syscall()----------------------------------
  952. ------------------------------------------------------------------------------*/
  953. long syscall(SYSCALL_SIG){
  954. if(realsyscall == NULL){
  955. dwr(MSG_ERROR, "syscall(): SYMBOL NOT FOUND.\n");
  956. return -1;
  957. }
  958. dwr(MSG_DEBUG_EXTRA,"syscall(%u, ...):\n", number);
  959. va_list ap;
  960. uintptr_t a,b,c,d,e,f;
  961. va_start(ap, number);
  962. a=va_arg(ap, uintptr_t);
  963. b=va_arg(ap, uintptr_t);
  964. c=va_arg(ap, uintptr_t);
  965. d=va_arg(ap, uintptr_t);
  966. e=va_arg(ap, uintptr_t);
  967. f=va_arg(ap, uintptr_t);
  968. va_end(ap);
  969. #if defined(__i386__)
  970. /* TODO: Implement for 32-bit systems: syscall(__NR_socketcall, 18, args);
  971. args[0] = (unsigned long) fd;
  972. args[1] = (unsigned long) addr;
  973. args[2] = (unsigned long) addrlen;
  974. args[3] = (unsigned long) flags;
  975. */
  976. #else
  977. if(number == __NR_accept4) {
  978. int sockfd = a;
  979. struct sockaddr * addr = (struct sockaddr*)b;
  980. socklen_t * addrlen = (socklen_t*)c;
  981. int flags = d;
  982. int old_errno = errno;
  983. int err = accept4(sockfd, addr, addrlen, flags);
  984. errno = old_errno;
  985. if(err == -EBADF)
  986. err = -EAGAIN;
  987. return err;
  988. }
  989. #endif
  990. return realsyscall(number,a,b,c,d,e,f);
  991. }