xref: /netbsd-src/external/ibm-public/postfix/dist/src/postdrop/postdrop.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: postdrop.c,v 1.2 2017/02/14 01:16:46 christos Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	postdrop 1
6 /* SUMMARY
7 /*	Postfix mail posting utility
8 /* SYNOPSIS
9 /*	\fBpostdrop\fR [\fB-rv\fR] [\fB-c \fIconfig_dir\fR]
10 /* DESCRIPTION
11 /*	The \fBpostdrop\fR(1) command creates a file in the \fBmaildrop\fR
12 /*	directory and copies its standard input to the file.
13 /*
14 /*	Options:
15 /* .IP "\fB-c \fIconfig_dir\fR"
16 /*	The \fBmain.cf\fR configuration file is in the named directory
17 /*	instead of the default configuration directory. See also the
18 /*	MAIL_CONFIG environment setting below.
19 /* .IP \fB-r\fR
20 /*	Use a Postfix-internal protocol for reading the message from
21 /*	standard input, and for reporting status information on standard
22 /*	output. This is currently the only supported method.
23 /* .IP \fB-v\fR
24 /*	Enable verbose logging for debugging purposes. Multiple \fB-v\fR
25 /*	options make the software increasingly verbose. As of Postfix 2.3,
26 /*	this option is available for the super-user only.
27 /* SECURITY
28 /* .ad
29 /* .fi
30 /*	The command is designed to run with set-group ID privileges, so
31 /*	that it can write to the \fBmaildrop\fR queue directory and so that
32 /*	it can connect to Postfix daemon processes.
33 /* DIAGNOSTICS
34 /*	Fatal errors: malformed input, I/O error, out of memory. Problems
35 /*	are logged to \fBsyslogd\fR(8) and to the standard error stream.
36 /*	When the input is incomplete, or when the process receives a HUP,
37 /*	INT, QUIT or TERM signal, the queue file is deleted.
38 /* ENVIRONMENT
39 /* .ad
40 /* .fi
41 /* .IP MAIL_CONFIG
42 /*	Directory with the \fBmain.cf\fR file. In order to avoid exploitation
43 /*	of set-group ID privileges, a non-standard directory is allowed only
44 /*	if:
45 /* .RS
46 /* .IP \(bu
47 /*	The name is listed in the standard \fBmain.cf\fR file with the
48 /*	\fBalternate_config_directories\fR configuration parameter.
49 /* .IP \(bu
50 /*	The command is invoked by the super-user.
51 /* .RE
52 /* CONFIGURATION PARAMETERS
53 /* .ad
54 /* .fi
55 /*	The following \fBmain.cf\fR parameters are especially relevant to
56 /*	this program.
57 /*	The text below provides only a parameter summary. See
58 /*	\fBpostconf\fR(5) for more details including examples.
59 /* .IP "\fBalternate_config_directories (empty)\fR"
60 /*	A list of non-default Postfix configuration directories that may
61 /*	be specified with "-c config_directory" on the command line, or
62 /*	via the MAIL_CONFIG environment parameter.
63 /* .IP "\fBconfig_directory (see 'postconf -d' output)\fR"
64 /*	The default location of the Postfix main.cf and master.cf
65 /*	configuration files.
66 /* .IP "\fBimport_environment (see 'postconf -d' output)\fR"
67 /*	The list of environment parameters that a Postfix process will
68 /*	import from a non-Postfix parent process.
69 /* .IP "\fBqueue_directory (see 'postconf -d' output)\fR"
70 /*	The location of the Postfix top-level queue directory.
71 /* .IP "\fBsyslog_facility (mail)\fR"
72 /*	The syslog facility of Postfix logging.
73 /* .IP "\fBsyslog_name (see 'postconf -d' output)\fR"
74 /*	The mail system name that is prepended to the process name in syslog
75 /*	records, so that "smtpd" becomes, for example, "postfix/smtpd".
76 /* .IP "\fBtrigger_timeout (10s)\fR"
77 /*	The time limit for sending a trigger to a Postfix daemon (for
78 /*	example, the \fBpickup\fR(8) or \fBqmgr\fR(8) daemon).
79 /* .PP
80 /*	Available in Postfix version 2.2 and later:
81 /* .IP "\fBauthorized_submit_users (static:anyone)\fR"
82 /*	List of users who are authorized to submit mail with the \fBsendmail\fR(1)
83 /*	command (and with the privileged \fBpostdrop\fR(1) helper command).
84 /* FILES
85 /*	/var/spool/postfix/maildrop, maildrop queue
86 /* SEE ALSO
87 /*	sendmail(1), compatibility interface
88 /*	postconf(5), configuration parameters
89 /*	syslogd(8), system logging
90 /* LICENSE
91 /* .ad
92 /* .fi
93 /*	The Secure Mailer license must be distributed with this software.
94 /* AUTHOR(S)
95 /*	Wietse Venema
96 /*	IBM T.J. Watson Research
97 /*	P.O. Box 704
98 /*	Yorktown Heights, NY 10598, USA
99 /*
100 /*	Wietse Venema
101 /*	Google, Inc.
102 /*	111 8th Avenue
103 /*	New York, NY 10011, USA
104 /*--*/
105 
106 /* System library. */
107 
108 #include <sys_defs.h>
109 #include <sys/stat.h>
110 #include <unistd.h>
111 #include <stdlib.h>
112 #include <stdio.h>			/* remove() */
113 #include <string.h>
114 #include <stdlib.h>
115 #include <signal.h>
116 #include <syslog.h>
117 #include <errno.h>
118 #include <warn_stat.h>
119 
120 /* Utility library. */
121 
122 #include <msg.h>
123 #include <mymalloc.h>
124 #include <vstream.h>
125 #include <vstring.h>
126 #include <msg_vstream.h>
127 #include <msg_syslog.h>
128 #include <argv.h>
129 #include <iostuff.h>
130 #include <stringops.h>
131 
132 /* Global library. */
133 
134 #include <mail_proto.h>
135 #include <mail_queue.h>
136 #include <mail_params.h>
137 #include <mail_version.h>
138 #include <mail_conf.h>
139 #include <mail_task.h>
140 #include <clean_env.h>
141 #include <mail_stream.h>
142 #include <cleanup_user.h>
143 #include <record.h>
144 #include <rec_type.h>
145 #include <mail_dict.h>
146 #include <user_acl.h>
147 #include <rec_attr_map.h>
148 #include <mail_parm_split.h>
149 
150 /* Application-specific. */
151 
152  /*
153   * WARNING WARNING WARNING
154   *
155   * This software is designed to run set-gid. In order to avoid exploitation of
156   * privilege, this software should not run any external commands, nor should
157   * it take any information from the user unless that information can be
158   * properly sanitized. To get an idea of how much information a process can
159   * inherit from a potentially hostile user, examine all the members of the
160   * process structure (typically, in /usr/include/sys/proc.h): the current
161   * directory, open files, timers, signals, environment, command line, umask,
162   * and so on.
163   */
164 
165  /*
166   * Local mail submission access list.
167   */
168 char   *var_submit_acl;
169 
170 static const CONFIG_STR_TABLE str_table[] = {
171     VAR_SUBMIT_ACL, DEF_SUBMIT_ACL, &var_submit_acl, 0, 0,
172     0,
173 };
174 
175  /*
176   * Queue file name. Global, so that the cleanup routine can find it when
177   * called by the run-time error handler.
178   */
179 static char *postdrop_path;
180 
181 /* postdrop_sig - catch signal and clean up */
182 
183 static void postdrop_sig(int sig)
184 {
185 
186     /*
187      * This is the fatal error handler. Don't try to do anything fancy.
188      *
189      * msg_vstream does not allocate memory, but msg_syslog may indirectly in
190      * syslog(), so it should not be called from a user-triggered signal
191      * handler.
192      *
193      * Assume atomic signal() updates, even when emulated with sigaction(). We
194      * use the in-kernel SIGINT handler address as an atomic variable to
195      * prevent nested postdrop_sig() calls. For this reason, main() must
196      * configure postdrop_sig() as SIGINT handler before other signal
197      * handlers are allowed to invoke postdrop_sig().
198      */
199     if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
200 	(void) signal(SIGQUIT, SIG_IGN);
201 	(void) signal(SIGTERM, SIG_IGN);
202 	(void) signal(SIGHUP, SIG_IGN);
203 	if (postdrop_path) {
204 	    (void) remove(postdrop_path);
205 	    postdrop_path = 0;
206 	}
207 	/* Future proofing. If you need exit() here then you broke Postfix. */
208 	if (sig)
209 	    _exit(sig);
210     }
211 }
212 
213 /* postdrop_cleanup - callback for the runtime error handler */
214 
215 static void postdrop_cleanup(void)
216 {
217     postdrop_sig(0);
218 }
219 
220 MAIL_VERSION_STAMP_DECLARE;
221 
222 /* main - the main program */
223 
224 int     main(int argc, char **argv)
225 {
226     struct stat st;
227     int     fd;
228     int     c;
229     VSTRING *buf;
230     int     status;
231     MAIL_STREAM *dst;
232     int     rec_type;
233     static char *segment_info[] = {
234 	REC_TYPE_POST_ENVELOPE, REC_TYPE_POST_CONTENT, REC_TYPE_POST_EXTRACT, ""
235     };
236     char  **expected;
237     uid_t   uid = getuid();
238     ARGV   *import_env;
239     const char *error_text;
240     char   *attr_name;
241     char   *attr_value;
242     const char *errstr;
243     char   *junk;
244     struct timeval start;
245     int     saved_errno;
246     int     from_count = 0;
247     int     rcpt_count = 0;
248     int     validate_input = 1;
249 
250     /*
251      * Fingerprint executables and core dumps.
252      */
253     MAIL_VERSION_STAMP_ALLOCATE;
254 
255     /*
256      * Be consistent with file permissions.
257      */
258     umask(022);
259 
260     /*
261      * To minimize confusion, make sure that the standard file descriptors
262      * are open before opening anything else. XXX Work around for 44BSD where
263      * fstat can return EBADF on an open file descriptor.
264      */
265     for (fd = 0; fd < 3; fd++)
266 	if (fstat(fd, &st) == -1
267 	    && (close(fd), open("/dev/null", O_RDWR, 0)) != fd)
268 	    msg_fatal("open /dev/null: %m");
269 
270     /*
271      * Set up logging. Censor the process name: it is provided by the user.
272      */
273     argv[0] = "postdrop";
274     msg_vstream_init(argv[0], VSTREAM_ERR);
275     msg_syslog_init(mail_task("postdrop"), LOG_PID, LOG_FACILITY);
276     set_mail_conf_str(VAR_PROCNAME, var_procname = mystrdup(argv[0]));
277 
278     /*
279      * Check the Postfix library version as soon as we enable logging.
280      */
281     MAIL_VERSION_CHECK;
282 
283     /*
284      * Parse JCL. This program is set-gid and must sanitize all command-line
285      * arguments. The configuration directory argument is validated by the
286      * mail configuration read routine. Don't do complex things until we have
287      * completed initializations.
288      */
289     while ((c = GETOPT(argc, argv, "c:rv")) > 0) {
290 	switch (c) {
291 	case 'c':
292 	    if (setenv(CONF_ENV_PATH, optarg, 1) < 0)
293 		msg_fatal("out of memory");
294 	    break;
295 	case 'r':				/* forward compatibility */
296 	    break;
297 	case 'v':
298 	    if (geteuid() == 0)
299 		msg_verbose++;
300 	    break;
301 	default:
302 	    msg_fatal("usage: %s [-c config_dir] [-v]", argv[0]);
303 	}
304     }
305 
306     /*
307      * Read the global configuration file and extract configuration
308      * information. Some claim that the user should supply the working
309      * directory instead. That might be OK, given that this command needs
310      * write permission in a subdirectory called "maildrop". However we still
311      * need to reliably detect incomplete input, and so we must perform
312      * record-level I/O. With that, we should also take the opportunity to
313      * perform some sanity checks on the input.
314      */
315     mail_conf_read();
316     /* Re-evaluate mail_task() after reading main.cf. */
317     msg_syslog_init(mail_task("postdrop"), LOG_PID, LOG_FACILITY);
318     get_mail_conf_str_table(str_table);
319 
320     /*
321      * Mail submission access control. Should this be in the user-land gate,
322      * or in the daemon process?
323      */
324     mail_dict_init();
325     if ((errstr = check_user_acl_byuid(VAR_SUBMIT_ACL, var_submit_acl,
326 				       uid)) != 0)
327 	msg_fatal("User %s(%ld) is not allowed to submit mail",
328 		  errstr, (long) uid);
329 
330     /*
331      * Stop run-away process accidents by limiting the queue file size. This
332      * is not a defense against DOS attack.
333      */
334     if (var_message_limit > 0 && get_file_limit() > var_message_limit)
335 	set_file_limit((off_t) var_message_limit);
336 
337     /*
338      * This program is installed with setgid privileges. Strip the process
339      * environment so that we don't have to trust the C library.
340      */
341     import_env = mail_parm_split(VAR_IMPORT_ENVIRON, var_import_environ);
342     clean_env(import_env->argv);
343     argv_free(import_env);
344 
345     if (chdir(var_queue_dir))
346 	msg_fatal("chdir %s: %m", var_queue_dir);
347     if (msg_verbose)
348 	msg_info("chdir %s", var_queue_dir);
349 
350     /*
351      * Set up signal handlers and a runtime error handler so that we can
352      * clean up incomplete output.
353      *
354      * postdrop_sig() uses the in-kernel SIGINT handler address as an atomic
355      * variable to prevent nested postdrop_sig() calls. For this reason, the
356      * SIGINT handler must be configured before other signal handlers are
357      * allowed to invoke postdrop_sig().
358      */
359     signal(SIGPIPE, SIG_IGN);
360     signal(SIGXFSZ, SIG_IGN);
361 
362     signal(SIGINT, postdrop_sig);
363     signal(SIGQUIT, postdrop_sig);
364     if (signal(SIGTERM, SIG_IGN) == SIG_DFL)
365 	signal(SIGTERM, postdrop_sig);
366     if (signal(SIGHUP, SIG_IGN) == SIG_DFL)
367 	signal(SIGHUP, postdrop_sig);
368     msg_cleanup(postdrop_cleanup);
369 
370     /* End of initializations. */
371 
372     /*
373      * Don't trust the caller's time information.
374      */
375     GETTIMEOFDAY(&start);
376 
377     /*
378      * Create queue file. mail_stream_file() never fails. Send the queue ID
379      * to the caller. Stash away a copy of the queue file name so we can
380      * clean up in case of a fatal error or an interrupt.
381      */
382     dst = mail_stream_file(MAIL_QUEUE_MAILDROP, MAIL_CLASS_PUBLIC,
383 			   var_pickup_service, 0444);
384     attr_print(VSTREAM_OUT, ATTR_FLAG_NONE,
385 	       SEND_ATTR_STR(MAIL_ATTR_QUEUEID, dst->id),
386 	       ATTR_TYPE_END);
387     vstream_fflush(VSTREAM_OUT);
388     postdrop_path = mystrdup(VSTREAM_PATH(dst->stream));
389 
390     /*
391      * Copy stdin to file. The format is checked so that we can recognize
392      * incomplete input and cancel the operation. With the sanity checks
393      * applied here, the pickup daemon could skip format checks and pass a
394      * file descriptor to the cleanup daemon. These are by no means all
395      * sanity checks - the cleanup service and queue manager services will
396      * reject messages that lack required information.
397      *
398      * If something goes wrong, slurp up the input before responding to the
399      * client, otherwise the client will give up after detecting SIGPIPE.
400      *
401      * Allow attribute records if the attribute specifies the MIME body type
402      * (sendmail -B).
403      */
404     vstream_control(VSTREAM_IN, CA_VSTREAM_CTL_PATH("stdin"), CA_VSTREAM_CTL_END);
405     buf = vstring_alloc(100);
406     expected = segment_info;
407     /* Override time information from the untrusted caller. */
408     rec_fprintf(dst->stream, REC_TYPE_TIME, REC_TYPE_TIME_FORMAT,
409 		REC_TYPE_TIME_ARG(start));
410     for (;;) {
411 	/* Don't allow PTR records. */
412 	rec_type = rec_get_raw(VSTREAM_IN, buf, var_line_limit, REC_FLAG_NONE);
413 	if (rec_type == REC_TYPE_EOF) {		/* request cancelled */
414 	    mail_stream_cleanup(dst);
415 	    if (remove(postdrop_path))
416 		msg_warn("uid=%ld: remove %s: %m", (long) uid, postdrop_path);
417 	    else if (msg_verbose)
418 		msg_info("remove %s", postdrop_path);
419 	    myfree(postdrop_path);
420 	    postdrop_path = 0;
421 	    exit(0);
422 	}
423 	if (rec_type == REC_TYPE_ERROR)
424 	    msg_fatal("uid=%ld: malformed input", (long) uid);
425 	if (strchr(*expected, rec_type) == 0)
426 	    msg_fatal("uid=%ld: unexpected record type: %d", (long) uid, rec_type);
427 	if (rec_type == **expected)
428 	    expected++;
429 	/* Override time information from the untrusted caller. */
430 	if (rec_type == REC_TYPE_TIME)
431 	    continue;
432 	/* Check these at submission time instead of pickup time. */
433 	if (rec_type == REC_TYPE_FROM)
434 	    from_count++;
435 	if (rec_type == REC_TYPE_RCPT)
436 	    rcpt_count++;
437 	/* Limit the attribute types that users may specify. */
438 	if (rec_type == REC_TYPE_ATTR) {
439 	    if ((error_text = split_nameval(vstring_str(buf), &attr_name,
440 					    &attr_value)) != 0) {
441 		msg_warn("uid=%ld: ignoring malformed record: %s: %.200s",
442 			 (long) uid, error_text, vstring_str(buf));
443 		continue;
444 	    }
445 #define STREQ(x,y) (strcmp(x,y) == 0)
446 
447 	    if ((STREQ(attr_name, MAIL_ATTR_ENCODING)
448 		 && (STREQ(attr_value, MAIL_ATTR_ENC_7BIT)
449 		     || STREQ(attr_value, MAIL_ATTR_ENC_8BIT)
450 		     || STREQ(attr_value, MAIL_ATTR_ENC_NONE)))
451 		|| STREQ(attr_name, MAIL_ATTR_DSN_ENVID)
452 		|| STREQ(attr_name, MAIL_ATTR_DSN_NOTIFY)
453 		|| rec_attr_map(attr_name)
454 		|| (STREQ(attr_name, MAIL_ATTR_RWR_CONTEXT)
455 		    && (STREQ(attr_value, MAIL_ATTR_RWR_LOCAL)
456 			|| STREQ(attr_value, MAIL_ATTR_RWR_REMOTE)))
457 		|| STREQ(attr_name, MAIL_ATTR_TRACE_FLAGS)) {	/* XXX */
458 		rec_fprintf(dst->stream, REC_TYPE_ATTR, "%s=%s",
459 			    attr_name, attr_value);
460 	    } else {
461 		msg_warn("uid=%ld: ignoring attribute record: %.200s=%.200s",
462 			 (long) uid, attr_name, attr_value);
463 	    }
464 	    continue;
465 	}
466 	if (REC_PUT_BUF(dst->stream, rec_type, buf) < 0) {
467 	    /* rec_get() errors must not clobber errno. */
468 	    saved_errno = errno;
469 	    while ((rec_type = rec_get_raw(VSTREAM_IN, buf, var_line_limit,
470 					   REC_FLAG_NONE)) != REC_TYPE_END
471 		   && rec_type != REC_TYPE_EOF)
472 		if (rec_type == REC_TYPE_ERROR)
473 		    msg_fatal("uid=%ld: malformed input", (long) uid);
474 	    validate_input = 0;
475 	    errno = saved_errno;
476 	    break;
477 	}
478 	if (rec_type == REC_TYPE_END)
479 	    break;
480     }
481     vstring_free(buf);
482 
483     /*
484      * As of Postfix 2.7 the pickup daemon discards mail without recipients.
485      * Such mail may enter the maildrop queue when "postsuper -r" is invoked
486      * before the queue manager deletes an already delivered message. Looking
487      * at file ownership is not a good way to make decisions on what mail to
488      * discard. Instead, the pickup server now requires that new submissions
489      * always have at least one recipient record.
490      *
491      * The Postfix sendmail command already rejects mail without recipients.
492      * However, in the future postdrop may receive mail via other programs,
493      * so we add a redundant recipient check here for future proofing.
494      *
495      * The test for the sender address is just for consistency of error
496      * reporting (report at submission time instead of pickup time). Besides
497      * the segment terminator records, there aren't any other mandatory
498      * records in a Postfix submission queue file.
499      */
500     if (validate_input && (from_count == 0 || rcpt_count == 0)) {
501 	status = CLEANUP_STAT_BAD;
502 	mail_stream_cleanup(dst);
503     }
504 
505     /*
506      * Finish the file.
507      */
508     else if ((status = mail_stream_finish(dst, (VSTRING *) 0)) != 0) {
509 	msg_warn("uid=%ld: %m", (long) uid);
510 	postdrop_cleanup();
511     }
512 
513     /*
514      * Disable deletion on fatal error before reporting success, so the file
515      * will not be deleted after we have taken responsibility for delivery.
516      */
517     if (postdrop_path) {
518 	junk = postdrop_path;
519 	postdrop_path = 0;
520 	myfree(junk);
521     }
522 
523     /*
524      * Send the completion status to the caller and terminate.
525      */
526     attr_print(VSTREAM_OUT, ATTR_FLAG_NONE,
527 	       SEND_ATTR_INT(MAIL_ATTR_STATUS, status),
528 	       SEND_ATTR_STR(MAIL_ATTR_WHY, ""),
529 	       ATTR_TYPE_END);
530     vstream_fflush(VSTREAM_OUT);
531     exit(status);
532 }
533