xref: /netbsd-src/external/ibm-public/postfix/dist/src/smtp/smtp_sasl_glue.c (revision 413d532bcc3f62d122e56d92e13ac64825a40baf)
1 /*	$NetBSD: smtp_sasl_glue.c,v 1.1.1.2 2013/01/02 18:59:08 tron Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	smtp_sasl_glue 3
6 /* SUMMARY
7 /*	Postfix SASL interface for SMTP client
8 /* SYNOPSIS
9 /*	#include smtp_sasl.h
10 /*
11 /*	void	smtp_sasl_initialize()
12 /*
13 /*	void	smtp_sasl_connect(session)
14 /*	SMTP_SESSION *session;
15 /*
16 /*	void	smtp_sasl_start(session, sasl_opts_name, sasl_opts_val)
17 /*	SMTP_SESSION *session;
18 /*
19 /*	int     smtp_sasl_passwd_lookup(session)
20 /*	SMTP_SESSION *session;
21 /*
22 /*	int	smtp_sasl_authenticate(session, why)
23 /*	SMTP_SESSION *session;
24 /*	DSN_BUF *why;
25 /*
26 /*	void	smtp_sasl_cleanup(session)
27 /*	SMTP_SESSION *session;
28 /*
29 /*	void	smtp_sasl_passivate(session, buf)
30 /*	SMTP_SESSION *session;
31 /*	VSTRING	*buf;
32 /*
33 /*	int	smtp_sasl_activate(session, buf)
34 /*	SMTP_SESSION *session;
35 /*	char	*buf;
36 /* DESCRIPTION
37 /*	smtp_sasl_initialize() initializes the SASL library. This
38 /*	routine must be called once at process startup, before any
39 /*	chroot operations.
40 /*
41 /*	smtp_sasl_connect() performs per-session initialization. This
42 /*	routine must be called once at the start of each connection.
43 /*
44 /*	smtp_sasl_start() performs per-session initialization. This
45 /*	routine must be called once per session before doing any SASL
46 /*	authentication. The sasl_opts_name and sasl_opts_val parameters are
47 /*	the postfix configuration parameters setting the security
48 /*	policy of the SASL authentication.
49 /*
50 /*	smtp_sasl_passwd_lookup() looks up the username/password
51 /*	for the current SMTP server. The result is zero in case
52 /*	of failure, a long jump in case of error.
53 /*
54 /*	smtp_sasl_authenticate() implements the SASL authentication
55 /*	dialog. The result is < 0 in case of protocol failure, zero in
56 /*	case of unsuccessful authentication, > 0 in case of success.
57 /*	The why argument is updated with a reason for failure.
58 /*	This routine must be called only when smtp_sasl_passwd_lookup()
59 /*	succeeds.
60 /*
61 /*	smtp_sasl_cleanup() cleans up. It must be called at the
62 /*	end of every SMTP session that uses SASL authentication.
63 /*	This routine is a noop for non-SASL sessions.
64 /*
65 /*	smtp_sasl_passivate() appends flattened SASL attributes to the
66 /*	specified buffer. The SASL attributes are not destroyed.
67 /*
68 /*	smtp_sasl_activate() restores SASL attributes from the
69 /*	specified buffer. The buffer is modified. A result < 0
70 /*	means there was an error.
71 /*
72 /*	Arguments:
73 /* .IP session
74 /*	Session context.
75 /* .IP mech_list
76 /*	String of SASL mechanisms (separated by blanks)
77 /* DIAGNOSTICS
78 /*	All errors are fatal.
79 /* LICENSE
80 /* .ad
81 /* .fi
82 /*	The Secure Mailer license must be distributed with this software.
83 /* AUTHOR(S)
84 /*	Original author:
85 /*	Till Franke
86 /*	SuSE Rhein/Main AG
87 /*	65760 Eschborn, Germany
88 /*
89 /*	Adopted by:
90 /*	Wietse Venema
91 /*	IBM T.J. Watson Research
92 /*	P.O. Box 704
93 /*	Yorktown Heights, NY 10598, USA
94 /*--*/
95 
96  /*
97   * System library.
98   */
99 #include <sys_defs.h>
100 #include <stdlib.h>
101 #include <string.h>
102 
103  /*
104   * Utility library
105   */
106 #include <msg.h>
107 #include <mymalloc.h>
108 #include <stringops.h>
109 #include <split_at.h>
110 
111  /*
112   * Global library
113   */
114 #include <mail_params.h>
115 #include <string_list.h>
116 #include <maps.h>
117 #include <mail_addr_find.h>
118 #include <smtp_stream.h>
119 
120  /*
121   * XSASL library.
122   */
123 #include <xsasl.h>
124 
125  /*
126   * Application-specific
127   */
128 #include "smtp.h"
129 #include "smtp_sasl.h"
130 #include "smtp_sasl_auth_cache.h"
131 
132 #ifdef USE_SASL_AUTH
133 
134  /*
135   * Per-host login/password information.
136   */
137 static MAPS *smtp_sasl_passwd_map;
138 
139  /*
140   * Supported SASL mechanisms.
141   */
142 STRING_LIST *smtp_sasl_mechs;
143 
144  /*
145   * SASL implementation handle.
146   */
147 static XSASL_CLIENT_IMPL *smtp_sasl_impl;
148 
149  /*
150   * The 535 SASL authentication failure cache.
151   */
152 #ifdef HAVE_SASL_AUTH_CACHE
153 static SMTP_SASL_AUTH_CACHE *smtp_sasl_auth_cache;
154 
155 #endif
156 
157 /* smtp_sasl_passwd_lookup - password lookup routine */
158 
159 int     smtp_sasl_passwd_lookup(SMTP_SESSION *session)
160 {
161     const char *myname = "smtp_sasl_passwd_lookup";
162     SMTP_STATE *state = session->state;
163     const char *value;
164     char   *passwd;
165 
166     /*
167      * Sanity check.
168      */
169     if (smtp_sasl_passwd_map == 0)
170 	msg_panic("%s: passwd map not initialized", myname);
171 
172     /*
173      * Look up the per-server password information. Try the hostname first,
174      * then try the destination.
175      *
176      * XXX Instead of using nexthop (the intended destination) we use dest
177      * (either the intended destination, or a fall-back destination).
178      *
179      * XXX SASL authentication currently depends on the host/domain but not on
180      * the TCP port. If the port is not :25, we should append it to the table
181      * lookup key. Code for this was briefly introduced into 2.2 snapshots,
182      * but didn't canonicalize the TCP port, and did not append the port to
183      * the MX hostname.
184      */
185     smtp_sasl_passwd_map->error = 0;
186     if (((state->misc_flags & SMTP_MISC_FLAG_USE_LMTP) == 0
187 	 && var_smtp_sender_auth && state->request->sender[0]
188 	 && (value = mail_addr_find(smtp_sasl_passwd_map,
189 				 state->request->sender, (char **) 0)) != 0)
190 	|| (smtp_sasl_passwd_map->error == 0
191 	    && (value = maps_find(smtp_sasl_passwd_map,
192 				  session->host, 0)) != 0)
193 	|| (smtp_sasl_passwd_map->error == 0
194 	    && (value = maps_find(smtp_sasl_passwd_map,
195 				  session->dest, 0)) != 0)) {
196 	if (session->sasl_username)
197 	    myfree(session->sasl_username);
198 	session->sasl_username = mystrdup(value);
199 	passwd = split_at(session->sasl_username, ':');
200 	if (session->sasl_passwd)
201 	    myfree(session->sasl_passwd);
202 	session->sasl_passwd = mystrdup(passwd ? passwd : "");
203 	if (msg_verbose)
204 	    msg_info("%s: host `%s' user `%s' pass `%s'",
205 		     myname, session->host,
206 		     session->sasl_username, session->sasl_passwd);
207 	return (1);
208     } else if (smtp_sasl_passwd_map->error) {
209 	msg_warn("%s: %s lookup error",
210 		  state->request->queue_id, smtp_sasl_passwd_map->title);
211 	vstream_longjmp(session->stream, SMTP_ERR_DATA);
212     } else {
213 	if (msg_verbose)
214 	    msg_info("%s: no auth info found (sender=`%s', host=`%s')",
215 		     myname, state->request->sender, session->host);
216 	return (0);
217     }
218 }
219 
220 /* smtp_sasl_initialize - per-process initialization (pre jail) */
221 
222 void    smtp_sasl_initialize(void)
223 {
224 
225     /*
226      * Sanity check.
227      */
228     if (smtp_sasl_passwd_map || smtp_sasl_impl)
229 	msg_panic("smtp_sasl_initialize: repeated call");
230     if (*var_smtp_sasl_passwd == 0)
231 	msg_fatal("specify a password table via the `%s' configuration parameter",
232 		  VAR_SMTP_SASL_PASSWD);
233 
234     /*
235      * Open the per-host password table and initialize the SASL library. Use
236      * shared locks for reading, just in case someone updates the table.
237      */
238     smtp_sasl_passwd_map = maps_create("smtp_sasl_passwd",
239 				       var_smtp_sasl_passwd,
240 				       DICT_FLAG_LOCK | DICT_FLAG_FOLD_FIX);
241     if ((smtp_sasl_impl = xsasl_client_init(var_smtp_sasl_type,
242 					    var_smtp_sasl_path)) == 0)
243 	msg_fatal("SASL library initialization");
244 
245     /*
246      * Initialize optional supported mechanism matchlist
247      */
248     if (*var_smtp_sasl_mechs)
249 	smtp_sasl_mechs = string_list_init(MATCH_FLAG_NONE,
250 					   var_smtp_sasl_mechs);
251 
252     /*
253      * Initialize the 535 SASL authentication failure cache.
254      */
255     if (*var_smtp_sasl_auth_cache_name) {
256 #ifdef HAVE_SASL_AUTH_CACHE
257 	smtp_sasl_auth_cache =
258 	    smtp_sasl_auth_cache_init(var_smtp_sasl_auth_cache_name,
259 				      var_smtp_sasl_auth_cache_time);
260 #else
261 	msg_warn("not compiled with TLS support -- "
262 		 "ignoring the " VAR_SMTP_SASL_AUTH_CACHE_NAME " setting");
263 #endif
264     }
265 }
266 
267 /* smtp_sasl_connect - per-session client initialization */
268 
269 void    smtp_sasl_connect(SMTP_SESSION *session)
270 {
271 
272     /*
273      * This initialization happens whenever we instantiate an SMTP session
274      * object. We don't instantiate a SASL client until we actually need one.
275      */
276     session->sasl_mechanism_list = 0;
277     session->sasl_username = 0;
278     session->sasl_passwd = 0;
279     session->sasl_client = 0;
280     session->sasl_reply = 0;
281 }
282 
283 /* smtp_sasl_start - per-session SASL initialization */
284 
285 void    smtp_sasl_start(SMTP_SESSION *session, const char *sasl_opts_name,
286 			        const char *sasl_opts_val)
287 {
288     XSASL_CLIENT_CREATE_ARGS create_args;
289 
290     if (msg_verbose)
291 	msg_info("starting new SASL client");
292     if ((session->sasl_client =
293 	 XSASL_CLIENT_CREATE(smtp_sasl_impl, &create_args,
294 			     stream = session->stream,
295 			     service = var_procname,
296 			     server_name = session->host,
297 			     security_options = sasl_opts_val)) == 0)
298 	msg_fatal("SASL per-connection initialization failed");
299     session->sasl_reply = vstring_alloc(20);
300 }
301 
302 /* smtp_sasl_authenticate - run authentication protocol */
303 
304 int     smtp_sasl_authenticate(SMTP_SESSION *session, DSN_BUF *why)
305 {
306     const char *myname = "smtp_sasl_authenticate";
307     SMTP_RESP *resp;
308     const char *mechanism;
309     int     result;
310     char   *line;
311     int     steps = 0;
312 
313     /*
314      * Sanity check.
315      */
316     if (session->sasl_mechanism_list == 0)
317 	msg_panic("%s: no mechanism list", myname);
318 
319     if (msg_verbose)
320 	msg_info("%s: %s: SASL mechanisms %s",
321 		 myname, session->namaddrport, session->sasl_mechanism_list);
322 
323     /*
324      * Avoid repeated login failures after a recent 535 error.
325      */
326 #ifdef HAVE_SASL_AUTH_CACHE
327     if (smtp_sasl_auth_cache
328 	&& smtp_sasl_auth_cache_find(smtp_sasl_auth_cache, session)) {
329 	char   *resp_dsn = smtp_sasl_auth_cache_dsn(smtp_sasl_auth_cache);
330 	char   *resp_str = smtp_sasl_auth_cache_text(smtp_sasl_auth_cache);
331 
332 	if (var_smtp_sasl_auth_soft_bounce && resp_dsn[0] == '5')
333 	    resp_dsn[0] = '4';
334 	dsb_update(why, resp_dsn, DSB_DEF_ACTION, DSB_MTYPE_DNS,
335 		   session->host, var_procname, resp_str,
336 		   "SASL [CACHED] authentication failed; server %s said: %s",
337 		   session->host, resp_str);
338 	return (0);
339     }
340 #endif
341 
342     /*
343      * Start the client side authentication protocol.
344      */
345     result = xsasl_client_first(session->sasl_client,
346 				session->sasl_mechanism_list,
347 				session->sasl_username,
348 				session->sasl_passwd,
349 				&mechanism, session->sasl_reply);
350     if (result != XSASL_AUTH_OK) {
351 	dsb_update(why, "4.7.0", DSB_DEF_ACTION, DSB_SKIP_RMTA,
352 		   DSB_DTYPE_SASL, STR(session->sasl_reply),
353 		   "SASL authentication failed; "
354 		   "cannot authenticate to server %s: %s",
355 		   session->namaddr, STR(session->sasl_reply));
356 	return (-1);
357     }
358 
359     /*
360      * Send the AUTH command and the optional initial client response.
361      * sasl_encode64() produces four bytes for each complete or incomplete
362      * triple of input bytes. Allocate an extra byte for string termination.
363      */
364     if (LEN(session->sasl_reply) > 0) {
365 	smtp_chat_cmd(session, "AUTH %s %s", mechanism,
366 		      STR(session->sasl_reply));
367     } else {
368 	smtp_chat_cmd(session, "AUTH %s", mechanism);
369     }
370 
371     /*
372      * Step through the authentication protocol until the server tells us
373      * that we are done.
374      */
375     while ((resp = smtp_chat_resp(session))->code / 100 == 3) {
376 
377 	/*
378 	 * Sanity check.
379 	 */
380 	if (++steps > 100) {
381 	    dsb_simple(why, "4.3.0", "SASL authentication failed; "
382 		       "authentication protocol loop with server %s",
383 		       session->namaddr);
384 	    return (-1);
385 	}
386 
387 	/*
388 	 * Process a server challenge.
389 	 */
390 	line = resp->str;
391 	(void) mystrtok(&line, "- \t\n");	/* skip over result code */
392 	result = xsasl_client_next(session->sasl_client, line,
393 				   session->sasl_reply);
394 	if (result != XSASL_AUTH_OK) {
395 	    dsb_update(why, "4.7.0", DSB_DEF_ACTION,	/* Fix 200512 */
396 		    DSB_SKIP_RMTA, DSB_DTYPE_SASL, STR(session->sasl_reply),
397 		       "SASL authentication failed; "
398 		       "cannot authenticate to server %s: %s",
399 		       session->namaddr, STR(session->sasl_reply));
400 	    return (-1);			/* Fix 200512 */
401 	}
402 
403 	/*
404 	 * Send a client response.
405 	 */
406 	smtp_chat_cmd(session, "%s", STR(session->sasl_reply));
407     }
408 
409     /*
410      * We completed the authentication protocol.
411      */
412     if (resp->code / 100 != 2) {
413 #ifdef HAVE_SASL_AUTH_CACHE
414 	/* Update the 535 authentication failure cache. */
415 	if (smtp_sasl_auth_cache && resp->code == 535)
416 	    smtp_sasl_auth_cache_store(smtp_sasl_auth_cache, session, resp);
417 #endif
418 	if (var_smtp_sasl_auth_soft_bounce && resp->code / 100 == 5)
419 	    STR(resp->dsn_buf)[0] = '4';
420 	dsb_update(why, resp->dsn, DSB_DEF_ACTION,
421 		   DSB_MTYPE_DNS, session->host,
422 		   var_procname, resp->str,
423 		   "SASL authentication failed; server %s said: %s",
424 		   session->namaddr, resp->str);
425 	return (0);
426     }
427     return (1);
428 }
429 
430 /* smtp_sasl_cleanup - per-session cleanup */
431 
432 void    smtp_sasl_cleanup(SMTP_SESSION *session)
433 {
434     if (session->sasl_username) {
435 	myfree(session->sasl_username);
436 	session->sasl_username = 0;
437     }
438     if (session->sasl_passwd) {
439 	myfree(session->sasl_passwd);
440 	session->sasl_passwd = 0;
441     }
442     if (session->sasl_mechanism_list) {
443 	/* allocated in smtp_sasl_helo_auth */
444 	myfree(session->sasl_mechanism_list);
445 	session->sasl_mechanism_list = 0;
446     }
447     if (session->sasl_client) {
448 	if (msg_verbose)
449 	    msg_info("disposing SASL state information");
450 	xsasl_client_free(session->sasl_client);
451 	session->sasl_client = 0;
452     }
453     if (session->sasl_reply) {
454 	vstring_free(session->sasl_reply);
455 	session->sasl_reply = 0;
456     }
457 }
458 
459 /* smtp_sasl_passivate - append serialized SASL attributes */
460 
461 void    smtp_sasl_passivate(SMTP_SESSION *session, VSTRING *buf)
462 {
463 }
464 
465 /* smtp_sasl_activate - de-serialize SASL attributes */
466 
467 int     smtp_sasl_activate(SMTP_SESSION *session, char *buf)
468 {
469     return (0);
470 }
471 
472 #endif
473