xref: /netbsd-src/external/ibm-public/postfix/dist/src/postqueue/postqueue.c (revision b1c86f5f087524e68db12794ee9c3e3da1ab17a0)
1 /*	$NetBSD: postqueue.c,v 1.1.1.2 2010/06/17 18:06:59 tron Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	postqueue 1
6 /* SUMMARY
7 /*	Postfix queue control
8 /* SYNOPSIS
9 /*	\fBpostqueue\fR [\fB-v\fR] [\fB-c \fIconfig_dir\fR] \fB-f\fR
10 /* .br
11 /*	\fBpostqueue\fR [\fB-v\fR] [\fB-c \fIconfig_dir\fR] \fB-i \fIqueue_id\fR
12 /* .br
13 /*	\fBpostqueue\fR [\fB-v\fR] [\fB-c \fIconfig_dir\fR] \fB-p\fR
14 /* .br
15 /*	\fBpostqueue\fR [\fB-v\fR] [\fB-c \fIconfig_dir\fR] \fB-s \fIsite\fR
16 /* DESCRIPTION
17 /*	The \fBpostqueue\fR(1) command implements the Postfix user interface
18 /*	for queue management. It implements operations that are
19 /*	traditionally available via the \fBsendmail\fR(1) command.
20 /*	See the \fBpostsuper\fR(1) command for queue operations
21 /*	that require super-user privileges such as deleting a message
22 /*	from the queue or changing the status of a message.
23 /*
24 /*	The following options are recognized:
25 /* .IP "\fB-c \fIconfig_dir\fR"
26 /*	The \fBmain.cf\fR configuration file is in the named directory
27 /*	instead of the default configuration directory. See also the
28 /*	MAIL_CONFIG environment setting below.
29 /* .IP \fB-f\fR
30 /*	Flush the queue: attempt to deliver all queued mail.
31 /*
32 /*	This option implements the traditional "\fBsendmail -q\fR" command,
33 /*	by contacting the Postfix \fBqmgr\fR(8) daemon.
34 /*
35 /*	Warning: flushing undeliverable mail frequently will result in
36 /*	poor delivery performance of all other mail.
37 /* .IP "\fB-i \fIqueue_id\fR"
38 /*	Schedule immediate delivery of deferred mail with the
39 /*	specified queue ID.
40 /*
41 /*	This option implements the traditional \fBsendmail -qI\fR
42 /*	command, by contacting the \fBflush\fR(8) server.
43 /*
44 /*	This feature is available with Postfix version 2.4 and later.
45 /* .IP \fB-p\fR
46 /*	Produce a traditional sendmail-style queue listing.
47 /*	This option implements the traditional \fBmailq\fR command,
48 /*	by contacting the Postfix \fBshowq\fR(8) daemon.
49 /*
50 /*	Each queue entry shows the queue file ID, message
51 /*	size, arrival time, sender, and the recipients that still need to
52 /*	be delivered.  If mail could not be delivered upon the last attempt,
53 /*	the reason for failure is shown. The queue ID string
54 /*	is followed by an optional status character:
55 /* .RS
56 /* .IP \fB*\fR
57 /*	The message is in the \fBactive\fR queue, i.e. the message is
58 /*	selected for delivery.
59 /* .IP \fB!\fR
60 /*	The message is in the \fBhold\fR queue, i.e. no further delivery
61 /*	attempt will be made until the mail is taken off hold.
62 /* .RE
63 /* .IP "\fB-s \fIsite\fR"
64 /*	Schedule immediate delivery of all mail that is queued for the named
65 /*	\fIsite\fR. A numerical site must be specified as a valid RFC 2821
66 /*	address literal enclosed in [], just like in email addresses.
67 /*	The site must be eligible for the "fast flush" service.
68 /*	See \fBflush\fR(8) for more information about the "fast flush"
69 /*	service.
70 /*
71 /*	This option implements the traditional "\fBsendmail -qR\fIsite\fR"
72 /*	command, by contacting the Postfix \fBflush\fR(8) daemon.
73 /* .IP \fB-v\fR
74 /*	Enable verbose logging for debugging purposes. Multiple \fB-v\fR
75 /*	options make the software increasingly verbose. As of Postfix 2.3,
76 /*	this option is available for the super-user only.
77 /* SECURITY
78 /* .ad
79 /* .fi
80 /*	This program is designed to run with set-group ID privileges, so
81 /*	that it can connect to Postfix daemon processes.
82 /* DIAGNOSTICS
83 /*	Problems are logged to \fBsyslogd\fR(8) and to the standard error
84 /*	stream.
85 /* ENVIRONMENT
86 /* .ad
87 /* .fi
88 /* .IP MAIL_CONFIG
89 /*	Directory with the \fBmain.cf\fR file. In order to avoid exploitation
90 /*	of set-group ID privileges, a non-standard directory is allowed only
91 /*	if:
92 /* .RS
93 /* .IP \(bu
94 /*	The name is listed in the standard \fBmain.cf\fR file with the
95 /*	\fBalternate_config_directories\fR configuration parameter.
96 /* .IP \(bu
97 /*	The command is invoked by the super-user.
98 /* .RE
99 /* CONFIGURATION PARAMETERS
100 /* .ad
101 /* .fi
102 /*	The following \fBmain.cf\fR parameters are especially relevant to
103 /*	this program.
104 /*	The text below provides only a parameter summary. See
105 /*	\fBpostconf\fR(5) for more details including examples.
106 /* .IP "\fBalternate_config_directories (empty)\fR"
107 /*	A list of non-default Postfix configuration directories that may
108 /*	be specified with "-c config_directory" on the command line, or
109 /*	via the MAIL_CONFIG environment parameter.
110 /* .IP "\fBconfig_directory (see 'postconf -d' output)\fR"
111 /*	The default location of the Postfix main.cf and master.cf
112 /*	configuration files.
113 /* .IP "\fBcommand_directory (see 'postconf -d' output)\fR"
114 /*	The location of all postfix administrative commands.
115 /* .IP "\fBfast_flush_domains ($relay_domains)\fR"
116 /*	Optional list of destinations that are eligible for per-destination
117 /*	logfiles with mail that is queued to those destinations.
118 /* .IP "\fBimport_environment (see 'postconf -d' output)\fR"
119 /*	The list of environment parameters that a Postfix process will
120 /*	import from a non-Postfix parent process.
121 /* .IP "\fBqueue_directory (see 'postconf -d' output)\fR"
122 /*	The location of the Postfix top-level queue directory.
123 /* .IP "\fBsyslog_facility (mail)\fR"
124 /*	The syslog facility of Postfix logging.
125 /* .IP "\fBsyslog_name (see 'postconf -d' output)\fR"
126 /*	The mail system name that is prepended to the process name in syslog
127 /*	records, so that "smtpd" becomes, for example, "postfix/smtpd".
128 /* .IP "\fBtrigger_timeout (10s)\fR"
129 /*	The time limit for sending a trigger to a Postfix daemon (for
130 /*	example, the \fBpickup\fR(8) or \fBqmgr\fR(8) daemon).
131 /* .PP
132 /*	Available in Postfix version 2.2 and later:
133 /* .IP "\fBauthorized_flush_users (static:anyone)\fR"
134 /*	List of users who are authorized to flush the queue.
135 /* .IP "\fBauthorized_mailq_users (static:anyone)\fR"
136 /*	List of users who are authorized to view the queue.
137 /* FILES
138 /*	/var/spool/postfix, mail queue
139 /* SEE ALSO
140 /*	qmgr(8), queue manager
141 /*	showq(8), list mail queue
142 /*	flush(8), fast flush service
143 /*	sendmail(1), Sendmail-compatible user interface
144 /*	postsuper(1), privileged queue operations
145 /* README FILES
146 /* .ad
147 /* .fi
148 /*	Use "\fBpostconf readme_directory\fR" or
149 /*	"\fBpostconf html_directory\fR" to locate this information.
150 /* .na
151 /* .nf
152 /*	ETRN_README, Postfix ETRN howto
153 /* LICENSE
154 /* .ad
155 /* .fi
156 /*	The Secure Mailer license must be distributed with this software.
157 /* HISTORY
158 /* .ad
159 /* .fi
160 /*	The postqueue command was introduced with Postfix version 1.1.
161 /* AUTHOR(S)
162 /*	Wietse Venema
163 /*	IBM T.J. Watson Research
164 /*	P.O. Box 704
165 /*	Yorktown Heights, NY 10598, USA
166 /*--*/
167 
168 /* System library. */
169 
170 #include <sys_defs.h>
171 #include <sys/stat.h>
172 #include <unistd.h>
173 #include <string.h>
174 #include <stdlib.h>
175 #include <signal.h>
176 #include <sysexits.h>
177 #include <errno.h>
178 
179 /* Utility library. */
180 
181 #include <msg.h>
182 #include <mymalloc.h>
183 #include <clean_env.h>
184 #include <vstream.h>
185 #include <msg_vstream.h>
186 #include <msg_syslog.h>
187 #include <argv.h>
188 #include <safe.h>
189 #include <connect.h>
190 #include <valid_hostname.h>
191 
192 /* Global library. */
193 
194 #include <mail_proto.h>
195 #include <mail_params.h>
196 #include <mail_version.h>
197 #include <mail_conf.h>
198 #include <mail_task.h>
199 #include <mail_run.h>
200 #include <mail_flush.h>
201 #include <mail_queue.h>
202 #include <flush_clnt.h>
203 #include <smtp_stream.h>
204 #include <user_acl.h>
205 #include <valid_mailhost_addr.h>
206 #include <mail_dict.h>
207 
208 /* Application-specific. */
209 
210  /*
211   * WARNING WARNING WARNING
212   *
213   * This software is designed to run set-gid. In order to avoid exploitation of
214   * privilege, this software should not run any external commands, nor should
215   * it take any information from the user, unless that information can be
216   * properly sanitized. To get an idea of how much information a process can
217   * inherit from a potentially hostile user, examine all the members of the
218   * process structure (typically, in /usr/include/sys/proc.h): the current
219   * directory, open files, timers, signals, environment, command line, umask,
220   * and so on.
221   */
222 
223  /*
224   * Modes of operation.
225   *
226   * XXX To support flush by recipient domain, or for destinations that have no
227   * mapping to logfile, the server has to defend against resource exhaustion
228   * attacks. A malicious user could fork off a postqueue client that starts
229   * an expensive requests and then kills the client immediately; this way she
230   * could create a high Postfix load on the system without ever exceeding her
231   * own per-user process limit. To prevent this, either the server needs to
232   * establish frequent proof of client liveliness with challenge/response, or
233   * the client needs to restrict expensive requests to privileged users only.
234   *
235   * We don't have this problem with queue listings. The showq server detects an
236   * EPIPE error after reporting a few queue entries.
237   */
238 #define PQ_MODE_DEFAULT		0	/* noop */
239 #define PQ_MODE_MAILQ_LIST	1	/* list mail queue */
240 #define PQ_MODE_FLUSH_QUEUE	2	/* flush queue */
241 #define PQ_MODE_FLUSH_SITE	3	/* flush site */
242 #define PQ_MODE_FLUSH_FILE	4	/* flush message */
243 
244  /*
245   * Silly little macros (SLMs).
246   */
247 #define STR	vstring_str
248 
249  /*
250   * Queue manipulation access lists.
251   */
252 char   *var_flush_acl;
253 char   *var_showq_acl;
254 
255 static const CONFIG_STR_TABLE str_table[] = {
256     VAR_FLUSH_ACL, DEF_FLUSH_ACL, &var_flush_acl, 0, 0,
257     VAR_SHOWQ_ACL, DEF_SHOWQ_ACL, &var_showq_acl, 0, 0,
258     0,
259 };
260 
261 /* show_queue - show queue status */
262 
263 static void show_queue(void)
264 {
265     const char *errstr;
266     char    buf[VSTREAM_BUFSIZE];
267     VSTREAM *showq;
268     int     n;
269     uid_t   uid = getuid();
270 
271     if (uid != 0 && uid != var_owner_uid
272 	&& (errstr = check_user_acl_byuid(var_showq_acl, uid)) != 0)
273 	msg_fatal_status(EX_NOPERM,
274 		       "User %s(%ld) is not allowed to view the mail queue",
275 			 errstr, (long) uid);
276 
277     /*
278      * Connect to the show queue service. Terminate silently when piping into
279      * a program that terminates early.
280      */
281     if ((showq = mail_connect(MAIL_CLASS_PUBLIC, var_showq_service, BLOCKING)) != 0) {
282 	while ((n = vstream_fread(showq, buf, sizeof(buf))) > 0) {
283 	    if (vstream_fwrite(VSTREAM_OUT, buf, n) != n
284 		|| vstream_fflush(VSTREAM_OUT) != 0) {
285 		if (errno == EPIPE)
286 		    break;
287 		msg_fatal("write error: %m");
288 	    }
289 	}
290 	if (vstream_fclose(showq) && errno != EPIPE)
291 	    msg_warn("close: %m");
292     }
293 
294     /*
295      * Don't assume that the mail system is down when the user has
296      * insufficient permission to access the showq socket.
297      */
298     else if (errno == EACCES) {
299 	msg_fatal_status(EX_SOFTWARE,
300 			 "Connect to the %s %s service: %m",
301 			 var_mail_name, var_showq_service);
302     }
303 
304     /*
305      * When the mail system is down, the superuser can still access the queue
306      * directly. Just run the showq program in stand-alone mode.
307      */
308     else if (geteuid() == 0) {
309 	ARGV   *argv;
310 	int     stat;
311 
312 	msg_warn("Mail system is down -- accessing queue directly");
313 	argv = argv_alloc(6);
314 	argv_add(argv, var_showq_service, "-u", "-S", (char *) 0);
315 	for (n = 0; n < msg_verbose; n++)
316 	    argv_add(argv, "-v", (char *) 0);
317 	argv_terminate(argv);
318 	stat = mail_run_foreground(var_daemon_dir, argv->argv);
319 	argv_free(argv);
320     }
321 
322     /*
323      * When the mail system is down, unprivileged users are stuck, because by
324      * design the mail system contains no set_uid programs. The only way for
325      * an unprivileged user to cross protection boundaries is to talk to the
326      * showq daemon.
327      */
328     else {
329 	msg_fatal_status(EX_UNAVAILABLE,
330 			 "Queue report unavailable - mail system is down");
331     }
332 }
333 
334 /* flush_queue - force delivery */
335 
336 static void flush_queue(void)
337 {
338     const char *errstr;
339     uid_t   uid = getuid();
340 
341     if (uid != 0 && uid != var_owner_uid
342 	&& (errstr = check_user_acl_byuid(var_flush_acl, uid)) != 0)
343 	msg_fatal_status(EX_NOPERM,
344 		      "User %s(%ld) is not allowed to flush the mail queue",
345 			 errstr, (long) uid);
346 
347     /*
348      * Trigger the flush queue service.
349      */
350     if (mail_flush_deferred() < 0)
351 	msg_fatal_status(EX_UNAVAILABLE,
352 			 "Cannot flush mail queue - mail system is down");
353     if (mail_flush_maildrop() < 0)
354 	msg_fatal_status(EX_UNAVAILABLE,
355 			 "Cannot flush mail queue - mail system is down");
356 }
357 
358 /* flush_site - flush mail for site */
359 
360 static void flush_site(const char *site)
361 {
362     int     status;
363     const char *errstr;
364     uid_t   uid = getuid();
365 
366     if (uid != 0 && uid != var_owner_uid
367 	&& (errstr = check_user_acl_byuid(var_flush_acl, uid)) != 0)
368 	msg_fatal_status(EX_NOPERM,
369 		      "User %s(%ld) is not allowed to flush the mail queue",
370 			 errstr, (long) uid);
371 
372     flush_init();
373 
374     switch (status = flush_send_site(site)) {
375     case FLUSH_STAT_OK:
376 	exit(0);
377     case FLUSH_STAT_BAD:
378 	msg_fatal_status(EX_USAGE, "Invalid request: \"%s\"", site);
379     case FLUSH_STAT_FAIL:
380 	msg_fatal_status(EX_UNAVAILABLE,
381 			 "Cannot flush mail queue - mail system is down");
382     case FLUSH_STAT_DENY:
383 	msg_fatal_status(EX_UNAVAILABLE,
384 		   "Flush service is not configured for destination \"%s\"",
385 			 site);
386     default:
387 	msg_fatal_status(EX_SOFTWARE,
388 			 "Unknown flush server reply status %d", status);
389     }
390 }
391 
392 /* flush_file - flush mail with specific queue ID */
393 
394 static void flush_file(const char *queue_id)
395 {
396     int     status;
397     const char *errstr;
398     uid_t   uid = getuid();
399 
400     if (uid != 0 && uid != var_owner_uid
401 	&& (errstr = check_user_acl_byuid(var_flush_acl, uid)) != 0)
402 	msg_fatal_status(EX_NOPERM,
403 		      "User %s(%ld) is not allowed to flush the mail queue",
404 			 errstr, (long) uid);
405 
406     switch (status = flush_send_file(queue_id)) {
407     case FLUSH_STAT_OK:
408 	exit(0);
409     case FLUSH_STAT_BAD:
410 	msg_fatal_status(EX_USAGE, "Invalid request: \"%s\"", queue_id);
411     case FLUSH_STAT_FAIL:
412 	msg_fatal_status(EX_UNAVAILABLE,
413 			 "Cannot flush mail queue - mail system is down");
414     default:
415 	msg_fatal_status(EX_SOFTWARE,
416 			 "Unexpected flush server reply status %d", status);
417     }
418 }
419 
420 /* unavailable - sanitize exit status from library run-time errors */
421 
422 static void unavailable(void)
423 {
424     exit(EX_UNAVAILABLE);
425 }
426 
427 /* usage - scream and die */
428 
429 static NORETURN usage(void)
430 {
431     msg_fatal_status(EX_USAGE, "usage: postqueue -f | postqueue -i queueid | postqueue -p | postqueue -s site");
432 }
433 
434 MAIL_VERSION_STAMP_DECLARE;
435 
436 /* main - the main program */
437 
438 int     main(int argc, char **argv)
439 {
440     struct stat st;
441     char   *slash;
442     int     c;
443     int     fd;
444     int     mode = PQ_MODE_DEFAULT;
445     char   *site_to_flush = 0;
446     char   *id_to_flush = 0;
447     ARGV   *import_env;
448     int     bad_site;
449 
450     /*
451      * Fingerprint executables and core dumps.
452      */
453     MAIL_VERSION_STAMP_ALLOCATE;
454 
455     /*
456      * Be consistent with file permissions.
457      */
458     umask(022);
459 
460     /*
461      * To minimize confusion, make sure that the standard file descriptors
462      * are open before opening anything else. XXX Work around for 44BSD where
463      * fstat can return EBADF on an open file descriptor.
464      */
465     for (fd = 0; fd < 3; fd++)
466 	if (fstat(fd, &st) == -1
467 	    && (close(fd), open("/dev/null", O_RDWR, 0)) != fd)
468 	    msg_fatal_status(EX_UNAVAILABLE, "open /dev/null: %m");
469 
470     /*
471      * Initialize. Set up logging, read the global configuration file and
472      * extract configuration information. Set up signal handlers so that we
473      * can clean up incomplete output.
474      */
475     if ((slash = strrchr(argv[0], '/')) != 0 && slash[1])
476 	argv[0] = slash + 1;
477     msg_vstream_init(argv[0], VSTREAM_ERR);
478     msg_cleanup(unavailable);
479     msg_syslog_init(mail_task("postqueue"), LOG_PID, LOG_FACILITY);
480     set_mail_conf_str(VAR_PROCNAME, var_procname = mystrdup(argv[0]));
481 
482     /*
483      * Parse JCL. This program is set-gid and must sanitize all command-line
484      * parameters. The configuration directory argument is validated by the
485      * mail configuration read routine. Don't do complex things until we have
486      * completed initializations.
487      */
488     while ((c = GETOPT(argc, argv, "c:fi:ps:v")) > 0) {
489 	switch (c) {
490 	case 'c':				/* non-default configuration */
491 	    if (setenv(CONF_ENV_PATH, optarg, 1) < 0)
492 		msg_fatal_status(EX_UNAVAILABLE, "out of memory");
493 	    break;
494 	case 'f':				/* flush queue */
495 	    if (mode != PQ_MODE_DEFAULT)
496 		usage();
497 	    mode = PQ_MODE_FLUSH_QUEUE;
498 	    break;
499 	case 'i':				/* flush queue file */
500 	    if (mode != PQ_MODE_DEFAULT)
501 		usage();
502 	    mode = PQ_MODE_FLUSH_FILE;
503 	    id_to_flush = optarg;
504 	    break;
505 	case 'p':				/* traditional mailq */
506 	    if (mode != PQ_MODE_DEFAULT)
507 		usage();
508 	    mode = PQ_MODE_MAILQ_LIST;
509 	    break;
510 	case 's':				/* flush site */
511 	    if (mode != PQ_MODE_DEFAULT)
512 		usage();
513 	    mode = PQ_MODE_FLUSH_SITE;
514 	    site_to_flush = optarg;
515 	    break;
516 	case 'v':
517 	    if (geteuid() == 0)
518 		msg_verbose++;
519 	    break;
520 	default:
521 	    usage();
522 	}
523     }
524     if (argc > optind)
525 	usage();
526 
527     /*
528      * Further initialization...
529      */
530     mail_conf_read();
531     if (strcmp(var_syslog_name, DEF_SYSLOG_NAME) != 0)
532 	msg_syslog_init(mail_task("postqueue"), LOG_PID, LOG_FACILITY);
533     mail_dict_init();				/* proxy, sql, ldap */
534     get_mail_conf_str_table(str_table);
535 
536     /*
537      * This program is designed to be set-gid, which makes it a potential
538      * target for attack. If not running as root, strip the environment so we
539      * don't have to trust the C library. If running as root, don't strip the
540      * environment so that showq can receive non-default configuration
541      * directory info when the mail system is down.
542      */
543     if (geteuid() != 0) {
544 	import_env = argv_split(var_import_environ, ", \t\r\n");
545 	clean_env(import_env->argv);
546 	argv_free(import_env);
547     }
548     if (chdir(var_queue_dir))
549 	msg_fatal_status(EX_UNAVAILABLE, "chdir %s: %m", var_queue_dir);
550 
551     signal(SIGPIPE, SIG_IGN);
552 
553     /* End of initializations. */
554 
555     /*
556      * Further input validation.
557      */
558     if (site_to_flush != 0) {
559 	bad_site = 0;
560 	if (*site_to_flush == '[') {
561 	    bad_site = !valid_mailhost_literal(site_to_flush, DONT_GRIPE);
562 	} else {
563 	    bad_site = !valid_hostname(site_to_flush, DONT_GRIPE);
564 	}
565 	if (bad_site)
566 	    msg_fatal_status(EX_USAGE,
567 	      "Cannot flush mail queue - invalid destination: \"%.100s%s\"",
568 		   site_to_flush, strlen(site_to_flush) > 100 ? "..." : "");
569     }
570     if (id_to_flush != 0) {
571 	if (!mail_queue_id_ok(id_to_flush))
572 	    msg_fatal_status(EX_USAGE,
573 		       "Cannot flush queue ID - invalid name: \"%.100s%s\"",
574 		       id_to_flush, strlen(id_to_flush) > 100 ? "..." : "");
575     }
576 
577     /*
578      * Start processing.
579      */
580     switch (mode) {
581     default:
582 	msg_panic("unknown operation mode: %d", mode);
583 	/* NOTREACHED */
584     case PQ_MODE_MAILQ_LIST:
585 	show_queue();
586 	exit(0);
587 	break;
588     case PQ_MODE_FLUSH_SITE:
589 	flush_site(site_to_flush);
590 	exit(0);
591 	break;
592     case PQ_MODE_FLUSH_FILE:
593 	flush_file(id_to_flush);
594 	exit(0);
595 	break;
596     case PQ_MODE_FLUSH_QUEUE:
597 	flush_queue();
598 	exit(0);
599 	break;
600     case PQ_MODE_DEFAULT:
601 	usage();
602 	/* NOTREACHED */
603     }
604 }
605