milterfrom.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. /*
  2. * Milterfrom
  3. *
  4. * Copyright (c) 2017, Max von Buelow
  5. * All rights reserved.
  6. * Contact: https://maxvonbuelow.de
  7. *
  8. * This file is part of the MilterFrom project.
  9. * https://github.com/magcks/milterfrom
  10. *
  11. * Redistribution and use in source and binary forms, with or without
  12. * modification, are permitted provided that the following conditions are met:
  13. * * Redistributions of source code must retain the above copyright
  14. * notice, this list of conditions and the following disclaimer.
  15. * * Redistributions in binary form must reproduce the above copyright
  16. * notice, this list of conditions and the following disclaimer in the
  17. * documentation and/or other materials provided with the distribution.
  18. * * Neither the name of the copyright holder nor the
  19. * names of its contributors may be used to endorse or promote products
  20. * derived from this software without specific prior written permission.
  21. *
  22. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  23. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  24. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  25. * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  26. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  27. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  28. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  29. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  31. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. */
  33. #include <sys/types.h>
  34. #include <sys/stat.h>
  35. #include <stdio.h>
  36. #include <stdlib.h>
  37. #include <string.h>
  38. #include <sysexits.h>
  39. #include <unistd.h>
  40. #include <errno.h>
  41. #include <pwd.h>
  42. #include <grp.h>
  43. #include <stdint.h>
  44. #include <syslog.h>
  45. #include <ctype.h>
  46. #include <stddef.h>
  47. #include "libmilter/mfapi.h"
  48. #include "libmilter/mfdef.h"
  49. struct mlfiPriv {
  50. int is_auth;
  51. char *env_from;
  52. size_t env_from_len;
  53. int reject;
  54. };
  55. #define MLFIPRIV ((struct mlfiPriv*)smfi_getpriv(ctx))
  56. #define VERSION "1.0.3"
  57. extern const char *__progname;
  58. static unsigned long mta_caps = 0;
  59. // Function to extract addresses from the header/envelope fields. If the field
  60. // contains a < with a subsequent >, the inner part is used. If not, the whole
  61. // header field is used. This allows matching "Max Mustermann
  62. // <max.mustermann@example.invalid>".
  63. const char *parse_address(const char *header, size_t *len) {
  64. if (!header || !len) return NULL;
  65. const char *start = NULL;
  66. const char *end = NULL;
  67. size_t i;
  68. /* Find the last '<' and the corresponding '>' */
  69. for (i = 0; header[i]; i++) {
  70. if (header[i] == '<') start = header + i + 1;
  71. else if (header[i] == '>') end = header + i;
  72. }
  73. if (start && end && start < end) {
  74. /* Trim whitespace from start */
  75. while (start < end && isspace((unsigned char)*start)) start++;
  76. /* Trim whitespace from end */
  77. while (end > start && isspace((unsigned char)*(end-1))) end--;
  78. /* Reject if empty */
  79. if (end <= start) return NULL;
  80. /* Reject if any control chars (\r, \n, 0x00-0x1F, 0x7F) */
  81. for (const char *p = start; p < end; p++) {
  82. if ((unsigned char)*p < 32 || *p == 127) return NULL;
  83. }
  84. *len = (size_t)(end - start);
  85. return start;
  86. }
  87. /* No angle brackets: treat the entire header as address */
  88. start = header;
  89. end = header + strlen(header);
  90. /* Trim whitespace */
  91. while (start < end && isspace((unsigned char)*start)) start++;
  92. while (end > start && isspace((unsigned char)*(end-1))) end--;
  93. if (end <= start) return NULL;
  94. /* Reject control characters */
  95. for (const char *p = start; p < end; p++) {
  96. if ((unsigned char)*p < 32 || *p == 127) return NULL;
  97. }
  98. *len = (size_t)(end - start);
  99. return start;
  100. }
  101. void log_event(SMFICTX *ctx, char *msg) {
  102. /* Log event with additional information */
  103. const char *author = smfi_getsymval(ctx, "{auth_authen}");
  104. const char *info = smfi_getsymval(ctx,"_");
  105. syslog(LOG_INFO,"%s for authenticated user (%s) from (%s)", msg, author, info);
  106. }
  107. void mlfi_cleanup(SMFICTX *ctx)
  108. {
  109. struct mlfiPriv *priv = MLFIPRIV;
  110. if (priv == NULL) return;
  111. free(priv->env_from);
  112. free(priv);
  113. smfi_setpriv(ctx, NULL);
  114. }
  115. sfsistat mlfi_envfrom(SMFICTX *ctx, char **envfrom)
  116. {
  117. struct mlfiPriv *priv;
  118. char *fromcp = NULL;
  119. // Allocate some private memory.
  120. priv = calloc(1, sizeof(*priv));
  121. if (priv == NULL) {
  122. return SMFIS_TEMPFAIL;
  123. }
  124. // Parse envelope from.
  125. size_t len = 0;
  126. const char *from = parse_address(*envfrom, &len);
  127. if (len == 0) {
  128. /* A 0 length from address means a "null reverse-path", which is valid per
  129. * RFC5321. */
  130. log_event(ctx, "Accepting message as envelope sender is null");
  131. return SMFIS_ACCEPT;
  132. }
  133. fromcp = strndup(from, len);
  134. if (fromcp == NULL) {
  135. return SMFIS_TEMPFAIL;
  136. }
  137. // Set private values.
  138. priv->is_auth = smfi_getsymval(ctx, "{auth_type}") ? 1 : 0;
  139. priv->env_from = fromcp;
  140. priv->env_from_len = len;
  141. priv->reject = 0;
  142. smfi_setpriv(ctx, priv);
  143. return SMFIS_CONTINUE;
  144. }
  145. sfsistat mlfi_header(SMFICTX *ctx, char *headerf, char *headerv)
  146. {
  147. struct mlfiPriv *priv = MLFIPRIV;
  148. if (priv == NULL) return SMFIS_CONTINUE;
  149. // Perform checks if the sender is authenticated and the message is not rejected yet (the mail may contain multiple from tags, all have to match!).
  150. if (priv->is_auth && !priv->reject) {
  151. if (strcasecmp(headerf, "from") == 0) {
  152. size_t len = 0;
  153. const char *from = parse_address(headerv, &len);
  154. // Check whether header from matches envelope from and reject if not.
  155. if (len != priv->env_from_len || strncasecmp(from, priv->env_from, len) != 0) {
  156. char *msg;
  157. size_t msg_len = 0;
  158. priv->reject = 1;
  159. msg_len = 55 + len + priv->env_from_len;
  160. msg = malloc(msg_len);
  161. if (msg != NULL) {
  162. snprintf(msg, msg_len, "Rejecting Envelope From (%s) and Header From (%s) mismatch", priv->env_from, from);
  163. log_event(ctx, msg);
  164. }
  165. free(msg);
  166. }
  167. }
  168. }
  169. return ((mta_caps & SMFIP_NR_HDR) != 0) ? SMFIS_NOREPLY : SMFIS_CONTINUE;
  170. }
  171. sfsistat mlfi_eom(SMFICTX *ctx)
  172. {
  173. struct mlfiPriv *priv = MLFIPRIV;
  174. if (priv == NULL) return SMFIS_CONTINUE;
  175. if (priv->reject) {
  176. smfi_setreply(ctx, "550", "5.7.1", "Rejected due to unmatching envelope and header sender.");
  177. mlfi_cleanup(ctx);
  178. return SMFIS_REJECT;
  179. }
  180. mlfi_cleanup(ctx);
  181. return SMFIS_CONTINUE;
  182. }
  183. sfsistat mlfi_abort(SMFICTX *ctx)
  184. {
  185. mlfi_cleanup(ctx);
  186. return SMFIS_CONTINUE;
  187. }
  188. sfsistat mlfi_negotiate(SMFICTX *ctx, unsigned long f0, unsigned long f1, unsigned long f2, unsigned long f3, unsigned long *pf0, unsigned long *pf1, unsigned long *pf2, unsigned long *pf3)
  189. {
  190. *pf0 = 0;
  191. /* milter protocol steps: all but connect, HELO, RCPT */
  192. *pf1 = SMFIP_NOCONNECT | SMFIP_NOHELO | SMFIP_NORCPT;
  193. mta_caps = f1;
  194. if ((mta_caps & SMFIP_NR_HDR) != 0) *pf1 |= SMFIP_NR_HDR;
  195. *pf2 = 0;
  196. *pf3 = 0;
  197. return SMFIS_CONTINUE;
  198. }
  199. struct smfiDesc smfilter =
  200. {
  201. "Header from check", /* filter name */
  202. SMFI_VERSION, /* version code -- do not change */
  203. 0, /* flags */
  204. NULL, /* connection info filter */
  205. NULL, /* SMTP HELO command filter */
  206. mlfi_envfrom, /* envelope sender filter */
  207. NULL, /* envelope recipient filter */
  208. mlfi_header, /* header filter */
  209. NULL, /* end of header */
  210. NULL, /* body block filter */
  211. mlfi_eom, /* end of message */
  212. mlfi_abort, /* message aborted */
  213. NULL, /* connection cleanup */
  214. NULL, /* unknown/unimplemented SMTP commands */
  215. NULL, /* DATA command filter */
  216. mlfi_negotiate /* option negotiation at connection startup */
  217. };
  218. uid_t get_uid(const char *name)
  219. {
  220. struct passwd *pwd = getpwnam(name);
  221. return pwd == NULL ? -1 : pwd->pw_uid;
  222. }
  223. gid_t get_gid(const char *name)
  224. {
  225. struct group *grp = getgrnam(name);
  226. return grp == NULL ? -1 : grp->gr_gid;
  227. }
  228. static void usage(FILE *stream) {
  229. fprintf(stream, "%s: A Milter program version %s to reject emails that have a mismatch between Envelope Sender and email Header From fields for authenticated users. This prevents spoofing that is currently not possible with \"reject_authenticated_sender_login_mismatch\" in Postfix\n", __progname, VERSION);
  230. fprintf(stream, "%s: usage: %s -s socketfile [options]\n"
  231. "\t-p pidfile \twrite process ID to pidfile name\n"
  232. "\t-d \tdaemonize to background and exit\n"
  233. "\t-u userid \tchange to specified userid\n"
  234. "\t-g groupid \tchange to specific groupid\n"
  235. "\t-v \tprint version number and terminate\n",
  236. __progname, __progname);
  237. }
  238. int main(int argc, char **argv)
  239. {
  240. int c, daemonize = 0;
  241. uid_t uid = -1; gid_t gid = -1;
  242. mode_t um = -1;
  243. char *pidfilename = NULL, *sockname = NULL;
  244. FILE *pidfile = NULL;
  245. u_int mvmajor;
  246. u_int mvminor;
  247. u_int mvrelease;
  248. while ((c = getopt(argc, argv, "dhvs:p:u:g:m:")) != -1) {
  249. switch (c) {
  250. case 's':
  251. sockname = strdup(optarg);
  252. break;
  253. case 'p':
  254. pidfilename = strdup(optarg);
  255. break;
  256. case 'd':
  257. daemonize = 1;
  258. break;
  259. case 'u':
  260. uid = get_uid(optarg);
  261. break;
  262. case 'g':
  263. gid = get_gid(optarg);
  264. break;
  265. case 'm':
  266. um = strtol(optarg, 0, 8);
  267. break;
  268. case 'h':
  269. usage(stdout);
  270. return EXIT_SUCCESS;
  271. case 'v':
  272. printf("%s: v%s\n", __progname, VERSION);
  273. printf("\tSMFI_VERSION 0x%x\n", SMFI_VERSION);
  274. (void)smfi_version(&mvmajor, &mvminor, &mvrelease);
  275. printf("\tlibmilter version %d.%d.%d\n", mvmajor, mvminor, mvrelease);
  276. return EXIT_SUCCESS;
  277. }
  278. }
  279. if (!sockname) {
  280. fprintf(stderr, "%s: Missing required -s argument\n", argv[0]);
  281. usage(stderr);
  282. return EX_USAGE;
  283. }
  284. if (pidfilename) {
  285. unlink(pidfilename);
  286. pidfile = fopen(pidfilename, "w");
  287. if (!pidfile) {
  288. fprintf(stderr, "Could not open pidfile: %s\n", strerror(errno));
  289. exit(1);
  290. }
  291. free(pidfilename);
  292. }
  293. if (um != (mode_t)-1) umask(um);
  294. if (gid != (gid_t)-1) setgid(gid);
  295. if (uid != (uid_t)-1) setuid(uid);
  296. if (daemonize) {
  297. if (daemon(0, 0) == -1) {
  298. fprintf(stderr, "daemon() failed: %s\n", strerror(errno));
  299. exit(EXIT_FAILURE);
  300. }
  301. }
  302. if (pidfile) {
  303. fprintf(pidfile, "%ld\n", (long)getpid());
  304. fclose(pidfile);
  305. }
  306. struct stat junk;
  307. if (stat(sockname, &junk) == 0) unlink(sockname);
  308. smfi_setconn(sockname);
  309. free(sockname);
  310. if (smfi_register(smfilter) == MI_FAILURE) {
  311. fprintf(stderr, "smfi_register failed\n");
  312. exit(EX_UNAVAILABLE);
  313. }
  314. openlog("milterfrom", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_MAIL);
  315. return smfi_main();
  316. }