Bubble android client. Fork of https://git.zx2c4.com/wireguard-android/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

650 lines
15 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 = WEXITSTATUS(ret);
  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. _cleanup_free_ char *mutable = xstrdup(dnses);
  242. _cleanup_free_ char *arglist = xmalloc(len * 4 + 1);
  243. _cleanup_free_ char *arg = xmalloc(len + 4);
  244. if (!len)
  245. return;
  246. arglist[0] = '\0';
  247. for (char *dns = strtok(mutable, ", \t\n"); dns; dns = strtok(NULL, ", \t\n")) {
  248. if (strchr(dns, '\'') || strchr(dns, '\\'))
  249. continue;
  250. snprintf(arg, len + 3, "'%s' ", dns);
  251. strncat(arglist, arg, len * 4 - 1);
  252. }
  253. if (!strlen(arglist))
  254. return;
  255. cndc("resolver setnetdns %u '' %s", netid, arglist);
  256. }
  257. static void add_addr(const char *iface, const char *addr)
  258. {
  259. if (strchr(addr, ':')) {
  260. cndc("interface ipv6 %s enable", iface);
  261. cmd("ip -6 addr add '%s' dev %s", addr, iface);
  262. } else {
  263. _cleanup_free_ char *mut_addr = strdup(addr);
  264. char *slash = strchr(mut_addr, '/');
  265. unsigned char mask = 32;
  266. if (slash) {
  267. *slash = '\0';
  268. mask = atoi(slash + 1);
  269. }
  270. cndc("interface setcfg %s '%s' %u", iface, mut_addr, mask);
  271. }
  272. }
  273. static void set_addr(const char *iface, const char *addrs)
  274. {
  275. _cleanup_free_ char *mutable = xstrdup(addrs);
  276. for (char *addr = strtok(mutable, ", \t\n"); addr; addr = strtok(NULL, ", \t\n")) {
  277. if (strchr(addr, '\'') || strchr(addr, '\\'))
  278. continue;
  279. add_addr(iface, addr);
  280. }
  281. }
  282. static int get_route_mtu(const char *endpoint)
  283. {
  284. DEFINE_CMD(c_route);
  285. DEFINE_CMD(c_dev);
  286. regmatch_t matches[2];
  287. regex_t regex_mtu, regex_dev;
  288. char *route, *mtu, *dev;
  289. xregcomp(&regex_mtu, "mtu ([0-9]+)", REG_EXTENDED);
  290. xregcomp(&regex_dev, "dev ([^ ]+)", REG_EXTENDED);
  291. if (strcmp(endpoint, "default"))
  292. route = cmd_ret(&c_route, "ip -o route get %s", endpoint);
  293. else
  294. route = cmd_ret(&c_route, "ip -o route show %s", endpoint);
  295. if (!route)
  296. return -1;
  297. if (!regexec(&regex_mtu, route, ARRAY_SIZE(matches), matches, 0)) {
  298. route[matches[1].rm_eo] = '\0';
  299. mtu = &route[matches[1].rm_so];
  300. } else if (!regexec(&regex_dev, route, ARRAY_SIZE(matches), matches, 0)) {
  301. route[matches[1].rm_eo] = '\0';
  302. dev = &route[matches[1].rm_so];
  303. route = cmd_ret(&c_dev, "ip -o link show dev %s", dev);
  304. if (!route)
  305. return -1;
  306. if (regexec(&regex_mtu, route, ARRAY_SIZE(matches), matches, 0))
  307. return -1;
  308. route[matches[1].rm_eo] = '\0';
  309. mtu = &route[matches[1].rm_so];
  310. } else
  311. return -1;
  312. return atoi(mtu);
  313. }
  314. static void set_mtu(const char *iface, unsigned int mtu)
  315. {
  316. DEFINE_CMD(c_endpoints);
  317. regex_t regex_endpoint;
  318. regmatch_t matches[2];
  319. int endpoint_mtu, next_mtu;
  320. if (mtu) {
  321. cndc("interface setmtu %s %u", iface, mtu);
  322. return;
  323. }
  324. xregcomp(&regex_endpoint, "^\\[?([a-z0-9:.]+)\\]?:[0-9]+$", REG_EXTENDED);
  325. endpoint_mtu = get_route_mtu("default");
  326. if (endpoint_mtu == -1)
  327. endpoint_mtu = 1500;
  328. for (char *endpoint = cmd_ret(&c_endpoints, "wg show %s endpoints", iface); endpoint; endpoint = cmd_ret(&c_endpoints, NULL)) {
  329. if (regexec(&regex_endpoint, endpoint, ARRAY_SIZE(matches), matches, 0))
  330. continue;
  331. endpoint[matches[1].rm_eo] = '\0';
  332. endpoint = &endpoint[matches[1].rm_so];
  333. next_mtu = get_route_mtu(endpoint);
  334. if (next_mtu > 0 && next_mtu < endpoint_mtu)
  335. endpoint_mtu = next_mtu;
  336. }
  337. cndc("interface setmtu %s %d", iface, endpoint_mtu - 80);
  338. }
  339. static void add_route(const char *iface, unsigned int netid, const char *route)
  340. {
  341. cndc("network route add %u %s %s", netid, iface, route);
  342. }
  343. static void set_routes(const char *iface, unsigned int netid)
  344. {
  345. DEFINE_CMD(c);
  346. for (char *allowedips = cmd_ret(&c, "wg show %s allowed-ips", iface); allowedips; allowedips = cmd_ret(&c, NULL)) {
  347. char *start = strchr(allowedips, '\t');
  348. if (!start)
  349. continue;
  350. ++start;
  351. for (char *allowedip = strtok(start, " \n"); allowedip; allowedip = strtok(NULL, " \n"))
  352. add_route(iface, netid, allowedip);
  353. }
  354. }
  355. static void set_config(const char *iface, const char *config)
  356. {
  357. FILE *config_writer;
  358. _cleanup_free_ char *cmd = concat("wg setconf ", iface, " /proc/self/fd/0", NULL);
  359. printf("[#] %s\n", cmd);
  360. config_writer = popen(cmd, "w");
  361. if (!config_writer) {
  362. perror("Error: popen");
  363. exit(errno);
  364. }
  365. if (fputs(config, config_writer) < 0) {
  366. perror("Error: fputs");
  367. exit(errno);
  368. }
  369. pclose(config_writer);
  370. }
  371. static void print_search_paths(FILE *file, const char *prefix)
  372. {
  373. _cleanup_free_ char *paths = strdup(WG_CONFIG_SEARCH_PATHS);
  374. for (char *path = strtok(paths, " "); path; path = strtok(NULL, " "))
  375. fprintf(file, "%s%s\n", prefix, path);
  376. }
  377. static void cmd_usage(const char *program)
  378. {
  379. printf( "Usage: %s [ up | down ] [ CONFIG_FILE | INTERFACE ]\n"
  380. "\n"
  381. " CONFIG_FILE is a configuration file, whose filename is the interface name\n"
  382. " followed by `.conf'. Otherwise, INTERFACE is an interface name, with\n"
  383. " configuration found at:\n\n", program);
  384. print_search_paths(stdout, " - ");
  385. printf( "\n It is to be readable by wg(8)'s `setconf' sub-command, with the exception\n"
  386. " of the following additions to the [Interface] section, which are handled by\n"
  387. " this program:\n\n"
  388. " - Address: may be specified one or more times and contains one or more\n"
  389. " IP addresses (with an optional CIDR mask) to be set for the interface.\n"
  390. " - MTU: an optional MTU for the interface; if unspecified, auto-calculated.\n"
  391. " - DNS: an optional DNS server to use while the device is up.\n\n"
  392. " See wg-quick(8) for more info and examples.\n");
  393. }
  394. static char *cleanup_iface = NULL;
  395. static void cmd_up_cleanup(void)
  396. {
  397. is_exiting = true;
  398. if (cleanup_iface)
  399. del_if(cleanup_iface);
  400. free(cleanup_iface);
  401. }
  402. static void cmd_up(const char *iface, const char *config, unsigned int mtu, const char *addrs, const char *dnses)
  403. {
  404. DEFINE_CMD(c);
  405. unsigned int netid = 0;
  406. if (cmd_ret(&c, "ip link show dev %s 2>/dev/null", iface)) {
  407. fprintf(stderr, "Error: %s already exists\n", iface);
  408. exit(EEXIST);
  409. }
  410. cleanup_iface = xstrdup(iface);
  411. atexit(cmd_up_cleanup);
  412. add_if(iface);
  413. set_config(iface, config);
  414. set_addr(iface, addrs);
  415. up_if(&netid, iface);
  416. set_dnses(netid, dnses);
  417. set_routes(iface, netid);
  418. set_mtu(iface, mtu);
  419. free(cleanup_iface);
  420. cleanup_iface = NULL;
  421. exit(EXIT_SUCCESS);
  422. }
  423. static void cmd_down(const char *iface)
  424. {
  425. DEFINE_CMD(c);
  426. bool found = false;
  427. char *ifaces = cmd_ret(&c, "wg show interfaces");
  428. if (ifaces) {
  429. for (char *eiface = strtok(ifaces, " \n"); eiface; eiface = strtok(NULL, " \n")) {
  430. if (!strcmp(iface, eiface)) {
  431. found = true;
  432. break;
  433. }
  434. }
  435. }
  436. if (!found) {
  437. fprintf(stderr, "Error: %s is not a WireGuard interface\n", iface);
  438. exit(EMEDIUMTYPE);
  439. }
  440. del_if(iface);
  441. exit(EXIT_SUCCESS);
  442. }
  443. static void parse_options(char **iface, char **config, unsigned int *mtu, char **addrs, char **dnses, const char *arg)
  444. {
  445. _cleanup_fclose_ FILE *file = NULL;
  446. _cleanup_free_ char *line = NULL;
  447. _cleanup_free_ char *filename = NULL;
  448. _cleanup_free_ char *paths = strdup(WG_CONFIG_SEARCH_PATHS);
  449. regex_t regex_iface, regex_conf;
  450. regmatch_t matches[2];
  451. struct stat sbuf;
  452. size_t n = 0;
  453. bool in_interface_section = false;
  454. *iface = *config = *addrs = *dnses = NULL;
  455. *mtu = 0;
  456. xregcomp(&regex_iface, "^[a-zA-Z0-9_=+.-]{1,16}$", REG_EXTENDED | REG_NOSUB);
  457. xregcomp(&regex_conf, "/?([a-zA-Z0-9_=+.-]{1,16})\\.conf$", REG_EXTENDED);
  458. if (!regexec(&regex_iface, arg, 0, NULL, 0)) {
  459. for (char *path = strtok(paths, " "); path; path = strtok(NULL, " ")) {
  460. free(filename);
  461. if (asprintf(&filename, "%s/%s.conf", path, arg) < 0) {
  462. perror("Error: asprintf");
  463. exit(errno);
  464. }
  465. file = fopen(filename, "r");
  466. if (file)
  467. break;
  468. }
  469. if (!file) {
  470. fprintf(stderr, "Error: Unable to find configuration file for `%s' in:\n", arg);
  471. print_search_paths(stderr, "- ");
  472. exit(errno);
  473. }
  474. } else {
  475. filename = xstrdup(arg);
  476. file = fopen(filename, "r");
  477. if (!file) {
  478. fprintf(stderr, "Error: Unable to find configuration file at `%s'\n", filename);
  479. exit(errno);
  480. }
  481. }
  482. if (regexec(&regex_conf, filename, ARRAY_SIZE(matches), matches, 0)) {
  483. fprintf(stderr, "Error: The config file must be a valid interface name, followed by .conf\n");
  484. exit(EINVAL);
  485. }
  486. if (fstat(fileno(file), &sbuf) < 0) {
  487. perror("Error: fstat");
  488. exit(errno);
  489. }
  490. if (sbuf.st_mode & 0007)
  491. fprintf(stderr, "Warning: `%s' is world accessible\n", filename);
  492. filename[matches[1].rm_eo] = 0;
  493. *iface = xstrdup(&filename[matches[1].rm_so]);
  494. while (getline(&line, &n, file) >= 0) {
  495. size_t len = strlen(line), j = 0;
  496. _cleanup_free_ char *clean = xmalloc(len + 1);
  497. for (size_t i = 0; i < len; ++i) {
  498. if (!isspace(line[i]))
  499. clean[j++] = line[i];
  500. }
  501. clean[j] = '\0';
  502. if (clean[0] == '[')
  503. in_interface_section = false;
  504. if (!strcasecmp(clean, "[Interface]"))
  505. in_interface_section = true;
  506. if (in_interface_section) {
  507. if (!strncasecmp(clean, "Address=", 8) && j > 8) {
  508. *addrs = concat_and_free(*addrs, ",", clean + 8);
  509. continue;
  510. } else if (!strncasecmp(clean, "DNS=", 4) && j > 4) {
  511. *dnses = concat_and_free(*dnses, ",", clean + 4);
  512. continue;
  513. } else if (!strncasecmp(clean, "MTU=", 4) && j > 4) {
  514. *mtu = atoi(clean + 4);
  515. continue;
  516. }
  517. }
  518. *config = concat_and_free(*config, "", line);
  519. }
  520. if (!*iface)
  521. *iface = xstrdup("");
  522. if (!*config)
  523. *config = xstrdup("");
  524. if (!*addrs)
  525. *addrs = xstrdup("");
  526. if (!*dnses)
  527. *dnses = xstrdup("");
  528. }
  529. int main(int argc, char *argv[])
  530. {
  531. _cleanup_free_ char *iface = NULL;
  532. _cleanup_free_ char *config = NULL;
  533. _cleanup_free_ char *addrs = NULL;
  534. _cleanup_free_ char *dnses = NULL;
  535. unsigned int mtu;
  536. if (argc == 2 && (!strcmp(argv[1], "help") || !strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")))
  537. cmd_usage(argv[0]);
  538. else if (argc == 3 && !strcmp(argv[1], "up")) {
  539. auto_su(argc, argv);
  540. parse_options(&iface, &config, &mtu, &addrs, &dnses, argv[2]);
  541. cmd_up(iface, config, mtu, addrs, dnses);
  542. } else if (argc == 3 && !strcmp(argv[1], "down")) {
  543. auto_su(argc, argv);
  544. parse_options(&iface, &config, &mtu, &addrs, &dnses, argv[2]);
  545. cmd_down(iface);
  546. } else {
  547. cmd_usage(argv[0]);
  548. return 1;
  549. }
  550. return 0;
  551. }