Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

postsrsd.c 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. /* PostSRSd - Sender Rewriting Scheme daemon for Postfix
  2. * Copyright (c) 2012 Timo Röhling <timo.roehling@gmx.de>
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 2 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. /* This program uses the libsrs2 library. The relevant source
  18. * files have been added to this distribution. */
  19. #include "srs2.h"
  20. #include <sys/types.h>
  21. #include <sys/socket.h>
  22. #include <netdb.h>
  23. #include <errno.h>
  24. #include <unistd.h>
  25. #include <fcntl.h>
  26. #include <pwd.h>
  27. #include <string.h>
  28. #include <poll.h>
  29. #include <wait.h>
  30. #include <syslog.h>
  31. #ifndef VERSION
  32. #define VERSION "1.1"
  33. #endif
  34. static char *self = NULL;
  35. static int bind_service (const char *service, int family)
  36. {
  37. struct addrinfo *addr, *it;
  38. struct addrinfo hints;
  39. int err, sock, flags;
  40. static const int one = 1;
  41. memset (&hints, 0, sizeof(hints));
  42. hints.ai_family = family;
  43. hints.ai_socktype = SOCK_STREAM;
  44. hints.ai_flags = AI_ADDRCONFIG | AI_V4MAPPED;
  45. err = getaddrinfo(NULL, service, &hints, &addr);
  46. if (err != 0) {
  47. fprintf(stderr, "%s: bind_service(%s): %s\n", self, service, gai_strerror(err));
  48. return -1;
  49. }
  50. sock = -1;
  51. for (it = addr; it; it = it->ai_next) {
  52. sock = socket(it->ai_family, it->ai_socktype, it->ai_protocol);
  53. if (sock < 0) goto fail;
  54. if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0) goto fail;
  55. if (bind(sock, it->ai_addr, it->ai_addrlen) < 0) goto fail;
  56. if (listen(sock, 10) < 0) goto fail;
  57. flags = fcntl (sock, F_GETFL, 0);
  58. if (flags < 0) goto fail;
  59. if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0) goto fail;
  60. break;
  61. fail:
  62. err = errno;
  63. if (sock >= 0) close (sock);
  64. sock = -1;
  65. }
  66. freeaddrinfo (addr);
  67. if (sock < 0)
  68. fprintf (stderr, "%s: bind_service(%s): %s\n", self, service, strerror(err));
  69. return sock;
  70. }
  71. static int is_hexdigit (char c)
  72. {
  73. return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
  74. }
  75. static char hex2num (char c)
  76. {
  77. if (c >= '0' && c <= '9') return c - '0';
  78. if (c >= 'a' && c <= 'f') return c - 'a' + 10;
  79. if (c >= 'A' && c <= 'F') return c - 'A' + 10;
  80. return 0;
  81. }
  82. static char num2hex (char c)
  83. {
  84. if (c < 10) return '0' + c;
  85. return 'a' + c - 10;
  86. }
  87. static char hex2char (const char *s)
  88. {
  89. return 16 * hex2num(s[0]) + hex2num(s[1]);
  90. }
  91. static void char2hex (char c, char *buf)
  92. {
  93. buf[0] = num2hex((c >> 4) & 0xf);
  94. buf[1] = num2hex((c ) & 0xf);
  95. }
  96. static char* url_decode (char *buf, size_t len, const char *input)
  97. {
  98. char *output = buf;
  99. if (!input || !output || len == 0) return NULL;
  100. while (*input && --len) {
  101. if (*input == '%' && is_hexdigit(input[1]) && is_hexdigit(input[2])) {
  102. *output++ = hex2char(++input);
  103. input += 2;
  104. } else {
  105. *output++ = *input++;
  106. }
  107. }
  108. *output = 0;
  109. return buf;
  110. }
  111. static char* url_encode (char* buf, size_t len, const char *input)
  112. {
  113. char *output = buf;
  114. if (!input || !output || len == 0) return NULL;
  115. while (*input && --len) {
  116. if (!isascii(*input) || !isgraph(*input) || *input == '%') {
  117. if (len <= 2) break;
  118. *output++ = '%';
  119. char2hex(*input++, output);
  120. output += 2; len -= 2;
  121. } else {
  122. *output++ = *input++;
  123. }
  124. }
  125. *output = 0;
  126. return buf;
  127. }
  128. static void handle_forward (srs_t *srs, FILE *fp, const char *address, const char *domain, const char **excludes)
  129. {
  130. int result;
  131. size_t addrlen;
  132. char value[1024];
  133. char outputbuf[1024], *output;
  134. addrlen = strlen(address);
  135. for(; *excludes; excludes++) {
  136. size_t len;
  137. len = strlen(*excludes);
  138. if (len >= addrlen) continue;
  139. if (strcasecmp(*excludes, &address[addrlen - len]) == 0 && (**excludes == '.' || address[addrlen - len - 1] == '@')) {
  140. fputs ("500 Domain excluded from SRS\n", fp);
  141. fflush (fp);
  142. return;
  143. }
  144. }
  145. result = srs_forward(srs, value, sizeof(value), address, domain);
  146. if (result == SRS_SUCCESS) {
  147. output = url_encode(outputbuf, sizeof(outputbuf), value);
  148. fprintf (fp, "200 %s\n", output);
  149. if (strcmp(address, value) != 0) syslog (LOG_MAIL | LOG_INFO, "srs_forward: <%s> rewritten as <%s>", address, value);
  150. } else {
  151. fprintf (fp, "500 %s\n", srs_strerror(result));
  152. if (result != SRS_ENOTREWRITTEN)
  153. syslog (LOG_MAIL | LOG_INFO, "srs_forward: <%s> not rewritten: %s", address, srs_strerror(result));
  154. }
  155. fflush (fp);
  156. }
  157. static void handle_reverse (srs_t *srs, FILE *fp, const char *address, const char *domain, const char **excludes)
  158. {
  159. int result;
  160. char value[1024];
  161. char outputbuf[1024], *output;
  162. result = srs_reverse(srs, value, sizeof(value), address);
  163. if (result == SRS_SUCCESS) {
  164. output = url_encode(outputbuf, sizeof(outputbuf), value);
  165. fprintf (fp, "200 %s\n", output);
  166. syslog (LOG_MAIL | LOG_INFO, "srs_reverse: <%s> rewritten as <%s>", address, value);
  167. } else {
  168. fprintf (fp, "500 %s\n", srs_strerror(result));
  169. if (result != SRS_ENOTREWRITTEN && result != SRS_ENOTSRSADDRESS)
  170. syslog (LOG_MAIL | LOG_INFO, "srs_reverse: <%s> not rewritten: %s", address, srs_strerror(result));
  171. }
  172. fflush (fp);
  173. }
  174. static void show_help ()
  175. {
  176. fprintf (stdout,
  177. "Sender Rewriting Scheme implementation for Postfix.\n\n"
  178. "Implements two TCP lookup tables to rewrite mail addresses\n"
  179. "as needed. The forward SRS is for sender envelope addresses\n"
  180. "to prevent SPF-related bounces. The reverse SRS is for\n"
  181. "recipient envelope addresses so that bounced mails can be\n"
  182. "routed back to their original sender.\n"
  183. "\n"
  184. "Usage: %s -s<file> -d<domain> [other options]\n"
  185. "Options:\n"
  186. " -s<file> read secrets from file (required)\n"
  187. " -d<domain> set domain name for rewrite (required)\n"
  188. " -f<port> set port for the forward SRS lookup (default: 10001)\n"
  189. " -r<port> set port for the reverse SRS lookup (default: 10002)\n"
  190. " -p<pidfile> write process ID to pidfile (default: none)\n"
  191. " -c<dir> chroot to <dir> (default: none)\n"
  192. " -u<user> switch user id after port bind (default: none)\n"
  193. " -t<seconds> timeout for idle client connections (default: 1800)\n"
  194. " -X<domain> exclude additional domain from address rewriting\n"
  195. " -D fork into background\n"
  196. " -4 force IPv4 socket (default: any)\n"
  197. " -6 force IPv6 socket (default: any)\n"
  198. " -h show this help\n"
  199. " -v show version\n"
  200. "\n",
  201. self
  202. );
  203. }
  204. typedef void(*handle_t)(srs_t*, FILE*, const char*, const char*, const char**);
  205. int main (int argc, char **argv)
  206. {
  207. int opt, timeout = 1800, family = AF_UNSPEC;
  208. int daemonize = FALSE;
  209. char *forward_service = NULL, *reverse_service = NULL,
  210. *user = NULL, *domain = NULL, *chroot_dir = NULL;
  211. int forward_sock, reverse_sock;
  212. char *secret_file = NULL, *pid_file = NULL;
  213. FILE *pf = NULL, *sf = NULL;
  214. struct passwd *pwd = NULL;
  215. char secretbuf[1024], *secret = NULL;
  216. char *tmp;
  217. srs_t *srs;
  218. struct pollfd fds[3];
  219. const char **excludes;
  220. size_t s1 = 0, s2 = 1;
  221. handle_t handler[2] = { handle_forward, handle_reverse };
  222. excludes = (const char**)calloc(1, sizeof(char*));
  223. tmp = strrchr(argv[0], '/');
  224. if (tmp) self = strdup(tmp + 1); else self = strdup(argv[0]);
  225. while ((opt = getopt(argc, argv, "46d:f:r:s:u:t:p:c:X::Dhv")) != -1) {
  226. switch (opt) {
  227. case '?':
  228. return EXIT_FAILURE;
  229. case '4':
  230. family = AF_INET;
  231. break;
  232. case '6':
  233. family = AF_INET6;
  234. break;
  235. case 'd':
  236. domain = strdup(optarg);
  237. break;
  238. case 'f':
  239. forward_service = strdup(optarg);
  240. break;
  241. case 'r':
  242. reverse_service = strdup(optarg);
  243. break;
  244. case 't':
  245. timeout = atoi(optarg);
  246. break;
  247. case 's':
  248. secret_file = strdup(optarg);
  249. break;
  250. case 'p':
  251. pid_file = strdup(optarg);
  252. break;
  253. case 'u':
  254. user = strdup(optarg);
  255. break;
  256. case 'c':
  257. chroot_dir = strdup(optarg);
  258. break;
  259. case 'D':
  260. daemonize = TRUE;
  261. break;
  262. case 'h':
  263. show_help();
  264. return EXIT_SUCCESS;
  265. case 'X':
  266. if (optarg != NULL) {
  267. tmp = strtok(optarg, ",; \t\r\n");
  268. while (tmp) {
  269. if (s1 + 1 >= s2) {
  270. s2 *= 2;
  271. excludes = (const char **)realloc(excludes, s2 * sizeof(char*));
  272. if (excludes == NULL) {
  273. fprintf (stderr, "%s: Out of memory\n\n", self);
  274. return EXIT_FAILURE;
  275. }
  276. }
  277. excludes[s1++] = strdup(tmp);
  278. tmp = strtok(NULL, ",; \t\r\n");
  279. }
  280. excludes[s1] = NULL;
  281. }
  282. break;
  283. case 'v':
  284. fprintf (stdout, "%s\n", VERSION);
  285. return EXIT_SUCCESS;
  286. }
  287. }
  288. if (optind < argc) {
  289. fprintf (stderr, "%s: extra argument on command line: %s\n", self, argv[optind]);
  290. return EXIT_FAILURE;
  291. }
  292. if (domain == NULL) {
  293. fprintf (stderr, "%s: You must set a home domain (-d)\n", self);
  294. return EXIT_FAILURE;
  295. }
  296. /* The stuff we do first may not be possible from within chroot or without privileges */
  297. /* Open pid file for writing (the actual process ID is filled in later) */
  298. if (pid_file) {
  299. pf = fopen (pid_file, "w");
  300. if (pf == NULL) {
  301. fprintf (stderr, "%s: Cannot write PID: %s\n\n", self, pid_file);
  302. return EXIT_FAILURE;
  303. }
  304. }
  305. /* Read secret. The default installation makes this root accessible only. */
  306. if (secret_file != NULL) {
  307. size_t len;
  308. sf = fopen(secret_file, "rb");
  309. if (sf == NULL) {
  310. fprintf (stderr, "%s: Cannot open file with secret: %s\n", self, secret_file);
  311. return EXIT_FAILURE;
  312. }
  313. } else {
  314. fprintf (stderr, "%s: You must set a secret (-s)\n", self);
  315. return EXIT_FAILURE;
  316. }
  317. /* Bind ports. May require privileges if the config specifies ports below 1024 */
  318. if (forward_service != NULL) {
  319. forward_sock = bind_service(forward_service, family);
  320. free (forward_service);
  321. } else {
  322. forward_sock = bind_service("10001", family);
  323. }
  324. if (forward_sock < 0) return EXIT_FAILURE;
  325. if (reverse_service != NULL) {
  326. reverse_sock = bind_service(reverse_service, family);
  327. free (reverse_service);
  328. } else {
  329. reverse_sock = bind_service("10002", family);
  330. }
  331. if (reverse_sock < 0) return EXIT_FAILURE;
  332. /* Open syslog now (NDELAY), because it may no longer reachable from chroot */
  333. openlog (self, LOG_PID | LOG_NDELAY, LOG_MAIL);
  334. /* We also have to lookup the uid of the unprivileged user for the same reason. */
  335. if (user) {
  336. errno = 0;
  337. pwd = getpwnam(user);
  338. if (pwd == NULL) {
  339. if (errno != 0)
  340. fprintf (stderr, "%s: Failed to lookup user: %s\n", self, strerror(errno));
  341. else
  342. fprintf (stderr, "%s: No such user: %s\n", self, user);
  343. return EXIT_FAILURE;
  344. }
  345. }
  346. /* Now we can chroot, which again requires root privileges */
  347. if (chroot_dir) {
  348. if (chdir(chroot_dir) < 0) {
  349. fprintf (stderr, "%s: Cannot change to chroot: %s\n", self, strerror(errno));
  350. return EXIT_FAILURE;
  351. }
  352. if (chroot(chroot_dir) < 0) {
  353. fprintf (stderr, "%s: Failed to enable chroot: %s\n", self, strerror(errno));
  354. return EXIT_FAILURE;
  355. }
  356. }
  357. /* Finally, we revert to the unprivileged user */
  358. if (pwd) {
  359. if (setuid(pwd->pw_uid) < 0) {
  360. fprintf (stderr, "%s: Failed to switch user id: %s\n", self, strerror(errno));
  361. return EXIT_FAILURE;
  362. }
  363. }
  364. /* Standard double fork technique to disavow all knowledge about the controlling terminal */
  365. if (daemonize) {
  366. close(0); close(1); close(2);
  367. if (fork() != 0) return EXIT_SUCCESS;
  368. setsid();
  369. if (fork() != 0) return EXIT_SUCCESS;
  370. }
  371. /* Make note of our actual process ID */
  372. if (pf) {
  373. fprintf (pf, "%d", (int)getpid());
  374. fclose (pf);
  375. }
  376. srs = srs_new();
  377. while ((secret = fgets(secretbuf, sizeof(secretbuf), sf))) {
  378. secret = strtok(secret, "\r\n");
  379. if (secret)
  380. srs_add_secret (srs, secret);
  381. }
  382. fclose (sf);
  383. srs_set_separator (srs, '+');
  384. fds[0].fd = forward_sock;
  385. fds[0].events = POLLIN;
  386. fds[1].fd = reverse_sock;
  387. fds[1].events = POLLIN;
  388. while(TRUE) {
  389. int i, conn;
  390. FILE *fp;
  391. char linebuf[1024], *line;
  392. char keybuf[1024], *key;
  393. if (poll(fds, 2, 1000) < 0) {
  394. if (errno == EINTR)
  395. continue;
  396. if (daemonize)
  397. syslog (LOG_MAIL | LOG_ERR, "Poll failure: %s", strerror(errno));
  398. else
  399. fprintf (stderr, "%s: Poll failure: %s\n", self, strerror(errno));
  400. return EXIT_FAILURE;
  401. }
  402. for (i = 0; i < 2; ++i) {
  403. if (fds[i].revents) {
  404. conn = accept(fds[i].fd, NULL, NULL);
  405. if (conn < 0) continue;
  406. if (fork() == 0) {
  407. // close listen sockets so that we don't stop the main daemon process from restarting
  408. close(forward_sock);
  409. close(reverse_sock);
  410. fp = fdopen(conn, "r+");
  411. if (fp == NULL) exit(EXIT_FAILURE);
  412. fds[2].fd = conn;
  413. fds[2].events = POLLIN;
  414. if (poll(&fds[2], 1, timeout * 1000) <= 0) return EXIT_FAILURE;
  415. line = fgets(linebuf, sizeof(linebuf), fp);
  416. while (line) {
  417. char* token;
  418. token = strtok(line, " \r\n");
  419. if (token == NULL || strcmp(token, "get") != 0) {
  420. fprintf (fp, "500 Invalid request\n");
  421. return EXIT_FAILURE;
  422. }
  423. token = strtok(NULL, "\r\n");
  424. if (!token) {
  425. fprintf (fp, "500 Invalid request\n");
  426. return EXIT_FAILURE;
  427. }
  428. key = url_decode(keybuf, sizeof(keybuf), token);
  429. if (!key) break;
  430. handler[i](srs, fp, key, domain, excludes);
  431. if (poll(&fds[2], 1, timeout * 1000) <= 0) break;
  432. line = fgets(linebuf, sizeof(linebuf), fp);
  433. }
  434. fclose (fp);
  435. return EXIT_SUCCESS;
  436. }
  437. close (conn);
  438. }
  439. }
  440. waitpid(-1, NULL, WNOHANG);
  441. }
  442. return EXIT_SUCCESS;
  443. }