1 /* Copyright (c) 2005-2018 Dovecot authors, see the included COPYING file */
2 
3 #include "lib.h"
4 #include "lib-signals.h"
5 #include "ioloop.h"
6 #include "env-util.h"
7 #include "istream.h"
8 #include "istream-seekable.h"
9 #include "path-util.h"
10 #include "safe-mkstemp.h"
11 #include "eacces-error.h"
12 #include "ipwd.h"
13 #include "str.h"
14 #include "str-sanitize.h"
15 #include "strescape.h"
16 #include "unichar.h"
17 #include "rfc822-parser.h"
18 #include "message-address.h"
19 #include "smtp-address.h"
20 #include "settings-parser.h"
21 #include "master-service.h"
22 #include "master-service-settings.h"
23 #include "mail-storage-service.h"
24 #include "mail-namespace.h"
25 #include "raw-storage.h"
26 #include "mail-deliver.h"
27 #include "mail-send.h"
28 #include "mbox-from.h"
29 #include "smtp-submit-settings.h"
30 #include "lda-settings.h"
31 
32 #include <stdio.h>
33 #include <sysexits.h>
34 
35 const struct smtp_address default_envelope_sender = {
36 	.localpart = "MAILER-DAEMON",
37 };
38 
39 /* After buffer grows larger than this, create a temporary file to /tmp
40    where to read the mail. */
41 #define MAIL_MAX_MEMORY_BUFFER (1024*128)
42 
43 struct event_category event_category_lda = {
44 	.name = "lda",
45 };
46 
47 static const char *wanted_headers[] = {
48 	"From", "To", "Message-ID", "Subject", "Return-Path",
49 	NULL
50 };
51 
seekable_fd_callback(const char ** path_r,void * context)52 static int seekable_fd_callback(const char **path_r, void *context)
53 {
54 	struct mail_deliver_input *dinput = context;
55 	string_t *path;
56 	int fd;
57 
58 	path = t_str_new(128);
59 	mail_user_set_get_temp_prefix(path, dinput->rcpt_user->set);
60 	fd = safe_mkstemp(path, 0600, (uid_t)-1, (gid_t)-1);
61 	if (fd == -1) {
62 		i_error("safe_mkstemp(%s) failed: %m", str_c(path));
63 		return -1;
64 	}
65 
66 	/* we just want the fd, unlink it */
67 	if (i_unlink(str_c(path)) < 0) {
68 		/* shouldn't happen.. */
69 		i_close_fd(&fd);
70 		return -1;
71 	}
72 
73 	*path_r = str_c(path);
74 	return fd;
75 }
76 
77 static struct istream *
create_raw_stream(struct mail_deliver_input * dinput,int fd,time_t * mtime_r)78 create_raw_stream(struct mail_deliver_input *dinput,
79 		  int fd, time_t *mtime_r)
80 {
81 	struct istream *input, *input2, *input_list[2];
82 	const unsigned char *data;
83 	const char *error;
84 	char *sender = NULL;
85 	size_t i, size;
86 	int ret, tz;
87 
88 	*mtime_r = (time_t)-1;
89 	fd_set_nonblock(fd, FALSE);
90 
91 	input = i_stream_create_fd(fd, 4096);
92 	input->blocking = TRUE;
93 	/* If input begins with a From-line, drop it */
94 	ret = i_stream_read_bytes(input, &data, &size, 5);
95 	if (ret > 0 && memcmp(data, "From ", 5) == 0) {
96 		/* skip until the first LF */
97 		i_stream_skip(input, 5);
98 		while (i_stream_read_more(input, &data, &size) > 0) {
99 			for (i = 0; i < size; i++) {
100 				if (data[i] == '\n')
101 					break;
102 			}
103 			if (i != size) {
104 				(void)mbox_from_parse(data, i, mtime_r, &tz,
105 						      &sender);
106 				i_stream_skip(input, i + 1);
107 				break;
108 			}
109 			i_stream_skip(input, size);
110 		}
111 	}
112 
113 	if (sender != NULL && dinput->mail_from == NULL) {
114 		struct smtp_address *mail_from = NULL;
115 		/* use the envelope sender from From_-line, but only if it
116 		   hasn't been specified with -f already. */
117 		if (smtp_address_parse_mailbox(pool_datastack_create(),
118 					       sender, 0, &mail_from,
119 					       &error) < 0) {
120 			i_warning("Failed to parse address from `From_'-line: %s",
121 				  error);
122 		}
123 		dinput->mail_from = mail_from;
124 	}
125 	i_free(sender);
126 
127 	if (input->v_offset == 0) {
128 		input2 = input;
129 		i_stream_ref(input2);
130 	} else {
131 		input2 = i_stream_create_limit(input, UOFF_T_MAX);
132 	}
133 	i_stream_unref(&input);
134 
135 	input_list[0] = input2; input_list[1] = NULL;
136 	input = i_stream_create_seekable(input_list, MAIL_MAX_MEMORY_BUFFER,
137 					 seekable_fd_callback, dinput);
138 	i_stream_unref(&input2);
139 	return input;
140 }
141 
142 static struct mail *
lda_raw_mail_open(struct mail_deliver_input * dinput,const char * path)143 lda_raw_mail_open(struct mail_deliver_input *dinput, const char *path)
144 {
145 	struct mail_user *raw_mail_user;
146 	struct mailbox *box;
147 	struct mailbox_transaction_context *t;
148 	struct mail *mail;
149 	struct mailbox_header_lookup_ctx *headers_ctx;
150 	const struct smtp_address *mail_from;
151 	struct istream *input;
152 	void **sets;
153 	time_t mtime;
154 	int ret;
155 
156 	sets = master_service_settings_get_others(master_service);
157 	raw_mail_user = raw_storage_create_from_set(dinput->rcpt_user->set_info,
158 						    sets[0]);
159 
160 	mail_from = (dinput->mail_from != NULL ?
161 		     dinput->mail_from : &default_envelope_sender);
162 	if (path == NULL) {
163 		input = create_raw_stream(dinput, 0, &mtime);
164 		i_stream_set_name(input, "stdin");
165 		ret = raw_mailbox_alloc_stream(raw_mail_user, input, mtime,
166 					       smtp_address_encode(mail_from), &box);
167 		i_stream_unref(&input);
168 	} else {
169 		ret = raw_mailbox_alloc_path(raw_mail_user, path, (time_t)-1,
170 					     smtp_address_encode(mail_from), &box);
171 	}
172 	if (ret < 0) {
173 		i_fatal("Can't open delivery mail as raw: %s",
174 			mailbox_get_last_internal_error(box, NULL));
175 	}
176 	mail_user_unref(&raw_mail_user);
177 
178 	t = mailbox_transaction_begin(box, 0, __func__);
179 	headers_ctx = mailbox_header_lookup_init(box, wanted_headers);
180 	mail = mail_alloc(t, 0, headers_ctx);
181 	mailbox_header_lookup_unref(&headers_ctx);
182 	mail_set_seq(mail, 1);
183 	return mail;
184 }
185 
186 static void
lda_set_rcpt_to(struct mail_deliver_input * dinput,const struct smtp_address * rcpt_to,const char * user,const char * rcpt_to_source)187 lda_set_rcpt_to(struct mail_deliver_input *dinput,
188 		const struct smtp_address *rcpt_to, const char *user,
189 		const char *rcpt_to_source)
190 {
191 	const char *error;
192 
193 	if (rcpt_to == NULL &&
194 	    *dinput->set->lda_original_recipient_header != '\0') {
195 		rcpt_to = mail_deliver_get_address(
196 			dinput->src_mail,
197 			dinput->set->lda_original_recipient_header);
198 		rcpt_to_source = t_strconcat(
199 			dinput->set->lda_original_recipient_header,
200 			" header", NULL);
201 	}
202 	if (rcpt_to == NULL) {
203 		struct smtp_address *user_addr;
204 
205 		if (smtp_address_parse_username(pool_datastack_create(), user,
206 						&user_addr, &error) < 0) {
207 			i_fatal_status(EX_USAGE,
208 				"Cannot obtain SMTP address from username `%s': %s",
209 				user, error);
210 		}
211 		if (user_addr->domain == NULL)
212 			user_addr->domain = dinput->set->hostname;
213 		rcpt_to = user_addr;
214 		rcpt_to_source = "user@hostname";
215 	}
216 
217 	dinput->rcpt_params.orcpt.addr = rcpt_to;
218 	if (dinput->rcpt_to == NULL)
219 		dinput->rcpt_to = rcpt_to;
220 
221 	e_debug(dinput->rcpt_user->event,
222 		"Destination address: %s (source: %s)",
223 		smtp_address_encode_path(rcpt_to), rcpt_to_source);
224 }
225 
226 static int
lda_do_deliver(struct mail_deliver_context * ctx,bool stderr_rejection)227 lda_do_deliver(struct mail_deliver_context *ctx, bool stderr_rejection)
228 {
229 	enum mail_deliver_error error_code;
230 	const char *error;
231 	int ret;
232 
233 	if (mail_deliver(ctx, &error_code, &error) >= 0)
234 		return EX_OK;
235 
236 	if (error_code == MAIL_DELIVER_ERROR_INTERNAL) {
237 		/* This shouldn't happen */
238 		return EX_TEMPFAIL;
239 	}
240 
241 	if (stderr_rejection) {
242 		/* write to stderr also for tempfails so that MTA
243 		   can log the reason if it wants to. */
244 		fprintf(stderr, "%s\n", error);
245 	}
246 
247 	switch (error_code) {
248 	case MAIL_DELIVER_ERROR_NONE:
249 		i_unreached();
250 	case MAIL_DELIVER_ERROR_TEMPORARY:
251 		return EX_TEMPFAIL;
252 	case MAIL_DELIVER_ERROR_REJECTED:
253 		break;
254 	case MAIL_DELIVER_ERROR_NOQUOTA:
255 		if (ctx->set->quota_full_tempfail)
256 			return EX_TEMPFAIL;
257 		ctx->mailbox_full = TRUE;
258 		break;
259 	case MAIL_DELIVER_ERROR_INTERNAL:
260 		i_unreached();
261 	}
262 
263 	/* Rejected */
264 
265 	ctx->dsn = TRUE;
266 
267 	/* we'll have to reply with permanent failure */
268 	mail_deliver_log(ctx, "rejected: %s",
269 			 str_sanitize(error, 512));
270 
271 	if (stderr_rejection)
272 		return EX_NOPERM;
273 	ret = mail_send_rejection(ctx, ctx->rcpt_to, error);
274 	if (ret != 0)
275 		return ret < 0 ? EX_TEMPFAIL : ret;
276 	/* ok, rejection sent */
277 
278 	return EX_OK;
279 }
280 
281 static int
lda_deliver(struct mail_deliver_input * dinput,struct mail_storage_service_user * service_user,const char * user,const char * path,struct smtp_address * rcpt_to,const char * rcpt_to_source,bool stderr_rejection)282 lda_deliver(struct mail_deliver_input *dinput,
283 	    struct mail_storage_service_user *service_user,
284 	    const char *user, const char *path,
285 	    struct smtp_address *rcpt_to, const char *rcpt_to_source,
286 	    bool stderr_rejection)
287 {
288 	struct mail_deliver_context ctx;
289 	const struct var_expand_table *var_table;
290 	struct lda_settings *lda_set;
291 	struct smtp_submit_settings *smtp_set;
292 	const char *errstr;
293 	int ret;
294 
295 	var_table = mail_user_var_expand_table(dinput->rcpt_user);
296 	smtp_set = mail_storage_service_user_get_set(service_user)[1];
297 	lda_set = mail_storage_service_user_get_set(service_user)[2];
298 	ret = settings_var_expand(
299 		&lda_setting_parser_info,
300 		lda_set, dinput->rcpt_user->pool, var_table,
301 		&errstr);
302 	if (ret > 0) {
303 		ret = settings_var_expand(
304 			&smtp_submit_setting_parser_info,
305 			smtp_set, dinput->rcpt_user->pool, var_table,
306 			&errstr);
307 	}
308 	if (ret <= 0)
309 		i_fatal("Failed to expand settings: %s", errstr);
310 	dinput->set = lda_set;
311 	dinput->smtp_set = smtp_set;
312 
313 	dinput->src_mail = lda_raw_mail_open(dinput, path);
314 	lda_set_rcpt_to(dinput, rcpt_to, user, rcpt_to_source);
315 
316 	mail_deliver_init(&ctx, dinput);
317 	ret = lda_do_deliver(&ctx, stderr_rejection);
318 	mail_deliver_deinit(&ctx);
319 
320 	return ret;
321 }
322 
failure_exit_callback(int * status)323 static void failure_exit_callback(int *status)
324 {
325 	/* we want all our exit codes to be sysexits.h compatible.
326 	   if we failed because of a logging related error, we most likely
327 	   aren't writing to stderr, so try writing there to give some kind of
328 	   a clue what's wrong. FATAL_LOGOPEN failure already wrote to
329 	   stderr, so don't duplicate it. */
330 	switch (*status) {
331 	case FATAL_LOGWRITE:
332 		fputs("Failed to write to log file", stderr);
333 		break;
334 	case FATAL_LOGERROR:
335 		fputs("Internal logging error", stderr);
336 		break;
337 	case FATAL_LOGOPEN:
338 	case FATAL_OUTOFMEM:
339 	case FATAL_EXEC:
340 	case FATAL_DEFAULT:
341 		break;
342 	default:
343 		return;
344 	}
345 	*status = EX_TEMPFAIL;
346 }
347 
print_help(void)348 static void print_help(void)
349 {
350 	printf(
351 "Usage: dovecot-lda [-c <config file>] [-d <username>] [-p <path>]\n"
352 "                   [-m <mailbox>] [-e] [-k] [-f <envelope sender>]\n"
353 "                   [-a <original envelope recipient>]\n"
354 "                   [-r <final envelope recipient>] \n");
355 }
356 
main(int argc,char * argv[])357 int main(int argc, char *argv[])
358 {
359 	const struct setting_parser_info *set_roots[] = {
360 		&smtp_submit_setting_parser_info,
361 		&lda_setting_parser_info,
362 		NULL
363 	};
364 	struct mail_deliver_input dinput;
365 	enum mail_storage_service_flags service_flags = 0;
366 	const char *user, *errstr, *path;
367 	struct smtp_address *rcpt_to, *final_rcpt_to, *mail_from;
368 	struct mail_storage_service_ctx *storage_service;
369 	struct mail_storage_service_user *service_user;
370 	struct mail_storage_service_input service_input;
371 	struct event *event;
372 	const char *user_source = "", *rcpt_to_source = "", *mail_from_error;
373 	uid_t process_euid;
374 	bool stderr_rejection = FALSE;
375 	int ret, c;
376 
377 	if (getuid() != geteuid() && geteuid() == 0) {
378 		/* running setuid - don't allow this if the binary is
379 		   executable by anyone */
380 		struct stat st;
381 
382 		if (stat(argv[0], &st) < 0) {
383 			fprintf(stderr, "stat(%s) failed: %s\n",
384 				argv[0], strerror(errno));
385 			return EX_TEMPFAIL;
386 		} else if ((st.st_mode & 1) != 0 && (st.st_mode & 04000) != 0) {
387 			fprintf(stderr, "%s must not be both world-executable "
388 				"and setuid-root. This allows root exploits. "
389 				"See http://wiki2.dovecot.org/LDA#multipleuids\n",
390 				argv[0]);
391 			return EX_TEMPFAIL;
392 		}
393 	}
394 
395 	i_set_failure_exit_callback(failure_exit_callback);
396 
397 	master_service = master_service_init("lda",
398 		MASTER_SERVICE_FLAG_STANDALONE |
399 		MASTER_SERVICE_FLAG_DONT_LOG_TO_STDERR |
400 		MASTER_SERVICE_FLAG_NO_INIT_DATASTACK_FRAME,
401 		&argc, &argv, "a:d:ef:m:p:r:");
402 
403 	event = event_create(NULL);
404 	event_add_category(event, &event_category_lda);
405 
406 	i_zero(&dinput);
407 	dinput.session = mail_deliver_session_init();
408 	dinput.rcpt_default_mailbox = "INBOX";
409 	path = NULL;
410 
411 	user = getenv("USER");
412 	mail_from = final_rcpt_to = rcpt_to = NULL;
413 	mail_from_error = NULL;
414 	while ((c = master_getopt(master_service)) > 0) {
415 		switch (c) {
416 		case 'a':
417 			/* original recipient address */
418 			if (smtp_address_parse_path(
419 				pool_datastack_create(), optarg,
420 				SMTP_ADDRESS_PARSE_FLAG_ALLOW_LOCALPART |
421 				SMTP_ADDRESS_PARSE_FLAG_BRACKETS_OPTIONAL,
422 				&rcpt_to, &errstr) < 0) {
423 				i_fatal_status(EX_USAGE,
424 					"Invalid -a parameter: %s", errstr);
425 			}
426 			rcpt_to_source = "-a parameter";
427 			break;
428 		case 'd':
429 			/* destination user */
430 			user = optarg;
431 			service_flags |= MAIL_STORAGE_SERVICE_FLAG_USERDB_LOOKUP;
432 			break;
433 		case 'e':
434 			stderr_rejection = TRUE;
435 			break;
436 		case 'f':
437 			/* envelope sender address */
438 			ret = smtp_address_parse_path(
439 				pool_datastack_create(), optarg,
440 				SMTP_ADDRESS_PARSE_FLAG_BRACKETS_OPTIONAL |
441 				SMTP_ADDRESS_PARSE_FLAG_ALLOW_LOCALPART |
442 				SMTP_ADDRESS_PARSE_FLAG_ALLOW_EMPTY |
443 				SMTP_ADDRESS_PARSE_FLAG_IGNORE_BROKEN |
444 				SMTP_ADDRESS_PARSE_FLAG_PRESERVE_RAW,
445 				&mail_from, &errstr);
446 			if (ret < 0 && !smtp_address_is_broken(mail_from)) {
447 				i_fatal_status(EX_USAGE,
448 					"Invalid -f parameter: %s", errstr);
449 			}
450 			if (ret < 0)
451 				mail_from_error = errstr;
452 			break;
453 		case 'm':
454 			/* destination mailbox.
455 			   Ignore -m "". This allows doing -m ${extension}
456 			   in Postfix to handle user+mailbox */
457 			if (*optarg != '\0') T_BEGIN {
458 				if (!uni_utf8_str_is_valid(optarg)) {
459 					i_fatal("Mailbox name not UTF-8: %s",
460 						optarg);
461 				}
462 				dinput.rcpt_default_mailbox = optarg;
463 			} T_END;
464 			break;
465 		case 'p':
466 			/* input path */
467 			if (t_abspath(optarg, &path, &errstr) < 0) {
468 				i_fatal("t_abspath(%s) failed: %s",
469 					optarg, errstr);
470 			}
471 			break;
472 		case 'r':
473 			/* final recipient address */
474 			if (smtp_address_parse_path(
475 				pool_datastack_create(), optarg,
476 				SMTP_ADDRESS_PARSE_FLAG_ALLOW_LOCALPART |
477 				SMTP_ADDRESS_PARSE_FLAG_BRACKETS_OPTIONAL,
478 				&final_rcpt_to, &errstr) < 0) {
479 				i_fatal_status(EX_USAGE,
480 					"Invalid -r parameter: %s", errstr);
481 			}
482 			break;
483 		default:
484 			print_help();
485 			return EX_USAGE;
486 		}
487 	}
488 	if (optind != argc) {
489 		print_help();
490 		i_fatal_status(EX_USAGE, "Unknown argument: %s", argv[optind]);
491 	}
492 
493 	process_euid = geteuid();
494 	if ((service_flags & MAIL_STORAGE_SERVICE_FLAG_USERDB_LOOKUP) != 0)
495 		;
496 	else if (process_euid != 0) {
497 		/* we're non-root. get our username and possibly our home. */
498 		struct passwd pw;
499 		const char *home;
500 
501 		home = getenv("HOME");
502 		if (user != NULL && home != NULL) {
503 			/* no need for a pw lookup */
504 			user_source = "USER environment";
505 		} else if ((ret = i_getpwuid(process_euid, &pw)) > 0) {
506 			user = t_strdup(pw.pw_name);
507 			if (home == NULL)
508 				env_put("HOME", pw.pw_dir);
509 			user_source = "passwd lookup for process euid";
510 		} else if (ret < 0) {
511 			/* temporary failure */
512 			i_fatal("getpwuid() failed: %m");
513 		} else if (user == NULL) {
514 			i_fatal_status(EX_USAGE,
515 				       "Couldn't lookup our username (uid=%s)",
516 				       dec2str(process_euid));
517 		}
518 	} else {
519 		i_fatal_status(EX_USAGE,
520 			"destination user parameter (-d user) not given");
521 	}
522 	master_service_init_finish(master_service);
523 
524 	dinput.mail_from = mail_from;
525 	dinput.rcpt_to = final_rcpt_to;
526 
527 	event_add_str(event, "protocol", "lda");
528 	event_add_str(event, "user", user);
529 	if (mail_from != NULL) {
530 		event_add_str(event, "mail_from",
531 			      smtp_address_encode(mail_from));
532 	}
533 	if (final_rcpt_to != NULL) {
534 		event_add_str(event, "rcpt_to",
535 			      smtp_address_encode(final_rcpt_to));
536 	}
537 	dinput.event_parent = event;
538 
539 	i_zero(&service_input);
540 	service_input.module = "lda";
541 	service_input.service = "lda";
542 	service_input.username = user;
543 	service_input.event_parent = event;
544 
545 	service_flags |= MAIL_STORAGE_SERVICE_FLAG_USE_SYSEXITS;
546 	storage_service = mail_storage_service_init(master_service, set_roots,
547 						    service_flags);
548 	mail_deliver_hooks_init();
549 	/* set before looking up the user (or ideally we'd do this between
550 	   _lookup() and _next(), but don't bother) */
551 	dinput.delivery_time_started = ioloop_timeval;
552 	ret = mail_storage_service_lookup_next(storage_service,
553 					       &service_input, &service_user,
554 					       &dinput.rcpt_user,
555 					       &errstr);
556 	if (ret <= 0) {
557 		if (ret < 0)
558 			i_fatal("%s", errstr);
559 		ret = EX_NOUSER;
560 	} else {
561 #ifdef SIGXFSZ
562 		lib_signals_ignore(SIGXFSZ, TRUE);
563 #endif
564 		if (*user_source != '\0') {
565 			e_debug(dinput.rcpt_user->event,
566 				"userdb lookup skipped, username taken from %s",
567 				user_source);
568 		}
569 		if (mail_from_error != NULL) {
570 			e_debug(event, "Broken -f parameter: %s "
571 				"(proceeding with <> as sender)",
572 				mail_from_error);
573 		}
574 
575 		ret = lda_deliver(&dinput, service_user, user, path,
576 				  rcpt_to, rcpt_to_source, stderr_rejection);
577 
578 		struct mailbox_transaction_context *t =
579 			dinput.src_mail->transaction;
580 		struct mailbox *box = dinput.src_mail->box;
581 
582 		mail_free(&dinput.src_mail);
583 		mailbox_transaction_rollback(&t);
584 		mailbox_free(&box);
585 
586 		mail_user_deinit(&dinput.rcpt_user);
587 		mail_storage_service_user_unref(&service_user);
588 	}
589 
590 	mail_deliver_session_deinit(&dinput.session);
591 	mail_storage_service_deinit(&storage_service);
592 
593 	event_unref(&event);
594 	master_service_deinit(&master_service);
595         return ret;
596 }
597