Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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. #ifdef HAVE_SYS_TIME_H
  30. #include <sys/time.h>
  31. #endif
  32. #ifdef HAVE_TIME_H
  33. #include <time.h>
  34. #endif
  35. #ifdef HAVE_SYS_WAIT_H
  36. #include <sys/wait.h>
  37. #endif
  38. #ifdef HAVE_WAIT_H
  39. #include <wait.h>
  40. #endif
  41. #include <syslog.h>
  42. #ifndef VERSION
  43. #define VERSION "1.4"
  44. #endif
  45. static char *self = NULL;
  46. static size_t bind_service (const char *listen_addr, const char *service, int family, int* socks, size_t max_socks)
  47. {
  48. struct addrinfo *addr, *it;
  49. struct addrinfo hints;
  50. int err, sock, flags;
  51. size_t count = 0;
  52. static const int one = 1;
  53. memset (&hints, 0, sizeof(hints));
  54. hints.ai_family = family;
  55. hints.ai_socktype = SOCK_STREAM;
  56. err = getaddrinfo(listen_addr, service, &hints, &addr);
  57. if (err != 0) {
  58. fprintf(stderr, "%s: bind_service(%s): %s\n", self, service, gai_strerror(err));
  59. return count;
  60. }
  61. sock = -1;
  62. for (it = addr; it; it = it->ai_next) {
  63. if (max_socks == 0) break;
  64. sock = socket(it->ai_family, it->ai_socktype, it->ai_protocol);
  65. if (sock < 0) goto fail;
  66. if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0) goto fail;
  67. if (bind(sock, it->ai_addr, it->ai_addrlen) < 0) goto fail;
  68. if (listen(sock, 10) < 0) goto fail;
  69. flags = fcntl (sock, F_GETFL, 0);
  70. if (flags < 0) goto fail;
  71. if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0) goto fail;
  72. *socks++ = sock;
  73. ++count;
  74. --max_socks;
  75. continue;
  76. fail:
  77. err = errno;
  78. if (sock >= 0) close (sock);
  79. }
  80. freeaddrinfo (addr);
  81. if (count == 0)
  82. fprintf (stderr, "%s: bind_service(%s): %s\n", self, service, strerror(err));
  83. return count;
  84. }
  85. static int is_hexdigit (char c)
  86. {
  87. return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
  88. }
  89. static char hex2num (char c)
  90. {
  91. if (c >= '0' && c <= '9') return c - '0';
  92. if (c >= 'a' && c <= 'f') return c - 'a' + 10;
  93. if (c >= 'A' && c <= 'F') return c - 'A' + 10;
  94. return 0;
  95. }
  96. static char num2hex (char c)
  97. {
  98. if (c < 10) return '0' + c;
  99. return 'a' + c - 10;
  100. }
  101. static char hex2char (const char *s)
  102. {
  103. return 16 * hex2num(s[0]) + hex2num(s[1]);
  104. }
  105. static void char2hex (char c, char *buf)
  106. {
  107. buf[0] = num2hex((c >> 4) & 0xf);
  108. buf[1] = num2hex((c ) & 0xf);
  109. }
  110. static char* url_decode (char *buf, size_t len, const char *input)
  111. {
  112. char *output = buf;
  113. if (!input || !output || len == 0) return NULL;
  114. while (*input && --len) {
  115. if (*input == '%' && is_hexdigit(input[1]) && is_hexdigit(input[2])) {
  116. *output++ = hex2char(++input);
  117. input += 2;
  118. } else {
  119. *output++ = *input++;
  120. }
  121. }
  122. *output = 0;
  123. return buf;
  124. }
  125. static char* url_encode (char* buf, size_t len, const char *input)
  126. {
  127. char *output = buf;
  128. if (!input || !output || len == 0) return NULL;
  129. while (*input && --len) {
  130. if (!isascii(*input) || !isgraph(*input) || *input == '%') {
  131. if (len <= 2) break;
  132. *output++ = '%';
  133. char2hex(*input++, output);
  134. output += 2; len -= 2;
  135. } else {
  136. *output++ = *input++;
  137. }
  138. }
  139. *output = 0;
  140. return buf;
  141. }
  142. static void handle_forward (srs_t *srs, FILE *fp, const char *address, const char *domain, const char **excludes)
  143. {
  144. int result;
  145. size_t addrlen;
  146. char value[1024];
  147. char outputbuf[1024], *output;
  148. addrlen = strlen(address);
  149. for(; *excludes; excludes++) {
  150. size_t len;
  151. len = strlen(*excludes);
  152. if (len >= addrlen) continue;
  153. if (strcasecmp(*excludes, &address[addrlen - len]) == 0 && (**excludes == '.' || address[addrlen - len - 1] == '@')) {
  154. fputs ("500 Domain excluded from SRS\n", fp);
  155. fflush (fp);
  156. return;
  157. }
  158. }
  159. result = srs_forward(srs, value, sizeof(value), address, domain);
  160. if (result == SRS_SUCCESS) {
  161. output = url_encode(outputbuf, sizeof(outputbuf), value);
  162. fprintf (fp, "200 %s\n", output);
  163. if (strcmp(address, value) != 0) syslog (LOG_MAIL | LOG_INFO, "srs_forward: <%s> rewritten as <%s>", address, value);
  164. } else {
  165. fprintf (fp, "500 %s\n", srs_strerror(result));
  166. if (result != SRS_ENOTREWRITTEN)
  167. syslog (LOG_MAIL | LOG_INFO, "srs_forward: <%s> not rewritten: %s", address, srs_strerror(result));
  168. }
  169. fflush (fp);
  170. }
  171. static void handle_reverse (srs_t *srs, FILE *fp, const char *address, const char *domain __attribute__((unused)), const char **excludes __attribute__((unused)) )
  172. {
  173. int result;
  174. char value[1024];
  175. char outputbuf[1024], *output;
  176. result = srs_reverse(srs, value, sizeof(value), address);
  177. if (result == SRS_SUCCESS) {
  178. output = url_encode(outputbuf, sizeof(outputbuf), value);
  179. fprintf (fp, "200 %s\n", output);
  180. syslog (LOG_MAIL | LOG_INFO, "srs_reverse: <%s> rewritten as <%s>", address, value);
  181. } else {
  182. fprintf (fp, "500 %s\n", srs_strerror(result));
  183. if (result != SRS_ENOTREWRITTEN && result != SRS_ENOTSRSADDRESS)
  184. syslog (LOG_MAIL | LOG_INFO, "srs_reverse: <%s> not rewritten: %s", address, srs_strerror(result));
  185. }
  186. fflush (fp);
  187. }
  188. static void show_help ()
  189. {
  190. fprintf (stdout,
  191. "Sender Rewriting Scheme implementation for Postfix.\n\n"
  192. "Implements two TCP lookup tables to rewrite mail addresses\n"
  193. "as needed. The forward SRS is for sender envelope addresses\n"
  194. "to prevent SPF-related bounces. The reverse SRS is for\n"
  195. "recipient envelope addresses so that bounced mails can be\n"
  196. "routed back to their original sender.\n"
  197. "\n"
  198. "Usage: %s -s<file> -d<domain> [other options]\n"
  199. "Options:\n"
  200. " -s<file> read secrets from file (required)\n"
  201. " -d<domain> set domain name for rewrite (required)\n"
  202. " -a<char> set first separator character which can be one of: -=+ (default: =)\n"
  203. " -n<num> length of hash to be used in rewritten addresses (default: 4)\n"
  204. " -N<num> minimum length of hash to accept for validation (default: 4)\n"
  205. " -l<addr> set socket listen address (default: 127.0.0.1)\n"
  206. " -f<port> set port for the forward SRS lookup (default: 10001)\n"
  207. " -r<port> set port for the reverse SRS lookup (default: 10002)\n"
  208. " -p<pidfile> write process ID to pidfile (default: none)\n"
  209. " -c<dir> chroot to <dir> (default: none)\n"
  210. " -u<user> switch user id after port bind (default: none)\n"
  211. " -t<seconds> timeout for idle client connections (default: 1800)\n"
  212. " -X<domain> exclude additional domain from address rewriting\n"
  213. " -e attempt to read above parameters from environment\n"
  214. " -D fork into background\n"
  215. " -4 force IPv4 socket (default: any)\n"
  216. " -6 force IPv6 socket (default: any)\n"
  217. " -h show this help\n"
  218. " -v show version\n"
  219. "\n",
  220. self
  221. );
  222. }
  223. typedef void(*handle_t)(srs_t*, FILE*, const char*, const char*, const char**);
  224. int main (int argc, char **argv)
  225. {
  226. int opt, timeout = 1800, family = AF_UNSPEC, hashlength = 0, hashmin = 0;
  227. int daemonize = FALSE;
  228. char *listen_addr = NULL, *forward_service = NULL, *reverse_service = NULL,
  229. *user = NULL, *domain = NULL, *chroot_dir = NULL;
  230. char separator = '=';
  231. char *secret_file = NULL, *pid_file = NULL;
  232. FILE *pf = NULL, *sf = NULL;
  233. struct passwd *pwd = NULL;
  234. char secretbuf[1024], *secret = NULL;
  235. char *tmp;
  236. time_t now;
  237. srs_t *srs;
  238. const char **excludes;
  239. size_t s1 = 0, s2 = 1;
  240. struct pollfd fds[4];
  241. size_t socket_count = 0, sc;
  242. int sockets[4] = { -1, -1, -1, -1 };
  243. handle_t handler[4] = { 0, 0, 0, 0 };
  244. excludes = (const char**)calloc(1, sizeof(char*));
  245. tmp = strrchr(argv[0], '/');
  246. if (tmp) self = strdup(tmp + 1); else self = strdup(argv[0]);
  247. while ((opt = getopt(argc, argv, "46d:a:l:f:r:s:n:N:u:t:p:c:X::Dhev")) != -1) {
  248. switch (opt) {
  249. case '?':
  250. return EXIT_FAILURE;
  251. case '4':
  252. family = AF_INET;
  253. break;
  254. case '6':
  255. family = AF_INET6;
  256. break;
  257. case 'd':
  258. domain = strdup(optarg);
  259. break;
  260. case 'a':
  261. separator = *optarg;
  262. break;
  263. case 'l':
  264. listen_addr = strdup(optarg);
  265. break;
  266. case 'f':
  267. forward_service = strdup(optarg);
  268. break;
  269. case 'r':
  270. reverse_service = strdup(optarg);
  271. break;
  272. case 't':
  273. timeout = atoi(optarg);
  274. break;
  275. case 's':
  276. secret_file = strdup(optarg);
  277. break;
  278. case 'n':
  279. hashlength = atoi(optarg);
  280. break;
  281. case 'N':
  282. hashmin = atoi(optarg);
  283. break;
  284. case 'p':
  285. pid_file = strdup(optarg);
  286. break;
  287. case 'u':
  288. user = strdup(optarg);
  289. break;
  290. case 'c':
  291. chroot_dir = strdup(optarg);
  292. break;
  293. case 'D':
  294. daemonize = TRUE;
  295. break;
  296. case 'h':
  297. show_help();
  298. return EXIT_SUCCESS;
  299. case 'X':
  300. if (optarg != NULL) {
  301. tmp = strtok(optarg, ",; \t\r\n");
  302. while (tmp) {
  303. if (s1 + 1 >= s2) {
  304. s2 *= 2;
  305. excludes = (const char **)realloc(excludes, s2 * sizeof(char*));
  306. if (excludes == NULL) {
  307. fprintf (stderr, "%s: Out of memory\n\n", self);
  308. return EXIT_FAILURE;
  309. }
  310. }
  311. excludes[s1++] = strdup(tmp);
  312. tmp = strtok(NULL, ",; \t\r\n");
  313. }
  314. excludes[s1] = NULL;
  315. }
  316. break;
  317. case 'e':
  318. if ( getenv("SRS_DOMAIN") != NULL )
  319. domain = strdup(getenv("SRS_DOMAIN"));
  320. if ( getenv("SRS_SEPARATOR") != NULL )
  321. separator = *getenv("SRS_SEPARATOR");
  322. if ( getenv("SRS_HASHLENGTH") != NULL )
  323. hashlength = atoi(getenv("SRS_HASHLENGTH"));
  324. if ( getenv("SRS_HASHMIN") != NULL )
  325. hashmin = atoi(getenv("SRS_HASHMIN"));
  326. if ( getenv("SRS_FORWARD_PORT") != NULL )
  327. forward_service = strdup(getenv("SRS_FORWARD_PORT"));
  328. if ( getenv("SRS_REVERSE_PORT") != NULL )
  329. reverse_service = strdup(getenv("SRS_REVERSE_PORT"));
  330. if ( getenv("SRS_TIMEOUT") != NULL )
  331. timeout = atoi(getenv("SRS_TIMEOUT"));
  332. if ( getenv("SRS_SECRET") != NULL )
  333. secret_file = strdup(getenv("SRS_SECRET"));
  334. if ( getenv("SRS_PID_FILE") != NULL )
  335. pid_file = strdup(getenv("SRS_PID_FILE"));
  336. if ( getenv("RUN_AS") != NULL )
  337. user = strdup(getenv("RUN_AS"));
  338. if ( getenv("CHROOT") != NULL )
  339. chroot_dir = strdup(getenv("CHROOT"));
  340. if (getenv("SRS_EXCLUDE_DOMAINS") != NULL) {
  341. tmp = strtok(getenv("SRS_EXCLUDE_DOMAINS"), ",; \t\r\n");
  342. while (tmp) {
  343. if (s1 + 1 >= s2) {
  344. s2 *= 2;
  345. excludes = (const char **)realloc(excludes, s2 * sizeof(char*));
  346. if (excludes == NULL) {
  347. fprintf (stderr, "%s: Out of memory\n\n", self);
  348. return EXIT_FAILURE;
  349. }
  350. }
  351. excludes[s1++] = strdup(tmp);
  352. tmp = strtok(NULL, ",; \t\r\n");
  353. }
  354. excludes[s1] = NULL;
  355. }
  356. break;
  357. case 'v':
  358. fprintf (stdout, "%s\n", VERSION);
  359. return EXIT_SUCCESS;
  360. }
  361. }
  362. if (optind < argc) {
  363. fprintf (stderr, "%s: extra argument on command line: %s\n", self, argv[optind]);
  364. return EXIT_FAILURE;
  365. }
  366. if (domain == NULL) {
  367. fprintf (stderr, "%s: You must set a home domain (-d)\n", self);
  368. return EXIT_FAILURE;
  369. }
  370. if (separator != '=' && separator != '+' && separator != '-') {
  371. fprintf (stderr, "%s: SRS separator character must be one of '=+-'\n", self);
  372. return EXIT_FAILURE;
  373. }
  374. if (forward_service == NULL) forward_service = strdup("10001");
  375. if (reverse_service == NULL) reverse_service = strdup("10002");
  376. /* The stuff we do first may not be possible from within chroot or without privileges */
  377. /* Open pid file for writing (the actual process ID is filled in later) */
  378. if (pid_file) {
  379. pf = fopen (pid_file, "w");
  380. if (pf == NULL) {
  381. fprintf (stderr, "%s: Cannot write PID: %s\n\n", self, pid_file);
  382. return EXIT_FAILURE;
  383. }
  384. }
  385. /* Read secret. The default installation makes this root accessible only. */
  386. if (secret_file != NULL) {
  387. sf = fopen(secret_file, "rb");
  388. if (sf == NULL) {
  389. fprintf (stderr, "%s: Cannot open file with secret: %s\n", self, secret_file);
  390. return EXIT_FAILURE;
  391. }
  392. } else {
  393. fprintf (stderr, "%s: You must set a secret (-s)\n", self);
  394. return EXIT_FAILURE;
  395. }
  396. /* Bind ports. May require privileges if the config specifies ports below 1024 */
  397. sc = bind_service(listen_addr, forward_service, family, &sockets[socket_count], 4 - socket_count);
  398. if (sc == 0) return EXIT_FAILURE;
  399. while (sc-- > 0) handler[socket_count++] = handle_forward;
  400. free (forward_service);
  401. sc = bind_service(listen_addr, reverse_service, family, &sockets[socket_count], 4 - socket_count);
  402. if (sc == 0) return EXIT_FAILURE;
  403. while (sc-- > 0) handler[socket_count++] = handle_reverse;
  404. free (reverse_service);
  405. /* Open syslog now (NDELAY), because it may no longer be reachable from chroot */
  406. openlog (self, LOG_PID | LOG_NDELAY, LOG_MAIL);
  407. /* Force loading of timezone info (suggested by patrickdk77) */
  408. now = time(NULL);
  409. localtime (&now);
  410. /* We also have to lookup the uid of the unprivileged user for the same reason. */
  411. if (user) {
  412. errno = 0;
  413. pwd = getpwnam(user);
  414. if (pwd == NULL) {
  415. if (errno != 0)
  416. fprintf (stderr, "%s: Failed to lookup user: %s\n", self, strerror(errno));
  417. else
  418. fprintf (stderr, "%s: No such user: %s\n", self, user);
  419. return EXIT_FAILURE;
  420. }
  421. }
  422. /* Now we can chroot, which again requires root privileges */
  423. if (chroot_dir) {
  424. if (chdir(chroot_dir) < 0) {
  425. fprintf (stderr, "%s: Cannot change to chroot: %s\n", self, strerror(errno));
  426. return EXIT_FAILURE;
  427. }
  428. if (chroot(chroot_dir) < 0) {
  429. fprintf (stderr, "%s: Failed to enable chroot: %s\n", self, strerror(errno));
  430. return EXIT_FAILURE;
  431. }
  432. }
  433. /* Finally, we revert to the unprivileged user */
  434. if (pwd) {
  435. if (setuid(pwd->pw_uid) < 0) {
  436. fprintf (stderr, "%s: Failed to switch user id: %s\n", self, strerror(errno));
  437. return EXIT_FAILURE;
  438. }
  439. }
  440. /* Standard double fork technique to disavow all knowledge about the controlling terminal */
  441. if (daemonize) {
  442. close(0); close(1); close(2);
  443. if (fork() != 0) return EXIT_SUCCESS;
  444. setsid();
  445. if (fork() != 0) return EXIT_SUCCESS;
  446. }
  447. /* Make note of our actual process ID */
  448. if (pf) {
  449. fprintf (pf, "%d", (int)getpid());
  450. fclose (pf);
  451. }
  452. srs = srs_new();
  453. while ((secret = fgets(secretbuf, sizeof(secretbuf), sf))) {
  454. secret = strtok(secret, "\r\n");
  455. if (secret)
  456. srs_add_secret (srs, secret);
  457. }
  458. fclose (sf);
  459. srs_set_separator (srs, separator);
  460. if (hashlength)
  461. srs_set_hashlength (srs, hashlength);
  462. if (hashmin)
  463. srs_set_hashmin (srs, hashmin);
  464. for (sc = 0; sc < socket_count; ++sc) {
  465. fds[sc].fd = sockets[sc];
  466. fds[sc].events = POLLIN;
  467. }
  468. while(TRUE) {
  469. int conn;
  470. FILE *fp;
  471. char linebuf[1024], *line;
  472. char keybuf[1024], *key;
  473. if (poll(fds, socket_count, 1000) < 0) {
  474. if (errno == EINTR)
  475. continue;
  476. if (daemonize)
  477. syslog (LOG_MAIL | LOG_ERR, "Poll failure: %s", strerror(errno));
  478. else
  479. fprintf (stderr, "%s: Poll failure: %s\n", self, strerror(errno));
  480. return EXIT_FAILURE;
  481. }
  482. for (sc = 0; sc < socket_count; ++sc) {
  483. if (fds[sc].revents) {
  484. conn = accept(fds[sc].fd, NULL, NULL);
  485. if (conn < 0) continue;
  486. if (fork() == 0) {
  487. int i;
  488. // close listen sockets so that we don't stop the main daemon process from restarting
  489. for (i = 0; i < socket_count; ++i) close (sockets[i]);
  490. fp = fdopen(conn, "r+");
  491. if (fp == NULL) exit(EXIT_FAILURE);
  492. fds[0].fd = conn;
  493. fds[0].events = POLLIN;
  494. if (poll(fds, 1, timeout * 1000) <= 0) return EXIT_FAILURE;
  495. line = fgets(linebuf, sizeof(linebuf), fp);
  496. while (line) {
  497. fseek (fp, 0, SEEK_CUR); /* Workaround for Solaris */
  498. char* token;
  499. token = strtok(line, " \r\n");
  500. if (token == NULL || strcmp(token, "get") != 0) {
  501. fprintf (fp, "500 Invalid request\n");
  502. fflush (fp);
  503. return EXIT_FAILURE;
  504. }
  505. token = strtok(NULL, "\r\n");
  506. if (!token) {
  507. fprintf (fp, "500 Invalid request\n");
  508. fflush (fp);
  509. return EXIT_FAILURE;
  510. }
  511. key = url_decode(keybuf, sizeof(keybuf), token);
  512. if (!key) break;
  513. handler[sc](srs, fp, key, domain, excludes);
  514. fflush (fp);
  515. if (poll(fds, 1, timeout * 1000) <= 0) break;
  516. line = fgets(linebuf, sizeof(linebuf), fp);
  517. }
  518. fclose (fp);
  519. return EXIT_SUCCESS;
  520. }
  521. close (conn);
  522. }
  523. }
  524. waitpid(-1, NULL, WNOHANG);
  525. }
  526. return EXIT_SUCCESS;
  527. }