Intercept.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  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. dwr(MSG_DEBUG, "get_new_fd(): RX: fd = (%d) over (%d)\n", newfd, oversock);
  210. return newfd;
  211. }
  212. /* Check whether the socket is mapped to the service or not. We
  213. need to know if this is a regular AF_LOCAL socket or an end of a socketpair
  214. that the service uses. We don't want to keep state in the intercept, so
  215. we simply ask the service via an RPC */
  216. int is_mapped_to_service(int sockfd)
  217. {
  218. dwr(MSG_DEBUG,"is_mapped_to_service()\n");
  219. char cmd[BUF_SZ];
  220. memset(cmd, '\0', BUF_SZ);
  221. cmd[0] = RPC_MAP_REQ;
  222. memcpy(&cmd[1], &sockfd, sizeof(sockfd));
  223. pthread_mutex_lock(&lock);
  224. if(send_command(fdret_sock, cmd) < 0)
  225. return -1;
  226. int err = get_retval();
  227. pthread_mutex_unlock(&lock);
  228. return err;
  229. }
  230. /*------------------------------------------------------------------------------
  231. ---------- Unix-domain socket lazy initializer (for fd-transfers)--------------
  232. ------------------------------------------------------------------------------*/
  233. /* Sets up the connection pipes and sockets to the service */
  234. int init_service_connection()
  235. {
  236. instance_count++;
  237. dwr(MSG_DEBUG,"init_service_connection()\n");
  238. struct sockaddr_un addr;
  239. int tfd = -1, attempts = 0, conn_err = -1;
  240. memset(&addr, 0, sizeof(addr));
  241. addr.sun_family = AF_UNIX;
  242. strncpy(addr.sun_path, af_sock_name, sizeof(addr.sun_path)-1);
  243. dwr(MSG_DEBUG, "init(): pre-realsocket\n");
  244. if ( (tfd = realsocket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
  245. perror("socket error");
  246. exit(-1);
  247. }
  248. dwr(MSG_DEBUG, "init(): post-realsocket, conn_err = %d, attempts = %d\n", conn_err, attempts);
  249. while(conn_err < 0 && attempts < SERVICE_CONNECT_ATTEMPTS) {
  250. dwr(MSG_DEBUG, "init(): Attempting!\n");
  251. conn_err = realconnect(tfd, (struct sockaddr*)&addr, sizeof(addr));
  252. dwr(MSG_DEBUG, "init(): post-realconnect\n");
  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,"\nsetsockopt(%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,"\ngetsockopt(%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,"\nsocket():\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("socket1", "", -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("socket2", "", -1);
  437. return -1;
  438. }
  439. if (socket_type < 0 || socket_type >= SOCK_MAX) {
  440. errno = EINVAL;
  441. handle_error("socket3", "", -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("socket4", "", -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("socket5", "", 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. char rbuf[16];
  483. newfd = get_new_fd(fdret_sock);
  484. if(newfd > 0)
  485. {
  486. dwr(MSG_DEBUG,"sending fd = %d to Service over (%d)\n", newfd, fdret_sock);
  487. /* send our local-fd number back to service so
  488. it can complete its mapping table entry */
  489. memset(cmd, '\0', BUF_SZ);
  490. cmd[0] = RPC_MAP;
  491. memcpy(&cmd[1], &newfd, sizeof(newfd));
  492. if(newfd > -1) {
  493. send_command(fdret_sock, cmd);
  494. pthread_mutex_unlock(&lock);
  495. errno = ERR_OK; /* OK */
  496. handle_error("socket6", "", newfd);
  497. return newfd;
  498. }
  499. else { /* Try to read retval+errno since we RXed a bad fd */
  500. dwr(MSG_DEBUG,"Error, service sent bad fd.\n");
  501. err = get_retval();
  502. pthread_mutex_unlock(&lock);
  503. handle_error("socket7", "", -1);
  504. return err;
  505. }
  506. }
  507. else {
  508. dwr(MSG_DEBUG,"Error while receiving new FD.\n");
  509. err = get_retval();
  510. pthread_mutex_unlock(&lock);
  511. handle_error("socket8", "", -1);
  512. return err;
  513. }
  514. }
  515. /*------------------------------------------------------------------------------
  516. ---------------------------------- connect() -----------------------------------
  517. ------------------------------------------------------------------------------*/
  518. /* int __fd, const struct sockaddr * __addr, socklen_t __len
  519. connect() intercept function */
  520. int connect(CONNECT_SIG)
  521. {
  522. if(realconnect == NULL){
  523. dwr(MSG_ERROR, "connect(): SYMBOL NOT FOUND.\n");
  524. return -1;
  525. }
  526. dwr(MSG_DEBUG,"\nconnect(%d):\n", __fd);
  527. print_addr(__addr);
  528. struct sockaddr_in *connaddr;
  529. connaddr = (struct sockaddr_in *) __addr;
  530. #ifdef CHECKS
  531. /* Check that this is a valid fd */
  532. if(fcntl(__fd, F_GETFD) < 0) {
  533. errno = EBADF;
  534. handle_error("connect", "EBADF", -1);
  535. return -1;
  536. }
  537. /* Check that it is a socket */
  538. int sock_type;
  539. socklen_t sock_type_len = sizeof(sock_type);
  540. if(getsockopt(__fd, SOL_SOCKET, SO_TYPE, (void *) &sock_type, &sock_type_len) < 0) {
  541. errno = ENOTSOCK;
  542. handle_error("connect", "ENOTSOCK", -1);
  543. return -1;
  544. }
  545. /* Check family */
  546. if (connaddr->sin_family < 0 || connaddr->sin_family >= NPROTO){
  547. errno = EAFNOSUPPORT;
  548. handle_error("connect", "EAFNOSUPPORT", -1);
  549. return -1;
  550. }
  551. /* FIXME: Check that address is in user space, return EFAULT ? */
  552. #endif
  553. /* make sure we don't touch any standard outputs */
  554. if(__fd == STDIN_FILENO || __fd == STDOUT_FILENO || __fd == STDERR_FILENO){
  555. if (realconnect == NULL) {
  556. handle_error("connect", "Unresolved symbol [connect]", -1);
  557. exit(-1);
  558. }
  559. return(realconnect(__fd, __addr, __len));
  560. }
  561. if(__addr != NULL && (connaddr->sin_family == AF_LOCAL
  562. || connaddr->sin_family == PF_NETLINK
  563. || connaddr->sin_family == AF_NETLINK
  564. || connaddr->sin_family == AF_UNIX)) {
  565. int err = realconnect(__fd, __addr, __len);
  566. perror("connect():");
  567. /* handle_error("connect", "Cannot connect to local socket", err); */
  568. return err;
  569. }
  570. /* Assemble and send RPC */
  571. int err;
  572. char cmd[BUF_SZ];
  573. memset(cmd, '\0', BUF_SZ);
  574. struct connect_st rpc_st;
  575. rpc_st.__tid = syscall(SYS_gettid);
  576. rpc_st.__fd = __fd;
  577. memcpy(&rpc_st.__addr, __addr, sizeof(struct sockaddr));
  578. memcpy(&rpc_st.__len, &__len, sizeof(socklen_t));
  579. cmd[0] = RPC_CONNECT;
  580. memcpy(&cmd[1], &rpc_st, sizeof(struct connect_st));
  581. pthread_mutex_lock(&lock);
  582. send_command(fdret_sock, cmd);
  583. /*
  584. if(sock_type && O_NONBLOCK) {
  585. pthread_mutex_unlock(&lock);
  586. return EINPROGRESS;
  587. }
  588. */
  589. err = get_retval();
  590. pthread_mutex_unlock(&lock);
  591. /* handle_error("connect", "", err); */
  592. return err;
  593. }
  594. /*------------------------------------------------------------------------------
  595. ---------------------------------- select() ------------------------------------
  596. ------------------------------------------------------------------------------*/
  597. /* int n, fd_set *readfds, fd_set *writefds,
  598. fd_set *exceptfds, struct timeval *timeout */
  599. int select(SELECT_SIG)
  600. {
  601. if(realselect == NULL){
  602. dwr(MSG_ERROR, "select(): SYMBOL NOT FOUND.\n");
  603. return -1;
  604. }
  605. /* dwr(MSG_DEBUG,"select():\n"); */
  606. return realselect(n, readfds, writefds, exceptfds, timeout);
  607. }
  608. /*------------------------------------------------------------------------------
  609. ------------------------------------ bind() ------------------------------------
  610. ------------------------------------------------------------------------------*/
  611. /* int sockfd, const struct sockaddr *addr, socklen_t addrlen
  612. bind() intercept function */
  613. int bind(BIND_SIG)
  614. {
  615. if(realbind == NULL){
  616. dwr(MSG_ERROR, "bind(): SYMBOL NOT FOUND.\n");
  617. return -1;
  618. }
  619. dwr(MSG_DEBUG,"\nbind(%d):\n", sockfd);
  620. print_addr(addr);
  621. #ifdef CHECKS
  622. /* Check that this is a valid fd */
  623. if(fcntl(sockfd, F_GETFD) < 0) {
  624. errno = EBADF;
  625. handle_error("bind", "EBADF", -1);
  626. return -1;
  627. }
  628. /* Check that it is a socket */
  629. int opt = -1;
  630. socklen_t opt_len;
  631. if(getsockopt(sockfd, SOL_SOCKET, SO_TYPE, (void *) &opt, &opt_len) < 0) {
  632. errno = ENOTSOCK;
  633. handle_error("bind", "ENOTSOCK", -1);
  634. return -1;
  635. }
  636. #endif
  637. int err;
  638. /* make sure we don't touch any standard outputs */
  639. if(sockfd == STDIN_FILENO || sockfd == STDOUT_FILENO || sockfd == STDERR_FILENO)
  640. return(realbind(sockfd, addr, addrlen));
  641. /* If local, just use normal syscall */
  642. struct sockaddr_in *connaddr;
  643. connaddr = (struct sockaddr_in *)addr;
  644. if(connaddr->sin_family == AF_LOCAL
  645. || connaddr->sin_family == AF_NETLINK
  646. || connaddr->sin_family == AF_UNIX) {
  647. int err = realbind(sockfd, addr, addrlen);
  648. dwr(MSG_DEBUG,"realbind, err = %d\n", err);
  649. return err;
  650. }
  651. /* Assemble and send RPC */
  652. char cmd[BUF_SZ];
  653. struct bind_st rpc_st;
  654. rpc_st.sockfd = sockfd;
  655. rpc_st.__tid = syscall(SYS_gettid);
  656. memcpy(&rpc_st.addr, addr, sizeof(struct sockaddr));
  657. memcpy(&rpc_st.addrlen, &addrlen, sizeof(socklen_t));
  658. cmd[0]=RPC_BIND;
  659. memcpy(&cmd[1], &rpc_st, sizeof(struct bind_st));
  660. pthread_mutex_lock(&lock);
  661. send_command(fdret_sock, cmd);
  662. err = get_retval();
  663. pthread_mutex_unlock(&lock);
  664. errno = ERR_OK;
  665. handle_error("bind", "", err);
  666. return err;
  667. }
  668. /*------------------------------------------------------------------------------
  669. ----------------------------------- accept4() ----------------------------------
  670. ------------------------------------------------------------------------------*/
  671. /* int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags */
  672. int accept4(ACCEPT4_SIG)
  673. {
  674. if(realaccept4 == NULL){
  675. dwr(MSG_ERROR, "accept4(): SYMBOL NOT FOUND.\n");
  676. return -1;
  677. }
  678. dwr(MSG_DEBUG,"\naccept4(%d):\n", sockfd);
  679. #ifdef CHECKS
  680. if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) {
  681. errno = EINVAL;
  682. return -1;
  683. }
  684. #endif
  685. int newfd = accept(sockfd, addr, addrlen);
  686. if(newfd > 0) {
  687. if(flags & SOCK_CLOEXEC)
  688. fcntl(newfd, F_SETFL, FD_CLOEXEC);
  689. if(flags & SOCK_NONBLOCK)
  690. fcntl(newfd, F_SETFL, O_NONBLOCK);
  691. }
  692. handle_error("accept4", "", newfd);
  693. return newfd;
  694. }
  695. /*------------------------------------------------------------------------------
  696. ----------------------------------- accept() -----------------------------------
  697. ------------------------------------------------------------------------------*/
  698. /* int sockfd struct sockaddr *addr, socklen_t *addrlen
  699. accept() intercept function */
  700. int accept(ACCEPT_SIG)
  701. {
  702. if(realaccept == NULL){
  703. dwr(MSG_ERROR, "accept(): SYMBOL NOT FOUND.\n");
  704. return -1;
  705. }
  706. dwr(MSG_DEBUG,"\naccept(%d):\n", sockfd);
  707. #ifdef CHECKS
  708. /* Check that this is a valid fd */
  709. if(fcntl(sockfd, F_GETFD) < 0) {
  710. return -1;
  711. errno = EBADF;
  712. dwr(MSG_DEBUG,"EBADF\n");
  713. handle_error("accept", "EBADF", -1);
  714. return -1;
  715. }
  716. /* Check that it is a socket */
  717. int opt;
  718. socklen_t opt_len;
  719. if(getsockopt(sockfd, SOL_SOCKET, SO_TYPE, (void *) &opt, &opt_len) < 0) {
  720. errno = ENOTSOCK;
  721. dwr(MSG_DEBUG,"ENOTSOCK\n");
  722. handle_error("accept", "ENOTSOCK", -1);
  723. return -1;
  724. }
  725. /* Check that this socket supports accept() */
  726. if(!(opt && (SOCK_STREAM | SOCK_SEQPACKET))) {
  727. errno = EOPNOTSUPP;
  728. dwr(MSG_DEBUG,"EOPNOTSUPP\n");
  729. handle_error("accept", "EOPNOTSUPP", -1);
  730. return -1;
  731. }
  732. /* Check that we haven't hit the soft-limit file descriptors allowed */
  733. struct rlimit rl;
  734. getrlimit(RLIMIT_NOFILE, &rl);
  735. if(sockfd >= rl.rlim_cur){
  736. errno = EMFILE;
  737. dwr(MSG_DEBUG,"EMFILE\n");
  738. handle_error("accept", "EMFILE", -1);
  739. return -1;
  740. }
  741. /* Check address length */
  742. if(addrlen < 0) {
  743. errno = EINVAL;
  744. dwr(MSG_DEBUG,"EINVAL\n");
  745. handle_error("accept", "EINVAL", -1);
  746. return -1;
  747. }
  748. #endif
  749. /* redirect calls for standard I/O descriptors to kernel */
  750. if(sockfd == STDIN_FILENO || sockfd == STDOUT_FILENO || sockfd == STDERR_FILENO){
  751. dwr(MSG_DEBUG,"realaccept():\n");
  752. return(realaccept(sockfd, addr, addrlen));
  753. }
  754. if(addr)
  755. addr->sa_family = AF_INET;
  756. /* TODO: also get address info */
  757. char cmd[BUF_SZ];
  758. if(realaccept == NULL) {
  759. handle_error("accept", "Unresolved symbol [accept]", -1);
  760. return -1;
  761. }
  762. /*
  763. if(opt & O_NONBLOCK)
  764. fcntl(sockfd, F_SETFL, O_NONBLOCK);
  765. */
  766. char rbuf[16], c[1];
  767. int new_conn_socket;
  768. int n = read(sockfd, c, sizeof(c)); /* Read signal byte */
  769. if(n > 0)
  770. {
  771. new_conn_socket = get_new_fd(fdret_sock);
  772. dwr(MSG_DEBUG, " accept(): RX: fd = (%d) over (%d)\n", new_conn_socket, fdret_sock);
  773. if(new_conn_socket > 0) {
  774. /* Send our local-fd number back to service so it can complete its mapping table */
  775. memset(cmd, '\0', BUF_SZ);
  776. cmd[0] = RPC_MAP;
  777. memcpy(&cmd[1], &new_conn_socket, sizeof(new_conn_socket));
  778. pthread_mutex_lock(&lock);
  779. dwr(MSG_DEBUG, "accept(): sending perceived fd (%d) to service.\n", new_conn_socket);
  780. int n_write = send_command(fdret_sock, cmd);
  781. if(n_write < 0) {
  782. errno = ECONNABORTED; /* TODO: Closest match, service unreachable */
  783. handle_error("accept", "ECONNABORTED - Error sending perceived FD to service", -1);
  784. return -1;
  785. }
  786. pthread_mutex_unlock(&lock);
  787. errno = ERR_OK;
  788. dwr(MSG_DEBUG,"*accept()=%d\n", new_conn_socket);
  789. handle_error("accept", "", new_conn_socket);
  790. return new_conn_socket; /* OK */
  791. }
  792. else {
  793. errno = ECONNABORTED; /* TODO: Closest match, service unreachable */
  794. handle_error("accept", "ECONNABORTED - Error receiving new FD from service", -1);
  795. return -1;
  796. }
  797. }
  798. errno = EBADF;
  799. handle_error("accept", "EBADF - Error reading signal byte from service", -1);
  800. return -1;
  801. }
  802. /*------------------------------------------------------------------------------
  803. ------------------------------------- listen()----------------------------------
  804. ------------------------------------------------------------------------------*/
  805. /* int sockfd, int backlog
  806. listen() intercept function */
  807. int listen(LISTEN_SIG)
  808. {
  809. if(reallisten == NULL){
  810. dwr(MSG_ERROR, "listen(): SYMBOL NOT FOUND.\n");
  811. return -1;
  812. }
  813. dwr(MSG_DEBUG,"\nlisten(%d):\n", sockfd);
  814. int sock_type;
  815. socklen_t sock_type_len = sizeof(sock_type);
  816. #ifdef CHECKS
  817. /* Check that this is a valid fd */
  818. if(fcntl(sockfd, F_GETFD) < 0) {
  819. errno = EBADF;
  820. handle_error("listen", "EBADF", -1);
  821. return -1;
  822. }
  823. /* Check that it is a socket */
  824. if(getsockopt(sockfd, SOL_SOCKET, SO_TYPE, (void *) &sock_type, &sock_type_len) < 0) {
  825. errno = ENOTSOCK;
  826. handle_error("listen", "ENOTSOCK", -1);
  827. return -1;
  828. }
  829. /* Check that this socket supports accept() */
  830. if(!(sock_type && (SOCK_STREAM | SOCK_SEQPACKET))) {
  831. errno = EOPNOTSUPP;
  832. handle_error("listen", "EOPNOTSUPP", -1);
  833. return -1;
  834. }
  835. #endif
  836. /* make sure we don't touch any standard outputs */
  837. if(sockfd == STDIN_FILENO || sockfd == STDOUT_FILENO || sockfd == STDERR_FILENO)
  838. return(reallisten(sockfd, backlog));
  839. if(is_mapped_to_service(sockfd) < 0) {
  840. /* We now know this socket is not one of our socketpairs */
  841. int err = reallisten(sockfd, backlog);
  842. dwr(MSG_DEBUG,"reallisten()=%d\n", err);
  843. return err;
  844. }
  845. /* Assemble and send RPC */
  846. char cmd[BUF_SZ];
  847. memset(cmd, '\0', BUF_SZ);
  848. struct listen_st rpc_st;
  849. rpc_st.sockfd = sockfd;
  850. rpc_st.backlog = backlog;
  851. rpc_st.__tid = syscall(SYS_gettid);
  852. cmd[0] = RPC_LISTEN;
  853. memcpy(&cmd[1], &rpc_st, sizeof(struct listen_st));
  854. pthread_mutex_lock(&lock);
  855. send_command(fdret_sock, cmd);
  856. get_retval();
  857. pthread_mutex_unlock(&lock);
  858. handle_error("listen", "", ERR_OK);
  859. return ERR_OK;
  860. }
  861. /*------------------------------------------------------------------------------
  862. -------------------------------------- clone()----------------------------------
  863. ------------------------------------------------------------------------------*/
  864. /* int (*fn)(void *), void *child_stack, int flags, void *arg, ... */
  865. int clone(CLONE_SIG)
  866. {
  867. if(realclone == NULL){
  868. dwr(MSG_ERROR, "clone(): SYMBOL NOT FOUND.\n");
  869. return -1;
  870. }
  871. dwr(MSG_DEBUG,"clone()\n");
  872. int err = realclone(fn, child_stack, flags, arg);
  873. checkpid();
  874. return err;
  875. }
  876. /*------------------------------------------------------------------------------
  877. -------------------------------------- poll()-----------------------------------
  878. ------------------------------------------------------------------------------*/
  879. /* struct pollfd *fds, nfds_t nfds, int timeout */
  880. /*
  881. int poll(POLL_SIG)
  882. {
  883. dwr(MSG_DEBUG,"poll()\n");
  884. return realpoll(fds, nfds, timeout);
  885. }
  886. */
  887. /*------------------------------------------------------------------------------
  888. -------------------------------------- close()-----------------------------------
  889. ------------------------------------------------------------------------------*/
  890. /* int fd */
  891. int close(CLOSE_SIG)
  892. {
  893. /* checkpid(); // Required for httpd-2.4.17-3.x86_64 -- After clone, some symbols aren't initialized yet */
  894. if(realclose == NULL){
  895. dwr(MSG_ERROR, "close(): SYMBOL NOT FOUND.\n");
  896. return -1;
  897. }
  898. dwr(MSG_DEBUG,"close(%d)\n", fd);
  899. if(fd == fdret_sock)
  900. return -1; /* TODO: Ignore request to shut down our rpc fd, this is *almost always* safe */
  901. if(fd != STDIN_FILENO && fd != STDOUT_FILENO && fd != STDERR_FILENO)
  902. return realclose(fd);
  903. return -1;
  904. }
  905. /*------------------------------------------------------------------------------
  906. -------------------------------------- dup2()-----------------------------------
  907. ------------------------------------------------------------------------------*/
  908. /* int oldfd, int newfd */
  909. int dup2(DUP2_SIG)
  910. {
  911. if(realdup2 == NULL){
  912. dwr(MSG_ERROR, "dup2(): SYMBOL NOT FOUND.\n");
  913. return -1;
  914. }
  915. dwr(MSG_DEBUG,"dup2(%d, %d)\n", oldfd, newfd);
  916. if(oldfd == fdret_sock) {
  917. dwr(MSG_DEBUG,"client application attempted to dup2 RPC socket (%d). This is not allowed.\n", oldfd);
  918. errno = EBADF;
  919. return -1;
  920. }
  921. if(oldfd != STDIN_FILENO && oldfd != STDOUT_FILENO && oldfd != STDERR_FILENO)
  922. if(newfd != STDIN_FILENO && newfd != STDOUT_FILENO && newfd != STDERR_FILENO)
  923. return realdup2(oldfd, newfd);
  924. return -1;
  925. }
  926. /*------------------------------------------------------------------------------
  927. -------------------------------------- dup3()-----------------------------------
  928. ------------------------------------------------------------------------------*/
  929. /* int oldfd, int newfd, int flags */
  930. int dup3(DUP3_SIG)
  931. {
  932. if(realdup3 == NULL){
  933. dwr(MSG_ERROR, "dup3(): SYMBOL NOT FOUND.\n");
  934. return -1;
  935. }
  936. dwr(MSG_DEBUG,"dup3(%d, %d, %d)\n", oldfd, newfd, flags);
  937. #ifdef DEBUG
  938. /* Only do this check if we want to debug the intercept, otherwise, dont mess with
  939. the client application's logging methods */
  940. if(newfd == STDIN_FILENO || newfd == STDOUT_FILENO || newfd == STDERR_FILENO)
  941. return newfd; /* FIXME: This is to prevent httpd from dup'ing over our stderr
  942. and preventing us from debugging */
  943. else
  944. #endif
  945. return realdup3(oldfd, newfd, flags);
  946. }
  947. /*------------------------------------------------------------------------------
  948. ------------------------------------ syscall()----------------------------------
  949. ------------------------------------------------------------------------------*/
  950. long syscall(SYSCALL_SIG){
  951. if(realsyscall == NULL){
  952. dwr(MSG_ERROR, "syscall(): SYMBOL NOT FOUND.\n");
  953. return -1;
  954. }
  955. dwr(MSG_DEBUG_EXTRA,"syscall(%u, ...):\n", number);
  956. va_list ap;
  957. uintptr_t a,b,c,d,e,f;
  958. va_start(ap, number);
  959. a=va_arg(ap, uintptr_t);
  960. b=va_arg(ap, uintptr_t);
  961. c=va_arg(ap, uintptr_t);
  962. d=va_arg(ap, uintptr_t);
  963. e=va_arg(ap, uintptr_t);
  964. f=va_arg(ap, uintptr_t);
  965. va_end(ap);
  966. #if defined(__i386__)
  967. /* TODO: Implement for 32-bit systems: syscall(__NR_socketcall, 18, args);
  968. args[0] = (unsigned long) fd;
  969. args[1] = (unsigned long) addr;
  970. args[2] = (unsigned long) addrlen;
  971. args[3] = (unsigned long) flags;
  972. */
  973. #else
  974. if(number == __NR_accept4) {
  975. int sockfd = a;
  976. struct sockaddr * addr = (struct sockaddr*)b;
  977. socklen_t * addrlen = (socklen_t*)c;
  978. int flags = d;
  979. int old_errno = errno;
  980. int err = accept4(sockfd, addr, addrlen, flags);
  981. errno = old_errno;
  982. if(err == -EBADF) {
  983. err = -EAGAIN; /* For hysterical raisins */
  984. }
  985. return err;
  986. }
  987. #endif
  988. return realsyscall(number,a,b,c,d,e,f);
  989. }