1 /*	$OpenBSD: smtpd.c,v 1.335 2020/09/23 19:11:50 martijn Exp $	*/
2 
3 /*
4  * Copyright (c) 2008 Gilles Chehade <gilles@poolp.org>
5  * Copyright (c) 2008 Pierre-Yves Ritschard <pyr@openbsd.org>
6  * Copyright (c) 2009 Jacek Masiulaniec <jacekm@dobremiasto.net>
7  *
8  * Permission to use, copy, modify, and distribute this software for any
9  * purpose with or without fee is hereby granted, provided that the above
10  * copyright notice and this permission notice appear in all copies.
11  *
12  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19  */
20 
21 #include "includes.h"
22 
23 #include <sys/file.h> /* Needed for flock */
24 #include <sys/types.h>
25 #include <sys/queue.h>
26 #include <sys/tree.h>
27 #include <sys/socket.h>
28 #include <sys/wait.h>
29 #include <sys/stat.h>
30 #include <sys/uio.h>
31 #include <sys/mman.h>
32 
33 #ifdef BSD_AUTH
34 #include <bsd_auth.h>
35 #endif
36 
37 #ifdef USE_PAM
38 #if defined(HAVE_SECURITY_PAM_APPL_H)
39 #include <security/pam_appl.h>
40 #elif defined (HAVE_PAM_PAM_APPL_H)
41 #include <pam/pam_appl.h>
42 #endif
43 #endif
44 
45 #ifdef HAVE_CRYPT_H
46 #include <crypt.h> /* needed for crypt() */
47 #endif
48 #include <dirent.h>
49 #include <err.h>
50 #include <errno.h>
51 #include <event.h>
52 #include <fcntl.h>
53 #include <grp.h> /* needed for setgroups */
54 #include <fts.h>
55 #include <grp.h>
56 #include <imsg.h>
57 #include <inttypes.h>
58 #include <libgen.h>
59 #ifdef HAVE_LOGIN_CAP_H
60 #include <login_cap.h>
61 #endif
62 #ifdef HAVE_PATHS_H
63 #include <paths.h>
64 #endif
65 #include <poll.h>
66 #include <pwd.h>
67 #include <signal.h>
68 #ifdef HAVE_SHADOW_H
69 #include <shadow.h> /* needed for getspnam() */
70 #endif
71 #include <stdio.h>
72 #include <syslog.h>
73 #include <limits.h>
74 #include <stdlib.h>
75 #include <string.h>
76 #include <sysexits.h>
77 #include <time.h>
78 #include <unistd.h>
79 #ifdef HAVE_UTIL_H
80 #include <util.h>
81 #endif
82 
83 #include <openssl/rand.h>
84 #include <openssl/ssl.h>
85 #include <openssl/evp.h>
86 
87 #include "smtpd.h"
88 #include "log.h"
89 #include "ssl.h"
90 
91 extern char *__progname;
92 
93 #define SMTPD_MAXARG 32
94 
95 static void parent_imsg(struct mproc *, struct imsg *);
96 static void usage(void);
97 static int smtpd(void);
98 static void parent_shutdown(void);
99 static void parent_send_config(int, short, void *);
100 static void parent_send_config_lka(void);
101 static void parent_send_config_pony(void);
102 static void parent_send_config_ca(void);
103 static void parent_sig_handler(int, short, void *);
104 static void forkmda(struct mproc *, uint64_t, struct deliver *);
105 static int parent_forward_open(char *, char *, uid_t, gid_t);
106 static struct child *child_add(pid_t, int, const char *);
107 static struct mproc *start_child(int, char **, char *);
108 static struct mproc *setup_peer(enum smtp_proc_type, pid_t, int);
109 static void setup_peers(struct mproc *, struct mproc *);
110 static void setup_done(struct mproc *);
111 static void setup_proc(void);
112 static struct mproc *setup_peer(enum smtp_proc_type, pid_t, int);
113 static int imsg_wait(struct imsgbuf *, struct imsg *, int);
114 
115 static void	offline_scan(int, short, void *);
116 static int	offline_add(char *, uid_t, gid_t);
117 static void	offline_done(void);
118 static int	offline_enqueue(char *, uid_t, gid_t);
119 
120 static void	purge_task(void);
121 static int	parent_auth_user(const char *, const char *);
122 static void	load_pki_tree(void);
123 static void	load_pki_keys(void);
124 
125 static void	fork_filter_processes(void);
126 static void	fork_filter_process(const char *, const char *, const char *, const char *, const char *, uint32_t);
127 
128 enum child_type {
129 	CHILD_DAEMON,
130 	CHILD_MDA,
131 	CHILD_PROCESSOR,
132 	CHILD_ENQUEUE_OFFLINE,
133 };
134 
135 struct child {
136 	pid_t			 pid;
137 	enum child_type		 type;
138 	const char		*title;
139 	int			 mda_out;
140 	uint64_t		 mda_id;
141 	char			*path;
142 	char			*cause;
143 };
144 
145 struct offline {
146 	TAILQ_ENTRY(offline)	 entry;
147 	uid_t			 uid;
148 	gid_t			 gid;
149 	char			*path;
150 };
151 
152 #define OFFLINE_READMAX		20
153 #define OFFLINE_QUEUEMAX	5
154 static size_t			offline_running = 0;
155 TAILQ_HEAD(, offline)		offline_q;
156 
157 static struct event		config_ev;
158 static struct event		offline_ev;
159 static struct timeval		offline_timeout;
160 
161 static pid_t			purge_pid = -1;
162 
163 extern char	**environ;
164 void		(*imsg_callback)(struct mproc *, struct imsg *);
165 
166 enum smtp_proc_type	smtpd_process;
167 
168 struct smtpd	*env = NULL;
169 
170 struct mproc	*p_control = NULL;
171 struct mproc	*p_lka = NULL;
172 struct mproc	*p_parent = NULL;
173 struct mproc	*p_queue = NULL;
174 struct mproc	*p_scheduler = NULL;
175 struct mproc	*p_pony = NULL;
176 struct mproc	*p_ca = NULL;
177 
178 const char	*backend_queue = "fs";
179 const char	*backend_scheduler = "ramqueue";
180 const char	*backend_stat = "ram";
181 
182 int	profiling = 0;
183 int	debug = 0;
184 int	foreground = 0;
185 int	control_socket = -1;
186 
187 struct tree	 children;
188 
189 /* Saved arguments to main(). */
190 char **saved_argv;
191 int saved_argc;
192 
193 static void
parent_imsg(struct mproc * p,struct imsg * imsg)194 parent_imsg(struct mproc *p, struct imsg *imsg)
195 {
196 	struct forward_req	*fwreq;
197 	struct filter_proc	*processor;
198 	struct deliver		 deliver;
199 	struct child		*c;
200 	struct msg		 m;
201 	const void		*data;
202 	const char		*username, *password, *cause, *procname;
203 	uint64_t		 reqid;
204 	size_t			 sz;
205 	void			*i;
206 	int			 fd, n, v, ret;
207 
208 	if (imsg == NULL)
209 		fatalx("process %s socket closed", p->name);
210 
211 	switch (imsg->hdr.type) {
212 	case IMSG_LKA_OPEN_FORWARD:
213 		CHECK_IMSG_DATA_SIZE(imsg, sizeof *fwreq);
214 		fwreq = imsg->data;
215 		fd = parent_forward_open(fwreq->user, fwreq->directory,
216 		    fwreq->uid, fwreq->gid);
217 		fwreq->status = 0;
218 		if (fd == -1 && errno != ENOENT) {
219 			if (errno == EAGAIN)
220 				fwreq->status = -1;
221 		}
222 		else
223 			fwreq->status = 1;
224 		m_compose(p, IMSG_LKA_OPEN_FORWARD, 0, 0, fd,
225 		    fwreq, sizeof *fwreq);
226 		return;
227 
228 	case IMSG_LKA_AUTHENTICATE:
229 		/*
230 		 * If we reached here, it means we want root to lookup
231 		 * system user.
232 		 */
233 		m_msg(&m, imsg);
234 		m_get_id(&m, &reqid);
235 		m_get_string(&m, &username);
236 		m_get_string(&m, &password);
237 		m_end(&m);
238 
239 		ret = parent_auth_user(username, password);
240 
241 		m_create(p, IMSG_LKA_AUTHENTICATE, 0, 0, -1);
242 		m_add_id(p, reqid);
243 		m_add_int(p, ret);
244 		m_close(p);
245 		return;
246 
247 	case IMSG_MDA_FORK:
248 		m_msg(&m, imsg);
249 		m_get_id(&m, &reqid);
250 		m_get_data(&m, &data, &sz);
251 		m_end(&m);
252 		if (sz != sizeof(deliver))
253 			fatalx("expected deliver");
254 		memmove(&deliver, data, sz);
255 		forkmda(p, reqid, &deliver);
256 		return;
257 
258 	case IMSG_MDA_KILL:
259 		m_msg(&m, imsg);
260 		m_get_id(&m, &reqid);
261 		m_get_string(&m, &cause);
262 		m_end(&m);
263 
264 		i = NULL;
265 		while ((n = tree_iter(&children, &i, NULL, (void**)&c)))
266 			if (c->type == CHILD_MDA &&
267 			    c->mda_id == reqid &&
268 			    c->cause == NULL)
269 				break;
270 		if (!n) {
271 			log_debug("debug: smtpd: "
272 			    "kill request: proc not found");
273 			return;
274 		}
275 
276 		c->cause = xstrdup(cause);
277 		log_debug("debug: smtpd: kill requested for %u: %s",
278 		    c->pid, c->cause);
279 		kill(c->pid, SIGTERM);
280 		return;
281 
282 	case IMSG_CTL_VERBOSE:
283 		m_msg(&m, imsg);
284 		m_get_int(&m, &v);
285 		m_end(&m);
286 		log_trace_verbose(v);
287 		return;
288 
289 	case IMSG_CTL_PROFILE:
290 		m_msg(&m, imsg);
291 		m_get_int(&m, &v);
292 		m_end(&m);
293 		profiling = v;
294 		return;
295 
296 	case IMSG_LKA_PROCESSOR_ERRFD:
297 		m_msg(&m, imsg);
298 		m_get_string(&m, &procname);
299 		m_end(&m);
300 
301 		processor = dict_xget(env->sc_filter_processes_dict, procname);
302 		m_create(p_lka, IMSG_LKA_PROCESSOR_ERRFD, 0, 0, processor->errfd);
303 		m_add_string(p_lka, procname);
304 		m_close(p_lka);
305 		return;
306 	}
307 
308 	errx(1, "parent_imsg: unexpected %s imsg from %s",
309 	    imsg_to_str(imsg->hdr.type), proc_title(p->proc));
310 }
311 
312 static void
usage(void)313 usage(void)
314 {
315 	extern char	*__progname;
316 
317 	fprintf(stderr, "usage: %s [-dFhnv] [-D macro=value] "
318 	    "[-f file] [-P system] [-T trace]\n", __progname);
319 	exit(1);
320 }
321 
322 static void
parent_shutdown(void)323 parent_shutdown(void)
324 {
325 	pid_t pid;
326 
327 	mproc_clear(p_ca);
328 	mproc_clear(p_pony);
329 	mproc_clear(p_control);
330 	mproc_clear(p_lka);
331 	mproc_clear(p_scheduler);
332 	mproc_clear(p_queue);
333 
334 	do {
335 		pid = waitpid(WAIT_MYPGRP, NULL, 0);
336 	} while (pid != -1 || (pid == -1 && errno == EINTR));
337 
338 	unlink(SMTPD_SOCKET);
339 
340 	log_info("Exiting");
341 	exit(0);
342 }
343 
344 static void
parent_send_config(int fd,short event,void * p)345 parent_send_config(int fd, short event, void *p)
346 {
347 	parent_send_config_lka();
348 	parent_send_config_pony();
349 	parent_send_config_ca();
350 	purge_config(PURGE_PKI);
351 }
352 
353 static void
parent_send_config_pony(void)354 parent_send_config_pony(void)
355 {
356 	log_debug("debug: parent_send_config: configuring pony process");
357 	m_compose(p_pony, IMSG_CONF_START, 0, 0, -1, NULL, 0);
358 	m_compose(p_pony, IMSG_CONF_END, 0, 0, -1, NULL, 0);
359 }
360 
361 void
parent_send_config_lka()362 parent_send_config_lka()
363 {
364 	log_debug("debug: parent_send_config_ruleset: reloading");
365 	m_compose(p_lka, IMSG_CONF_START, 0, 0, -1, NULL, 0);
366 	m_compose(p_lka, IMSG_CONF_END, 0, 0, -1, NULL, 0);
367 }
368 
369 static void
parent_send_config_ca(void)370 parent_send_config_ca(void)
371 {
372 	log_debug("debug: parent_send_config: configuring ca process");
373 	m_compose(p_ca, IMSG_CONF_START, 0, 0, -1, NULL, 0);
374 	m_compose(p_ca, IMSG_CONF_END, 0, 0, -1, NULL, 0);
375 }
376 
377 static void
parent_sig_handler(int sig,short event,void * p)378 parent_sig_handler(int sig, short event, void *p)
379 {
380 	struct child	*child;
381 	int		 status, fail;
382 	pid_t		 pid;
383 	char		*cause;
384 
385 	switch (sig) {
386 	case SIGTERM:
387 	case SIGINT:
388 		log_debug("debug: got signal %d", sig);
389 		parent_shutdown();
390 		/* NOT REACHED */
391 
392 	case SIGCHLD:
393 		do {
394 			int len;
395 			enum mda_resp_status mda_status;
396 			int mda_sysexit;
397 
398 			pid = waitpid(-1, &status, WNOHANG);
399 			if (pid <= 0)
400 				continue;
401 
402 			fail = 0;
403 			if (WIFSIGNALED(status)) {
404 				fail = 1;
405 				len = asprintf(&cause, "terminated; signal %d",
406 				    WTERMSIG(status));
407 				mda_status = MDA_TEMPFAIL;
408 				mda_sysexit = 0;
409 			} else if (WIFEXITED(status)) {
410 				if (WEXITSTATUS(status) != 0) {
411 					fail = 1;
412 					len = asprintf(&cause,
413 					    "exited abnormally");
414 					mda_sysexit = WEXITSTATUS(status);
415 					if (mda_sysexit == EX_OSERR ||
416 					    mda_sysexit == EX_TEMPFAIL)
417 						mda_status = MDA_TEMPFAIL;
418 					else
419 						mda_status = MDA_PERMFAIL;
420 				} else {
421 					len = asprintf(&cause, "exited okay");
422 					mda_status = MDA_OK;
423 					mda_sysexit = 0;
424 				}
425 			} else
426 				/* WIFSTOPPED or WIFCONTINUED */
427 				continue;
428 
429 			if (len == -1)
430 				fatal("asprintf");
431 
432 			if (pid == purge_pid)
433 				purge_pid = -1;
434 
435 			child = tree_pop(&children, pid);
436 			if (child == NULL)
437 				goto skip;
438 
439 			switch (child->type) {
440 			case CHILD_PROCESSOR:
441 				if (fail) {
442 					log_warnx("warn: lost processor: %s %s",
443 					    child->title, cause);
444 					parent_shutdown();
445 				}
446 				break;
447 
448 			case CHILD_DAEMON:
449 				if (fail)
450 					log_warnx("warn: lost child: %s %s",
451 					    child->title, cause);
452 				break;
453 
454 			case CHILD_MDA:
455 				if (WIFSIGNALED(status) &&
456 				    WTERMSIG(status) == SIGALRM) {
457 					char *tmp;
458 					if (asprintf(&tmp,
459 					    "terminated; timeout") != -1) {
460 						free(cause);
461 						cause = tmp;
462 					}
463 				}
464 				else if (child->cause &&
465 				    WIFSIGNALED(status) &&
466 				    WTERMSIG(status) == SIGTERM) {
467 					free(cause);
468 					cause = child->cause;
469 					child->cause = NULL;
470 				}
471 				free(child->cause);
472 				log_debug("debug: smtpd: mda process done "
473 				    "for session %016"PRIx64 ": %s",
474 				    child->mda_id, cause);
475 
476 				m_create(p_pony, IMSG_MDA_DONE, 0, 0,
477 				    child->mda_out);
478 				m_add_id(p_pony, child->mda_id);
479 				m_add_int(p_pony, mda_status);
480 				m_add_int(p_pony, mda_sysexit);
481 				m_add_string(p_pony, cause);
482 				m_close(p_pony);
483 
484 				break;
485 
486 			case CHILD_ENQUEUE_OFFLINE:
487 				if (fail)
488 					log_warnx("warn: smtpd: "
489 					    "couldn't enqueue offline "
490 					    "message %s; smtpctl %s",
491 					    child->path, cause);
492 				else
493 					unlink(child->path);
494 				free(child->path);
495 				offline_done();
496 				break;
497 
498 			default:
499 				fatalx("smtpd: unexpected child type");
500 			}
501 			free(child);
502     skip:
503 			free(cause);
504 		} while (pid > 0 || (pid == -1 && errno == EINTR));
505 
506 		break;
507 	default:
508 		fatalx("smtpd: unexpected signal");
509 	}
510 }
511 
512 int
main(int argc,char * argv[])513 main(int argc, char *argv[])
514 {
515 	int		 c, i;
516 	int		 opts, flags;
517 	const char	*conffile = CONF_FILE;
518 	int		 save_argc = argc;
519 	char		**save_argv = argv;
520 	char		*rexec = NULL;
521 	struct smtpd	*conf;
522 
523 #ifdef NEED_PROGNAME
524 	__progname = get_progname(argv[0]);
525 #endif
526 	__progname = xstrdup(__progname);
527 
528 	/* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
529 	saved_argc = argc;
530 	saved_argv = xcalloc(argc + 1, sizeof(*saved_argv));
531 	for (i = 0; i < argc; i++)
532 		saved_argv[i] = xstrdup(argv[i]);
533 	saved_argv[i] = NULL;
534 
535 #ifdef NEED_SETPROCTITLE
536 	/* Prepare for later setproctitle emulation */
537 	compat_init_setproctitle(argc, argv);
538 	argv = saved_argv;
539 #endif
540 
541 	/* this is to work around GNU getopt + portable setproctitle() fuckery */
542 	save_argc = saved_argc;
543 	save_argv = saved_argv;
544 
545 	if ((conf = config_default()) == NULL)
546 		err(1, NULL);
547 
548 	env = conf;
549 
550 	flags = 0;
551 	opts = 0;
552 	debug = 0;
553 	tracing = 0;
554 
555 	log_init(1, LOG_MAIL);
556 
557 	TAILQ_INIT(&offline_q);
558 
559 	while ((c = getopt(argc, argv, "B:dD:hnP:f:FT:vx:")) != -1) {
560 		switch (c) {
561 		case 'B':
562 			if (strstr(optarg, "queue=") == optarg)
563 				backend_queue = strchr(optarg, '=') + 1;
564 			else if (strstr(optarg, "scheduler=") == optarg)
565 				backend_scheduler = strchr(optarg, '=') + 1;
566 			else if (strstr(optarg, "stat=") == optarg)
567 				backend_stat = strchr(optarg, '=') + 1;
568 			else
569 				log_warnx("warn: "
570 				    "invalid backend specifier %s",
571 				    optarg);
572 			break;
573 		case 'd':
574 			foreground = 1;
575 			foreground_log = 1;
576 			break;
577 		case 'D':
578 			if (cmdline_symset(optarg) < 0)
579 				log_warnx("warn: "
580 				    "could not parse macro definition %s",
581 				    optarg);
582 			break;
583 		case 'h':
584 			log_info("version: " SMTPD_NAME " " SMTPD_VERSION);
585 			usage();
586 			break;
587 		case 'n':
588 			debug = 2;
589 			opts |= SMTPD_OPT_NOACTION;
590 			break;
591 		case 'f':
592 			conffile = optarg;
593 			break;
594 		case 'F':
595 			foreground = 1;
596 			break;
597 
598 		case 'T':
599 			if (!strcmp(optarg, "imsg"))
600 				tracing |= TRACE_IMSG;
601 			else if (!strcmp(optarg, "io"))
602 				tracing |= TRACE_IO;
603 			else if (!strcmp(optarg, "smtp"))
604 				tracing |= TRACE_SMTP;
605 			else if (!strcmp(optarg, "filters"))
606 				tracing |= TRACE_FILTERS;
607 			else if (!strcmp(optarg, "mta") ||
608 			    !strcmp(optarg, "transfer"))
609 				tracing |= TRACE_MTA;
610 			else if (!strcmp(optarg, "bounce") ||
611 			    !strcmp(optarg, "bounces"))
612 				tracing |= TRACE_BOUNCE;
613 			else if (!strcmp(optarg, "scheduler"))
614 				tracing |= TRACE_SCHEDULER;
615 			else if (!strcmp(optarg, "lookup"))
616 				tracing |= TRACE_LOOKUP;
617 			else if (!strcmp(optarg, "stat") ||
618 			    !strcmp(optarg, "stats"))
619 				tracing |= TRACE_STAT;
620 			else if (!strcmp(optarg, "rules"))
621 				tracing |= TRACE_RULES;
622 			else if (!strcmp(optarg, "mproc"))
623 				tracing |= TRACE_MPROC;
624 			else if (!strcmp(optarg, "expand"))
625 				tracing |= TRACE_EXPAND;
626 			else if (!strcmp(optarg, "table") ||
627 			    !strcmp(optarg, "tables"))
628 				tracing |= TRACE_TABLES;
629 			else if (!strcmp(optarg, "queue"))
630 				tracing |= TRACE_QUEUE;
631 			else if (!strcmp(optarg, "all"))
632 				tracing |= ~TRACE_DEBUG;
633 			else if (!strcmp(optarg, "profstat"))
634 				profiling |= PROFILE_TOSTAT;
635 			else if (!strcmp(optarg, "profile-imsg"))
636 				profiling |= PROFILE_IMSG;
637 			else if (!strcmp(optarg, "profile-queue"))
638 				profiling |= PROFILE_QUEUE;
639 			else
640 				log_warnx("warn: unknown trace flag \"%s\"",
641 				    optarg);
642 			break;
643 		case 'P':
644 			if (!strcmp(optarg, "smtp"))
645 				flags |= SMTPD_SMTP_PAUSED;
646 			else if (!strcmp(optarg, "mta"))
647 				flags |= SMTPD_MTA_PAUSED;
648 			else if (!strcmp(optarg, "mda"))
649 				flags |= SMTPD_MDA_PAUSED;
650 			break;
651 		case 'v':
652 			tracing |=  TRACE_DEBUG;
653 			break;
654 		case 'x':
655 			rexec = optarg;
656 			break;
657 		default:
658 			usage();
659 		}
660 	}
661 
662 	argv += optind;
663 	argc -= optind;
664 
665 	if (argc || *argv)
666 		usage();
667 
668 	env->sc_opts |= opts;
669 
670 	ssl_init();
671 
672 	if (parse_config(conf, conffile, opts))
673 		exit(1);
674 
675 	if (RAND_status() != 1)
676 		errx(1, "PRNG is not seeded");
677 
678 	if (strlcpy(env->sc_conffile, conffile, PATH_MAX)
679 	    >= PATH_MAX)
680 		errx(1, "config file exceeds PATH_MAX");
681 
682 	if (env->sc_opts & SMTPD_OPT_NOACTION) {
683 		if (env->sc_queue_key &&
684 		    crypto_setup(env->sc_queue_key,
685 		    strlen(env->sc_queue_key)) == 0) {
686 			fatalx("crypto_setup:"
687 			    "invalid key for queue encryption");
688 		}
689 		load_pki_tree();
690 		load_pki_keys();
691 		fprintf(stderr, "configuration OK\n");
692 		exit(0);
693 	}
694 
695 	env->sc_flags |= flags;
696 
697 	/* check for root privileges */
698 	if (geteuid())
699 		errx(1, "need root privileges");
700 
701 	log_init(foreground_log, LOG_MAIL);
702 	log_trace_verbose(tracing);
703 	load_pki_tree();
704 	load_pki_keys();
705 
706 	log_debug("debug: using \"%s\" queue backend", backend_queue);
707 	log_debug("debug: using \"%s\" scheduler backend", backend_scheduler);
708 	log_debug("debug: using \"%s\" stat backend", backend_stat);
709 
710 	if (env->sc_hostname[0] == '\0')
711 		errx(1, "machine does not have a hostname set");
712 	env->sc_uptime = time(NULL);
713 
714 	if (rexec == NULL) {
715 		smtpd_process = PROC_PARENT;
716 
717 		if (env->sc_queue_flags & QUEUE_ENCRYPTION) {
718 			if (env->sc_queue_key == NULL) {
719 				char	*password;
720 
721 				password = getpass("queue key: ");
722 				if (password == NULL)
723 					err(1, "getpass");
724 
725 				env->sc_queue_key = strdup(password);
726 				explicit_bzero(password, strlen(password));
727 				if (env->sc_queue_key == NULL)
728 					err(1, "strdup");
729 			}
730 			else {
731 				char   *buf = NULL;
732 				size_t	sz = 0;
733 				ssize_t	len;
734 
735 				if (strcasecmp(env->sc_queue_key, "stdin") == 0) {
736 					if ((len = getline(&buf, &sz, stdin)) == -1)
737 						err(1, "getline");
738 					if (buf[len - 1] == '\n')
739 						buf[len - 1] = '\0';
740 					env->sc_queue_key = buf;
741 				}
742 			}
743 		}
744 
745 		log_info("info: %s %s starting", SMTPD_NAME, SMTPD_VERSION);
746 
747 		if (!foreground)
748 			if (daemon(0, 0) == -1)
749 				err(1, "failed to daemonize");
750 
751 		/* setup all processes */
752 
753 		p_ca = start_child(save_argc, save_argv, "ca");
754 		p_ca->proc = PROC_CA;
755 
756 		p_control = start_child(save_argc, save_argv, "control");
757 		p_control->proc = PROC_CONTROL;
758 
759 		p_lka = start_child(save_argc, save_argv, "lka");
760 		p_lka->proc = PROC_LKA;
761 
762 		p_pony = start_child(save_argc, save_argv, "pony");
763 		p_pony->proc = PROC_PONY;
764 
765 		p_queue = start_child(save_argc, save_argv, "queue");
766 		p_queue->proc = PROC_QUEUE;
767 
768 		p_scheduler = start_child(save_argc, save_argv, "scheduler");
769 		p_scheduler->proc = PROC_SCHEDULER;
770 
771 		setup_peers(p_control, p_ca);
772 		setup_peers(p_control, p_lka);
773 		setup_peers(p_control, p_pony);
774 		setup_peers(p_control, p_queue);
775 		setup_peers(p_control, p_scheduler);
776 		setup_peers(p_pony, p_ca);
777 		setup_peers(p_pony, p_lka);
778 		setup_peers(p_pony, p_queue);
779 		setup_peers(p_queue, p_lka);
780 		setup_peers(p_queue, p_scheduler);
781 
782 		if (env->sc_queue_key) {
783 			if (imsg_compose(&p_queue->imsgbuf, IMSG_SETUP_KEY, 0,
784 			    0, -1, env->sc_queue_key, strlen(env->sc_queue_key)
785 			    + 1) == -1)
786 				fatal("imsg_compose");
787 			if (imsg_flush(&p_queue->imsgbuf) == -1)
788 				fatal("imsg_flush");
789 		}
790 
791 		setup_done(p_ca);
792 		setup_done(p_control);
793 		setup_done(p_lka);
794 		setup_done(p_pony);
795 		setup_done(p_queue);
796 		setup_done(p_scheduler);
797 
798 		log_debug("smtpd: setup done");
799 
800 		return smtpd();
801 	}
802 
803 	if (!strcmp(rexec, "ca")) {
804 		smtpd_process = PROC_CA;
805 		setup_proc();
806 
807 		return ca();
808 	}
809 
810 	else if (!strcmp(rexec, "control")) {
811 		smtpd_process = PROC_CONTROL;
812 		setup_proc();
813 
814 		/* the control socket ensures that only one smtpd instance is running */
815 		control_socket = control_create_socket();
816 
817 		env->sc_stat = stat_backend_lookup(backend_stat);
818 		if (env->sc_stat == NULL)
819 			errx(1, "could not find stat backend \"%s\"", backend_stat);
820 
821 		return control();
822 	}
823 
824 	else if (!strcmp(rexec, "lka")) {
825 		smtpd_process = PROC_LKA;
826 		setup_proc();
827 
828 		return lka();
829 	}
830 
831 	else if (!strcmp(rexec, "pony")) {
832 		smtpd_process = PROC_PONY;
833 		setup_proc();
834 
835 		return pony();
836 	}
837 
838 	else if (!strcmp(rexec, "queue")) {
839 		smtpd_process = PROC_QUEUE;
840 		setup_proc();
841 
842 		if (env->sc_queue_flags & QUEUE_COMPRESSION)
843 			env->sc_comp = compress_backend_lookup("gzip");
844 
845 		if (!queue_init(backend_queue, 1))
846 			errx(1, "could not initialize queue backend");
847 
848 		return queue();
849 	}
850 
851 	else if (!strcmp(rexec, "scheduler")) {
852 		smtpd_process = PROC_SCHEDULER;
853 		setup_proc();
854 
855 		for (i = 0; i < MAX_BOUNCE_WARN; i++) {
856 			if (env->sc_bounce_warn[i] == 0)
857 				break;
858 			log_debug("debug: bounce warning after %s",
859 			    duration_to_text(env->sc_bounce_warn[i]));
860 		}
861 
862 		return scheduler();
863 	}
864 
865 	fatalx("bad rexec: %s", rexec);
866 
867 	return (1);
868 }
869 
870 static struct mproc *
start_child(int save_argc,char ** save_argv,char * rexec)871 start_child(int save_argc, char **save_argv, char *rexec)
872 {
873 	struct mproc *p;
874 	char *argv[SMTPD_MAXARG];
875 	int sp[2], argc = 0;
876 	pid_t pid;
877 
878 	if (save_argc >= SMTPD_MAXARG - 2)
879 		fatalx("too many arguments");
880 
881 	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, sp) == -1)
882 		fatal("socketpair");
883 
884 	io_set_nonblocking(sp[0]);
885 	io_set_nonblocking(sp[1]);
886 
887 	switch (pid = fork()) {
888 	case -1:
889 		fatal("%s: fork", save_argv[0]);
890 	case 0:
891 		break;
892 	default:
893 		close(sp[0]);
894 		p = calloc(1, sizeof(*p));
895 		if (p == NULL)
896 			fatal("calloc");
897 		if((p->name = strdup(rexec)) == NULL)
898 			fatal("strdup");
899 		mproc_init(p, sp[1]);
900 		p->pid = pid;
901 		p->handler = parent_imsg;
902 		return p;
903 	}
904 
905 	if (sp[0] != 3) {
906 		if (dup2(sp[0], 3) == -1)
907 			fatal("%s: dup2", rexec);
908 	} else if (fcntl(sp[0], F_SETFD, 0) == -1)
909 		fatal("%s: fcntl", rexec);
910 
911 	xclosefrom(4);
912 
913 	for (argc = 0; argc < save_argc; argc++)
914 		argv[argc] = save_argv[argc];
915 	argv[argc++] = "-x";
916 	argv[argc++] = rexec;
917 	argv[argc++] = NULL;
918 
919 	execvp(argv[0], argv);
920 	fatal("%s: execvp", rexec);
921 }
922 
923 static void
setup_peers(struct mproc * a,struct mproc * b)924 setup_peers(struct mproc *a, struct mproc *b)
925 {
926 	int sp[2];
927 
928 	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, sp) == -1)
929 		fatal("socketpair");
930 
931 	io_set_nonblocking(sp[0]);
932 	io_set_nonblocking(sp[1]);
933 
934 	if (imsg_compose(&a->imsgbuf, IMSG_SETUP_PEER, b->proc, b->pid, sp[0],
935 	    NULL, 0) == -1)
936 		fatal("imsg_compose");
937 	if (imsg_flush(&a->imsgbuf) == -1)
938 		fatal("imsg_flush");
939 
940 	if (imsg_compose(&b->imsgbuf, IMSG_SETUP_PEER, a->proc, a->pid, sp[1],
941 	    NULL, 0) == -1)
942 		fatal("imsg_compose");
943 	if (imsg_flush(&b->imsgbuf) == -1)
944 		fatal("imsg_flush");
945 }
946 
947 static void
setup_done(struct mproc * p)948 setup_done(struct mproc *p)
949 {
950 	struct imsg imsg;
951 
952 	if (imsg_compose(&p->imsgbuf, IMSG_SETUP_DONE, 0, 0, -1, NULL, 0) == -1)
953 		fatal("imsg_compose");
954 	if (imsg_flush(&p->imsgbuf) == -1)
955 		fatal("imsg_flush");
956 
957 	if (imsg_wait(&p->imsgbuf, &imsg, 10000) == -1)
958 		fatal("imsg_wait");
959 
960 	if (imsg.hdr.type != IMSG_SETUP_DONE)
961 		fatalx("expect IMSG_SETUP_DONE");
962 
963 	log_debug("setup_done: %s[%d] done", p->name, p->pid);
964 
965 	imsg_free(&imsg);
966 }
967 
968 static void
setup_proc(void)969 setup_proc(void)
970 {
971 	struct imsgbuf *ibuf;
972 	struct imsg imsg;
973         int setup = 1;
974 
975 	log_procinit(proc_title(smtpd_process));
976 
977 	p_parent = calloc(1, sizeof(*p_parent));
978 	if (p_parent == NULL)
979 		fatal("calloc");
980 	if((p_parent->name = strdup("parent")) == NULL)
981 		fatal("strdup");
982 	p_parent->proc = PROC_PARENT;
983 	p_parent->handler = imsg_dispatch;
984 	mproc_init(p_parent, 3);
985 
986 	ibuf = &p_parent->imsgbuf;
987 
988 	while (setup) {
989 		if (imsg_wait(ibuf, &imsg, 10000) == -1)
990 			fatal("imsg_wait");
991 
992 		switch (imsg.hdr.type) {
993 		case IMSG_SETUP_KEY:
994 			env->sc_queue_key = strdup(imsg.data);
995 			break;
996 		case IMSG_SETUP_PEER:
997 			setup_peer(imsg.hdr.peerid, imsg.hdr.pid, imsg.fd);
998 			break;
999 		case IMSG_SETUP_DONE:
1000 			setup = 0;
1001 			break;
1002 		default:
1003 			fatal("bad imsg %d", imsg.hdr.type);
1004 		}
1005 		imsg_free(&imsg);
1006 	}
1007 
1008 	if (imsg_compose(ibuf, IMSG_SETUP_DONE, 0, 0, -1, NULL, 0) == -1)
1009 		fatal("imsg_compose");
1010 
1011 	if (imsg_flush(ibuf) == -1)
1012 		fatal("imsg_flush");
1013 
1014 	log_debug("setup_proc: %s done", proc_title(smtpd_process));
1015 }
1016 
1017 static struct mproc *
setup_peer(enum smtp_proc_type proc,pid_t pid,int sock)1018 setup_peer(enum smtp_proc_type proc, pid_t pid, int sock)
1019 {
1020 	struct mproc *p, **pp;
1021 
1022 	log_debug("setup_peer: %s -> %s[%u] fd=%d", proc_title(smtpd_process),
1023 	    proc_title(proc), pid, sock);
1024 
1025 	if (sock == -1)
1026 		fatalx("peer socket not received");
1027 
1028 	switch (proc) {
1029 	case PROC_LKA:
1030 		pp = &p_lka;
1031 		break;
1032 	case PROC_QUEUE:
1033 		pp = &p_queue;
1034 		break;
1035 	case PROC_CONTROL:
1036 		pp = &p_control;
1037 		break;
1038 	case PROC_SCHEDULER:
1039 		pp = &p_scheduler;
1040 		break;
1041 	case PROC_PONY:
1042 		pp = &p_pony;
1043 		break;
1044 	case PROC_CA:
1045 		pp = &p_ca;
1046 		break;
1047 	default:
1048 		fatalx("unknown peer");
1049 	}
1050 
1051 	if (*pp)
1052 		fatalx("peer already set");
1053 
1054 	p = calloc(1, sizeof(*p));
1055 	if (p == NULL)
1056 		fatal("calloc");
1057 	if((p->name = strdup(proc_title(proc))) == NULL)
1058 		fatal("strdup");
1059 	mproc_init(p, sock);
1060 	p->pid = pid;
1061 	p->proc = proc;
1062 	p->handler = imsg_dispatch;
1063 
1064 	*pp = p;
1065 
1066 	return p;
1067 }
1068 
1069 static int
imsg_wait(struct imsgbuf * ibuf,struct imsg * imsg,int timeout)1070 imsg_wait(struct imsgbuf *ibuf, struct imsg *imsg, int timeout)
1071 {
1072 	struct pollfd pfd[1];
1073 	ssize_t n;
1074 
1075 	pfd[0].fd = ibuf->fd;
1076 	pfd[0].events = POLLIN;
1077 
1078 	while (1) {
1079 		if ((n = imsg_get(ibuf, imsg)) == -1)
1080 			return -1;
1081 		if (n)
1082 			return 1;
1083 
1084 		n = poll(pfd, 1, timeout);
1085 		if (n == -1)
1086 			return -1;
1087 		if (n == 0) {
1088 			errno = ETIMEDOUT;
1089 			return -1;
1090 		}
1091 
1092 		if (((n = imsg_read(ibuf)) == -1 && errno != EAGAIN) || n == 0)
1093 			return -1;
1094 	}
1095 }
1096 
1097 int
smtpd(void)1098 smtpd(void) {
1099 	struct event	 ev_sigint;
1100 	struct event	 ev_sigterm;
1101 	struct event	 ev_sigchld;
1102 	struct event	 ev_sighup;
1103 	struct timeval	 tv;
1104 
1105 	imsg_callback = parent_imsg;
1106 
1107 	tree_init(&children);
1108 
1109 	child_add(p_queue->pid, CHILD_DAEMON, proc_title(PROC_QUEUE));
1110 	child_add(p_control->pid, CHILD_DAEMON, proc_title(PROC_CONTROL));
1111 	child_add(p_lka->pid, CHILD_DAEMON, proc_title(PROC_LKA));
1112 	child_add(p_scheduler->pid, CHILD_DAEMON, proc_title(PROC_SCHEDULER));
1113 	child_add(p_pony->pid, CHILD_DAEMON, proc_title(PROC_PONY));
1114 	child_add(p_ca->pid, CHILD_DAEMON, proc_title(PROC_CA));
1115 
1116 	event_init();
1117 
1118 	signal_set(&ev_sigint, SIGINT, parent_sig_handler, NULL);
1119 	signal_set(&ev_sigterm, SIGTERM, parent_sig_handler, NULL);
1120 	signal_set(&ev_sigchld, SIGCHLD, parent_sig_handler, NULL);
1121 	signal_set(&ev_sighup, SIGHUP, parent_sig_handler, NULL);
1122 	signal_add(&ev_sigint, NULL);
1123 	signal_add(&ev_sigterm, NULL);
1124 	signal_add(&ev_sigchld, NULL);
1125 	signal_add(&ev_sighup, NULL);
1126 	signal(SIGPIPE, SIG_IGN);
1127 
1128 	config_peer(PROC_CONTROL);
1129 	config_peer(PROC_LKA);
1130 	config_peer(PROC_QUEUE);
1131 	config_peer(PROC_CA);
1132 	config_peer(PROC_PONY);
1133 
1134 	evtimer_set(&config_ev, parent_send_config, NULL);
1135 	memset(&tv, 0, sizeof(tv));
1136 	evtimer_add(&config_ev, &tv);
1137 
1138 	/* defer offline scanning for a second */
1139 	evtimer_set(&offline_ev, offline_scan, NULL);
1140 	offline_timeout.tv_sec = 1;
1141 	offline_timeout.tv_usec = 0;
1142 	evtimer_add(&offline_ev, &offline_timeout);
1143 
1144 	if (pidfile(NULL) < 0)
1145 		err(1, "pidfile");
1146 
1147 	fork_filter_processes();
1148 
1149 	purge_task();
1150 
1151 #if HAVE_PLEDGE
1152 	if (pledge("stdio rpath wpath cpath fattr tmppath "
1153 	    "getpw sendfd proc exec id inet chown unix", NULL) == -1)
1154 		err(1, "pledge");
1155 #endif
1156 
1157 	event_dispatch();
1158 	fatalx("exited event loop");
1159 
1160 	return (0);
1161 }
1162 
1163 static void
load_pki_tree(void)1164 load_pki_tree(void)
1165 {
1166 	struct pki	*pki;
1167 	struct ca	*sca;
1168 	const char	*k;
1169 	void		*iter_dict;
1170 
1171 	log_debug("debug: init ssl-tree");
1172 	iter_dict = NULL;
1173 	while (dict_iter(env->sc_pki_dict, &iter_dict, &k, (void **)&pki)) {
1174 		log_debug("info: loading pki information for %s", k);
1175 		if (pki->pki_cert_file == NULL)
1176 			fatalx("load_pki_tree: missing certificate file");
1177 		if (pki->pki_key_file == NULL)
1178 			fatalx("load_pki_tree: missing key file");
1179 
1180 		if (!ssl_load_certificate(pki, pki->pki_cert_file))
1181 			fatalx("load_pki_tree: failed to load certificate file");
1182 	}
1183 
1184 	log_debug("debug: init ca-tree");
1185 	iter_dict = NULL;
1186 	while (dict_iter(env->sc_ca_dict, &iter_dict, &k, (void **)&sca)) {
1187 		log_debug("info: loading CA information for %s", k);
1188 		if (!ssl_load_cafile(sca, sca->ca_cert_file))
1189 			fatalx("load_pki_tree: failed to load CA file");
1190 	}
1191 }
1192 
1193 void
load_pki_keys(void)1194 load_pki_keys(void)
1195 {
1196 	struct pki	*pki;
1197 	const char	*k;
1198 	void		*iter_dict;
1199 
1200 	log_debug("debug: init ssl-tree");
1201 	iter_dict = NULL;
1202 	while (dict_iter(env->sc_pki_dict, &iter_dict, &k, (void **)&pki)) {
1203 		log_debug("info: loading pki keys for %s", k);
1204 
1205 		if (!ssl_load_keyfile(pki, pki->pki_key_file, k))
1206 			fatalx("load_pki_keys: failed to load key file");
1207 	}
1208 }
1209 
1210 int
fork_proc_backend(const char * key,const char * conf,const char * procname)1211 fork_proc_backend(const char *key, const char *conf, const char *procname)
1212 {
1213 	pid_t		pid;
1214 	int		sp[2];
1215 	char		path[PATH_MAX];
1216 	char		name[PATH_MAX];
1217 	char		*arg;
1218 
1219 	if (strlcpy(name, conf, sizeof(name)) >= sizeof(name)) {
1220 		log_warnx("warn: %s-proc: conf too long", key);
1221 		return (0);
1222 	}
1223 
1224 	arg = strchr(name, ':');
1225 	if (arg)
1226 		*arg++ = '\0';
1227 
1228 	if (snprintf(path, sizeof(path), PATH_LIBEXEC "/%s-%s", key, name) >=
1229 	    (ssize_t)sizeof(path)) {
1230 		log_warn("warn: %s-proc: exec path too long", key);
1231 		return (-1);
1232 	}
1233 
1234 	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, sp) == -1) {
1235 		log_warn("warn: %s-proc: socketpair", key);
1236 		return (-1);
1237 	}
1238 
1239 	if ((pid = fork()) == -1) {
1240 		log_warn("warn: %s-proc: fork", key);
1241 		close(sp[0]);
1242 		close(sp[1]);
1243 		return (-1);
1244 	}
1245 
1246 	if (pid == 0) {
1247 		/* child process */
1248 		dup2(sp[0], STDIN_FILENO);
1249 		closefrom(STDERR_FILENO + 1);
1250 
1251 		if (procname == NULL)
1252 			procname = name;
1253 
1254 		execl(path, procname, arg, (char *)NULL);
1255 		err(1, "execl: %s", path);
1256 	}
1257 
1258 	/* parent process */
1259 	close(sp[0]);
1260 
1261 	return (sp[1]);
1262 }
1263 
1264 struct child *
child_add(pid_t pid,int type,const char * title)1265 child_add(pid_t pid, int type, const char *title)
1266 {
1267 	struct child	*child;
1268 
1269 	if ((child = calloc(1, sizeof(*child))) == NULL)
1270 		fatal("smtpd: child_add: calloc");
1271 
1272 	child->pid = pid;
1273 	child->type = type;
1274 	child->title = title;
1275 
1276 	tree_xset(&children, pid, child);
1277 
1278 	return (child);
1279 }
1280 
1281 static void
purge_task(void)1282 purge_task(void)
1283 {
1284 	struct passwd	*pw;
1285 	DIR		*d;
1286 	int		 n;
1287 	uid_t		 uid;
1288 	gid_t		 gid;
1289 
1290 	n = 0;
1291 	if ((d = opendir(PATH_SPOOL PATH_PURGE))) {
1292 		while (readdir(d) != NULL)
1293 			n++;
1294 		closedir(d);
1295 	} else
1296 		log_warn("warn: purge_task: opendir");
1297 
1298 	if (n > 2) {
1299 		switch (purge_pid = fork()) {
1300 		case -1:
1301 			log_warn("warn: purge_task: fork");
1302 			break;
1303 		case 0:
1304 			if ((pw = getpwnam(SMTPD_QUEUE_USER)) == NULL)
1305 				fatalx("unknown user " SMTPD_QUEUE_USER);
1306 			if (chroot(PATH_SPOOL PATH_PURGE) == -1)
1307 				fatal("smtpd: chroot");
1308 			if (chdir("/") == -1)
1309 				fatal("smtpd: chdir");
1310 			uid = pw->pw_uid;
1311 			gid = pw->pw_gid;
1312 			if (setgroups(1, &gid) ||
1313 			    setresgid(gid, gid, gid) ||
1314 			    setresuid(uid, uid, uid))
1315 				fatal("smtpd: cannot drop privileges");
1316 			rmtree("/", 1);
1317 			_exit(0);
1318 			break;
1319 		default:
1320 			break;
1321 		}
1322 	}
1323 }
1324 
1325 static void
fork_filter_processes(void)1326 fork_filter_processes(void)
1327 {
1328 	const char	*name;
1329 	void		*iter;
1330 	const char	*fn;
1331 	struct filter_config *fc;
1332 	struct filter_config *fcs;
1333 	struct filter_proc *fp;
1334 	size_t		 i;
1335 
1336 	/* For each filter chain, assign the registered subsystem to subfilters */
1337 	iter = NULL;
1338 	while (dict_iter(env->sc_filters_dict, &iter, (const char **)&fn, (void **)&fc)) {
1339 		if (fc->chain) {
1340 			for (i = 0; i < fc->chain_size; ++i) {
1341 				fcs = dict_xget(env->sc_filters_dict, fc->chain[i]);
1342 				fcs->filter_subsystem |= fc->filter_subsystem;
1343 			}
1344 		}
1345 	}
1346 
1347 	/* For each filter, assign the registered subsystem to underlying proc */
1348 	iter = NULL;
1349 	while (dict_iter(env->sc_filters_dict, &iter, (const char **)&fn, (void **)&fc)) {
1350 		if (fc->proc) {
1351 			fp = dict_xget(env->sc_filter_processes_dict, fc->proc);
1352 			fp->filter_subsystem |= fc->filter_subsystem;
1353 		}
1354 	}
1355 
1356 	iter = NULL;
1357 	while (dict_iter(env->sc_filter_processes_dict, &iter, &name, (void **)&fp))
1358 		fork_filter_process(name, fp->command, fp->user, fp->group, fp->chroot, fp->filter_subsystem);
1359 }
1360 
1361 static void
fork_filter_process(const char * name,const char * command,const char * user,const char * group,const char * chroot_path,uint32_t subsystems)1362 fork_filter_process(const char *name, const char *command, const char *user, const char *group, const char *chroot_path, uint32_t subsystems)
1363 {
1364 	pid_t		 pid;
1365 	struct filter_proc	*processor;
1366 	char		 buf;
1367 	int		 sp[2], errfd[2];
1368 	struct passwd	*pw;
1369 	struct group	*gr;
1370 	char		 exec[_POSIX_ARG_MAX];
1371 	int		 execr;
1372 
1373 	if (user == NULL)
1374 		user = SMTPD_USER;
1375 	if ((pw = getpwnam(user)) == NULL)
1376 		err(1, "getpwnam");
1377 
1378 	if (group) {
1379 		if ((gr = getgrnam(group)) == NULL)
1380 			err(1, "getgrnam");
1381 	}
1382 	else {
1383 		if ((gr = getgrgid(pw->pw_gid)) == NULL)
1384 			err(1, "getgrgid");
1385 	}
1386 
1387 	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, sp) == -1)
1388 		err(1, "socketpair");
1389 	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, errfd) == -1)
1390 		err(1, "socketpair");
1391 
1392 	if ((pid = fork()) == -1)
1393 		err(1, "fork");
1394 
1395 	/* parent passes the child fd over to lka */
1396 	if (pid > 0) {
1397 		processor = dict_xget(env->sc_filter_processes_dict, name);
1398 		processor->errfd = errfd[1];
1399 		child_add(pid, CHILD_PROCESSOR, name);
1400 		close(sp[0]);
1401 		close(errfd[0]);
1402 		m_create(p_lka, IMSG_LKA_PROCESSOR_FORK, 0, 0, sp[1]);
1403 		m_add_string(p_lka, name);
1404 		m_add_u32(p_lka, (uint32_t)subsystems);
1405 		m_close(p_lka);
1406 		return;
1407 	}
1408 
1409 	close(sp[1]);
1410 	close(errfd[1]);
1411 	dup2(sp[0], STDIN_FILENO);
1412 	dup2(sp[0], STDOUT_FILENO);
1413 	dup2(errfd[0], STDERR_FILENO);
1414 
1415 	if (chroot_path) {
1416 		if (chroot(chroot_path) != 0 || chdir("/") != 0)
1417 			err(1, "chroot: %s", chroot_path);
1418 	}
1419 
1420 	if (setgroups(1, &gr->gr_gid) ||
1421 	    setresgid(gr->gr_gid, gr->gr_gid, gr->gr_gid) ||
1422 	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
1423 		err(1, "fork_filter_process: cannot drop privileges");
1424 
1425 	xclosefrom(STDERR_FILENO + 1);
1426 
1427 	if (setsid() < 0)
1428 		err(1, "setsid");
1429 	if (signal(SIGPIPE, SIG_DFL) == SIG_ERR ||
1430 	    signal(SIGINT, SIG_DFL) == SIG_ERR ||
1431 	    signal(SIGTERM, SIG_DFL) == SIG_ERR ||
1432 	    signal(SIGCHLD, SIG_DFL) == SIG_ERR ||
1433 	    signal(SIGHUP, SIG_DFL) == SIG_ERR)
1434 		err(1, "signal");
1435 
1436 	if (command[0] == '/')
1437 		execr = snprintf(exec, sizeof(exec), "exec %s", command);
1438 	else
1439 		execr = snprintf(exec, sizeof(exec), "exec %s/%s",
1440 		    PATH_LIBEXEC, command);
1441 	if (execr >= (int) sizeof(exec))
1442 		errx(1, "%s: exec path too long", name);
1443 
1444 	/*
1445 	 * Wait for lka to acknowledge that it received the fd.
1446 	 * This prevents a race condition between the filter sending an error
1447 	 * message, and exiting and lka not being able to log it because of
1448 	 * SIGCHLD.
1449 	 * (Ab)use read to determine if the fd is installed; since stderr is
1450 	 * never going to be read from we can shutdown(2) the write-end in lka.
1451 	 */
1452 	if (read(STDERR_FILENO, &buf, 1) != 0)
1453 		errx(1, "lka didn't properly close write end of error socket");
1454 	if (system(exec) == -1)
1455 		err(1, NULL);
1456 
1457 	/* there's no successful exit from a processor */
1458 	_exit(1);
1459 }
1460 
1461 static void
forkmda(struct mproc * p,uint64_t id,struct deliver * deliver)1462 forkmda(struct mproc *p, uint64_t id, struct deliver *deliver)
1463 {
1464 	char		 ebuf[128], sfn[32];
1465 	struct dispatcher	*dsp;
1466 	struct child	*child;
1467 	pid_t		 pid;
1468 	int		 allout, pipefd[2];
1469 	struct passwd	*pw;
1470 	const char	*pw_name;
1471 	uid_t	pw_uid;
1472 	gid_t	pw_gid;
1473 	const char	*pw_dir;
1474 
1475 	dsp = dict_xget(env->sc_dispatchers, deliver->dispatcher);
1476 	if (dsp->type != DISPATCHER_LOCAL)
1477 		fatalx("non-local dispatcher called from forkmda()");
1478 
1479 	log_debug("debug: smtpd: forking mda for session %016"PRIx64
1480 	    ": %s as %s", id, deliver->userinfo.username,
1481 	    dsp->u.local.user ? dsp->u.local.user : deliver->userinfo.username);
1482 
1483 	if (dsp->u.local.user) {
1484 		if ((pw = getpwnam(dsp->u.local.user)) == NULL) {
1485 			(void)snprintf(ebuf, sizeof ebuf,
1486 			    "delivery user '%s' does not exist",
1487 			    dsp->u.local.user);
1488 			m_create(p_pony, IMSG_MDA_DONE, 0, 0, -1);
1489 			m_add_id(p_pony, id);
1490 			m_add_int(p_pony, MDA_PERMFAIL);
1491 			m_add_int(p_pony, EX_NOUSER);
1492 			m_add_string(p_pony, ebuf);
1493 			m_close(p_pony);
1494 			return;
1495 		}
1496 		pw_name = pw->pw_name;
1497 		pw_uid = pw->pw_uid;
1498 		pw_gid = pw->pw_gid;
1499 		pw_dir = pw->pw_dir;
1500 	}
1501 	else {
1502 		pw_name = deliver->userinfo.username;
1503 		pw_uid = deliver->userinfo.uid;
1504 		pw_gid = deliver->userinfo.gid;
1505 		pw_dir = deliver->userinfo.directory;
1506 	}
1507 
1508 	if (pw_uid == 0 && deliver->mda_exec[0]) {
1509 		pw_name = deliver->userinfo.username;
1510 		pw_uid = deliver->userinfo.uid;
1511 		pw_gid = deliver->userinfo.gid;
1512 		pw_dir = deliver->userinfo.directory;
1513 	}
1514 
1515 	if (pw_uid == 0 && !dsp->u.local.is_mbox) {
1516 		(void)snprintf(ebuf, sizeof ebuf, "not allowed to deliver to: %s",
1517 		    deliver->userinfo.username);
1518 		m_create(p_pony, IMSG_MDA_DONE, 0, 0, -1);
1519 		m_add_id(p_pony, id);
1520 		m_add_int(p_pony, MDA_PERMFAIL);
1521 		m_add_int(p_pony, EX_NOPERM);
1522 		m_add_string(p_pony, ebuf);
1523 		m_close(p_pony);
1524 		return;
1525 	}
1526 
1527 	if (pipe(pipefd) == -1) {
1528 		(void)snprintf(ebuf, sizeof ebuf, "pipe: %s", strerror(errno));
1529 		m_create(p_pony, IMSG_MDA_DONE, 0, 0, -1);
1530 		m_add_id(p_pony, id);
1531 		m_add_int(p_pony, MDA_TEMPFAIL);
1532 		m_add_int(p_pony, EX_OSERR);
1533 		m_add_string(p_pony, ebuf);
1534 		m_close(p_pony);
1535 		return;
1536 	}
1537 
1538 	/* prepare file which captures stdout and stderr */
1539 	(void)strlcpy(sfn, "/tmp/smtpd.out.XXXXXXXXXXX", sizeof(sfn));
1540 	allout = mkstemp(sfn);
1541 	if (allout == -1) {
1542 		(void)snprintf(ebuf, sizeof ebuf, "mkstemp: %s", strerror(errno));
1543 		m_create(p_pony, IMSG_MDA_DONE, 0, 0, -1);
1544 		m_add_id(p_pony, id);
1545 		m_add_int(p_pony, MDA_TEMPFAIL);
1546 		m_add_int(p_pony, EX_OSERR);
1547 		m_add_string(p_pony, ebuf);
1548 		m_close(p_pony);
1549 		close(pipefd[0]);
1550 		close(pipefd[1]);
1551 		return;
1552 	}
1553 	unlink(sfn);
1554 
1555 	pid = fork();
1556 	if (pid == -1) {
1557 		(void)snprintf(ebuf, sizeof ebuf, "fork: %s", strerror(errno));
1558 		m_create(p_pony, IMSG_MDA_DONE, 0, 0, -1);
1559 		m_add_id(p_pony, id);
1560 		m_add_int(p_pony, MDA_TEMPFAIL);
1561 		m_add_int(p_pony, EX_OSERR);
1562 		m_add_string(p_pony, ebuf);
1563 		m_close(p_pony);
1564 		close(pipefd[0]);
1565 		close(pipefd[1]);
1566 		close(allout);
1567 		return;
1568 	}
1569 
1570 	/* parent passes the child fd over to mda */
1571 	if (pid > 0) {
1572 		child = child_add(pid, CHILD_MDA, NULL);
1573 		child->mda_out = allout;
1574 		child->mda_id = id;
1575 		close(pipefd[0]);
1576 		m_create(p, IMSG_MDA_FORK, 0, 0, pipefd[1]);
1577 		m_add_id(p, id);
1578 		m_close(p);
1579 		return;
1580 	}
1581 
1582 	/* mbox helper, create mailbox before privdrop if it doesn't exist */
1583 	if (dsp->u.local.is_mbox)
1584 		mda_mbox_init(deliver);
1585 
1586 	if (chdir(pw_dir) == -1 && chdir("/") == -1)
1587 		err(1, "chdir");
1588 	if (setgroups(1, &pw_gid) ||
1589 	    setresgid(pw_gid, pw_gid, pw_gid) ||
1590 	    setresuid(pw_uid, pw_uid, pw_uid))
1591 		err(1, "forkmda: cannot drop privileges");
1592 	if (dup2(pipefd[0], STDIN_FILENO) == -1 ||
1593 	    dup2(allout, STDOUT_FILENO) == -1 ||
1594 	    dup2(allout, STDERR_FILENO) == -1)
1595 		err(1, "forkmda: dup2");
1596 	closefrom(STDERR_FILENO + 1);
1597 	if (setsid() < 0)
1598 		err(1, "setsid");
1599 	if (signal(SIGPIPE, SIG_DFL) == SIG_ERR ||
1600 	    signal(SIGINT, SIG_DFL) == SIG_ERR ||
1601 	    signal(SIGTERM, SIG_DFL) == SIG_ERR ||
1602 	    signal(SIGCHLD, SIG_DFL) == SIG_ERR ||
1603 	    signal(SIGHUP, SIG_DFL) == SIG_ERR)
1604 		err(1, "signal");
1605 
1606 	/* avoid hangs by setting 5m timeout */
1607 	alarm(300);
1608 
1609         if (dsp->u.local.is_mbox &&
1610             dsp->u.local.mda_wrapper == NULL &&
1611             deliver->mda_exec[0] == '\0')
1612                 mda_mbox(deliver);
1613         else
1614                 mda_unpriv(dsp, deliver, pw_name, pw_dir);
1615 }
1616 
1617 static void
offline_scan(int fd,short ev,void * arg)1618 offline_scan(int fd, short ev, void *arg)
1619 {
1620 	char		*path_argv[2];
1621 	FTS		*fts = arg;
1622 	FTSENT		*e;
1623 	int		 n = 0;
1624 
1625 	path_argv[0] = PATH_SPOOL PATH_OFFLINE;
1626 	path_argv[1] = NULL;
1627 
1628 	if (fts == NULL) {
1629 		log_debug("debug: smtpd: scanning offline queue...");
1630 		fts = fts_open(path_argv, FTS_PHYSICAL | FTS_NOCHDIR, NULL);
1631 		if (fts == NULL) {
1632 			log_warn("fts_open: %s", path_argv[0]);
1633 			return;
1634 		}
1635 	}
1636 
1637 	while ((e = fts_read(fts)) != NULL) {
1638 		if (e->fts_info != FTS_F)
1639 			continue;
1640 
1641 		/* offline files must be at depth 1 */
1642 		if (e->fts_level != 1)
1643 			continue;
1644 
1645 		/* offline file group must match parent directory group */
1646 		if (e->fts_statp->st_gid != e->fts_parent->fts_statp->st_gid)
1647 			continue;
1648 
1649 		if (e->fts_statp->st_size == 0) {
1650 			if (unlink(e->fts_accpath) == -1)
1651 				log_warnx("warn: smtpd: could not unlink %s", e->fts_accpath);
1652 			continue;
1653 		}
1654 
1655 		if (offline_add(e->fts_name, e->fts_statp->st_uid,
1656 		    e->fts_statp->st_gid)) {
1657 			log_warnx("warn: smtpd: "
1658 			    "could not add offline message %s", e->fts_name);
1659 			continue;
1660 		}
1661 
1662 		if ((n++) == OFFLINE_READMAX) {
1663 			evtimer_set(&offline_ev, offline_scan, fts);
1664 			offline_timeout.tv_sec = 0;
1665 			offline_timeout.tv_usec = 100000;
1666 			evtimer_add(&offline_ev, &offline_timeout);
1667 			return;
1668 		}
1669 	}
1670 
1671 	log_debug("debug: smtpd: offline scanning done");
1672 	fts_close(fts);
1673 }
1674 
1675 static int
offline_enqueue(char * name,uid_t uid,gid_t gid)1676 offline_enqueue(char *name, uid_t uid, gid_t gid)
1677 {
1678 	char		*path;
1679 	struct stat	 sb;
1680 	pid_t		 pid;
1681 	struct child	*child;
1682 	struct passwd	*pw;
1683 	int		 pathlen;
1684 
1685 	pathlen = asprintf(&path, "%s/%s", PATH_SPOOL PATH_OFFLINE, name);
1686 	if (pathlen == -1) {
1687 		log_warnx("warn: smtpd: asprintf");
1688 		return (-1);
1689 	}
1690 
1691 	if (pathlen >= PATH_MAX) {
1692 		log_warnx("warn: smtpd: pathname exceeds PATH_MAX");
1693 		free(path);
1694 		return (-1);
1695 	}
1696 
1697 	log_debug("debug: smtpd: enqueueing offline message %s", path);
1698 
1699 	if ((pid = fork()) == -1) {
1700 		log_warn("warn: smtpd: fork");
1701 		free(path);
1702 		return (-1);
1703 	}
1704 
1705 	if (pid == 0) {
1706 		char	*envp[2], *p = NULL, *tmp;
1707 		int	 fd;
1708 		FILE	*fp;
1709 		size_t	 sz = 0;
1710 		ssize_t	 len;
1711 		arglist	 args;
1712 
1713 		closefrom(STDERR_FILENO + 1);
1714 
1715 		memset(&args, 0, sizeof(args));
1716 
1717 		if ((fd = open(path, O_RDONLY|O_NOFOLLOW|O_NONBLOCK)) == -1) {
1718 			log_warn("warn: smtpd: open: %s", path);
1719 			_exit(1);
1720 		}
1721 
1722 		if (fstat(fd, &sb) == -1) {
1723 			log_warn("warn: smtpd: fstat: %s", path);
1724 			_exit(1);
1725 		}
1726 
1727 		if (!S_ISREG(sb.st_mode)) {
1728 			log_warnx("warn: smtpd: file %s (uid %d) not regular",
1729 			    path, sb.st_uid);
1730 			_exit(1);
1731 		}
1732 
1733 		if (sb.st_nlink != 1) {
1734 			log_warnx("warn: smtpd: file %s is hard-link", path);
1735 			_exit(1);
1736 		}
1737 
1738 		if (sb.st_uid != uid) {
1739 			log_warnx("warn: smtpd: file %s has bad uid %d",
1740 			    path, sb.st_uid);
1741 			_exit(1);
1742 		}
1743 
1744 		if (sb.st_gid != gid) {
1745 			log_warnx("warn: smtpd: file %s has bad gid %d",
1746 			    path, sb.st_gid);
1747 			_exit(1);
1748 		}
1749 
1750 		pw = getpwuid(sb.st_uid);
1751 		if (pw == NULL) {
1752 			log_warnx("warn: smtpd: getpwuid for uid %d failed",
1753 			    sb.st_uid);
1754 			_exit(1);
1755 		}
1756 
1757 		if (setgroups(1, &pw->pw_gid) ||
1758 		    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
1759 		    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
1760 			_exit(1);
1761 
1762 		if ((fp = fdopen(fd, "r")) == NULL)
1763 			_exit(1);
1764 
1765 		if (chdir(pw->pw_dir) == -1 && chdir("/") == -1)
1766 			_exit(1);
1767 
1768 		if (setsid() == -1 ||
1769 		    signal(SIGPIPE, SIG_DFL) == SIG_ERR ||
1770 		    dup2(fileno(fp), STDIN_FILENO) == -1)
1771 			_exit(1);
1772 
1773 		if ((len = getline(&p, &sz, fp)) == -1)
1774 			_exit(1);
1775 
1776 		if (p[len - 1] != '\n')
1777 			_exit(1);
1778 		p[len - 1] = '\0';
1779 
1780 		addargs(&args, "%s", "sendmail");
1781 		addargs(&args, "%s", "-S");
1782 
1783 		while ((tmp = strsep(&p, "|")) != NULL)
1784 			addargs(&args, "%s", tmp);
1785 
1786 		free(p);
1787 		if (lseek(fileno(fp), len, SEEK_SET) == -1)
1788 			_exit(1);
1789 
1790 		envp[0] = "PATH=" _PATH_DEFPATH;
1791 		envp[1] = (char *)NULL;
1792 		environ = envp;
1793 
1794 		execvp(PATH_SMTPCTL, args.list);
1795 		_exit(1);
1796 	}
1797 
1798 	offline_running++;
1799 	child = child_add(pid, CHILD_ENQUEUE_OFFLINE, NULL);
1800 	child->path = path;
1801 
1802 	return (0);
1803 }
1804 
1805 static int
offline_add(char * path,uid_t uid,gid_t gid)1806 offline_add(char *path, uid_t uid, gid_t gid)
1807 {
1808 	struct offline	*q;
1809 
1810 	if (offline_running < OFFLINE_QUEUEMAX)
1811 		/* skip queue */
1812 		return offline_enqueue(path, uid, gid);
1813 
1814 	q = malloc(sizeof(*q) + strlen(path) + 1);
1815 	if (q == NULL)
1816 		return (-1);
1817 	q->uid = uid;
1818 	q->gid = gid;
1819 	q->path = (char *)q + sizeof(*q);
1820 	memmove(q->path, path, strlen(path) + 1);
1821 	TAILQ_INSERT_TAIL(&offline_q, q, entry);
1822 
1823 	return (0);
1824 }
1825 
1826 static void
offline_done(void)1827 offline_done(void)
1828 {
1829 	struct offline	*q;
1830 
1831 	offline_running--;
1832 
1833 	while (offline_running < OFFLINE_QUEUEMAX) {
1834 		if ((q = TAILQ_FIRST(&offline_q)) == NULL)
1835 			break; /* all done */
1836 		TAILQ_REMOVE(&offline_q, q, entry);
1837 		offline_enqueue(q->path, q->uid, q->gid);
1838 		free(q);
1839 	}
1840 }
1841 
1842 static int
parent_forward_open(char * username,char * directory,uid_t uid,gid_t gid)1843 parent_forward_open(char *username, char *directory, uid_t uid, gid_t gid)
1844 {
1845 	char		pathname[PATH_MAX];
1846 	int		fd;
1847 	struct stat	sb;
1848 
1849 	if (!bsnprintf(pathname, sizeof (pathname), "%s/.forward",
1850 		directory)) {
1851 		log_warnx("warn: smtpd: %s: pathname too large", pathname);
1852 		return -1;
1853 	}
1854 
1855 	if (stat(directory, &sb) == -1) {
1856 		log_warn("warn: smtpd: parent_forward_open: %s", directory);
1857 		return -1;
1858 	}
1859 	if (sb.st_mode & S_ISVTX) {
1860 		log_warnx("warn: smtpd: parent_forward_open: %s is sticky",
1861 		    directory);
1862 		errno = EAGAIN;
1863 		return -1;
1864 	}
1865 
1866 	do {
1867 		fd = open(pathname, O_RDONLY|O_NOFOLLOW|O_NONBLOCK);
1868 	} while (fd == -1 && errno == EINTR);
1869 	if (fd == -1) {
1870 		if (errno == ENOENT)
1871 			return -1;
1872 		if (errno == EMFILE || errno == ENFILE || errno == EIO) {
1873 			errno = EAGAIN;
1874 			return -1;
1875 		}
1876 		if (errno == ELOOP)
1877 			log_warnx("warn: smtpd: parent_forward_open: %s: "
1878 			    "cannot follow symbolic links", pathname);
1879 		else
1880 			log_warn("warn: smtpd: parent_forward_open: %s", pathname);
1881 		return -1;
1882 	}
1883 
1884 	if (!secure_file(fd, pathname, directory, uid, 1)) {
1885 		log_warnx("warn: smtpd: %s: unsecure file", pathname);
1886 		close(fd);
1887 		return -1;
1888 	}
1889 
1890 	return fd;
1891 }
1892 
1893 void
imsg_dispatch(struct mproc * p,struct imsg * imsg)1894 imsg_dispatch(struct mproc *p, struct imsg *imsg)
1895 {
1896 	struct timespec	t0, t1, dt;
1897 	int		msg;
1898 
1899 	if (imsg == NULL) {
1900 		imsg_callback(p, imsg);
1901 		return;
1902 	}
1903 
1904 	log_imsg(smtpd_process, p->proc, imsg);
1905 
1906 	if (profiling & PROFILE_IMSG)
1907 		clock_gettime(CLOCK_MONOTONIC, &t0);
1908 
1909 	msg = imsg->hdr.type;
1910 	imsg_callback(p, imsg);
1911 
1912 	if (profiling & PROFILE_IMSG) {
1913 		clock_gettime(CLOCK_MONOTONIC, &t1);
1914 		timespecsub(&t1, &t0, &dt);
1915 
1916 		log_debug("profile-imsg: %s %s %s %d %lld.%09ld",
1917 		    proc_name(smtpd_process),
1918 		    proc_name(p->proc),
1919 		    imsg_to_str(msg),
1920 		    (int)imsg->hdr.len,
1921 		    (long long)dt.tv_sec,
1922 		    dt.tv_nsec);
1923 
1924 		if (profiling & PROFILE_TOSTAT) {
1925 			char	key[STAT_KEY_SIZE];
1926 			/* can't profstat control process yet */
1927 			if (smtpd_process == PROC_CONTROL)
1928 				return;
1929 
1930 			if (!bsnprintf(key, sizeof key,
1931 				"profiling.imsg.%s.%s.%s",
1932 				proc_name(smtpd_process),
1933 				proc_name(p->proc),
1934 				imsg_to_str(msg)))
1935 				return;
1936 			stat_set(key, stat_timespec(&dt));
1937 		}
1938 	}
1939 }
1940 
1941 void
log_imsg(int to,int from,struct imsg * imsg)1942 log_imsg(int to, int from, struct imsg *imsg)
1943 {
1944 
1945 	if (to == PROC_CONTROL && imsg->hdr.type == IMSG_STAT_SET)
1946 		return;
1947 
1948 	if (imsg->fd != -1)
1949 		log_trace(TRACE_IMSG, "imsg: %s <- %s: %s (len=%zu, fd=%d)",
1950 		    proc_name(to),
1951 		    proc_name(from),
1952 		    imsg_to_str(imsg->hdr.type),
1953 		    imsg->hdr.len - IMSG_HEADER_SIZE,
1954 		    imsg->fd);
1955 	else
1956 		log_trace(TRACE_IMSG, "imsg: %s <- %s: %s (len=%zu)",
1957 		    proc_name(to),
1958 		    proc_name(from),
1959 		    imsg_to_str(imsg->hdr.type),
1960 		    imsg->hdr.len - IMSG_HEADER_SIZE);
1961 }
1962 
1963 const char *
proc_title(enum smtp_proc_type proc)1964 proc_title(enum smtp_proc_type proc)
1965 {
1966 	switch (proc) {
1967 	case PROC_PARENT:
1968 		return "[priv]";
1969 	case PROC_LKA:
1970 		return "lookup";
1971 	case PROC_QUEUE:
1972 		return "queue";
1973 	case PROC_CONTROL:
1974 		return "control";
1975 	case PROC_SCHEDULER:
1976 		return "scheduler";
1977 	case PROC_PONY:
1978 		return "pony express";
1979 	case PROC_CA:
1980 		return "klondike";
1981 	case PROC_CLIENT:
1982 		return "client";
1983 	case PROC_PROCESSOR:
1984 		return "processor";
1985 	}
1986 	return "unknown";
1987 }
1988 
1989 const char *
proc_name(enum smtp_proc_type proc)1990 proc_name(enum smtp_proc_type proc)
1991 {
1992 	switch (proc) {
1993 	case PROC_PARENT:
1994 		return "parent";
1995 	case PROC_LKA:
1996 		return "lka";
1997 	case PROC_QUEUE:
1998 		return "queue";
1999 	case PROC_CONTROL:
2000 		return "control";
2001 	case PROC_SCHEDULER:
2002 		return "scheduler";
2003 	case PROC_PONY:
2004 		return "pony";
2005 	case PROC_CA:
2006 		return "ca";
2007 	case PROC_CLIENT:
2008 		return "client-proc";
2009 	default:
2010 		return "unknown";
2011 	}
2012 }
2013 
2014 #define CASE(x) case x : return #x
2015 
2016 const char *
imsg_to_str(int type)2017 imsg_to_str(int type)
2018 {
2019 	static char	 buf[32];
2020 
2021 	switch (type) {
2022 	CASE(IMSG_NONE);
2023 
2024 	CASE(IMSG_CTL_OK);
2025 	CASE(IMSG_CTL_FAIL);
2026 
2027 	CASE(IMSG_CTL_GET_DIGEST);
2028 	CASE(IMSG_CTL_GET_STATS);
2029 	CASE(IMSG_CTL_LIST_MESSAGES);
2030 	CASE(IMSG_CTL_LIST_ENVELOPES);
2031 	CASE(IMSG_CTL_MTA_SHOW_HOSTS);
2032 	CASE(IMSG_CTL_MTA_SHOW_RELAYS);
2033 	CASE(IMSG_CTL_MTA_SHOW_ROUTES);
2034 	CASE(IMSG_CTL_MTA_SHOW_HOSTSTATS);
2035 	CASE(IMSG_CTL_MTA_BLOCK);
2036 	CASE(IMSG_CTL_MTA_UNBLOCK);
2037 	CASE(IMSG_CTL_MTA_SHOW_BLOCK);
2038 	CASE(IMSG_CTL_PAUSE_EVP);
2039 	CASE(IMSG_CTL_PAUSE_MDA);
2040 	CASE(IMSG_CTL_PAUSE_MTA);
2041 	CASE(IMSG_CTL_PAUSE_SMTP);
2042 	CASE(IMSG_CTL_PROFILE);
2043 	CASE(IMSG_CTL_PROFILE_DISABLE);
2044 	CASE(IMSG_CTL_PROFILE_ENABLE);
2045 	CASE(IMSG_CTL_RESUME_EVP);
2046 	CASE(IMSG_CTL_RESUME_MDA);
2047 	CASE(IMSG_CTL_RESUME_MTA);
2048 	CASE(IMSG_CTL_RESUME_SMTP);
2049 	CASE(IMSG_CTL_RESUME_ROUTE);
2050 	CASE(IMSG_CTL_REMOVE);
2051 	CASE(IMSG_CTL_SCHEDULE);
2052 	CASE(IMSG_CTL_SHOW_STATUS);
2053 	CASE(IMSG_CTL_TRACE_DISABLE);
2054 	CASE(IMSG_CTL_TRACE_ENABLE);
2055 	CASE(IMSG_CTL_UPDATE_TABLE);
2056 	CASE(IMSG_CTL_VERBOSE);
2057 	CASE(IMSG_CTL_DISCOVER_EVPID);
2058 	CASE(IMSG_CTL_DISCOVER_MSGID);
2059 
2060 	CASE(IMSG_CTL_SMTP_SESSION);
2061 
2062 	CASE(IMSG_GETADDRINFO);
2063 	CASE(IMSG_GETADDRINFO_END);
2064 	CASE(IMSG_GETNAMEINFO);
2065 	CASE(IMSG_RES_QUERY);
2066 
2067 	CASE(IMSG_CERT_INIT);
2068 	CASE(IMSG_CERT_CERTIFICATE);
2069 	CASE(IMSG_CERT_VERIFY);
2070 
2071 	CASE(IMSG_SETUP_KEY);
2072 	CASE(IMSG_SETUP_PEER);
2073 	CASE(IMSG_SETUP_DONE);
2074 
2075 	CASE(IMSG_CONF_START);
2076 	CASE(IMSG_CONF_END);
2077 
2078 	CASE(IMSG_STAT_INCREMENT);
2079 	CASE(IMSG_STAT_DECREMENT);
2080 	CASE(IMSG_STAT_SET);
2081 
2082 	CASE(IMSG_LKA_AUTHENTICATE);
2083 	CASE(IMSG_LKA_OPEN_FORWARD);
2084 	CASE(IMSG_LKA_ENVELOPE_SUBMIT);
2085 	CASE(IMSG_LKA_ENVELOPE_COMMIT);
2086 
2087 	CASE(IMSG_QUEUE_DELIVER);
2088 	CASE(IMSG_QUEUE_DELIVERY_OK);
2089 	CASE(IMSG_QUEUE_DELIVERY_TEMPFAIL);
2090 	CASE(IMSG_QUEUE_DELIVERY_PERMFAIL);
2091 	CASE(IMSG_QUEUE_DELIVERY_LOOP);
2092 	CASE(IMSG_QUEUE_DISCOVER_EVPID);
2093 	CASE(IMSG_QUEUE_DISCOVER_MSGID);
2094 	CASE(IMSG_QUEUE_ENVELOPE_ACK);
2095 	CASE(IMSG_QUEUE_ENVELOPE_COMMIT);
2096 	CASE(IMSG_QUEUE_ENVELOPE_REMOVE);
2097 	CASE(IMSG_QUEUE_ENVELOPE_SCHEDULE);
2098 	CASE(IMSG_QUEUE_ENVELOPE_SUBMIT);
2099 	CASE(IMSG_QUEUE_HOLDQ_HOLD);
2100 	CASE(IMSG_QUEUE_HOLDQ_RELEASE);
2101 	CASE(IMSG_QUEUE_MESSAGE_COMMIT);
2102 	CASE(IMSG_QUEUE_MESSAGE_ROLLBACK);
2103 	CASE(IMSG_QUEUE_SMTP_SESSION);
2104 	CASE(IMSG_QUEUE_TRANSFER);
2105 
2106 	CASE(IMSG_MDA_DELIVERY_OK);
2107 	CASE(IMSG_MDA_DELIVERY_TEMPFAIL);
2108 	CASE(IMSG_MDA_DELIVERY_PERMFAIL);
2109 	CASE(IMSG_MDA_DELIVERY_LOOP);
2110 	CASE(IMSG_MDA_DELIVERY_HOLD);
2111 	CASE(IMSG_MDA_DONE);
2112 	CASE(IMSG_MDA_FORK);
2113 	CASE(IMSG_MDA_HOLDQ_RELEASE);
2114 	CASE(IMSG_MDA_LOOKUP_USERINFO);
2115 	CASE(IMSG_MDA_KILL);
2116 	CASE(IMSG_MDA_OPEN_MESSAGE);
2117 
2118 	CASE(IMSG_MTA_DELIVERY_OK);
2119 	CASE(IMSG_MTA_DELIVERY_TEMPFAIL);
2120 	CASE(IMSG_MTA_DELIVERY_PERMFAIL);
2121 	CASE(IMSG_MTA_DELIVERY_LOOP);
2122 	CASE(IMSG_MTA_DELIVERY_HOLD);
2123 	CASE(IMSG_MTA_DNS_HOST);
2124 	CASE(IMSG_MTA_DNS_HOST_END);
2125 	CASE(IMSG_MTA_DNS_MX);
2126 	CASE(IMSG_MTA_DNS_MX_PREFERENCE);
2127 	CASE(IMSG_MTA_HOLDQ_RELEASE);
2128 	CASE(IMSG_MTA_LOOKUP_CREDENTIALS);
2129 	CASE(IMSG_MTA_LOOKUP_SOURCE);
2130 	CASE(IMSG_MTA_LOOKUP_HELO);
2131 	CASE(IMSG_MTA_LOOKUP_SMARTHOST);
2132 	CASE(IMSG_MTA_OPEN_MESSAGE);
2133 	CASE(IMSG_MTA_SCHEDULE);
2134 
2135 	CASE(IMSG_SCHED_ENVELOPE_BOUNCE);
2136 	CASE(IMSG_SCHED_ENVELOPE_DELIVER);
2137 	CASE(IMSG_SCHED_ENVELOPE_EXPIRE);
2138 	CASE(IMSG_SCHED_ENVELOPE_INJECT);
2139 	CASE(IMSG_SCHED_ENVELOPE_REMOVE);
2140 	CASE(IMSG_SCHED_ENVELOPE_TRANSFER);
2141 
2142 	CASE(IMSG_SMTP_AUTHENTICATE);
2143 	CASE(IMSG_SMTP_MESSAGE_COMMIT);
2144 	CASE(IMSG_SMTP_MESSAGE_CREATE);
2145 	CASE(IMSG_SMTP_MESSAGE_ROLLBACK);
2146 	CASE(IMSG_SMTP_MESSAGE_OPEN);
2147 	CASE(IMSG_SMTP_CHECK_SENDER);
2148 	CASE(IMSG_SMTP_EXPAND_RCPT);
2149 	CASE(IMSG_SMTP_LOOKUP_HELO);
2150 
2151 	CASE(IMSG_SMTP_REQ_CONNECT);
2152 	CASE(IMSG_SMTP_REQ_HELO);
2153 	CASE(IMSG_SMTP_REQ_MAIL);
2154 	CASE(IMSG_SMTP_REQ_RCPT);
2155 	CASE(IMSG_SMTP_REQ_DATA);
2156 	CASE(IMSG_SMTP_REQ_EOM);
2157 	CASE(IMSG_SMTP_EVENT_RSET);
2158 	CASE(IMSG_SMTP_EVENT_COMMIT);
2159 	CASE(IMSG_SMTP_EVENT_ROLLBACK);
2160 	CASE(IMSG_SMTP_EVENT_DISCONNECT);
2161 
2162 	CASE(IMSG_LKA_PROCESSOR_FORK);
2163 	CASE(IMSG_LKA_PROCESSOR_ERRFD);
2164 
2165 	CASE(IMSG_REPORT_SMTP_LINK_CONNECT);
2166 	CASE(IMSG_REPORT_SMTP_LINK_DISCONNECT);
2167 	CASE(IMSG_REPORT_SMTP_LINK_TLS);
2168 	CASE(IMSG_REPORT_SMTP_LINK_GREETING);
2169 	CASE(IMSG_REPORT_SMTP_LINK_IDENTIFY);
2170 	CASE(IMSG_REPORT_SMTP_LINK_AUTH);
2171 
2172 	CASE(IMSG_REPORT_SMTP_TX_RESET);
2173 	CASE(IMSG_REPORT_SMTP_TX_BEGIN);
2174 	CASE(IMSG_REPORT_SMTP_TX_ENVELOPE);
2175 	CASE(IMSG_REPORT_SMTP_TX_COMMIT);
2176 	CASE(IMSG_REPORT_SMTP_TX_ROLLBACK);
2177 
2178 	CASE(IMSG_REPORT_SMTP_PROTOCOL_CLIENT);
2179 	CASE(IMSG_REPORT_SMTP_PROTOCOL_SERVER);
2180 
2181 	CASE(IMSG_FILTER_SMTP_BEGIN);
2182 	CASE(IMSG_FILTER_SMTP_END);
2183 	CASE(IMSG_FILTER_SMTP_PROTOCOL);
2184 	CASE(IMSG_FILTER_SMTP_DATA_BEGIN);
2185 	CASE(IMSG_FILTER_SMTP_DATA_END);
2186 
2187 	CASE(IMSG_CA_RSA_PRIVENC);
2188 	CASE(IMSG_CA_RSA_PRIVDEC);
2189 	CASE(IMSG_CA_ECDSA_SIGN);
2190 	default:
2191 		(void)snprintf(buf, sizeof(buf), "IMSG_??? (%d)", type);
2192 
2193 		return buf;
2194 	}
2195 }
2196 
2197 #ifdef BSD_AUTH
2198 int
parent_auth_bsd(const char * username,const char * password)2199 parent_auth_bsd(const char *username, const char *password)
2200 {
2201 	char	user[LOGIN_NAME_MAX];
2202 	char	pass[LINE_MAX];
2203 	int	ret;
2204 
2205 	(void)strlcpy(user, username, sizeof(user));
2206 	(void)strlcpy(pass, password, sizeof(pass));
2207 
2208 	ret = auth_userokay(user, NULL, "auth-smtp", pass);
2209 	if (ret)
2210 		return LKA_OK;
2211 	return LKA_PERMFAIL;
2212 }
2213 #endif
2214 
2215 #ifdef USE_PAM
2216 int
pam_conv_password(int num_msg,const struct pam_message ** msg,struct pam_response ** respp,void * password)2217 pam_conv_password(int num_msg, const struct pam_message **msg,
2218     struct pam_response **respp, void *password)
2219 {
2220 	struct pam_response *response;
2221 
2222 	if (num_msg != 1)
2223 		return PAM_CONV_ERR;
2224 
2225 	response = calloc(1, sizeof(struct pam_response));
2226 	if (response == NULL || (response->resp = strdup(password)) == NULL) {
2227 		free(response);
2228 		return PAM_BUF_ERR;
2229 	}
2230 
2231 	*respp = response;
2232 	return PAM_SUCCESS;
2233 }
2234 int
parent_auth_pam(const char * username,const char * password)2235 parent_auth_pam(const char *username, const char *password)
2236 {
2237 	int rc;
2238 	pam_handle_t *pamh = NULL;
2239 	struct pam_conv conv = { pam_conv_password, (char *)password };
2240 
2241 	if ((rc = pam_start(USE_PAM_SERVICE, username, &conv, &pamh)) != PAM_SUCCESS)
2242 		goto end;
2243 	if ((rc = pam_authenticate(pamh, 0)) != PAM_SUCCESS)
2244 		goto end;
2245 	if ((rc = pam_acct_mgmt(pamh, 0)) != PAM_SUCCESS)
2246 		goto end;
2247 
2248 end:
2249 	pam_end(pamh, rc);
2250 
2251 	switch (rc) {
2252 		case PAM_SUCCESS:
2253 			return LKA_OK;
2254 		case PAM_SYSTEM_ERR:
2255 		case PAM_ABORT:
2256 		case PAM_AUTHINFO_UNAVAIL:
2257 			return LKA_TEMPFAIL;
2258 		default:
2259 			return LKA_PERMFAIL;
2260 	}
2261 }
2262 #endif
2263 
2264 #ifdef HAVE_GETSPNAM
2265 int
parent_auth_getspnam(const char * username,const char * password)2266 parent_auth_getspnam(const char *username, const char *password)
2267 {
2268        struct spwd *pw;
2269        char *ep;
2270 
2271        errno = 0;
2272        do {
2273                pw = getspnam(username);
2274        } while (pw == NULL && errno == EINTR);
2275 
2276        if (pw == NULL) {
2277                if (errno)
2278                        return LKA_TEMPFAIL;
2279                return LKA_PERMFAIL;
2280        }
2281 
2282        if ((ep = crypt(password, pw->sp_pwdp)) == NULL)
2283 	       return LKA_PERMFAIL;
2284 
2285        if (strcmp(pw->sp_pwdp, ep) == 0)
2286                return LKA_OK;
2287 
2288        return LKA_PERMFAIL;
2289 }
2290 #endif
2291 
2292 int
parent_auth_pwd(const char * username,const char * password)2293 parent_auth_pwd(const char *username, const char *password)
2294 {
2295        struct passwd *pw;
2296        char *ep;
2297 
2298        errno = 0;
2299        do {
2300                pw = getpwnam(username);
2301        } while (pw == NULL && errno == EINTR);
2302 
2303        if (pw == NULL) {
2304                if (errno)
2305                        return LKA_TEMPFAIL;
2306                return LKA_PERMFAIL;
2307        }
2308 
2309        if ((ep = crypt(password, pw->pw_passwd)) == NULL)
2310 	       return LKA_PERMFAIL;
2311 
2312        if (strcmp(pw->pw_passwd, ep) == 0)
2313                return LKA_OK;
2314 
2315        return LKA_PERMFAIL;
2316 }
2317 
2318 int
parent_auth_user(const char * username,const char * password)2319 parent_auth_user(const char *username, const char *password)
2320 {
2321 #if defined(BSD_AUTH)
2322 	return (parent_auth_bsd(username, password));
2323 #elif defined(USE_PAM)
2324 	return (parent_auth_pam(username, password));
2325 #elif defined(HAVE_GETSPNAM)
2326 	return (parent_auth_getspnam(username, password));
2327 #else
2328 	return (parent_auth_pwd(username, password));
2329 #endif
2330 }
2331