xref: /netbsd-src/external/ibm-public/postfix/dist/src/tlsmgr/tlsmgr.c (revision 501cd18a74d52bfcca7d9e7e3b0d472bbc870558)
1 /*	$NetBSD: tlsmgr.c,v 1.1.1.3 2014/07/06 19:27:57 tron Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	tlsmgr 8
6 /* SUMMARY
7 /*	Postfix TLS session cache and PRNG manager
8 /* SYNOPSIS
9 /*	\fBtlsmgr\fR [generic Postfix daemon options]
10 /* DESCRIPTION
11 /*	The \fBtlsmgr\fR(8) manages the Postfix TLS session caches.
12 /*	It stores and retrieves cache entries on request by
13 /*	\fBsmtpd\fR(8) and \fBsmtp\fR(8) processes, and periodically
14 /*	removes entries that have expired.
15 /*
16 /*	The \fBtlsmgr\fR(8) also manages the PRNG (pseudo random number
17 /*	generator) pool. It answers queries by the \fBsmtpd\fR(8)
18 /*	and \fBsmtp\fR(8)
19 /*	processes to seed their internal PRNG pools.
20 /*
21 /*	The \fBtlsmgr\fR(8)'s PRNG pool is initially seeded from
22 /*	an external source (EGD, /dev/urandom, or regular file).
23 /*	It is updated at configurable pseudo-random intervals with
24 /*	data from the external source. It is updated periodically
25 /*	with data from TLS session cache entries and with the time
26 /*	of day, and is updated with the time of day whenever a
27 /*	process requests \fBtlsmgr\fR(8) service.
28 /*
29 /*	The \fBtlsmgr\fR(8) saves the PRNG state to an exchange file
30 /*	periodically and when the process terminates, and reads
31 /*	the exchange file when initializing its PRNG.
32 /* SECURITY
33 /* .ad
34 /* .fi
35 /*	The \fBtlsmgr\fR(8) is not security-sensitive. The code that maintains
36 /*	the external and internal PRNG pools does not "trust" the
37 /*	data that it manipulates, and the code that maintains the
38 /*	TLS session cache does not touch the contents of the cached
39 /*	entries, except for seeding its internal PRNG pool.
40 /*
41 /*	The \fBtlsmgr\fR(8) can be run chrooted and with reduced privileges.
42 /*	At process startup it connects to the entropy source and
43 /*	exchange file, and creates or truncates the optional TLS
44 /*	session cache files.
45 /*
46 /*	With Postfix version 2.5 and later, the \fBtlsmgr\fR(8) no
47 /*	longer uses root privileges when opening cache files. These
48 /*	files should now be stored under the Postfix-owned
49 /*	\fBdata_directory\fR.  As a migration aid, an attempt to
50 /*	open a cache file under a non-Postfix directory is redirected
51 /*	to the Postfix-owned \fBdata_directory\fR, and a warning
52 /*	is logged.
53 /* DIAGNOSTICS
54 /*	Problems and transactions are logged to the syslog daemon.
55 /* BUGS
56 /*	There is no automatic means to limit the number of entries in the
57 /*	TLS session caches and/or the size of the TLS cache files.
58 /* CONFIGURATION PARAMETERS
59 /* .ad
60 /* .fi
61 /*	Changes to \fBmain.cf\fR are not picked up automatically,
62 /*	because \fBtlsmgr\fR(8) is a persistent processes.  Use the
63 /*	command "\fBpostfix reload\fR" after a configuration change.
64 /*
65 /*	The text below provides only a parameter summary. See
66 /*	\fBpostconf\fR(5) for more details including examples.
67 /* TLS SESSION CACHE
68 /* .ad
69 /* .fi
70 /* .IP "\fBlmtp_tls_loglevel (0)\fR"
71 /*	The LMTP-specific version of the smtp_tls_loglevel
72 /*	configuration parameter.
73 /* .IP "\fBlmtp_tls_session_cache_database (empty)\fR"
74 /*	The LMTP-specific version of the smtp_tls_session_cache_database
75 /*	configuration parameter.
76 /* .IP "\fBlmtp_tls_session_cache_timeout (3600s)\fR"
77 /*	The LMTP-specific version of the smtp_tls_session_cache_timeout
78 /*	configuration parameter.
79 /* .IP "\fBsmtp_tls_loglevel (0)\fR"
80 /*	Enable additional Postfix SMTP client logging of TLS activity.
81 /* .IP "\fBsmtp_tls_session_cache_database (empty)\fR"
82 /*	Name of the file containing the optional Postfix SMTP client
83 /*	TLS session cache.
84 /* .IP "\fBsmtp_tls_session_cache_timeout (3600s)\fR"
85 /*	The expiration time of Postfix SMTP client TLS session cache
86 /*	information.
87 /* .IP "\fBsmtpd_tls_loglevel (0)\fR"
88 /*	Enable additional Postfix SMTP server logging of TLS activity.
89 /* .IP "\fBsmtpd_tls_session_cache_database (empty)\fR"
90 /*	Name of the file containing the optional Postfix SMTP server
91 /*	TLS session cache.
92 /* .IP "\fBsmtpd_tls_session_cache_timeout (3600s)\fR"
93 /*	The expiration time of Postfix SMTP server TLS session cache
94 /*	information.
95 /* PSEUDO RANDOM NUMBER GENERATOR
96 /* .ad
97 /* .fi
98 /* .IP "\fBtls_random_source (see 'postconf -d' output)\fR"
99 /*	The external entropy source for the in-memory \fBtlsmgr\fR(8) pseudo
100 /*	random number generator (PRNG) pool.
101 /* .IP "\fBtls_random_bytes (32)\fR"
102 /*	The number of bytes that \fBtlsmgr\fR(8) reads from $tls_random_source
103 /*	when (re)seeding the in-memory pseudo random number generator (PRNG)
104 /*	pool.
105 /* .IP "\fBtls_random_exchange_name (see 'postconf -d' output)\fR"
106 /*	Name of the pseudo random number generator (PRNG) state file
107 /*	that is maintained by \fBtlsmgr\fR(8).
108 /* .IP "\fBtls_random_prng_update_period (3600s)\fR"
109 /*	The time between attempts by \fBtlsmgr\fR(8) to save the state of
110 /*	the pseudo random number generator (PRNG) to the file specified
111 /*	with $tls_random_exchange_name.
112 /* .IP "\fBtls_random_reseed_period (3600s)\fR"
113 /*	The maximal time between attempts by \fBtlsmgr\fR(8) to re-seed the
114 /*	in-memory pseudo random number generator (PRNG) pool from external
115 /*	sources.
116 /* MISCELLANEOUS CONTROLS
117 /* .ad
118 /* .fi
119 /* .IP "\fBconfig_directory (see 'postconf -d' output)\fR"
120 /*	The default location of the Postfix main.cf and master.cf
121 /*	configuration files.
122 /* .IP "\fBdata_directory (see 'postconf -d' output)\fR"
123 /*	The directory with Postfix-writable data files (for example:
124 /*	caches, pseudo-random numbers).
125 /* .IP "\fBdaemon_timeout (18000s)\fR"
126 /*	How much time a Postfix daemon process may take to handle a
127 /*	request before it is terminated by a built-in watchdog timer.
128 /* .IP "\fBprocess_id (read-only)\fR"
129 /*	The process ID of a Postfix command or daemon process.
130 /* .IP "\fBprocess_name (read-only)\fR"
131 /*	The process name of a Postfix command or daemon process.
132 /* .IP "\fBsyslog_facility (mail)\fR"
133 /*	The syslog facility of Postfix logging.
134 /* .IP "\fBsyslog_name (see 'postconf -d' output)\fR"
135 /*	The mail system name that is prepended to the process name in syslog
136 /*	records, so that "smtpd" becomes, for example, "postfix/smtpd".
137 /* SEE ALSO
138 /*	smtp(8), Postfix SMTP client
139 /*	smtpd(8), Postfix SMTP server
140 /*	postconf(5), configuration parameters
141 /*	master(5), generic daemon options
142 /*	master(8), process manager
143 /*	syslogd(8), system logging
144 /* README FILES
145 /* .ad
146 /* .fi
147 /*	Use "\fBpostconf readme_directory\fR" or
148 /*	"\fBpostconf html_directory\fR" to locate this information.
149 /* .na
150 /* .nf
151 /*	TLS_README, Postfix TLS configuration and operation
152 /* LICENSE
153 /* .ad
154 /* .fi
155 /*	The Secure Mailer license must be distributed with this software.
156 /* HISTORY
157 /*	This service was introduced with Postfix version 2.2.
158 /* AUTHOR(S)
159 /*	Lutz Jaenicke
160 /*	BTU Cottbus
161 /*	Allgemeine Elektrotechnik
162 /*	Universitaetsplatz 3-4
163 /*	D-03044 Cottbus, Germany
164 /*
165 /*	Adapted by:
166 /*	Wietse Venema
167 /*	IBM T.J. Watson Research
168 /*	P.O. Box 704
169 /*	Yorktown Heights, NY 10598, USA
170 /*--*/
171 
172 /* System library. */
173 
174 #include <sys_defs.h>
175 #include <sys/stat.h>
176 #include <stdlib.h>
177 #include <unistd.h>
178 #include <ctype.h>
179 #include <errno.h>
180 #include <string.h>
181 #include <sys/time.h>			/* gettimeofday, not POSIX */
182 #include <limits.h>
183 
184 #ifndef UCHAR_MAX
185 #define UCHAR_MAX 0xff
186 #endif
187 
188 /* OpenSSL library. */
189 
190 #ifdef USE_TLS
191 #include <openssl/rand.h>		/* For the PRNG */
192 #endif
193 
194 /* Utility library. */
195 
196 #include <msg.h>
197 #include <events.h>
198 #include <stringops.h>
199 #include <mymalloc.h>
200 #include <iostuff.h>
201 #include <vstream.h>
202 #include <vstring.h>
203 #include <vstring_vstream.h>
204 #include <attr.h>
205 #include <set_eugid.h>
206 #include <htable.h>
207 #include <warn_stat.h>
208 
209 /* Global library. */
210 
211 #include <mail_conf.h>
212 #include <mail_params.h>
213 #include <mail_version.h>
214 #include <mail_proto.h>
215 #include <data_redirect.h>
216 
217 /* Master process interface. */
218 
219 #include <master_proto.h>
220 #include <mail_server.h>
221 
222 /* TLS library. */
223 
224 #ifdef USE_TLS
225 #include <tls_mgr.h>
226 #define TLS_INTERNAL
227 #include <tls.h>			/* TLS_MGR_SCACHE_<type> */
228 #include <tls_prng.h>
229 #include <tls_scache.h>
230 
231 /* Application-specific. */
232 
233  /*
234   * Tunables.
235   */
236 char   *var_tls_rand_source;
237 int     var_tls_rand_bytes;
238 int     var_tls_reseed_period;
239 int     var_tls_prng_exch_period;
240 char   *var_smtpd_tls_loglevel;
241 char   *var_smtpd_tls_scache_db;
242 int     var_smtpd_tls_scache_timeout;
243 char   *var_smtp_tls_loglevel;
244 char   *var_smtp_tls_scache_db;
245 int     var_smtp_tls_scache_timeout;
246 char   *var_lmtp_tls_loglevel;
247 char   *var_lmtp_tls_scache_db;
248 int     var_lmtp_tls_scache_timeout;
249 char   *var_tls_rand_exch_name;
250 
251  /*
252   * Bound the time that we are willing to wait for an I/O operation. This
253   * produces better error messages than waiting until the watchdog timer
254   * kills the process.
255   */
256 #define TLS_MGR_TIMEOUT	10
257 
258  /*
259   * State for updating the PRNG exchange file.
260   */
261 static TLS_PRNG_SRC *rand_exch;
262 
263  /*
264   * State for seeding the internal PRNG from external source.
265   */
266 static TLS_PRNG_SRC *rand_source_dev;
267 static TLS_PRNG_SRC *rand_source_egd;
268 static TLS_PRNG_SRC *rand_source_file;
269 
270  /*
271   * The external entropy source type is encoded in the source name. The
272   * obvious alternative is to have separate configuration parameters per
273   * source type, so that one process can query multiple external sources.
274   */
275 #define DEV_PREF "dev:"
276 #define DEV_PREF_LEN (sizeof((DEV_PREF)) - 1)
277 #define DEV_PATH(dev) ((dev) + EGD_PREF_LEN)
278 
279 #define EGD_PREF "egd:"
280 #define EGD_PREF_LEN (sizeof((EGD_PREF)) - 1)
281 #define EGD_PATH(egd) ((egd) + EGD_PREF_LEN)
282 
283  /*
284   * State for TLS session caches.
285   */
286 typedef struct {
287     char   *cache_label;		/* cache short-hand name */
288     TLS_SCACHE *cache_info;		/* cache handle */
289     int     cache_active;		/* cache status */
290     char  **cache_db;			/* main.cf parameter value */
291     const char *log_param;		/* main.cf parameter name */
292     char  **log_level;			/* main.cf parameter value */
293     int    *cache_timeout;		/* main.cf parameter value */
294 } TLSMGR_SCACHE;
295 
296 static TLSMGR_SCACHE cache_table[] = {
297     TLS_MGR_SCACHE_SMTPD, 0, 0, &var_smtpd_tls_scache_db,
298     VAR_SMTPD_TLS_LOGLEVEL,
299     &var_smtpd_tls_loglevel, &var_smtpd_tls_scache_timeout,
300     TLS_MGR_SCACHE_SMTP, 0, 0, &var_smtp_tls_scache_db,
301     VAR_SMTP_TLS_LOGLEVEL,
302     &var_smtp_tls_loglevel, &var_smtp_tls_scache_timeout,
303     TLS_MGR_SCACHE_LMTP, 0, 0, &var_lmtp_tls_scache_db,
304     VAR_LMTP_TLS_LOGLEVEL,
305     &var_lmtp_tls_loglevel, &var_lmtp_tls_scache_timeout,
306     0,
307 };
308 
309 #define	smtpd_cache	(cache_table[0])
310 
311  /*
312   * SLMs.
313   */
314 #define STR(x)		vstring_str(x)
315 #define LEN(x)		VSTRING_LEN(x)
316 #define STREQ(x, y)	(strcmp((x), (y)) == 0)
317 
318 /* tlsmgr_prng_exch_event - update PRNG exchange file */
319 
320 static void tlsmgr_prng_exch_event(int unused_event, char *dummy)
321 {
322     const char *myname = "tlsmgr_prng_exch_event";
323     unsigned char randbyte;
324     int     next_period;
325     struct stat st;
326 
327     if (msg_verbose)
328 	msg_info("%s: update PRNG exchange file", myname);
329 
330     /*
331      * Sanity check. If the PRNG exchange file was removed, there is no point
332      * updating it further. Restart the process and update the new file.
333      */
334     if (fstat(rand_exch->fd, &st) < 0)
335 	msg_fatal("cannot fstat() the PRNG exchange file: %m");
336     if (st.st_nlink == 0) {
337 	msg_warn("PRNG exchange file was removed -- exiting to reopen");
338 	sleep(1);
339 	exit(0);
340     }
341     tls_prng_exch_update(rand_exch);
342 
343     /*
344      * Make prediction difficult for outsiders and calculate the time for the
345      * next execution randomly.
346      */
347     RAND_bytes(&randbyte, 1);
348     next_period = (var_tls_prng_exch_period * randbyte) / UCHAR_MAX;
349     event_request_timer(tlsmgr_prng_exch_event, dummy, next_period);
350 }
351 
352 /* tlsmgr_reseed_event - re-seed the internal PRNG pool */
353 
354 static void tlsmgr_reseed_event(int unused_event, char *dummy)
355 {
356     int     next_period;
357     unsigned char randbyte;
358     int     must_exit = 0;
359 
360     /*
361      * Reseed the internal PRNG from external source. Errors are recoverable.
362      * We simply restart and reconnect without making a fuss. This is OK
363      * because we do require that exchange file updates succeed. The exchange
364      * file is the only entropy source that really matters in the long term.
365      *
366      * If the administrator specifies an external randomness source that we
367      * could not open upon start-up, restart to see if we can open it now
368      * (and log a nagging warning if we can't).
369      */
370     if (*var_tls_rand_source) {
371 
372 	/*
373 	 * Source is a random device.
374 	 */
375 	if (rand_source_dev) {
376 	    if (tls_prng_dev_read(rand_source_dev, var_tls_rand_bytes) <= 0) {
377 		msg_info("cannot read from entropy device %s: %m -- "
378 			 "exiting to reopen", DEV_PATH(var_tls_rand_source));
379 		must_exit = 1;
380 	    }
381 	}
382 
383 	/*
384 	 * Source is an EGD compatible socket.
385 	 */
386 	else if (rand_source_egd) {
387 	    if (tls_prng_egd_read(rand_source_egd, var_tls_rand_bytes) <= 0) {
388 		msg_info("lost connection to EGD server %s -- "
389 		     "exiting to reconnect", EGD_PATH(var_tls_rand_source));
390 		must_exit = 1;
391 	    }
392 	}
393 
394 	/*
395 	 * Source is a regular file. Read the content once and close the
396 	 * file.
397 	 */
398 	else if (rand_source_file) {
399 	    if (tls_prng_file_read(rand_source_file, var_tls_rand_bytes) <= 0)
400 		msg_warn("cannot read from entropy file %s: %m",
401 			 var_tls_rand_source);
402 	    tls_prng_file_close(rand_source_file);
403 	    rand_source_file = 0;
404 	    var_tls_rand_source[0] = 0;
405 	}
406 
407 	/*
408 	 * Could not open the external source upon start-up. See if we can
409 	 * open it this time. Save PRNG state before we exit.
410 	 */
411 	else {
412 	    msg_info("exiting to reopen external entropy source %s",
413 		     var_tls_rand_source);
414 	    must_exit = 1;
415 	}
416     }
417 
418     /*
419      * Save PRNG state in case we must exit.
420      */
421     if (must_exit) {
422 	if (rand_exch)
423 	    tls_prng_exch_update(rand_exch);
424 	sleep(1);
425 	exit(0);
426     }
427 
428     /*
429      * Make prediction difficult for outsiders and calculate the time for the
430      * next execution randomly.
431      */
432     RAND_bytes(&randbyte, 1);
433     next_period = (var_tls_reseed_period * randbyte) / UCHAR_MAX;
434     event_request_timer(tlsmgr_reseed_event, dummy, next_period);
435 }
436 
437 /* tlsmgr_cache_run_event - start TLS session cache scan */
438 
439 static void tlsmgr_cache_run_event(int unused_event, char *ctx)
440 {
441     const char *myname = "tlsmgr_cache_run_event";
442     TLSMGR_SCACHE *cache = (TLSMGR_SCACHE *) ctx;
443 
444     /*
445      * This routine runs when it is time for another TLS session cache scan.
446      * Make sure this routine gets called again in the future.
447      *
448      * Don't start a new scan when the timer goes off while cache cleanup is
449      * still in progress.
450      */
451     if (cache->cache_info->verbose)
452 	msg_info("%s: start TLS %s session cache cleanup",
453 		 myname, cache->cache_label);
454 
455     if (cache->cache_active == 0)
456 	cache->cache_active =
457 	    tls_scache_sequence(cache->cache_info, DICT_SEQ_FUN_FIRST,
458 				TLS_SCACHE_SEQUENCE_NOTHING);
459 
460     event_request_timer(tlsmgr_cache_run_event, (char *) cache,
461 			cache->cache_info->timeout);
462 }
463 
464 /* tlsmgr_key - return matching or current RFC 5077 session ticket keys */
465 
466 static int tlsmgr_key(VSTRING *buffer, int timeout)
467 {
468     TLS_TICKET_KEY *key;
469     TLS_TICKET_KEY tmp;
470     unsigned char *name;
471     time_t  now = time((time_t *) 0);
472 
473     /* In tlsmgr requests we encode null key names as empty strings. */
474     name = LEN(buffer) ? (unsigned char *) STR(buffer) : 0;
475 
476     /*
477      * Each key's encrypt and subsequent decrypt-only timeout is half of the
478      * total session timeout.
479      */
480     timeout /= 2;
481 
482     /* Attempt to locate existing key */
483     if ((key = tls_scache_key(name, now, timeout)) == 0) {
484 	if (name == 0) {
485 	    /* Create new encryption key */
486 	    if (RAND_bytes(tmp.name, TLS_TICKET_NAMELEN) <= 0
487 		|| RAND_bytes(tmp.bits, TLS_TICKET_KEYLEN) <= 0
488 		|| RAND_bytes(tmp.hmac, TLS_TICKET_MACLEN) <= 0)
489 		return (TLS_MGR_STAT_ERR);
490 	    tmp.tout = now + timeout - 1;
491 	    key = tls_scache_key_rotate(&tmp);
492 	} else {
493 	    /* No matching decryption key found */
494 	    return (TLS_MGR_STAT_ERR);
495 	}
496     }
497     /* Return value overrites name buffer */
498     vstring_memcpy(buffer, (char *) key, sizeof(*key));
499     return (TLS_MGR_STAT_OK);
500 }
501 
502 /* tlsmgr_loop - TLS manager main loop */
503 
504 static int tlsmgr_loop(char *unused_name, char **unused_argv)
505 {
506     struct timeval tv;
507     int     active = 0;
508     TLSMGR_SCACHE *ent;
509 
510     /*
511      * Update the PRNG pool with the time of day. We do it here after every
512      * event (including internal timer events and external client request
513      * events), instead of doing it in individual event call-back routines.
514      */
515     GETTIMEOFDAY(&tv);
516     RAND_seed(&tv, sizeof(struct timeval));
517 
518     /*
519      * This routine runs as part of the event handling loop, after the event
520      * manager has delivered a timer or I/O event, or after it has waited for
521      * a specified amount of time. The result value of tlsmgr_loop()
522      * specifies how long the event manager should wait for the next event.
523      *
524      * We use this loop to interleave TLS session cache cleanup with other
525      * activity. Interleaved processing is needed when we use a client-server
526      * protocol for entropy and session state exchange with smtp(8) and
527      * smtpd(8) processes.
528      */
529 #define DONT_WAIT	0
530 #define WAIT_FOR_EVENT	(-1)
531 
532     for (ent = cache_table; ent->cache_label; ++ent) {
533 	if (ent->cache_info && ent->cache_active)
534 	    active |= ent->cache_active =
535 		tls_scache_sequence(ent->cache_info, DICT_SEQ_FUN_NEXT,
536 				    TLS_SCACHE_SEQUENCE_NOTHING);
537     }
538 
539     return (active ? DONT_WAIT : WAIT_FOR_EVENT);
540 }
541 
542 /* tlsmgr_request_receive - receive request */
543 
544 static int tlsmgr_request_receive(VSTREAM *client_stream, VSTRING *request)
545 {
546     int     count;
547 
548     /*
549      * Kluge: choose the protocol depending on the request size.
550      */
551     if (read_wait(vstream_fileno(client_stream), var_ipc_timeout) < 0) {
552 	msg_warn("timeout while waiting for data from %s",
553 		 VSTREAM_PATH(client_stream));
554 	return (-1);
555     }
556     if ((count = peekfd(vstream_fileno(client_stream))) < 0) {
557 	msg_warn("cannot examine read buffer of %s: %m",
558 		 VSTREAM_PATH(client_stream));
559 	return (-1);
560     }
561 
562     /*
563      * Short request: master trigger. Use the string+null protocol.
564      */
565     if (count <= 2) {
566 	if (vstring_get_null(request, client_stream) == VSTREAM_EOF) {
567 	    msg_warn("end-of-input while reading request from %s: %m",
568 		     VSTREAM_PATH(client_stream));
569 	    return (-1);
570 	}
571     }
572 
573     /*
574      * Long request: real tlsmgr client. Use the attribute list protocol.
575      */
576     else {
577 	if (attr_scan(client_stream,
578 		      ATTR_FLAG_MORE | ATTR_FLAG_STRICT,
579 		      ATTR_TYPE_STR, TLS_MGR_ATTR_REQ, request,
580 		      ATTR_TYPE_END) != 1) {
581 	    return (-1);
582 	}
583     }
584     return (0);
585 }
586 
587 /* tlsmgr_service - respond to external request */
588 
589 static void tlsmgr_service(VSTREAM *client_stream, char *unused_service,
590 			           char **argv)
591 {
592     static VSTRING *request = 0;
593     static VSTRING *cache_type = 0;
594     static VSTRING *cache_id = 0;
595     static VSTRING *buffer = 0;
596     int     len;
597     static char wakeup[] = {		/* master wakeup request */
598 	TRIGGER_REQ_WAKEUP,
599 	0,
600     };
601     TLSMGR_SCACHE *ent;
602     int     status = TLS_MGR_STAT_FAIL;
603 
604     /*
605      * Sanity check. This service takes no command-line arguments.
606      */
607     if (argv[0])
608 	msg_fatal("unexpected command-line argument: %s", argv[0]);
609 
610     /*
611      * Initialize. We're select threaded, so we can use static buffers.
612      */
613     if (request == 0) {
614 	request = vstring_alloc(10);
615 	cache_type = vstring_alloc(10);
616 	cache_id = vstring_alloc(10);
617 	buffer = vstring_alloc(10);
618     }
619 
620     /*
621      * This routine runs whenever a client connects to the socket dedicated
622      * to the tlsmgr service (including wake up events sent by the master).
623      * All connection-management stuff is handled by the common code in
624      * multi_server.c.
625      */
626     if (tlsmgr_request_receive(client_stream, request) == 0) {
627 
628 	/*
629 	 * Load session from cache.
630 	 */
631 	if (STREQ(STR(request), TLS_MGR_REQ_LOOKUP)) {
632 	    if (attr_scan(client_stream, ATTR_FLAG_STRICT,
633 			  ATTR_TYPE_STR, TLS_MGR_ATTR_CACHE_TYPE, cache_type,
634 			  ATTR_TYPE_STR, TLS_MGR_ATTR_CACHE_ID, cache_id,
635 			  ATTR_TYPE_END) == 2) {
636 		for (ent = cache_table; ent->cache_label; ++ent)
637 		    if (strcmp(ent->cache_label, STR(cache_type)) == 0)
638 			break;
639 		if (ent->cache_label == 0) {
640 		    msg_warn("bogus cache type \"%s\" in \"%s\" request",
641 			     STR(cache_type), TLS_MGR_REQ_LOOKUP);
642 		    VSTRING_RESET(buffer);
643 		} else if (ent->cache_info == 0) {
644 
645 		    /*
646 		     * Cache type valid, but not enabled
647 		     */
648 		    VSTRING_RESET(buffer);
649 		} else {
650 		    status = tls_scache_lookup(ent->cache_info,
651 					       STR(cache_id), buffer) ?
652 			TLS_MGR_STAT_OK : TLS_MGR_STAT_ERR;
653 		}
654 	    }
655 	    attr_print(client_stream, ATTR_FLAG_NONE,
656 		       ATTR_TYPE_INT, MAIL_ATTR_STATUS, status,
657 		       ATTR_TYPE_DATA, TLS_MGR_ATTR_SESSION,
658 		       LEN(buffer), STR(buffer),
659 		       ATTR_TYPE_END);
660 	}
661 
662 	/*
663 	 * Save session to cache.
664 	 */
665 	else if (STREQ(STR(request), TLS_MGR_REQ_UPDATE)) {
666 	    if (attr_scan(client_stream, ATTR_FLAG_STRICT,
667 			  ATTR_TYPE_STR, TLS_MGR_ATTR_CACHE_TYPE, cache_type,
668 			  ATTR_TYPE_STR, TLS_MGR_ATTR_CACHE_ID, cache_id,
669 			  ATTR_TYPE_DATA, TLS_MGR_ATTR_SESSION, buffer,
670 			  ATTR_TYPE_END) == 3) {
671 		for (ent = cache_table; ent->cache_label; ++ent)
672 		    if (strcmp(ent->cache_label, STR(cache_type)) == 0)
673 			break;
674 		if (ent->cache_label == 0) {
675 		    msg_warn("bogus cache type \"%s\" in \"%s\" request",
676 			     STR(cache_type), TLS_MGR_REQ_UPDATE);
677 		} else if (ent->cache_info != 0) {
678 		    status =
679 			tls_scache_update(ent->cache_info, STR(cache_id),
680 					  STR(buffer), LEN(buffer)) ?
681 			TLS_MGR_STAT_OK : TLS_MGR_STAT_ERR;
682 		}
683 	    }
684 	    attr_print(client_stream, ATTR_FLAG_NONE,
685 		       ATTR_TYPE_INT, MAIL_ATTR_STATUS, status,
686 		       ATTR_TYPE_END);
687 	}
688 
689 	/*
690 	 * Delete session from cache.
691 	 */
692 	else if (STREQ(STR(request), TLS_MGR_REQ_DELETE)) {
693 	    if (attr_scan(client_stream, ATTR_FLAG_STRICT,
694 			  ATTR_TYPE_STR, TLS_MGR_ATTR_CACHE_TYPE, cache_type,
695 			  ATTR_TYPE_STR, TLS_MGR_ATTR_CACHE_ID, cache_id,
696 			  ATTR_TYPE_END) == 2) {
697 		for (ent = cache_table; ent->cache_label; ++ent)
698 		    if (strcmp(ent->cache_label, STR(cache_type)) == 0)
699 			break;
700 		if (ent->cache_label == 0) {
701 		    msg_warn("bogus cache type \"%s\" in \"%s\" request",
702 			     STR(cache_type), TLS_MGR_REQ_DELETE);
703 		} else if (ent->cache_info != 0) {
704 		    status = tls_scache_delete(ent->cache_info,
705 					       STR(cache_id)) ?
706 			TLS_MGR_STAT_OK : TLS_MGR_STAT_ERR;
707 		}
708 	    }
709 	    attr_print(client_stream, ATTR_FLAG_NONE,
710 		       ATTR_TYPE_INT, MAIL_ATTR_STATUS, status,
711 		       ATTR_TYPE_END);
712 	}
713 
714 	/*
715 	 * RFC 5077 TLS session ticket keys
716 	 */
717 	else if (STREQ(STR(request), TLS_MGR_REQ_TKTKEY)) {
718 	    if (attr_scan(client_stream, ATTR_FLAG_STRICT,
719 			  ATTR_TYPE_DATA, TLS_MGR_ATTR_KEYNAME, buffer,
720 			  ATTR_TYPE_END) == 1) {
721 		if (LEN(buffer) != 0 && LEN(buffer) != TLS_TICKET_NAMELEN) {
722 		    msg_warn("invalid session ticket key name length: %ld",
723 			     (long) LEN(buffer));
724 		    VSTRING_RESET(buffer);
725 		} else if (*smtpd_cache.cache_timeout <= 0) {
726 		    status = TLS_MGR_STAT_ERR;
727 		    VSTRING_RESET(buffer);
728 		} else {
729 		    status = tlsmgr_key(buffer, *smtpd_cache.cache_timeout);
730 		}
731 	    }
732 	    attr_print(client_stream, ATTR_FLAG_NONE,
733 		       ATTR_TYPE_INT, MAIL_ATTR_STATUS, status,
734 		       ATTR_TYPE_DATA, TLS_MGR_ATTR_KEYBUF,
735 		       LEN(buffer), STR(buffer),
736 		       ATTR_TYPE_END);
737 	}
738 
739 	/*
740 	 * Entropy request.
741 	 */
742 	else if (STREQ(STR(request), TLS_MGR_REQ_SEED)) {
743 	    if (attr_scan(client_stream, ATTR_FLAG_STRICT,
744 			  ATTR_TYPE_INT, TLS_MGR_ATTR_SIZE, &len,
745 			  ATTR_TYPE_END) == 1) {
746 		VSTRING_RESET(buffer);
747 		if (len <= 0 || len > 255) {
748 		    msg_warn("bogus seed length \"%d\" in \"%s\" request",
749 			     len, TLS_MGR_REQ_SEED);
750 		} else {
751 		    VSTRING_SPACE(buffer, len);
752 		    RAND_bytes((unsigned char *) STR(buffer), len);
753 		    VSTRING_AT_OFFSET(buffer, len);	/* XXX not part of the
754 							 * official interface */
755 		    status = TLS_MGR_STAT_OK;
756 		}
757 	    }
758 	    attr_print(client_stream, ATTR_FLAG_NONE,
759 		       ATTR_TYPE_INT, MAIL_ATTR_STATUS, status,
760 		       ATTR_TYPE_DATA, TLS_MGR_ATTR_SEED,
761 		       LEN(buffer), STR(buffer),
762 		       ATTR_TYPE_END);
763 	}
764 
765 	/*
766 	 * Caching policy request.
767 	 */
768 	else if (STREQ(STR(request), TLS_MGR_REQ_POLICY)) {
769 	    int     cachable = 0;
770 	    int     timeout = 0;
771 
772 	    if (attr_scan(client_stream, ATTR_FLAG_STRICT,
773 			  ATTR_TYPE_STR, TLS_MGR_ATTR_CACHE_TYPE, cache_type,
774 			  ATTR_TYPE_END) == 1) {
775 		for (ent = cache_table; ent->cache_label; ++ent)
776 		    if (strcmp(ent->cache_label, STR(cache_type)) == 0)
777 			break;
778 		if (ent->cache_label == 0) {
779 		    msg_warn("bogus cache type \"%s\" in \"%s\" request",
780 			     STR(cache_type), TLS_MGR_REQ_POLICY);
781 		} else {
782 		    cachable = (ent->cache_info != 0) ? 1 : 0;
783 		    timeout = *ent->cache_timeout;
784 		    status = TLS_MGR_STAT_OK;
785 		}
786 	    }
787 	    attr_print(client_stream, ATTR_FLAG_NONE,
788 		       ATTR_TYPE_INT, MAIL_ATTR_STATUS, status,
789 		       ATTR_TYPE_INT, TLS_MGR_ATTR_CACHABLE, cachable,
790 		       ATTR_TYPE_INT, TLS_MGR_ATTR_SESSTOUT, timeout,
791 		       ATTR_TYPE_END);
792 	}
793 
794 	/*
795 	 * Master trigger. Normally, these triggers arrive only after some
796 	 * other process requested the tlsmgr's service. The purpose is to
797 	 * restart the tlsmgr after it aborted due to a fatal run-time error,
798 	 * so that it can continue its housekeeping even while nothing is
799 	 * using TLS.
800 	 *
801 	 * XXX Which begs the question, if TLS isn't used often, do we need a
802 	 * tlsmgr background process? It could terminate when the session
803 	 * caches are empty.
804 	 */
805 	else if (STREQ(STR(request), wakeup)) {
806 	    if (msg_verbose)
807 		msg_info("received master trigger");
808 	    multi_server_disconnect(client_stream);
809 	    return;				/* NOT: vstream_fflush */
810 	}
811     }
812 
813     /*
814      * Protocol error.
815      */
816     else {
817 	attr_print(client_stream, ATTR_FLAG_NONE,
818 		   ATTR_TYPE_INT, MAIL_ATTR_STATUS, TLS_MGR_STAT_FAIL,
819 		   ATTR_TYPE_END);
820     }
821     vstream_fflush(client_stream);
822 }
823 
824 /* tlsmgr_pre_init - pre-jail initialization */
825 
826 static void tlsmgr_pre_init(char *unused_name, char **unused_argv)
827 {
828     char   *path;
829     struct timeval tv;
830     TLSMGR_SCACHE *ent;
831     VSTRING *redirect;
832     HTABLE *dup_filter;
833     const char *dup_label;
834 
835     /*
836      * If nothing else works then at least this will get us a few bits of
837      * entropy.
838      *
839      * XXX This is our first call into the OpenSSL library. We should find out
840      * if this can be moved to the post-jail initialization phase, without
841      * breaking compatibility with existing installations.
842      */
843     GETTIMEOFDAY(&tv);
844     tv.tv_sec ^= getpid();
845     RAND_seed(&tv, sizeof(struct timeval));
846 
847     /*
848      * Open the external entropy source. We will not be able to open it again
849      * after we are sent to chroot jail, so we keep it open. Errors are not
850      * fatal. The exchange file (see below) is the only entropy source that
851      * really matters in the long run.
852      *
853      * Security note: we open the entropy source while privileged, but we don't
854      * access the source until after we release privileges. This way, none of
855      * the OpenSSL code gets to execute while we are privileged.
856      */
857     if (*var_tls_rand_source) {
858 
859 	/*
860 	 * Source is a random device.
861 	 */
862 	if (!strncmp(var_tls_rand_source, DEV_PREF, DEV_PREF_LEN)) {
863 	    path = DEV_PATH(var_tls_rand_source);
864 	    rand_source_dev = tls_prng_dev_open(path, TLS_MGR_TIMEOUT);
865 	    if (rand_source_dev == 0)
866 		msg_warn("cannot open entropy device %s: %m", path);
867 	}
868 
869 	/*
870 	 * Source is an EGD compatible socket.
871 	 */
872 	else if (!strncmp(var_tls_rand_source, EGD_PREF, EGD_PREF_LEN)) {
873 	    path = EGD_PATH(var_tls_rand_source);
874 	    rand_source_egd = tls_prng_egd_open(path, TLS_MGR_TIMEOUT);
875 	    if (rand_source_egd == 0)
876 		msg_warn("cannot connect to EGD server %s: %m", path);
877 	}
878 
879 	/*
880 	 * Source is regular file. We read this only once.
881 	 */
882 	else {
883 	    rand_source_file =
884 		tls_prng_file_open(var_tls_rand_source, TLS_MGR_TIMEOUT);
885 	}
886     } else {
887 	msg_warn("no entropy source specified with parameter %s",
888 		 VAR_TLS_RAND_SOURCE);
889 	msg_warn("encryption keys etc. may be predictable");
890     }
891 
892     /*
893      * Security: don't create root-owned files that contain untrusted data.
894      * And don't create Postfix-owned files in root-owned directories,
895      * either. We want a correct relationship between (file/directory)
896      * ownership and (file/directory) content.
897      */
898     SAVE_AND_SET_EUGID(var_owner_uid, var_owner_gid);
899     redirect = vstring_alloc(100);
900 
901     /*
902      * Open the PRNG exchange file before going to jail, but don't use root
903      * privileges. Start the exchange file read/update pseudo thread after
904      * dropping privileges.
905      */
906     if (*var_tls_rand_exch_name) {
907 	rand_exch =
908 	    tls_prng_exch_open(data_redirect_file(redirect,
909 						  var_tls_rand_exch_name));
910 	if (rand_exch == 0)
911 	    msg_fatal("cannot open PRNG exchange file %s: %m",
912 		      var_tls_rand_exch_name);
913     }
914 
915     /*
916      * Open the session cache files and discard old information before going
917      * to jail, but don't use root privilege. Start the cache maintenance
918      * pseudo threads after dropping privileges.
919      */
920     dup_filter = htable_create(sizeof(cache_table) / sizeof(cache_table[0]));
921     for (ent = cache_table; ent->cache_label; ++ent) {
922 	/* Sanitize session timeout */
923 	if (*ent->cache_timeout > 0) {
924 	    if (*ent->cache_timeout < TLS_SESSION_LIFEMIN)
925 		*ent->cache_timeout = TLS_SESSION_LIFEMIN;
926 	} else {
927 	    *ent->cache_timeout = 0;
928 	}
929 	/* External cache database disabled if timeout is non-positive */
930 	if (*ent->cache_timeout > 0 && **ent->cache_db) {
931 	    if ((dup_label = htable_find(dup_filter, *ent->cache_db)) != 0)
932 		msg_fatal("do not use the same TLS cache file %s for %s and %s",
933 			  *ent->cache_db, dup_label, ent->cache_label);
934 	    htable_enter(dup_filter, *ent->cache_db, ent->cache_label);
935 	    ent->cache_info =
936 		tls_scache_open(data_redirect_map(redirect, *ent->cache_db),
937 				ent->cache_label,
938 				tls_log_mask(ent->log_param,
939 					   *ent->log_level) & TLS_LOG_CACHE,
940 				*ent->cache_timeout);
941 	}
942     }
943     htable_free(dup_filter, (void (*) (char *)) 0);
944 
945     /*
946      * Clean up and restore privilege.
947      */
948     vstring_free(redirect);
949     RESTORE_SAVED_EUGID();
950 }
951 
952 /* tlsmgr_post_init - post-jail initialization */
953 
954 static void tlsmgr_post_init(char *unused_name, char **unused_argv)
955 {
956     TLSMGR_SCACHE *ent;
957 
958 #define NULL_EVENT	(0)
959 #define NULL_CONTEXT	((char *) 0)
960 
961     /*
962      * This routine runs after the skeleton code has entered the chroot jail,
963      * but before any client requests are serviced. Prevent automatic process
964      * suicide after a limited number of client requests or after a limited
965      * amount of idle time.
966      */
967     var_use_limit = 0;
968     var_idle_limit = 0;
969 
970     /*
971      * Start the internal PRNG re-seeding pseudo thread first.
972      */
973     if (*var_tls_rand_source) {
974 	if (var_tls_reseed_period > INT_MAX / UCHAR_MAX)
975 	    var_tls_reseed_period = INT_MAX / UCHAR_MAX;
976 	tlsmgr_reseed_event(NULL_EVENT, NULL_CONTEXT);
977     }
978 
979     /*
980      * Start the exchange file read/update pseudo thread.
981      */
982     if (*var_tls_rand_exch_name) {
983 	if (var_tls_prng_exch_period > INT_MAX / UCHAR_MAX)
984 	    var_tls_prng_exch_period = INT_MAX / UCHAR_MAX;
985 	tlsmgr_prng_exch_event(NULL_EVENT, NULL_CONTEXT);
986     }
987 
988     /*
989      * Start the cache maintenance pseudo threads last. Strictly speaking
990      * there is nothing to clean up after we truncate the database to zero
991      * length, but early cleanup makes verbose logging more informative (we
992      * get positive confirmation that the cleanup threads are running).
993      */
994     for (ent = cache_table; ent->cache_label; ++ent)
995 	if (ent->cache_info)
996 	    tlsmgr_cache_run_event(NULL_EVENT, (char *) ent);
997 }
998 
999 /* tlsmgr_before_exit - save PRNG state before exit */
1000 
1001 static void tlsmgr_before_exit(char *unused_service_name, char **unused_argv)
1002 {
1003 
1004     /*
1005      * Save state before we exit after "postfix reload".
1006      */
1007     if (rand_exch)
1008 	tls_prng_exch_update(rand_exch);
1009 }
1010 
1011 MAIL_VERSION_STAMP_DECLARE;
1012 
1013 /* main - the main program */
1014 
1015 int     main(int argc, char **argv)
1016 {
1017     static const CONFIG_STR_TABLE str_table[] = {
1018 	VAR_TLS_RAND_SOURCE, DEF_TLS_RAND_SOURCE, &var_tls_rand_source, 0, 0,
1019 	VAR_TLS_RAND_EXCH_NAME, DEF_TLS_RAND_EXCH_NAME, &var_tls_rand_exch_name, 0, 0,
1020 	VAR_SMTPD_TLS_SCACHE_DB, DEF_SMTPD_TLS_SCACHE_DB, &var_smtpd_tls_scache_db, 0, 0,
1021 	VAR_SMTP_TLS_SCACHE_DB, DEF_SMTP_TLS_SCACHE_DB, &var_smtp_tls_scache_db, 0, 0,
1022 	VAR_LMTP_TLS_SCACHE_DB, DEF_LMTP_TLS_SCACHE_DB, &var_lmtp_tls_scache_db, 0, 0,
1023 	VAR_SMTPD_TLS_LOGLEVEL, DEF_SMTPD_TLS_LOGLEVEL, &var_smtpd_tls_loglevel, 0, 0,
1024 	VAR_SMTP_TLS_LOGLEVEL, DEF_SMTP_TLS_LOGLEVEL, &var_smtp_tls_loglevel, 0, 0,
1025 	VAR_LMTP_TLS_LOGLEVEL, DEF_LMTP_TLS_LOGLEVEL, &var_lmtp_tls_loglevel, 0, 0,
1026 	0,
1027     };
1028     static const CONFIG_TIME_TABLE time_table[] = {
1029 	VAR_TLS_RESEED_PERIOD, DEF_TLS_RESEED_PERIOD, &var_tls_reseed_period, 1, 0,
1030 	VAR_TLS_PRNG_UPD_PERIOD, DEF_TLS_PRNG_UPD_PERIOD, &var_tls_prng_exch_period, 1, 0,
1031 	VAR_SMTPD_TLS_SCACHTIME, DEF_SMTPD_TLS_SCACHTIME, &var_smtpd_tls_scache_timeout, 0, MAX_SMTPD_TLS_SCACHETIME,
1032 	VAR_SMTP_TLS_SCACHTIME, DEF_SMTP_TLS_SCACHTIME, &var_smtp_tls_scache_timeout, 0, MAX_SMTP_TLS_SCACHETIME,
1033 	VAR_LMTP_TLS_SCACHTIME, DEF_LMTP_TLS_SCACHTIME, &var_lmtp_tls_scache_timeout, 0, MAX_LMTP_TLS_SCACHETIME,
1034 	0,
1035     };
1036     static const CONFIG_INT_TABLE int_table[] = {
1037 	VAR_TLS_RAND_BYTES, DEF_TLS_RAND_BYTES, &var_tls_rand_bytes, 1, 0,
1038 	0,
1039     };
1040 
1041     /*
1042      * Fingerprint executables and core dumps.
1043      */
1044     MAIL_VERSION_STAMP_ALLOCATE;
1045 
1046     /*
1047      * Use the multi service skeleton, and require that no-one else is
1048      * monitoring our service port while this process runs.
1049      */
1050     multi_server_main(argc, argv, tlsmgr_service,
1051 		      MAIL_SERVER_TIME_TABLE, time_table,
1052 		      MAIL_SERVER_INT_TABLE, int_table,
1053 		      MAIL_SERVER_STR_TABLE, str_table,
1054 		      MAIL_SERVER_PRE_INIT, tlsmgr_pre_init,
1055 		      MAIL_SERVER_POST_INIT, tlsmgr_post_init,
1056 		      MAIL_SERVER_EXIT, tlsmgr_before_exit,
1057 		      MAIL_SERVER_LOOP, tlsmgr_loop,
1058 		      MAIL_SERVER_SOLITARY,
1059 		      0);
1060 }
1061 
1062 #else
1063 
1064 /* tlsmgr_service - respond to external trigger(s), non-TLS version */
1065 
1066 static void tlsmgr_service(VSTREAM *unused_stream, char *unused_service,
1067 			           char **unused_argv)
1068 {
1069     msg_info("TLS support is not compiled in -- exiting");
1070 }
1071 
1072 /* main - the main program, non-TLS version */
1073 
1074 int     main(int argc, char **argv)
1075 {
1076 
1077     /*
1078      * 200411 We can't simply use msg_fatal() here, because the logging
1079      * hasn't been initialized. The text would disappear because stderr is
1080      * redirected to /dev/null.
1081      *
1082      * We invoke multi_server_main() to complete program initialization
1083      * (including logging) and then invoke the tlsmgr_service() routine to
1084      * log the message that says why this program will not run.
1085      */
1086     multi_server_main(argc, argv, tlsmgr_service,
1087 		      0);
1088 }
1089 
1090 #endif
1091