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