1 /*
2  * Copyright (C) 2000-8 Brendan Cully <brendan@kublai.com>
3  *
4  *     This program is free software; you can redistribute it and/or modify
5  *     it under the terms of the GNU General Public License as published by
6  *     the Free Software Foundation; either version 2 of the License, or
7  *     (at your option) any later version.
8  *
9  *     This program is distributed in the hope that it will be useful,
10  *     but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *     GNU General Public License for more details.
13  *
14  *     You should have received a copy of the GNU General Public License
15  *     along with this program; if not, write to the Free Software
16  *     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17  */
18 
19 /* common SASL helper routines */
20 
21 #if HAVE_CONFIG_H
22 # include "config.h"
23 #endif
24 
25 #include "mutt.h"
26 #include "account.h"
27 #include "mutt_sasl.h"
28 #include "mutt_socket.h"
29 
30 #include <errno.h>
31 #include <netdb.h>
32 #include <sasl/sasl.h>
33 #include <sys/socket.h>
34 #include <netinet/in.h>
35 
getnameinfo_err(int ret)36 static int getnameinfo_err(int ret)
37 {
38   int err;
39   dprint (1, (debugfile, "getnameinfo: "));
40   switch(ret)
41   {
42      case EAI_AGAIN:
43        dprint (1, (debugfile, "The name could not be resolved at this time.  Future attempts may succeed.\n"));
44        err=SASL_TRYAGAIN;
45        break;
46      case EAI_BADFLAGS:
47        dprint (1, (debugfile, "The flags had an invalid value.\n"));
48        err=SASL_BADPARAM;
49        break;
50      case EAI_FAIL:
51        dprint (1, (debugfile, "A non-recoverable error occurred.\n"));
52        err=SASL_FAIL;
53        break;
54      case EAI_FAMILY:
55        dprint (1, (debugfile, "The address family was not recognized or the address length was invalid for the specified family.\n"));
56        err=SASL_BADPROT;
57        break;
58      case EAI_MEMORY:
59        dprint (1, (debugfile, "There was a memory allocation failure.\n"));
60        err=SASL_NOMEM;
61        break;
62      case EAI_NONAME:
63        dprint (1, (debugfile, "The name does not resolve for the supplied parameters.  NI_NAMEREQD is set and the host's name cannot be located, or both nodename and servname were null.\n"));
64        err=SASL_FAIL; /* no real equivalent */
65        break;
66      case EAI_SYSTEM:
67        dprint (1, (debugfile, "A system error occurred.  The error code can be found in errno(%d,%s)).\n",errno,strerror(errno)));
68        err=SASL_FAIL; /* no real equivalent */
69        break;
70      default:
71        dprint (1, (debugfile, "Unknown error %d\n",ret));
72        err=SASL_FAIL; /* no real equivalent */
73        break;
74   }
75   return err;
76 }
77 
78 /* arbitrary. SASL will probably use a smaller buffer anyway. OTOH it's
79  * been a while since I've had access to an SASL server which negotiated
80  * a protection buffer. */
81 #define M_SASL_MAXBUF 65536
82 
83 #define IP_PORT_BUFLEN 1024
84 
85 static sasl_callback_t mutt_sasl_callbacks[5];
86 
87 static int mutt_sasl_start (void);
88 
89 /* callbacks */
90 static int mutt_sasl_cb_log (void* context, int priority, const char* message);
91 static int mutt_sasl_cb_authname (void* context, int id, const char** result,
92   unsigned int* len);
93 static int mutt_sasl_cb_pass (sasl_conn_t* conn, void* context, int id,
94   sasl_secret_t** psecret);
95 
96 /* socket wrappers for a SASL security layer */
97 static int mutt_sasl_conn_open (CONNECTION* conn);
98 static int mutt_sasl_conn_close (CONNECTION* conn);
99 static int mutt_sasl_conn_read (CONNECTION* conn, char* buf, size_t len);
100 static int mutt_sasl_conn_write (CONNECTION* conn, const char* buf,
101   size_t count);
102 static int mutt_sasl_conn_poll (CONNECTION* conn);
103 
104 /* utility function, stolen from sasl2 sample code */
iptostring(const struct sockaddr * addr,socklen_t addrlen,char * out,unsigned outlen)105 static int iptostring(const struct sockaddr *addr, socklen_t addrlen,
106                      char *out, unsigned outlen) {
107     char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
108     int ret;
109 
110     if(!addr || !out) return SASL_BADPARAM;
111 
112     ret=getnameinfo(addr, addrlen, hbuf, sizeof(hbuf), pbuf, sizeof(pbuf),
113                    NI_NUMERICHOST |
114 #ifdef NI_WITHSCOPEID
115 		   NI_WITHSCOPEID |
116 #endif
117 		   NI_NUMERICSERV);
118     if(ret)
119       return getnameinfo_err(ret);
120 
121     if(outlen < strlen(hbuf) + strlen(pbuf) + 2)
122         return SASL_BUFOVER;
123 
124     snprintf(out, outlen, "%s;%s", hbuf, pbuf);
125 
126     return SASL_OK;
127 }
128 
129 /* mutt_sasl_start: called before doing a SASL exchange - initialises library
130  *   (if necessary). */
mutt_sasl_start(void)131 int mutt_sasl_start (void)
132 {
133   static unsigned char sasl_init = 0;
134 
135   static sasl_callback_t callbacks[2];
136   int rc;
137 
138   if (sasl_init)
139     return SASL_OK;
140 
141   /* set up default logging callback */
142   callbacks[0].id = SASL_CB_LOG;
143   callbacks[0].proc = mutt_sasl_cb_log;
144   callbacks[0].context = NULL;
145 
146   callbacks[1].id = SASL_CB_LIST_END;
147   callbacks[1].proc = NULL;
148   callbacks[1].context = NULL;
149 
150   rc = sasl_client_init (callbacks);
151 
152   if (rc != SASL_OK)
153   {
154     dprint (1, (debugfile, "mutt_sasl_start: libsasl initialisation failed.\n"));
155     return SASL_FAIL;
156   }
157 
158   sasl_init = 1;
159 
160   return SASL_OK;
161 }
162 
163 /* mutt_sasl_client_new: wrapper for sasl_client_new which also sets various
164  * security properties. If this turns out to be fine for POP too we can
165  * probably stop exporting mutt_sasl_get_callbacks(). */
mutt_sasl_client_new(CONNECTION * conn,sasl_conn_t ** saslconn)166 int mutt_sasl_client_new (CONNECTION* conn, sasl_conn_t** saslconn)
167 {
168   sasl_security_properties_t secprops;
169   struct sockaddr_storage local, remote;
170   socklen_t size;
171   char iplocalport[IP_PORT_BUFLEN], ipremoteport[IP_PORT_BUFLEN];
172   char* plp = NULL;
173   char* prp = NULL;
174   const char* service;
175   int rc;
176 
177   if (mutt_sasl_start () != SASL_OK)
178     return -1;
179 
180   switch (conn->account.type)
181   {
182     case M_ACCT_TYPE_IMAP:
183       service = "imap";
184       break;
185     case M_ACCT_TYPE_POP:
186       service = "pop";
187       break;
188     case M_ACCT_TYPE_SMTP:
189       service = "smtp";
190       break;
191     default:
192       mutt_error (_("Unknown SASL profile"));
193       return -1;
194   }
195 
196   size = sizeof (local);
197   if (!getsockname (conn->fd, (struct sockaddr *)&local, &size)) {
198     if (!iptostring((struct sockaddr *)&local, size, iplocalport,
199 		      IP_PORT_BUFLEN) != SASL_OK)
200       plp = iplocalport;
201     else
202       dprint (2, (debugfile, "SASL failed to parse local IP address\n"));
203   }
204   else
205     dprint (2, (debugfile, "SASL failed to get local IP address\n"));
206 
207   size = sizeof (remote);
208   if (!getpeername (conn->fd, (struct sockaddr *)&remote, &size)){
209     if (!iptostring((struct sockaddr *)&remote, size, ipremoteport,
210 		      IP_PORT_BUFLEN) != SASL_OK)
211       prp = ipremoteport;
212     else
213       dprint (2, (debugfile, "SASL failed to parse remote IP address\n"));
214   }
215   else
216     dprint (2, (debugfile, "SASL failed to get remote IP address\n"));
217 
218   dprint (2, (debugfile, "SASL local ip: %s, remote ip:%s\n", NONULL(plp),
219 	      NONULL(prp)));
220 
221   rc = sasl_client_new (service, conn->account.host, plp, prp,
222     mutt_sasl_get_callbacks (&conn->account), 0, saslconn);
223 
224   if (rc != SASL_OK)
225   {
226     mutt_error (_("Error allocating SASL connection"));
227     return -1;
228   }
229 
230   memset (&secprops, 0, sizeof (secprops));
231   /* Work around a casting bug in the SASL krb4 module */
232   secprops.max_ssf = 0x7fff;
233   secprops.maxbufsize = M_SASL_MAXBUF;
234   if (sasl_setprop (*saslconn, SASL_SEC_PROPS, &secprops) != SASL_OK)
235   {
236     mutt_error (_("Error setting SASL security properties"));
237     return -1;
238   }
239 
240   if (conn->ssf)
241   {
242     /* I'm not sure this actually has an effect, at least with SASLv2 */
243     dprint (2, (debugfile, "External SSF: %d\n", conn->ssf));
244     if (sasl_setprop (*saslconn, SASL_SSF_EXTERNAL, &(conn->ssf)) != SASL_OK)
245     {
246       mutt_error (_("Error setting SASL external security strength"));
247       return -1;
248     }
249   }
250   if (conn->account.user[0])
251   {
252     dprint (2, (debugfile, "External authentication name: %s\n", conn->account.user));
253     if (sasl_setprop (*saslconn, SASL_AUTH_EXTERNAL, conn->account.user) != SASL_OK)
254     {
255       mutt_error (_("Error setting SASL external user name"));
256       return -1;
257     }
258   }
259 
260   return 0;
261 }
262 
mutt_sasl_get_callbacks(ACCOUNT * account)263 sasl_callback_t* mutt_sasl_get_callbacks (ACCOUNT* account)
264 {
265   sasl_callback_t* callback;
266 
267   callback = mutt_sasl_callbacks;
268 
269   callback->id = SASL_CB_USER;
270   callback->proc = mutt_sasl_cb_authname;
271   callback->context = account;
272   callback++;
273 
274   callback->id = SASL_CB_AUTHNAME;
275   callback->proc = mutt_sasl_cb_authname;
276   callback->context = account;
277   callback++;
278 
279   callback->id = SASL_CB_PASS;
280   callback->proc = mutt_sasl_cb_pass;
281   callback->context = account;
282   callback++;
283 
284   callback->id = SASL_CB_GETREALM;
285   callback->proc = NULL;
286   callback->context = NULL;
287   callback++;
288 
289   callback->id = SASL_CB_LIST_END;
290   callback->proc = NULL;
291   callback->context = NULL;
292 
293   return mutt_sasl_callbacks;
294 }
295 
mutt_sasl_interact(sasl_interact_t * interaction)296 int mutt_sasl_interact (sasl_interact_t* interaction)
297 {
298   char prompt[SHORT_STRING];
299   char resp[SHORT_STRING];
300 
301   while (interaction->id != SASL_CB_LIST_END)
302   {
303     dprint (2, (debugfile, "mutt_sasl_interact: filling in SASL interaction %ld.\n", interaction->id));
304 
305     snprintf (prompt, sizeof (prompt), "%s: ", interaction->prompt);
306     resp[0] = '\0';
307     if (option (OPTNOCURSES) || mutt_get_field (prompt, resp, sizeof (resp), 0))
308       return SASL_FAIL;
309 
310     interaction->len = mutt_strlen (resp)+1;
311     interaction->result = safe_malloc (interaction->len);
312     memcpy ((char *)interaction->result, resp, interaction->len);
313 
314     interaction++;
315   }
316 
317   return SASL_OK;
318 }
319 
320 /* SASL can stack a protection layer on top of an existing connection.
321  * To handle this, we store a saslconn_t in conn->sockdata, and write
322  * wrappers which en/decode the read/write stream, then replace sockdata
323  * with an embedded copy of the old sockdata and call the underlying
324  * functions (which we've also preserved). I thought about trying to make
325  * a general stackable connection system, but it seemed like overkill -
326  * something is wrong if we have 15 filters on top of a socket. Anyway,
327  * anything else which wishes to stack can use the same method. The only
328  * disadvantage is we have to write wrappers for all the socket methods,
329  * even if we only stack over read and write. Thinking about it, the
330  * abstraction problem is that there is more in CONNECTION than there
331  * needs to be. Ideally it would have only (void*)data and methods. */
332 
333 /* mutt_sasl_setup_conn: replace connection methods, sockdata with
334  *   SASL wrappers, for protection layers. Also get ssf, as a fastpath
335  *   for the read/write methods. */
mutt_sasl_setup_conn(CONNECTION * conn,sasl_conn_t * saslconn)336 void mutt_sasl_setup_conn (CONNECTION* conn, sasl_conn_t* saslconn)
337 {
338   SASL_DATA* sasldata = (SASL_DATA*) safe_malloc (sizeof (SASL_DATA));
339   /* work around sasl_getprop aliasing issues */
340   const void* tmp;
341 
342   sasldata->saslconn = saslconn;
343   /* get ssf so we know whether we have to (en|de)code read/write */
344   sasl_getprop (saslconn, SASL_SSF, &tmp);
345   sasldata->ssf = tmp;
346   dprint (3, (debugfile, "SASL protection strength: %u\n", *sasldata->ssf));
347   /* Add SASL SSF to transport SSF */
348   conn->ssf += *sasldata->ssf;
349   sasl_getprop (saslconn, SASL_MAXOUTBUF, &tmp);
350   sasldata->pbufsize = tmp;
351   dprint (3, (debugfile, "SASL protection buffer size: %u\n", *sasldata->pbufsize));
352 
353   /* clear input buffer */
354   sasldata->buf = NULL;
355   sasldata->bpos = 0;
356   sasldata->blen = 0;
357 
358   /* preserve old functions */
359   sasldata->sockdata = conn->sockdata;
360   sasldata->msasl_open = conn->conn_open;
361   sasldata->msasl_close = conn->conn_close;
362   sasldata->msasl_read = conn->conn_read;
363   sasldata->msasl_write = conn->conn_write;
364   sasldata->msasl_poll = conn->conn_poll;
365 
366   /* and set up new functions */
367   conn->sockdata = sasldata;
368   conn->conn_open = mutt_sasl_conn_open;
369   conn->conn_close = mutt_sasl_conn_close;
370   conn->conn_read = mutt_sasl_conn_read;
371   conn->conn_write = mutt_sasl_conn_write;
372   conn->conn_poll = mutt_sasl_conn_poll;
373 }
374 
375 /* mutt_sasl_cb_log: callback to log SASL messages */
mutt_sasl_cb_log(void * context,int priority,const char * message)376 static int mutt_sasl_cb_log (void* context, int priority, const char* message)
377 {
378   dprint (priority, (debugfile, "SASL: %s\n", message));
379 
380   return SASL_OK;
381 }
382 
mutt_sasl_done(void)383 void mutt_sasl_done (void)
384 {
385   sasl_done ();
386 }
387 
388 /* mutt_sasl_cb_authname: callback to retrieve authname or user from ACCOUNT */
mutt_sasl_cb_authname(void * context,int id,const char ** result,unsigned * len)389 static int mutt_sasl_cb_authname (void* context, int id, const char** result,
390   unsigned* len)
391 {
392   ACCOUNT* account = (ACCOUNT*) context;
393 
394   if (!result)
395     return SASL_FAIL;
396 
397   *result = NULL;
398   if (len)
399     *len = 0;
400 
401   if (!account)
402     return SASL_BADPARAM;
403 
404   dprint (2, (debugfile, "mutt_sasl_cb_authname: getting %s for %s:%u\n",
405 	      id == SASL_CB_AUTHNAME ? "authname" : "user",
406 	      account->host, account->port));
407 
408   if (id == SASL_CB_AUTHNAME)
409   {
410     if (mutt_account_getlogin (account))
411       return SASL_FAIL;
412     *result = account->login;
413   }
414   else
415   {
416     if (mutt_account_getuser (account))
417       return SASL_FAIL;
418     *result = account->user;
419   }
420 
421   if (len)
422     *len = strlen (*result);
423 
424   return SASL_OK;
425 }
426 
mutt_sasl_cb_pass(sasl_conn_t * conn,void * context,int id,sasl_secret_t ** psecret)427 static int mutt_sasl_cb_pass (sasl_conn_t* conn, void* context, int id,
428   sasl_secret_t** psecret)
429 {
430   ACCOUNT* account = (ACCOUNT*) context;
431   int len;
432 
433   if (!account || !psecret)
434     return SASL_BADPARAM;
435 
436   dprint (2, (debugfile,
437     "mutt_sasl_cb_pass: getting password for %s@%s:%u\n", account->login,
438     account->host, account->port));
439 
440   if (mutt_account_getpass (account))
441     return SASL_FAIL;
442 
443   len = strlen (account->pass);
444 
445   *psecret = (sasl_secret_t*) safe_malloc (sizeof (sasl_secret_t) + len);
446   (*psecret)->len = len;
447   strcpy ((char*)(*psecret)->data, account->pass);	/* __STRCPY_CHECKED__ */
448 
449   return SASL_OK;
450 }
451 
452 /* mutt_sasl_conn_open: empty wrapper for underlying open function. We
453  *   don't know in advance that a connection will use SASL, so we
454  *   replace conn's methods with sasl methods when authentication
455  *   is successful, using mutt_sasl_setup_conn */
mutt_sasl_conn_open(CONNECTION * conn)456 static int mutt_sasl_conn_open (CONNECTION* conn)
457 {
458   SASL_DATA* sasldata;
459   int rc;
460 
461   sasldata = (SASL_DATA*) conn->sockdata;
462   conn->sockdata = sasldata->sockdata;
463   rc = (sasldata->msasl_open) (conn);
464   conn->sockdata = sasldata;
465 
466   return rc;
467 }
468 
469 /* mutt_sasl_conn_close: calls underlying close function and disposes of
470  *   the sasl_conn_t object, then restores connection to pre-sasl state */
mutt_sasl_conn_close(CONNECTION * conn)471 static int mutt_sasl_conn_close (CONNECTION* conn)
472 {
473   SASL_DATA* sasldata;
474   int rc;
475 
476   sasldata = (SASL_DATA*) conn->sockdata;
477 
478   /* restore connection's underlying methods */
479   conn->sockdata = sasldata->sockdata;
480   conn->conn_open = sasldata->msasl_open;
481   conn->conn_close = sasldata->msasl_close;
482   conn->conn_read = sasldata->msasl_read;
483   conn->conn_write = sasldata->msasl_write;
484   conn->conn_poll = sasldata->msasl_poll;
485 
486   /* release sasl resources */
487   sasl_dispose (&sasldata->saslconn);
488   FREE (&sasldata);
489 
490   /* call underlying close */
491   rc = (conn->conn_close) (conn);
492 
493   return rc;
494 }
495 
mutt_sasl_conn_read(CONNECTION * conn,char * buf,size_t len)496 static int mutt_sasl_conn_read (CONNECTION* conn, char* buf, size_t len)
497 {
498   SASL_DATA* sasldata;
499   int rc;
500 
501   unsigned int olen;
502 
503   sasldata = (SASL_DATA*) conn->sockdata;
504 
505   /* if we still have data in our read buffer, copy it into buf */
506   if (sasldata->blen > sasldata->bpos)
507   {
508     olen = (sasldata->blen - sasldata->bpos > len) ? len :
509       sasldata->blen - sasldata->bpos;
510 
511     memcpy (buf, sasldata->buf+sasldata->bpos, olen);
512     sasldata->bpos += olen;
513 
514     return olen;
515   }
516 
517   conn->sockdata = sasldata->sockdata;
518 
519   sasldata->bpos = 0;
520   sasldata->blen = 0;
521 
522   /* and decode the result, if necessary */
523   if (*sasldata->ssf)
524   {
525     do
526     {
527       /* call the underlying read function to fill the buffer */
528       rc = (sasldata->msasl_read) (conn, buf, len);
529       if (rc <= 0)
530 	goto out;
531 
532       rc = sasl_decode (sasldata->saslconn, buf, rc, &sasldata->buf,
533         &sasldata->blen);
534       if (rc != SASL_OK)
535       {
536 	dprint (1, (debugfile, "SASL decode failed: %s\n",
537           sasl_errstring (rc, NULL, NULL)));
538 	goto out;
539       }
540     }
541     while (!sasldata->blen);
542 
543     olen = (sasldata->blen - sasldata->bpos > len) ? len :
544       sasldata->blen - sasldata->bpos;
545 
546     memcpy (buf, sasldata->buf, olen);
547     sasldata->bpos += olen;
548 
549     rc = olen;
550   }
551   else
552     rc = (sasldata->msasl_read) (conn, buf, len);
553 
554   out:
555     conn->sockdata = sasldata;
556 
557     return rc;
558 }
559 
mutt_sasl_conn_write(CONNECTION * conn,const char * buf,size_t len)560 static int mutt_sasl_conn_write (CONNECTION* conn, const char* buf,
561   size_t len)
562 {
563   SASL_DATA* sasldata;
564   int rc;
565 
566   const char *pbuf;
567   unsigned int olen, plen;
568 
569   sasldata = (SASL_DATA*) conn->sockdata;
570   conn->sockdata = sasldata->sockdata;
571 
572   /* encode data, if necessary */
573   if (*sasldata->ssf)
574   {
575     /* handle data larger than MAXOUTBUF */
576     do
577     {
578       olen = (len > *sasldata->pbufsize) ? *sasldata->pbufsize : len;
579 
580       rc = sasl_encode (sasldata->saslconn, buf, olen, &pbuf, &plen);
581       if (rc != SASL_OK)
582       {
583 	dprint (1, (debugfile, "SASL encoding failed: %s\n",
584           sasl_errstring (rc, NULL, NULL)));
585 	goto fail;
586       }
587 
588       rc = (sasldata->msasl_write) (conn, pbuf, plen);
589       if (rc != plen)
590 	goto fail;
591 
592       len -= olen;
593       buf += olen;
594     }
595     while (len > *sasldata->pbufsize);
596   }
597   else
598   /* just write using the underlying socket function */
599     rc = (sasldata->msasl_write) (conn, buf, len);
600 
601   conn->sockdata = sasldata;
602 
603   return rc;
604 
605  fail:
606   conn->sockdata = sasldata;
607   return -1;
608 }
609 
mutt_sasl_conn_poll(CONNECTION * conn)610 static int mutt_sasl_conn_poll (CONNECTION* conn)
611 {
612   SASL_DATA* sasldata = conn->sockdata;
613   int rc;
614 
615   conn->sockdata = sasldata->sockdata;
616   rc = sasldata->msasl_poll (conn);
617   conn->sockdata = sasldata;
618 
619   return rc;
620 }
621