Bubble android client. Fork of https://git.zx2c4.com/wireguard-android/
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

667 lines
16 KiB

  1. /* SPDX-License-Identifier: GPL-2.0
  2. *
  3. * Copyright (C) 2015-2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
  4. *
  5. * This is a shell script written in C. It very intentionally still functions like
  6. * a shell script, calling out to external executables such as ip(8).
  7. */
  8. #define _GNU_SOURCE
  9. #include <stdlib.h>
  10. #include <stdio.h>
  11. #include <stdbool.h>
  12. #include <string.h>
  13. #include <strings.h>
  14. #include <stdarg.h>
  15. #include <ctype.h>
  16. #include <time.h>
  17. #include <unistd.h>
  18. #include <errno.h>
  19. #include <regex.h>
  20. #include <sys/types.h>
  21. #include <sys/stat.h>
  22. #include <sys/wait.h>
  23. #include <sys/param.h>
  24. #ifndef WG_CONFIG_SEARCH_PATHS
  25. #define WG_CONFIG_SEARCH_PATHS "/data/misc/wireguard /data/data/com.wireguard.android/files"
  26. #endif
  27. #define _printf_(x, y) __attribute__((format(printf, x, y)))
  28. #define _cleanup_(x) __attribute__((cleanup(x)))
  29. #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
  30. static bool is_exiting = false;
  31. static void *xmalloc(size_t size)
  32. {
  33. void *ret = malloc(size);
  34. if (ret)
  35. return ret;
  36. perror("Error: malloc");
  37. exit(errno);
  38. }
  39. static void *xstrdup(const char *str)
  40. {
  41. char *ret = strdup(str);
  42. if (ret)
  43. return ret;
  44. perror("Error: strdup");
  45. exit(errno);
  46. }
  47. static void xregcomp(regex_t *preg, const char *regex, int cflags)
  48. {
  49. if (regcomp(preg, regex, cflags)) {
  50. fprintf(stderr, "Error: Regex compilation error\n");
  51. exit(EBADR);
  52. }
  53. }
  54. static char *concat(char *first, ...)
  55. {
  56. va_list args;
  57. size_t len = 0;
  58. char *ret;
  59. va_start(args, first);
  60. for (char *i = first; i; i = va_arg(args, char *))
  61. len += strlen(i);
  62. va_end(args);
  63. ret = xmalloc(len + 1);
  64. ret[0] = '\0';
  65. va_start(args, first);
  66. for (char *i = first; i; i = va_arg(args, char *))
  67. strcat(ret, i);
  68. va_end(args);
  69. return ret;
  70. }
  71. static char *concat_and_free(char *orig, const char *delim, const char *new_line)
  72. {
  73. char *ret;
  74. if (!orig)
  75. ret = xstrdup(new_line);
  76. else
  77. ret = concat(orig, delim, new_line, NULL);
  78. free(orig);
  79. return ret;
  80. }
  81. struct command_buffer {
  82. char *line;
  83. size_t len;
  84. FILE *stream;
  85. };
  86. static void free_command_buffer(struct command_buffer *c)
  87. {
  88. if (!c)
  89. return;
  90. if (c->stream)
  91. pclose(c->stream);
  92. free(c->line);
  93. }
  94. static void freep(void *p)
  95. {
  96. free(*(void **)p);
  97. }
  98. static void fclosep(FILE **f)
  99. {
  100. if (*f)
  101. fclose(*f);
  102. }
  103. #define _cleanup_free_ _cleanup_(freep)
  104. #define _cleanup_fclose_ _cleanup_(fclosep)
  105. #define DEFINE_CMD(name) _cleanup_(free_command_buffer) struct command_buffer name = { 0 };
  106. static char *vcmd_ret(struct command_buffer *c, const char *cmd_fmt, va_list args)
  107. {
  108. _cleanup_free_ char *cmd = NULL;
  109. if (!c->stream && !cmd_fmt)
  110. return NULL;
  111. if (c->stream && cmd_fmt)
  112. pclose(c->stream);
  113. if (cmd_fmt) {
  114. if (vasprintf(&cmd, cmd_fmt, args) < 0) {
  115. perror("Error: vasprintf");
  116. exit(errno);
  117. }
  118. c->stream = popen(cmd, "r");
  119. if (!c->stream) {
  120. perror("Error: popen");
  121. exit(errno);
  122. }
  123. }
  124. errno = 0;
  125. if (getline(&c->line, &c->len, c->stream) < 0) {
  126. if (errno) {
  127. perror("Error: getline");
  128. exit(errno);
  129. }
  130. return NULL;
  131. }
  132. return c->line;
  133. }
  134. _printf_(1, 2) static void cmd(const char *cmd_fmt, ...)
  135. {
  136. _cleanup_free_ char *cmd = NULL;
  137. va_list args;
  138. int ret;
  139. va_start(args, cmd_fmt);
  140. if (vasprintf(&cmd, cmd_fmt, args) < 0) {
  141. perror("Error: vasprintf");
  142. exit(errno);
  143. }
  144. va_end(args);
  145. printf("[#] %s\n", cmd);
  146. ret = system(cmd);
  147. if (ret < 0)
  148. ret = ESRCH;
  149. else if (ret > 0)
  150. ret = WIFEXITED(ret) ? WEXITSTATUS(ret) : EIO;
  151. if (ret && !is_exiting)
  152. exit(ret);
  153. }
  154. _printf_(2, 3) static char *cmd_ret(struct command_buffer *c, const char *cmd_fmt, ...)
  155. {
  156. va_list args;
  157. char *ret;
  158. va_start(args, cmd_fmt);
  159. ret = vcmd_ret(c, cmd_fmt, args);
  160. va_end(args);
  161. return ret;
  162. }
  163. _printf_(1, 2) static void cndc(const char *cmd_fmt, ...)
  164. {
  165. DEFINE_CMD(c);
  166. int error_code;
  167. char *ret;
  168. va_list args;
  169. _cleanup_free_ char *ndc_fmt = concat("ndc ", cmd_fmt, NULL);
  170. va_start(args, cmd_fmt);
  171. printf("[#] ");
  172. vprintf(ndc_fmt, args);
  173. printf("\n");
  174. va_end(args);
  175. va_start(args, cmd_fmt);
  176. ret = vcmd_ret(&c, ndc_fmt, args);
  177. va_end(args);
  178. if (!ret) {
  179. fprintf(stderr, "Error: could not call ndc\n");
  180. exit(ENOSYS);
  181. }
  182. error_code = atoi(ret);
  183. if (error_code >= 400 && error_code < 600) {
  184. fprintf(stderr, "Error: %s\n", ret);
  185. exit(ENONET);
  186. }
  187. }
  188. static void auto_su(int argc, char *argv[])
  189. {
  190. char *args[argc + 4];
  191. if (!getuid())
  192. return;
  193. args[0] = "su";
  194. args[1] = "-p";
  195. args[2] = "-c";
  196. memcpy(&args[3], argv, argc * sizeof(*args));
  197. args[argc + 3] = NULL;
  198. printf("[$] su -p -c ");
  199. for (int i = 0; i < argc; ++i)
  200. printf("%s%c", argv[i], i == argc - 1 ? '\n' : ' ');
  201. execvp("su", args);
  202. exit(errno);
  203. }
  204. static void add_if(const char *iface)
  205. {
  206. cmd("ip link add %s type wireguard", iface);
  207. }
  208. static void del_if(const char *iface)
  209. {
  210. DEFINE_CMD(c);
  211. regex_t reg;
  212. regmatch_t matches[2];
  213. char *netid = NULL;
  214. _cleanup_free_ char *regex = concat("0xc([0-9a-f]+)/0xcffff lookup ", iface, NULL);
  215. xregcomp(&reg, regex, REG_EXTENDED);
  216. cmd("ip link del %s", iface);
  217. for (char *ret = cmd_ret(&c, "ip rule show"); ret; ret = cmd_ret(&c, NULL)) {
  218. if (!regexec(&reg, ret, ARRAY_SIZE(matches), matches, 0)) {
  219. ret[matches[1].rm_eo] = '\0';
  220. netid = &ret[matches[1].rm_so];
  221. break;
  222. }
  223. }
  224. if (netid)
  225. cndc("network destroy %lu", strtoul(netid, NULL, 16));
  226. }
  227. static void up_if(unsigned int *netid, const char *iface)
  228. {
  229. srandom(time(NULL) ^ getpid()); /* Not real randomness. */
  230. while (*netid < 4096)
  231. *netid = random() & 0xfffe;
  232. cmd("wg set %s fwmark 0x20000", iface);
  233. cndc("interface setcfg %s up", iface);
  234. cndc("network create %u vpn 1 1", *netid);
  235. cndc("network interface add %u %s", *netid, iface);
  236. cndc("network users add %u 0-99999", *netid);
  237. }
  238. static void set_dnses(unsigned int netid, const char *dnses)
  239. {
  240. size_t len = strlen(dnses);
  241. if (len > (1<<16))
  242. return;
  243. _cleanup_free_ char *mutable = xstrdup(dnses);
  244. _cleanup_free_ char *arglist = xmalloc(len * 4 + 1);
  245. _cleanup_free_ char *arg = xmalloc(len + 4);
  246. if (!len)
  247. return;
  248. arglist[0] = '\0';
  249. for (char *dns = strtok(mutable, ", \t\n"); dns; dns = strtok(NULL, ", \t\n")) {
  250. if (strchr(dns, '\'') || strchr(dns, '\\'))
  251. continue;
  252. snprintf(arg, len + 3, "'%s' ", dns);
  253. strncat(arglist, arg, len * 4 - 1);
  254. }
  255. if (!strlen(arglist))
  256. return;
  257. cndc("resolver setnetdns %u '' %s", netid, arglist);
  258. }
  259. static void add_addr(const char *iface, const char *addr)
  260. {
  261. if (strchr(addr, ':')) {
  262. cndc("interface ipv6 %s enable", iface);
  263. cmd("ip -6 addr add '%s' dev %s", addr, iface);
  264. } else {
  265. _cleanup_free_ char *mut_addr = strdup(addr);
  266. char *slash = strchr(mut_addr, '/');
  267. unsigned char mask = 32;
  268. if (slash) {
  269. *slash = '\0';
  270. mask = atoi(slash + 1);
  271. }
  272. cndc("interface setcfg %s '%s' %u", iface, mut_addr, mask);
  273. }
  274. }
  275. static void set_addr(const char *iface, const char *addrs)
  276. {
  277. _cleanup_free_ char *mutable = xstrdup(addrs);
  278. for (char *addr = strtok(mutable, ", \t\n"); addr; addr = strtok(NULL, ", \t\n")) {
  279. if (strchr(addr, '\'') || strchr(addr, '\\'))
  280. continue;
  281. add_addr(iface, addr);
  282. }
  283. }
  284. static int get_route_mtu(const char *endpoint)
  285. {
  286. DEFINE_CMD(c_route);
  287. DEFINE_CMD(c_dev);
  288. regmatch_t matches[2];
  289. regex_t regex_mtu, regex_dev;
  290. char *route, *mtu, *dev;
  291. xregcomp(&regex_mtu, "mtu ([0-9]+)", REG_EXTENDED);
  292. xregcomp(&regex_dev, "dev ([^ ]+)", REG_EXTENDED);
  293. if (strcmp(endpoint, "default"))
  294. route = cmd_ret(&c_route, "ip -o route get %s", endpoint);
  295. else
  296. route = cmd_ret(&c_route, "ip -o route show %s", endpoint);
  297. if (!route)
  298. return -1;
  299. if (!regexec(&regex_mtu, route, ARRAY_SIZE(matches), matches, 0)) {
  300. route[matches[1].rm_eo] = '\0';
  301. mtu = &route[matches[1].rm_so];
  302. } else if (!regexec(&regex_dev, route, ARRAY_SIZE(matches), matches, 0)) {
  303. route[matches[1].rm_eo] = '\0';
  304. dev = &route[matches[1].rm_so];
  305. route = cmd_ret(&c_dev, "ip -o link show dev %s", dev);
  306. if (!route)
  307. return -1;
  308. if (regexec(&regex_mtu, route, ARRAY_SIZE(matches), matches, 0))
  309. return -1;
  310. route[matches[1].rm_eo] = '\0';
  311. mtu = &route[matches[1].rm_so];
  312. } else
  313. return -1;
  314. return atoi(mtu);
  315. }
  316. static void set_mtu(const char *iface, unsigned int mtu)
  317. {
  318. DEFINE_CMD(c_endpoints);
  319. regex_t regex_endpoint;
  320. regmatch_t matches[2];
  321. int endpoint_mtu, next_mtu;
  322. if (mtu) {
  323. cndc("interface setmtu %s %u", iface, mtu);
  324. return;
  325. }
  326. xregcomp(&regex_endpoint, "^\\[?([a-z0-9:.]+)\\]?:[0-9]+$", REG_EXTENDED);
  327. endpoint_mtu = get_route_mtu("default");
  328. if (endpoint_mtu == -1)
  329. endpoint_mtu = 1500;
  330. for (char *endpoint = cmd_ret(&c_endpoints, "wg show %s endpoints", iface); endpoint; endpoint = cmd_ret(&c_endpoints, NULL)) {
  331. if (regexec(&regex_endpoint, endpoint, ARRAY_SIZE(matches), matches, 0))
  332. continue;
  333. endpoint[matches[1].rm_eo] = '\0';
  334. endpoint = &endpoint[matches[1].rm_so];
  335. next_mtu = get_route_mtu(endpoint);
  336. if (next_mtu > 0 && next_mtu < endpoint_mtu)
  337. endpoint_mtu = next_mtu;
  338. }
  339. cndc("interface setmtu %s %d", iface, endpoint_mtu - 80);
  340. }
  341. static void add_route(const char *iface, unsigned int netid, const char *route)
  342. {
  343. cndc("network route add %u %s %s", netid, iface, route);
  344. }
  345. static void set_routes(const char *iface, unsigned int netid)
  346. {
  347. DEFINE_CMD(c);
  348. for (char *allowedips = cmd_ret(&c, "wg show %s allowed-ips", iface); allowedips; allowedips = cmd_ret(&c, NULL)) {
  349. char *start = strchr(allowedips, '\t');
  350. if (!start)
  351. continue;
  352. ++start;
  353. for (char *allowedip = strtok(start, " \n"); allowedip; allowedip = strtok(NULL, " \n"))
  354. add_route(iface, netid, allowedip);
  355. }
  356. }
  357. static void set_config(const char *iface, const char *config)
  358. {
  359. FILE *config_writer;
  360. _cleanup_free_ char *cmd = concat("wg setconf ", iface, " /proc/self/fd/0", NULL);
  361. int ret;
  362. printf("[#] %s\n", cmd);
  363. config_writer = popen(cmd, "w");
  364. if (!config_writer) {
  365. perror("Error: popen");
  366. exit(errno);
  367. }
  368. if (fputs(config, config_writer) < 0) {
  369. perror("Error: fputs");
  370. exit(errno);
  371. }
  372. ret = pclose(config_writer);
  373. if (ret)
  374. exit(WIFEXITED(ret) ? WEXITSTATUS(ret) : EIO);
  375. }
  376. static void broadcast_change(void)
  377. {
  378. const char *pkg = getenv("CALLING_PACKAGE");
  379. if (!pkg || strcmp(pkg, "com.wireguard.android"))
  380. cmd("am broadcast -a com.wireguard.android.WGQUICK_CHANGE com.wireguard.android");
  381. }
  382. static void print_search_paths(FILE *file, const char *prefix)
  383. {
  384. _cleanup_free_ char *paths = strdup(WG_CONFIG_SEARCH_PATHS);
  385. for (char *path = strtok(paths, " "); path; path = strtok(NULL, " "))
  386. fprintf(file, "%s%s\n", prefix, path);
  387. }
  388. static void cmd_usage(const char *program)
  389. {
  390. printf( "Usage: %s [ up | down ] [ CONFIG_FILE | INTERFACE ]\n"
  391. "\n"
  392. " CONFIG_FILE is a configuration file, whose filename is the interface name\n"
  393. " followed by `.conf'. Otherwise, INTERFACE is an interface name, with\n"
  394. " configuration found at:\n\n", program);
  395. print_search_paths(stdout, " - ");
  396. printf( "\n It is to be readable by wg(8)'s `setconf' sub-command, with the exception\n"
  397. " of the following additions to the [Interface] section, which are handled by\n"
  398. " this program:\n\n"
  399. " - Address: may be specified one or more times and contains one or more\n"
  400. " IP addresses (with an optional CIDR mask) to be set for the interface.\n"
  401. " - MTU: an optional MTU for the interface; if unspecified, auto-calculated.\n"
  402. " - DNS: an optional DNS server to use while the device is up.\n\n"
  403. " See wg-quick(8) for more info and examples.\n");
  404. }
  405. static char *cleanup_iface = NULL;
  406. static void cmd_up_cleanup(void)
  407. {
  408. is_exiting = true;
  409. if (cleanup_iface)
  410. del_if(cleanup_iface);
  411. free(cleanup_iface);
  412. }
  413. static void cmd_up(const char *iface, const char *config, unsigned int mtu, const char *addrs, const char *dnses)
  414. {
  415. DEFINE_CMD(c);
  416. unsigned int netid = 0;
  417. if (cmd_ret(&c, "ip link show dev %s 2>/dev/null", iface)) {
  418. fprintf(stderr, "Error: %s already exists\n", iface);
  419. exit(EEXIST);
  420. }
  421. cleanup_iface = xstrdup(iface);
  422. atexit(cmd_up_cleanup);
  423. add_if(iface);
  424. set_config(iface, config);
  425. set_addr(iface, addrs);
  426. up_if(&netid, iface);
  427. set_dnses(netid, dnses);
  428. set_routes(iface, netid);
  429. set_mtu(iface, mtu);
  430. broadcast_change();
  431. free(cleanup_iface);
  432. cleanup_iface = NULL;
  433. exit(EXIT_SUCCESS);
  434. }
  435. static void cmd_down(const char *iface)
  436. {
  437. DEFINE_CMD(c);
  438. bool found = false;
  439. char *ifaces = cmd_ret(&c, "wg show interfaces");
  440. if (ifaces) {
  441. for (char *eiface = strtok(ifaces, " \n"); eiface; eiface = strtok(NULL, " \n")) {
  442. if (!strcmp(iface, eiface)) {
  443. found = true;
  444. break;
  445. }
  446. }
  447. }
  448. if (!found) {
  449. fprintf(stderr, "Error: %s is not a WireGuard interface\n", iface);
  450. exit(EMEDIUMTYPE);
  451. }
  452. del_if(iface);
  453. broadcast_change();
  454. exit(EXIT_SUCCESS);
  455. }
  456. static void parse_options(char **iface, char **config, unsigned int *mtu, char **addrs, char **dnses, const char *arg)
  457. {
  458. _cleanup_fclose_ FILE *file = NULL;
  459. _cleanup_free_ char *line = NULL;
  460. _cleanup_free_ char *filename = NULL;
  461. _cleanup_free_ char *paths = strdup(WG_CONFIG_SEARCH_PATHS);
  462. regex_t regex_iface, regex_conf;
  463. regmatch_t matches[2];
  464. struct stat sbuf;
  465. size_t n = 0;
  466. bool in_interface_section = false;
  467. *iface = *config = *addrs = *dnses = NULL;
  468. *mtu = 0;
  469. xregcomp(&regex_iface, "^[a-zA-Z0-9_=+.-]{1,15}$", REG_EXTENDED | REG_NOSUB);
  470. xregcomp(&regex_conf, "/?([a-zA-Z0-9_=+.-]{1,15})\\.conf$", REG_EXTENDED);
  471. if (!regexec(&regex_iface, arg, 0, NULL, 0)) {
  472. for (char *path = strtok(paths, " "); path; path = strtok(NULL, " ")) {
  473. free(filename);
  474. if (asprintf(&filename, "%s/%s.conf", path, arg) < 0) {
  475. perror("Error: asprintf");
  476. exit(errno);
  477. }
  478. file = fopen(filename, "r");
  479. if (file)
  480. break;
  481. }
  482. if (!file) {
  483. fprintf(stderr, "Error: Unable to find configuration file for `%s' in:\n", arg);
  484. print_search_paths(stderr, "- ");
  485. exit(errno);
  486. }
  487. } else {
  488. filename = xstrdup(arg);
  489. file = fopen(filename, "r");
  490. if (!file) {
  491. fprintf(stderr, "Error: Unable to find configuration file at `%s'\n", filename);
  492. exit(errno);
  493. }
  494. }
  495. if (regexec(&regex_conf, filename, ARRAY_SIZE(matches), matches, 0)) {
  496. fprintf(stderr, "Error: The config file must be a valid interface name, followed by .conf\n");
  497. exit(EINVAL);
  498. }
  499. if (fstat(fileno(file), &sbuf) < 0) {
  500. perror("Error: fstat");
  501. exit(errno);
  502. }
  503. if (sbuf.st_mode & 0007)
  504. fprintf(stderr, "Warning: `%s' is world accessible\n", filename);
  505. filename[matches[1].rm_eo] = 0;
  506. *iface = xstrdup(&filename[matches[1].rm_so]);
  507. while (getline(&line, &n, file) >= 0) {
  508. size_t len = strlen(line), j = 0;
  509. if (len > (1<<16))
  510. return;
  511. _cleanup_free_ char *clean = xmalloc(len + 1);
  512. for (size_t i = 0; i < len; ++i) {
  513. if (!isspace(line[i]))
  514. clean[j++] = line[i];
  515. }
  516. clean[j] = '\0';
  517. if (clean[0] == '[')
  518. in_interface_section = false;
  519. if (!strcasecmp(clean, "[Interface]"))
  520. in_interface_section = true;
  521. if (in_interface_section) {
  522. if (!strncasecmp(clean, "Address=", 8) && j > 8) {
  523. *addrs = concat_and_free(*addrs, ",", clean + 8);
  524. continue;
  525. } else if (!strncasecmp(clean, "DNS=", 4) && j > 4) {
  526. *dnses = concat_and_free(*dnses, ",", clean + 4);
  527. continue;
  528. } else if (!strncasecmp(clean, "MTU=", 4) && j > 4) {
  529. *mtu = atoi(clean + 4);
  530. continue;
  531. }
  532. }
  533. *config = concat_and_free(*config, "", line);
  534. }
  535. if (!*iface)
  536. *iface = xstrdup("");
  537. if (!*config)
  538. *config = xstrdup("");
  539. if (!*addrs)
  540. *addrs = xstrdup("");
  541. if (!*dnses)
  542. *dnses = xstrdup("");
  543. }
  544. int main(int argc, char *argv[])
  545. {
  546. _cleanup_free_ char *iface = NULL;
  547. _cleanup_free_ char *config = NULL;
  548. _cleanup_free_ char *addrs = NULL;
  549. _cleanup_free_ char *dnses = NULL;
  550. unsigned int mtu;
  551. if (argc == 2 && (!strcmp(argv[1], "help") || !strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")))
  552. cmd_usage(argv[0]);
  553. else if (argc == 3 && !strcmp(argv[1], "up")) {
  554. auto_su(argc, argv);
  555. parse_options(&iface, &config, &mtu, &addrs, &dnses, argv[2]);
  556. cmd_up(iface, config, mtu, addrs, dnses);
  557. } else if (argc == 3 && !strcmp(argv[1], "down")) {
  558. auto_su(argc, argv);
  559. parse_options(&iface, &config, &mtu, &addrs, &dnses, argv[2]);
  560. cmd_down(iface);
  561. } else {
  562. cmd_usage(argv[0]);
  563. return 1;
  564. }
  565. return 0;
  566. }