xref: /netbsd-src/external/ibm-public/postfix/dist/src/postdrop/postdrop.c (revision 413d532bcc3f62d122e56d92e13ac64825a40baf)
1 /*	$NetBSD: postdrop.c,v 1.1.1.4 2013/01/02 18:59:03 tron 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 
101 /* System library. */
102 
103 #include <sys_defs.h>
104 #include <sys/stat.h>
105 #include <unistd.h>
106 #include <stdlib.h>
107 #include <stdio.h>			/* remove() */
108 #include <string.h>
109 #include <stdlib.h>
110 #include <signal.h>
111 #include <syslog.h>
112 #include <errno.h>
113 #include <warn_stat.h>
114 
115 /* Utility library. */
116 
117 #include <msg.h>
118 #include <mymalloc.h>
119 #include <vstream.h>
120 #include <vstring.h>
121 #include <msg_vstream.h>
122 #include <msg_syslog.h>
123 #include <argv.h>
124 #include <iostuff.h>
125 #include <stringops.h>
126 
127 /* Global library. */
128 
129 #include <mail_proto.h>
130 #include <mail_queue.h>
131 #include <mail_params.h>
132 #include <mail_version.h>
133 #include <mail_conf.h>
134 #include <mail_task.h>
135 #include <clean_env.h>
136 #include <mail_stream.h>
137 #include <cleanup_user.h>
138 #include <record.h>
139 #include <rec_type.h>
140 #include <user_acl.h>
141 #include <rec_attr_map.h>
142 
143 /* Application-specific. */
144 
145  /*
146   * WARNING WARNING WARNING
147   *
148   * This software is designed to run set-gid. In order to avoid exploitation of
149   * privilege, this software should not run any external commands, nor should
150   * it take any information from the user unless that information can be
151   * properly sanitized. To get an idea of how much information a process can
152   * inherit from a potentially hostile user, examine all the members of the
153   * process structure (typically, in /usr/include/sys/proc.h): the current
154   * directory, open files, timers, signals, environment, command line, umask,
155   * and so on.
156   */
157 
158  /*
159   * Local mail submission access list.
160   */
161 char   *var_submit_acl;
162 
163 static const CONFIG_STR_TABLE str_table[] = {
164     VAR_SUBMIT_ACL, DEF_SUBMIT_ACL, &var_submit_acl, 0, 0,
165     0,
166 };
167 
168  /*
169   * Queue file name. Global, so that the cleanup routine can find it when
170   * called by the run-time error handler.
171   */
172 static char *postdrop_path;
173 
174 /* postdrop_sig - catch signal and clean up */
175 
176 static void postdrop_sig(int sig)
177 {
178 
179     /*
180      * This is the fatal error handler. Don't try to do anything fancy.
181      *
182      * msg_vstream does not allocate memory, but msg_syslog may indirectly in
183      * syslog(), so it should not be called from a user-triggered signal
184      * handler.
185      *
186      * Assume atomic signal() updates, even when emulated with sigaction(). We
187      * use the in-kernel SIGINT handler address as an atomic variable to
188      * prevent nested postdrop_sig() calls. For this reason, main() must
189      * configure postdrop_sig() as SIGINT handler before other signal
190      * handlers are allowed to invoke postdrop_sig().
191      */
192     if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
193 	(void) signal(SIGQUIT, SIG_IGN);
194 	(void) signal(SIGTERM, SIG_IGN);
195 	(void) signal(SIGHUP, SIG_IGN);
196 	if (postdrop_path) {
197 	    (void) remove(postdrop_path);
198 	    postdrop_path = 0;
199 	}
200 	/* Future proofing. If you need exit() here then you broke Postfix. */
201 	if (sig)
202 	    _exit(sig);
203     }
204 }
205 
206 /* postdrop_cleanup - callback for the runtime error handler */
207 
208 static void postdrop_cleanup(void)
209 {
210     postdrop_sig(0);
211 }
212 
213 MAIL_VERSION_STAMP_DECLARE;
214 
215 /* main - the main program */
216 
217 int     main(int argc, char **argv)
218 {
219     struct stat st;
220     int     fd;
221     int     c;
222     VSTRING *buf;
223     int     status;
224     MAIL_STREAM *dst;
225     int     rec_type;
226     static char *segment_info[] = {
227 	REC_TYPE_POST_ENVELOPE, REC_TYPE_POST_CONTENT, REC_TYPE_POST_EXTRACT, ""
228     };
229     char  **expected;
230     uid_t   uid = getuid();
231     ARGV   *import_env;
232     const char *error_text;
233     char   *attr_name;
234     char   *attr_value;
235     const char *errstr;
236     char   *junk;
237     struct timeval start;
238     int     saved_errno;
239     int     from_count = 0;
240     int     rcpt_count = 0;
241     int     validate_input = 1;
242 
243     /*
244      * Fingerprint executables and core dumps.
245      */
246     MAIL_VERSION_STAMP_ALLOCATE;
247 
248     /*
249      * Be consistent with file permissions.
250      */
251     umask(022);
252 
253     /*
254      * To minimize confusion, make sure that the standard file descriptors
255      * are open before opening anything else. XXX Work around for 44BSD where
256      * fstat can return EBADF on an open file descriptor.
257      */
258     for (fd = 0; fd < 3; fd++)
259 	if (fstat(fd, &st) == -1
260 	    && (close(fd), open("/dev/null", O_RDWR, 0)) != fd)
261 	    msg_fatal("open /dev/null: %m");
262 
263     /*
264      * Set up logging. Censor the process name: it is provided by the user.
265      */
266     argv[0] = "postdrop";
267     msg_vstream_init(argv[0], VSTREAM_ERR);
268     msg_syslog_init(mail_task("postdrop"), LOG_PID, LOG_FACILITY);
269     set_mail_conf_str(VAR_PROCNAME, var_procname = mystrdup(argv[0]));
270 
271     /*
272      * Check the Postfix library version as soon as we enable logging.
273      */
274     MAIL_VERSION_CHECK;
275 
276     /*
277      * Parse JCL. This program is set-gid and must sanitize all command-line
278      * arguments. The configuration directory argument is validated by the
279      * mail configuration read routine. Don't do complex things until we have
280      * completed initializations.
281      */
282     while ((c = GETOPT(argc, argv, "c:rv")) > 0) {
283 	switch (c) {
284 	case 'c':
285 	    if (setenv(CONF_ENV_PATH, optarg, 1) < 0)
286 		msg_fatal("out of memory");
287 	    break;
288 	case 'r':				/* forward compatibility */
289 	    break;
290 	case 'v':
291 	    if (geteuid() == 0)
292 		msg_verbose++;
293 	    break;
294 	default:
295 	    msg_fatal("usage: %s [-c config_dir] [-v]", argv[0]);
296 	}
297     }
298 
299     /*
300      * Read the global configuration file and extract configuration
301      * information. Some claim that the user should supply the working
302      * directory instead. That might be OK, given that this command needs
303      * write permission in a subdirectory called "maildrop". However we still
304      * need to reliably detect incomplete input, and so we must perform
305      * record-level I/O. With that, we should also take the opportunity to
306      * perform some sanity checks on the input.
307      */
308     mail_conf_read();
309     if (strcmp(var_syslog_name, DEF_SYSLOG_NAME) != 0)
310 	msg_syslog_init(mail_task("postdrop"), LOG_PID, LOG_FACILITY);
311     get_mail_conf_str_table(str_table);
312 
313     /*
314      * Mail submission access control. Should this be in the user-land gate,
315      * or in the daemon process?
316      */
317     if ((errstr = check_user_acl_byuid(var_submit_acl, uid)) != 0)
318 	msg_fatal("User %s(%ld) is not allowed to submit mail",
319 		  errstr, (long) uid);
320 
321     /*
322      * Stop run-away process accidents by limiting the queue file size. This
323      * is not a defense against DOS attack.
324      */
325     if (var_message_limit > 0 && get_file_limit() > var_message_limit)
326 	set_file_limit((off_t) var_message_limit);
327 
328     /*
329      * This program is installed with setgid privileges. Strip the process
330      * environment so that we don't have to trust the C library.
331      */
332     import_env = argv_split(var_import_environ, ", \t\r\n");
333     clean_env(import_env->argv);
334     argv_free(import_env);
335 
336     if (chdir(var_queue_dir))
337 	msg_fatal("chdir %s: %m", var_queue_dir);
338     if (msg_verbose)
339 	msg_info("chdir %s", var_queue_dir);
340 
341     /*
342      * Set up signal handlers and a runtime error handler so that we can
343      * clean up incomplete output.
344      *
345      * postdrop_sig() uses the in-kernel SIGINT handler address as an atomic
346      * variable to prevent nested postdrop_sig() calls. For this reason, the
347      * SIGINT handler must be configured before other signal handlers are
348      * allowed to invoke postdrop_sig().
349      */
350     signal(SIGPIPE, SIG_IGN);
351     signal(SIGXFSZ, SIG_IGN);
352 
353     signal(SIGINT, postdrop_sig);
354     signal(SIGQUIT, postdrop_sig);
355     if (signal(SIGTERM, SIG_IGN) == SIG_DFL)
356 	signal(SIGTERM, postdrop_sig);
357     if (signal(SIGHUP, SIG_IGN) == SIG_DFL)
358 	signal(SIGHUP, postdrop_sig);
359     msg_cleanup(postdrop_cleanup);
360 
361     /* End of initializations. */
362 
363     /*
364      * Don't trust the caller's time information.
365      */
366     GETTIMEOFDAY(&start);
367 
368     /*
369      * Create queue file. mail_stream_file() never fails. Send the queue ID
370      * to the caller. Stash away a copy of the queue file name so we can
371      * clean up in case of a fatal error or an interrupt.
372      */
373     dst = mail_stream_file(MAIL_QUEUE_MAILDROP, MAIL_CLASS_PUBLIC,
374 			   var_pickup_service, 0444);
375     attr_print(VSTREAM_OUT, ATTR_FLAG_NONE,
376 	       ATTR_TYPE_STR, MAIL_ATTR_QUEUEID, dst->id,
377 	       ATTR_TYPE_END);
378     vstream_fflush(VSTREAM_OUT);
379     postdrop_path = mystrdup(VSTREAM_PATH(dst->stream));
380 
381     /*
382      * Copy stdin to file. The format is checked so that we can recognize
383      * incomplete input and cancel the operation. With the sanity checks
384      * applied here, the pickup daemon could skip format checks and pass a
385      * file descriptor to the cleanup daemon. These are by no means all
386      * sanity checks - the cleanup service and queue manager services will
387      * reject messages that lack required information.
388      *
389      * If something goes wrong, slurp up the input before responding to the
390      * client, otherwise the client will give up after detecting SIGPIPE.
391      *
392      * Allow attribute records if the attribute specifies the MIME body type
393      * (sendmail -B).
394      */
395     vstream_control(VSTREAM_IN, VSTREAM_CTL_PATH, "stdin", VSTREAM_CTL_END);
396     buf = vstring_alloc(100);
397     expected = segment_info;
398     /* Override time information from the untrusted caller. */
399     rec_fprintf(dst->stream, REC_TYPE_TIME, REC_TYPE_TIME_FORMAT,
400 		REC_TYPE_TIME_ARG(start));
401     for (;;) {
402 	/* Don't allow PTR records. */
403 	rec_type = rec_get_raw(VSTREAM_IN, buf, var_line_limit, REC_FLAG_NONE);
404 	if (rec_type == REC_TYPE_EOF) {		/* request cancelled */
405 	    mail_stream_cleanup(dst);
406 	    if (remove(postdrop_path))
407 		msg_warn("uid=%ld: remove %s: %m", (long) uid, postdrop_path);
408 	    else if (msg_verbose)
409 		msg_info("remove %s", postdrop_path);
410 	    myfree(postdrop_path);
411 	    postdrop_path = 0;
412 	    exit(0);
413 	}
414 	if (rec_type == REC_TYPE_ERROR)
415 	    msg_fatal("uid=%ld: malformed input", (long) uid);
416 	if (strchr(*expected, rec_type) == 0)
417 	    msg_fatal("uid=%ld: unexpected record type: %d", (long) uid, rec_type);
418 	if (rec_type == **expected)
419 	    expected++;
420 	/* Override time information from the untrusted caller. */
421 	if (rec_type == REC_TYPE_TIME)
422 	    continue;
423 	/* Check these at submission time instead of pickup time. */
424 	if (rec_type == REC_TYPE_FROM)
425 	    from_count++;
426 	if (rec_type == REC_TYPE_RCPT)
427 	    rcpt_count++;
428 	/* Limit the attribute types that users may specify. */
429 	if (rec_type == REC_TYPE_ATTR) {
430 	    if ((error_text = split_nameval(vstring_str(buf), &attr_name,
431 					    &attr_value)) != 0) {
432 		msg_warn("uid=%ld: ignoring malformed record: %s: %.200s",
433 			 (long) uid, error_text, vstring_str(buf));
434 		continue;
435 	    }
436 #define STREQ(x,y) (strcmp(x,y) == 0)
437 
438 	    if ((STREQ(attr_name, MAIL_ATTR_ENCODING)
439 		 && (STREQ(attr_value, MAIL_ATTR_ENC_7BIT)
440 		     || STREQ(attr_value, MAIL_ATTR_ENC_8BIT)
441 		     || STREQ(attr_value, MAIL_ATTR_ENC_NONE)))
442 		|| STREQ(attr_name, MAIL_ATTR_DSN_ENVID)
443 		|| STREQ(attr_name, MAIL_ATTR_DSN_NOTIFY)
444 		|| rec_attr_map(attr_name)
445 		|| (STREQ(attr_name, MAIL_ATTR_RWR_CONTEXT)
446 		    && (STREQ(attr_value, MAIL_ATTR_RWR_LOCAL)
447 			|| STREQ(attr_value, MAIL_ATTR_RWR_REMOTE)))
448 		|| STREQ(attr_name, MAIL_ATTR_TRACE_FLAGS)) {	/* XXX */
449 		rec_fprintf(dst->stream, REC_TYPE_ATTR, "%s=%s",
450 			    attr_name, attr_value);
451 	    } else {
452 		msg_warn("uid=%ld: ignoring attribute record: %.200s=%.200s",
453 			 (long) uid, attr_name, attr_value);
454 	    }
455 	    continue;
456 	}
457 	if (REC_PUT_BUF(dst->stream, rec_type, buf) < 0) {
458 	    /* rec_get() errors must not clobber errno. */
459 	    saved_errno = errno;
460 	    while ((rec_type = rec_get_raw(VSTREAM_IN, buf, var_line_limit,
461 					   REC_FLAG_NONE)) != REC_TYPE_END
462 		   && rec_type != REC_TYPE_EOF)
463 		if (rec_type == REC_TYPE_ERROR)
464 		    msg_fatal("uid=%ld: malformed input", (long) uid);
465 	    validate_input = 0;
466 	    errno = saved_errno;
467 	    break;
468 	}
469 	if (rec_type == REC_TYPE_END)
470 	    break;
471     }
472     vstring_free(buf);
473 
474     /*
475      * As of Postfix 2.7 the pickup daemon discards mail without recipients.
476      * Such mail may enter the maildrop queue when "postsuper -r" is invoked
477      * before the queue manager deletes an already delivered message. Looking
478      * at file ownership is not a good way to make decisions on what mail to
479      * discard. Instead, the pickup server now requires that new submissions
480      * always have at least one recipient record.
481      *
482      * The Postfix sendmail command already rejects mail without recipients.
483      * However, in the future postdrop may receive mail via other programs,
484      * so we add a redundant recipient check here for future proofing.
485      *
486      * The test for the sender address is just for consistency of error
487      * reporting (report at submission time instead of pickup time). Besides
488      * the segment terminator records, there aren't any other mandatory
489      * records in a Postfix submission queue file.
490      */
491     if (validate_input && (from_count == 0 || rcpt_count == 0)) {
492 	status = CLEANUP_STAT_BAD;
493 	mail_stream_cleanup(dst);
494     }
495 
496     /*
497      * Finish the file.
498      */
499     else if ((status = mail_stream_finish(dst, (VSTRING *) 0)) != 0) {
500 	msg_warn("uid=%ld: %m", (long) uid);
501 	postdrop_cleanup();
502     }
503 
504     /*
505      * Disable deletion on fatal error before reporting success, so the file
506      * will not be deleted after we have taken responsibility for delivery.
507      */
508     if (postdrop_path) {
509 	junk = postdrop_path;
510 	postdrop_path = 0;
511 	myfree(junk);
512     }
513 
514     /*
515      * Send the completion status to the caller and terminate.
516      */
517     attr_print(VSTREAM_OUT, ATTR_FLAG_NONE,
518 	       ATTR_TYPE_INT, MAIL_ATTR_STATUS, status,
519 	       ATTR_TYPE_STR, MAIL_ATTR_WHY, "",
520 	       ATTR_TYPE_END);
521     vstream_fflush(VSTREAM_OUT);
522     exit(status);
523 }
524