1 /* SASL server API implementation
2  * Rob Siemborski
3  * Tim Martin
4  */
5 /*
6  * Copyright (c) 1998-2016 Carnegie Mellon University.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. The name "Carnegie Mellon University" must not be used to
21  *    endorse or promote products derived from this software without
22  *    prior written permission. For permission or any other legal
23  *    details, please contact
24  *      Carnegie Mellon University
25  *      Center for Technology Transfer and Enterprise Creation
26  *      4615 Forbes Avenue
27  *      Suite 302
28  *      Pittsburgh, PA  15213
29  *      (412) 268-7393, fax: (412) 268-7395
30  *      innovation@andrew.cmu.edu
31  *
32  * 4. Redistributions of any form whatsoever must retain the following
33  *    acknowledgment:
34  *    "This product includes software developed by Computing Services
35  *     at Carnegie Mellon University (http://www.cmu.edu/computing/)."
36  *
37  * CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
38  * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
39  * AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
40  * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
41  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
42  * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
43  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
44  */
45 
46 #include <config.h>
47 
48 /* checkpw stuff */
49 
50 #include <stdio.h>
51 #include "sasl.h"
52 #include "saslutil.h"
53 #include "saslplug.h"
54 #include "saslint.h"
55 
56 #include <assert.h>
57 #ifdef HAVE_UNISTD_H
58 #include <unistd.h>
59 #endif
60 #include <fcntl.h>
61 #ifdef USE_DOORS
62 #include <sys/mman.h>
63 #include <door.h>
64 #endif
65 
66 #include <stdlib.h>
67 
68 #ifndef WIN32
69 #include <strings.h>
70 #include <netdb.h>
71 #include <netinet/in.h>
72 #include <sys/un.h>
73 #else
74 #include <string.h>
75 #endif
76 
77 #include <limits.h>
78 #include <sys/types.h>
79 #include <ctype.h>
80 
81 #ifdef HAVE_PWD_H
82 #include <pwd.h>
83 #endif /* HAVE_PWD_H */
84 #ifdef HAVE_SHADOW_H
85 #include <shadow.h>
86 #endif /* HAVE_SHADOW_H */
87 
88 #if defined(HAVE_PWCHECK) || defined(HAVE_SASLAUTHD) || defined(HAVE_AUTHDAEMON)
89 # include <errno.h>
90 # include <sys/types.h>
91 # include <sys/socket.h>
92 # include <sys/un.h>
93 # ifdef HAVE_UNISTD_H
94 #  include <unistd.h>
95 # endif
96 #endif
97 
98 
99 /* we store the following secret to check plaintext passwords:
100  *
101  * <salt> \0 <secret>
102  *
103  * where <secret> = MD5(<salt>, "sasldb", <pass>)
104  */
_sasl_make_plain_secret(const char * salt,const char * passwd,size_t passlen,sasl_secret_t ** secret)105 static int _sasl_make_plain_secret(const char *salt,
106 				   const char *passwd, size_t passlen,
107 				   sasl_secret_t **secret)
108 {
109     MD5_CTX ctx;
110     unsigned sec_len = 16 + 1 + 16; /* salt + "\0" + hash */
111 
112     *secret = (sasl_secret_t *) sasl_ALLOC(sizeof(sasl_secret_t) +
113 					   sec_len * sizeof(char));
114     if (*secret == NULL) {
115 	return SASL_NOMEM;
116     }
117 
118     _sasl_MD5Init(&ctx);
119     _sasl_MD5Update(&ctx, (const unsigned char *) salt, 16);
120     _sasl_MD5Update(&ctx, (const unsigned char *) "sasldb", 6);
121     _sasl_MD5Update(&ctx, (const unsigned char *) passwd, (unsigned int) passlen);
122     memcpy((*secret)->data, salt, 16);
123     (*secret)->data[16] = '\0';
124     _sasl_MD5Final((*secret)->data + 17, &ctx);
125     (*secret)->len = sec_len;
126 
127     return SASL_OK;
128 }
129 
130 /* verify user password using auxprop plugins
131  */
auxprop_verify_password(sasl_conn_t * conn,const char * userstr,const char * passwd,const char * service,const char * user_realm)132 static int auxprop_verify_password(sasl_conn_t *conn,
133 				   const char *userstr,
134 				   const char *passwd,
135 				   const char *service __attribute__((unused)),
136 				   const char *user_realm __attribute__((unused)))
137 {
138     int ret = SASL_FAIL;
139     int result = SASL_OK;
140     sasl_server_conn_t *sconn = (sasl_server_conn_t *)conn;
141     const char *password_request[] = { SASL_AUX_PASSWORD,
142 				       "*cmusaslsecretPLAIN",
143 				       NULL };
144     struct propval auxprop_values[3];
145 
146     if (!conn || !userstr)
147 	return SASL_BADPARAM;
148 
149     /* We need to clear any previous results and re-canonify to
150      * ensure correctness */
151 
152     prop_clear (sconn->sparams->propctx, 0);
153 
154     /* ensure its requested */
155     result = prop_request(sconn->sparams->propctx, password_request);
156 
157     if(result != SASL_OK) return result;
158 
159     result = _sasl_canon_user_lookup (conn,
160 				      userstr,
161 				      0,
162 				      SASL_CU_AUTHID | SASL_CU_AUTHZID,
163 				      &(conn->oparams));
164     if(result != SASL_OK) return result;
165 
166     result = prop_getnames(sconn->sparams->propctx, password_request,
167 			   auxprop_values);
168     if (result < 0) {
169 	return result;
170     }
171 
172     /* Verify that the returned <name>s are correct.
173        But we defer checking for NULL values till after we verify
174        that a passwd is specified. */
175     if (!auxprop_values[0].name && !auxprop_values[1].name) {
176 	return SASL_NOUSER;
177     }
178 
179     /* It is possible for us to get useful information out of just
180      * the lookup, so we won't check that we have a password until now */
181     if(!passwd) {
182 	ret = SASL_BADPARAM;
183 	goto done;
184     }
185 
186     if ((!auxprop_values[0].values || !auxprop_values[0].values[0])
187 	&& (!auxprop_values[1].values || !auxprop_values[1].values[0])) {
188 	return SASL_NOUSER;
189     }
190 
191     /* At the point this has been called, the username has been canonified
192      * and we've done the auxprop lookup.  This should be easy. */
193     if(auxprop_values[0].name
194        && auxprop_values[0].values
195        && auxprop_values[0].values[0]
196        && !strcmp(auxprop_values[0].values[0], passwd)) {
197 	/* We have a plaintext version and it matched! */
198 	return SASL_OK;
199     } else if(auxprop_values[1].name
200 	      && auxprop_values[1].values
201 	      && auxprop_values[1].values[0]) {
202 	const char *db_secret = auxprop_values[1].values[0];
203 	sasl_secret_t *construct;
204 
205 	ret = _sasl_make_plain_secret(db_secret, passwd,
206 				      strlen(passwd),
207 				      &construct);
208 	if (ret != SASL_OK) {
209 	    goto done;
210 	}
211 
212 	if (!memcmp(db_secret, construct->data, construct->len)) {
213 	    /* password verified! */
214 	    ret = SASL_OK;
215 	} else {
216 	    /* passwords do not match */
217 	    ret = SASL_BADAUTH;
218 	}
219 
220 	sasl_FREE(construct);
221     } else {
222 	/* passwords do not match */
223 	ret = SASL_BADAUTH;
224     }
225 
226     /* erase the plaintext password */
227     sconn->sparams->utils->prop_erase(sconn->sparams->propctx,
228 				      password_request[0]);
229 
230  done:
231     /* We're not going to erase the property here because other people
232      * may want it */
233     return ret;
234 }
235 
236 #if 0
237 /* Verify user password using auxprop plugins. Allow verification against a hashed password,
238  * or non-retrievable password. Don't use cmusaslsecretPLAIN attribute.
239  *
240  * This function is similar to auxprop_verify_password().
241  */
242 static int auxprop_verify_password_hashed(sasl_conn_t *conn,
243 					  const char *userstr,
244 					  const char *passwd,
245 					  const char *service __attribute__((unused)),
246 					  const char *user_realm __attribute__((unused)))
247 {
248     int ret = SASL_FAIL;
249     int result = SASL_OK;
250     sasl_server_conn_t *sconn = (sasl_server_conn_t *)conn;
251     const char *password_request[] = { SASL_AUX_PASSWORD,
252 				       NULL };
253     struct propval auxprop_values[2];
254     unsigned extra_cu_flags = 0;
255 
256     if (!conn || !userstr)
257 	return SASL_BADPARAM;
258 
259     /* We need to clear any previous results and re-canonify to
260      * ensure correctness */
261 
262     prop_clear(sconn->sparams->propctx, 0);
263 
264     /* ensure its requested */
265     result = prop_request(sconn->sparams->propctx, password_request);
266 
267     if (result != SASL_OK) return result;
268 
269     /* We need to pass "password" down to the auxprop_lookup */
270     /* NB: We don't support binary passwords */
271     if (passwd != NULL) {
272 	prop_set (sconn->sparams->propctx,
273 		  SASL_AUX_PASSWORD,
274 		  passwd,
275 		  -1);
276 	extra_cu_flags = SASL_CU_VERIFY_AGAINST_HASH;
277     }
278 
279     result = _sasl_canon_user_lookup (conn,
280 				      userstr,
281 				      0,
282 				      SASL_CU_AUTHID | SASL_CU_AUTHZID | extra_cu_flags,
283 				      &(conn->oparams));
284 
285     if (result != SASL_OK) return result;
286 
287     result = prop_getnames(sconn->sparams->propctx, password_request,
288 			   auxprop_values);
289     if (result < 0) {
290 	return result;
291     }
292 
293     /* Verify that the returned <name>s are correct.
294        But we defer checking for NULL values till after we verify
295        that a passwd is specified. */
296     if (!auxprop_values[0].name && !auxprop_values[1].name) {
297 	return SASL_NOUSER;
298     }
299 
300     /* It is possible for us to get useful information out of just
301      * the lookup, so we won't check that we have a password until now */
302     if (!passwd) {
303 	ret = SASL_BADPARAM;
304 	goto done;
305     }
306 
307     if ((!auxprop_values[0].values || !auxprop_values[0].values[0])) {
308 	return SASL_NOUSER;
309     }
310 
311     /* At the point this has been called, the username has been canonified
312      * and we've done the auxprop lookup.  This should be easy. */
313 
314     /* NB: Note that if auxprop_lookup failed to verify the password,
315        then the userPassword property value would be NULL */
316     if (auxprop_values[0].name
317         && auxprop_values[0].values
318         && auxprop_values[0].values[0]
319         && !strcmp(auxprop_values[0].values[0], passwd)) {
320 	/* We have a plaintext version and it matched! */
321 	return SASL_OK;
322     } else {
323 	/* passwords do not match */
324 	ret = SASL_BADAUTH;
325     }
326 
327  done:
328     /* We're not going to erase the property here because other people
329      * may want it */
330     return ret;
331 }
332 #endif
333 
334 #ifdef DO_SASL_CHECKAPOP
_sasl_auxprop_verify_apop(sasl_conn_t * conn,const char * userstr,const char * challenge,const char * response,const char * user_realm)335 int _sasl_auxprop_verify_apop(sasl_conn_t *conn,
336 			      const char *userstr,
337 			      const char *challenge,
338 			      const char *response,
339 			      const char *user_realm __attribute__((unused)))
340 {
341     int ret = SASL_BADAUTH;
342     char *userid = NULL;
343     char *realm = NULL;
344     unsigned char digest[16];
345     char digeststr[33];
346     const char *password_request[] = { SASL_AUX_PASSWORD, NULL };
347     struct propval auxprop_values[2];
348     sasl_server_conn_t *sconn = (sasl_server_conn_t *)conn;
349     MD5_CTX ctx;
350     int i;
351 
352     if (!conn || !userstr || !challenge || !response)
353        PARAMERROR(conn)
354 
355     /* We've done the auxprop lookup already (in our caller) */
356     /* sadly, APOP has no provision for storing secrets */
357     ret = prop_getnames(sconn->sparams->propctx, password_request,
358 			auxprop_values);
359     if(ret < 0) {
360 	sasl_seterror(conn, 0, "could not perform password lookup");
361 	goto done;
362     }
363 
364     if(!auxprop_values[0].name ||
365        !auxprop_values[0].values ||
366        !auxprop_values[0].values[0]) {
367 	sasl_seterror(conn, 0, "could not find password");
368 	ret = SASL_NOUSER;
369 	goto done;
370     }
371 
372     _sasl_MD5Init(&ctx);
373     _sasl_MD5Update(&ctx, (const unsigned char *) challenge, strlen(challenge));
374     _sasl_MD5Update(&ctx, (const unsigned char *) auxprop_values[0].values[0],
375 		    strlen(auxprop_values[0].values[0]));
376     _sasl_MD5Final(digest, &ctx);
377 
378     /* erase the plaintext password */
379     sconn->sparams->utils->prop_erase(sconn->sparams->propctx,
380 				      password_request[0]);
381 
382     /* convert digest from binary to ASCII hex */
383     for (i = 0; i < 16; i++)
384       sprintf(digeststr + (i*2), "%02x", digest[i]);
385 
386     if (!strncasecmp(digeststr, response, 32)) {
387       /* password verified! */
388       ret = SASL_OK;
389     } else {
390       /* passwords do not match */
391       ret = SASL_BADAUTH;
392     }
393 
394  done:
395     if (ret == SASL_BADAUTH) sasl_seterror(conn, SASL_NOLOG,
396 					   "login incorrect");
397     if (userid) sasl_FREE(userid);
398     if (realm)  sasl_FREE(realm);
399 
400     return ret;
401 }
402 #endif /* DO_SASL_CHECKAPOP */
403 
404 #if defined(HAVE_PWCHECK) || defined(HAVE_SASLAUTHD) || defined(HAVE_AUTHDAEMON)
405 /*
406  * Wait for file descriptor to be writable. Return with error if timeout.
407  */
write_wait(int fd,unsigned delta)408 static int write_wait(int fd, unsigned delta)
409 {
410     fd_set wfds;
411     fd_set efds;
412     struct timeval tv;
413 
414     /*
415      * Wait for file descriptor fd to be writable. Retry on
416      * interruptions. Return with error upon timeout.
417      */
418     while (1) {
419 	FD_ZERO(&wfds);
420 	FD_ZERO(&efds);
421 	FD_SET(fd, &wfds);
422 	FD_SET(fd, &efds);
423 	tv.tv_sec = (long) delta;
424 	tv.tv_usec = 0;
425 	switch(select(fd + 1, 0, &wfds, &efds, &tv)) {
426 	case 0:
427 	    /* Timeout. */
428 	    errno = ETIMEDOUT;
429 	    return -1;
430 	case +1:
431 	    if (FD_ISSET(fd, &wfds)) {
432 		/* Success, file descriptor is writable. */
433 		return 0;
434 	    }
435 	    return -1;
436 	case -1:
437 	    if (errno == EINTR || errno == EAGAIN)
438 		continue;
439             return -1;
440 	default:
441 	    /* Error catch-all. */
442 	    return -1;
443 	}
444     }
445     /* Not reached. */
446     return -1;
447 }
448 
449 /*
450  * Keep calling the writev() system call with 'fd', 'iov', and 'iovcnt'
451  * until all the data is written out or an error/timeout occurs.
452  */
retry_writev(int fd,struct iovec * iov,int iovcnt,unsigned delta)453 static int retry_writev(int fd, struct iovec *iov, int iovcnt, unsigned delta)
454 {
455     int n;
456     int i;
457     int written = 0;
458     static int iov_max =
459 #ifdef MAXIOV
460 	MAXIOV
461 #else
462 #ifdef IOV_MAX
463 	IOV_MAX
464 #else
465 	8192
466 #endif
467 #endif
468 	;
469 
470     for (;;) {
471 	while (iovcnt && iov[0].iov_len == 0) {
472 	    iov++;
473 	    iovcnt--;
474 	}
475 
476 	if (!iovcnt) return written;
477 
478 	if (delta > 0) {
479 	    if (write_wait(fd, delta))
480 		return -1;
481 	}
482 	n = writev(fd, iov, iovcnt > iov_max ? iov_max : iovcnt);
483 	if (n == -1) {
484 	    if (errno == EINVAL && iov_max > 10) {
485 		iov_max /= 2;
486 		continue;
487 	    }
488 	    if (errno == EINTR) continue;
489 	    return -1;
490 	}
491 
492 	written += n;
493 
494 	for (i = 0; i < iovcnt; i++) {
495 	    if ((int) iov[i].iov_len > n) {
496 		iov[i].iov_base = (char *)iov[i].iov_base + n;
497 		iov[i].iov_len -= n;
498 		break;
499 	    }
500 	    n -= iov[i].iov_len;
501 	    iov[i].iov_len = 0;
502 	}
503 
504 	if (i == iovcnt) return written;
505     }
506 }
507 
508 #endif
509 
510 #ifdef HAVE_PWCHECK
511 /* pwcheck daemon-authenticated login */
pwcheck_verify_password(sasl_conn_t * conn,const char * userid,const char * passwd,const char * service,const char * user_realm)512 static int pwcheck_verify_password(sasl_conn_t *conn,
513 				   const char *userid,
514 				   const char *passwd,
515 				   const char *service __attribute__((unused)),
516 				   const char *user_realm
517 				               __attribute__((unused)))
518 {
519     int s;
520     struct sockaddr_un srvaddr;
521     int r;
522     struct iovec iov[10];
523     static char response[1024];
524     unsigned start, n;
525     char pwpath[1024];
526 
527     if (strlen(PWCHECKDIR)+8+1 > sizeof(pwpath)) return SASL_FAIL;
528 
529     strcpy(pwpath, PWCHECKDIR);
530     strcat(pwpath, "/pwcheck");
531 
532     s = socket(AF_UNIX, SOCK_STREAM, 0);
533     if (s == -1) return errno;
534 
535     memset((char *)&srvaddr, 0, sizeof(srvaddr));
536     srvaddr.sun_family = AF_UNIX;
537     strncpy(srvaddr.sun_path, pwpath, sizeof(srvaddr.sun_path));
538     r = connect(s, (struct sockaddr *)&srvaddr, sizeof(srvaddr));
539     if (r == -1) {
540 	sasl_seterror(conn,0,"cannot connect to pwcheck server");
541 	return SASL_FAIL;
542     }
543 
544     iov[0].iov_base = (char *)userid;
545     iov[0].iov_len = strlen(userid)+1;
546     iov[1].iov_base = (char *)passwd;
547     iov[1].iov_len = strlen(passwd)+1;
548 
549     retry_writev(s, iov, 2, 0);
550 
551     start = 0;
552     while (start < sizeof(response) - 1) {
553 	n = read(s, response+start, sizeof(response) - 1 - start);
554 	if (n < 1) break;
555 	start += n;
556     }
557 
558     close(s);
559 
560     if (start > 1 && !strncmp(response, "OK", 2)) {
561 	return SASL_OK;
562     }
563 
564     response[start] = '\0';
565     sasl_seterror(conn,0,response);
566     return SASL_BADAUTH;
567 }
568 
569 #endif
570 
571 #if defined(HAVE_SASLAUTHD) || defined(HAVE_AUTHDAEMON)
read_wait(int fd,unsigned delta)572 static int read_wait(int fd, unsigned delta)
573 {
574     fd_set rfds;
575     fd_set efds;
576     struct timeval tv;
577     /*
578      * Wait for file descriptor fd to be readable. Retry on
579      * interruptions. Return with error upon timeout.
580      */
581     while (1) {
582 	FD_ZERO(&rfds);
583 	FD_ZERO(&efds);
584 	FD_SET(fd, &rfds);
585 	FD_SET(fd, &efds);
586 	tv.tv_sec = (long) delta;
587 	tv.tv_usec = 0;
588 	switch(select(fd + 1, &rfds, 0, &efds, &tv)) {
589 	case 0:
590 	    /* Timeout. */
591 	    errno = ETIMEDOUT;
592 	    return -1;
593 	case +1:
594 	case +2:
595 	    if (FD_ISSET(fd, &rfds)) {
596 		/* Success, file descriptor is readable. */
597 		return 0;
598 	    }
599 	    return -1;
600 	case -1:
601 	    if (errno == EINTR || errno == EAGAIN)
602 		continue;
603             return -1;
604 	default:
605 	    /* Error catch-all. */
606 	    return -1;
607 	}
608     }
609     /* Not reached. */
610     return -1;
611 }
612 
613 /*
614  * Keep calling the read() system call until all the data is read in,
615  * timeout, EOF, or an error occurs. This function returns the number
616  * of useful bytes, or -1 if timeout/error.
617  */
retry_read(int fd,void * buf0,unsigned nbyte,unsigned delta)618 static int retry_read(int fd, void *buf0, unsigned nbyte, unsigned delta)
619 {
620     int nr;
621     unsigned nleft = nbyte;
622     char *buf = (char*) buf0;
623 
624     while (nleft >= 1) {
625 	if (delta > 0) {
626 	    if (read_wait(fd, delta))
627 		return -1;
628 	}
629 	nr = read(fd, buf, nleft);
630 	if (nr < 0) {
631 	    if (errno == EINTR || errno == EAGAIN)
632 		continue;
633 	    return -1;
634 	} else if (nr == 0) {
635 	    break;
636 	}
637       buf += nr;
638       nleft -= nr;
639     }
640     return nbyte - nleft;
641 }
642 #endif
643 
644 #ifdef HAVE_SASLAUTHD
645 /* saslauthd-authenticated login */
saslauthd_verify_password(sasl_conn_t * conn,const char * userid,const char * passwd,const char * service,const char * user_realm)646 static int saslauthd_verify_password(sasl_conn_t *conn,
647 				     const char *userid,
648 				     const char *passwd,
649 				     const char *service,
650 				     const char *user_realm)
651 {
652     char response[1024];
653     char query[8192];
654     char *query_end = query;
655     int s;
656     struct sockaddr_un srvaddr;
657     sasl_getopt_t *getopt;
658     void *context;
659     char pwpath[sizeof(srvaddr.sun_path)];
660     const char *p = NULL;
661     char *freeme = NULL;
662 #ifdef USE_DOORS
663     door_arg_t arg;
664 #endif
665 
666     /* check to see if the user configured a rundir */
667     if (_sasl_getcallback(conn, SASL_CB_GETOPT,
668                           (sasl_callback_ft *)&getopt, &context) == SASL_OK) {
669 	getopt(context, NULL, "saslauthd_path", &p, NULL);
670     }
671     if (p) {
672         if (strlen(p) >= sizeof(pwpath))
673             return SASL_FAIL;
674 
675 	strncpy(pwpath, p, sizeof(pwpath) - 1);
676         pwpath[strlen(p)] = '\0';
677     } else {
678 	if (strlen(PATH_SASLAUTHD_RUNDIR) + 4 + 1 > sizeof(pwpath))
679 	    return SASL_FAIL;
680 
681 	strcpy(pwpath, PATH_SASLAUTHD_RUNDIR "/mux");
682     }
683 
684     /* Split out username/realm if necessary */
685     if(strrchr(userid,'@') != NULL) {
686 	char *rtmp;
687 
688 	if(_sasl_strdup(userid, &freeme, NULL) != SASL_OK)
689 	    goto fail;
690 
691 	userid = freeme;
692 	rtmp = strrchr(userid,'@');
693 	*rtmp = '\0';
694 	user_realm = rtmp + 1;
695     }
696 
697     /*
698      * build request of the form:
699      *
700      * count authid count password count service count realm
701      */
702     {
703  	unsigned short max_len, req_len, u_len, p_len, s_len, r_len;
704 
705 	max_len = (unsigned short) sizeof(query);
706 
707 	/* prevent buffer overflow */
708 	if ((strlen(userid) > USHRT_MAX) ||
709 	    (strlen(passwd) > USHRT_MAX) ||
710 	    (strlen(service) > USHRT_MAX) ||
711 	    (user_realm && (strlen(user_realm) > USHRT_MAX))) {
712 	    goto toobig;
713 	}
714 
715  	u_len = (strlen(userid));
716  	p_len = (strlen(passwd));
717 	s_len = (strlen(service));
718 	r_len = ((user_realm ? strlen(user_realm) : 0));
719 
720 	/* prevent buffer overflow */
721 	req_len = 30;
722 	if (max_len - req_len < u_len) goto toobig;
723 	req_len += u_len;
724 	if (max_len - req_len < p_len) goto toobig;
725 	req_len += p_len;
726 	if (max_len - req_len < s_len) goto toobig;
727 	req_len += s_len;
728 	if (max_len - req_len < r_len) goto toobig;
729 
730 	u_len = htons(u_len);
731 	p_len = htons(p_len);
732 	s_len = htons(s_len);
733 	r_len = htons(r_len);
734 
735 	memcpy(query_end, &u_len, sizeof(unsigned short));
736 	query_end += sizeof(unsigned short);
737 	while (*userid) *query_end++ = *userid++;
738 
739 	memcpy(query_end, &p_len, sizeof(unsigned short));
740 	query_end += sizeof(unsigned short);
741 	while (*passwd) *query_end++ = *passwd++;
742 
743 	memcpy(query_end, &s_len, sizeof(unsigned short));
744 	query_end += sizeof(unsigned short);
745 	while (*service) *query_end++ = *service++;
746 
747 	memcpy(query_end, &r_len, sizeof(unsigned short));
748 	query_end += sizeof(unsigned short);
749 	if (user_realm) while (*user_realm) *query_end++ = *user_realm++;
750     }
751 
752 #ifdef USE_DOORS
753     s = open(pwpath, O_RDONLY);
754     if (s < 0) {
755 	sasl_seterror(conn, 0, "cannot open door to saslauthd server: %m", errno);
756 	goto fail;
757     }
758 
759     arg.data_ptr = query;
760     arg.data_size = query_end - query;
761     arg.desc_ptr = NULL;
762     arg.desc_num = 0;
763     arg.rbuf = response;
764     arg.rsize = sizeof(response);
765 
766     if (door_call(s, &arg) < 0) {
767       /* Parameters are undefined */
768       close(s);
769       sasl_seterror(conn, 0, "door call to saslauthd server failed: %m", errno);
770       goto fail;
771     }
772 
773     if (arg.data_ptr != response || arg.data_size >= sizeof(response)) {
774 	/* oh damn, we got back a really long response */
775 	munmap(arg.rbuf, arg.rsize);
776 	close(s);
777 	sasl_seterror(conn, 0, "saslauthd sent an overly long response");
778 	goto fail;
779     }
780     response[arg.data_size] = '\0';
781 
782     close(s);
783 #else
784     /* unix sockets */
785 
786     s = socket(AF_UNIX, SOCK_STREAM, 0);
787     if (s == -1) {
788 	sasl_seterror(conn, 0, "cannot create socket for saslauthd: %m", errno);
789 	goto fail;
790     }
791 
792     memset((char *)&srvaddr, 0, sizeof(srvaddr));
793     srvaddr.sun_family = AF_UNIX;
794     strncpy(srvaddr.sun_path, pwpath, sizeof(srvaddr.sun_path) - 1);
795     srvaddr.sun_path[strlen(pwpath)] = '\0';
796 
797     {
798 	int r = connect(s, (struct sockaddr *) &srvaddr, sizeof(srvaddr));
799 	if (r == -1) {
800 	    close(s);
801 	    sasl_seterror(conn, 0, "cannot connect to saslauthd server: %m", errno);
802 	    goto fail;
803 	}
804     }
805 
806     {
807  	struct iovec iov[8];
808 
809 	iov[0].iov_len = query_end - query;
810 	iov[0].iov_base = query;
811 
812 	if (retry_writev(s, iov, 1, 0) == -1) {
813 	    close(s);
814             sasl_seterror(conn, 0, "write failed");
815 	    goto fail;
816   	}
817     }
818 
819     {
820 	unsigned short count = 0;
821 
822 	/*
823 	 * read response of the form:
824 	 *
825 	 * count result
826 	 */
827 	if (retry_read(s, &count, sizeof(count), 0) < (int) sizeof(count)) {
828 	    sasl_seterror(conn, 0, "size read failed");
829 	    goto fail;
830 	}
831 
832 	count = ntohs(count);
833 	if (count < 2) { /* MUST have at least "OK" or "NO" */
834 	    close(s);
835 	    sasl_seterror(conn, 0, "bad response from saslauthd");
836 	    goto fail;
837 	}
838 
839 	count = (int)sizeof(response) <= count ? sizeof(response) - 1 : count;
840 	if (retry_read(s, response, count, 0) < count) {
841 	    close(s);
842 	    sasl_seterror(conn, 0, "read failed");
843 	    goto fail;
844 	}
845 	response[count] = '\0';
846     }
847 
848     close(s);
849 #endif /* USE_DOORS */
850 
851     if(freeme) free(freeme);
852 
853     if (!strncmp(response, "OK", 2)) {
854 	return SASL_OK;
855     }
856 
857     sasl_seterror(conn, SASL_NOLOG, "authentication failed");
858     return SASL_BADAUTH;
859 
860  toobig:
861     /* request just too damn big */
862     sasl_seterror(conn, 0, "saslauthd request too large");
863 
864  fail:
865     if (freeme) free(freeme);
866     return SASL_FAIL;
867 }
868 
869 #endif
870 
871 #ifdef HAVE_AUTHDAEMON
872 /*
873  * Preliminary support for Courier's authdaemond.
874  */
875 #define AUTHDAEMON_IO_TIMEOUT 30
876 
authdaemon_blocking(int fd,int block)877 static int authdaemon_blocking(int fd, int block)
878 {
879     int f, r;
880 
881     /* Get the fd's blocking bit. */
882     f = fcntl(fd, F_GETFL, 0);
883     if (f == -1)
884 	return -1;
885 
886     /* Adjust the bitmap accordingly. */
887 #ifndef O_NONBLOCK
888 #define NB_BITMASK FNDELAY
889 #else
890 #define NB_BITMASK O_NONBLOCK
891 #endif
892     if (block)
893 	f &= ~NB_BITMASK;
894     else
895 	f |=  NB_BITMASK;
896 #undef NB_BITMASK
897 
898     /* Adjust the fd's blocking bit. */
899     r = fcntl(fd, F_SETFL, f);
900     if (r)
901 	return -1;
902 
903     /* Success. */
904     return 0;
905 }
906 
authdaemon_connect(sasl_conn_t * conn,const char * path)907 static int authdaemon_connect(sasl_conn_t *conn, const char *path)
908 {
909     int r, s = -1;
910     struct sockaddr_un srvaddr;
911 
912     if (strlen(path) >= sizeof(srvaddr.sun_path)) {
913 	sasl_seterror(conn, 0, "unix socket path too large", errno);
914 	goto fail;
915     }
916 
917     s = socket(AF_UNIX, SOCK_STREAM, 0);
918     if (s == -1) {
919 	sasl_seterror(conn, 0, "cannot create socket for connection to Courier authdaemond: %m", errno);
920 	goto fail;
921     }
922 
923     memset((char *)&srvaddr, 0, sizeof(srvaddr));
924     srvaddr.sun_family = AF_UNIX;
925     strncpy(srvaddr.sun_path, path, sizeof(srvaddr.sun_path) - 1);
926 
927     /* Use nonblocking unix socket connect(2). */
928     if (authdaemon_blocking(s, 0)) {
929 	sasl_seterror(conn, 0, "cannot set nonblocking bit: %m", errno);
930 	goto fail;
931     }
932 
933     r = connect(s, (struct sockaddr *) &srvaddr, sizeof(srvaddr));
934     if (r == -1) {
935 	sasl_seterror(conn, 0, "cannot connect to Courier authdaemond: %m", errno);
936 	goto fail;
937     }
938 
939     if (authdaemon_blocking(s, 1)) {
940 	sasl_seterror(conn, 0, "cannot clear nonblocking bit: %m", errno);
941 	goto fail;
942     }
943 
944     return s;
945 fail:
946     if (s >= 0)
947 	close(s);
948     return -1;
949 }
950 
authdaemon_build_query(const char * service,const char * authtype,const char * user,const char * passwd)951 static char *authdaemon_build_query(const char *service,
952 				    const char *authtype,
953 				    const char *user,
954 				    const char *passwd)
955 {
956     int sz;
957     int l = strlen(service)
958             + 1
959             + strlen(authtype)
960             + 1
961             + strlen(user)
962             + 1
963             + strlen(passwd)
964             + 1;
965     char *buf, n[5];
966     if (snprintf(n, sizeof(n), "%d", l) >= (int)sizeof(n))
967 	return NULL;
968     sz = strlen(n) + l + 20;
969     if (!(buf = sasl_ALLOC(sz)))
970 	return NULL;
971     snprintf(buf,
972              sz,
973              "AUTH %s\n%s\n%s\n%s\n%s\n\n",
974              n,
975              service,
976              authtype,
977              user,
978              passwd);
979     return buf;
980 }
981 
authdaemon_read(int fd,void * buf0,unsigned sz)982 static int authdaemon_read(int fd, void *buf0, unsigned sz)
983 {
984     int nr;
985     char *buf = (char*) buf0;
986     if (sz <= 1)
987 	return -1;
988     if ((nr = retry_read(fd, buf0, sz - 1, AUTHDAEMON_IO_TIMEOUT)) < 0)
989 	return -1;
990     /* We need a null-terminated buffer. */
991     buf[nr] = 0;
992     /* Check for overflow condition. */
993     return nr + 1 < (int)sz ? 0 : -1;
994 }
995 
authdaemon_write(int fd,void * buf0,unsigned sz)996 static int authdaemon_write(int fd, void *buf0, unsigned sz)
997 {
998     int nw;
999     struct iovec io;
1000     io.iov_len = sz;
1001     io.iov_base = buf0;
1002     nw = retry_writev(fd, &io, 1, AUTHDAEMON_IO_TIMEOUT);
1003     return nw == (int)sz ? 0 : -1;
1004 }
1005 
authdaemon_talk(sasl_conn_t * conn,int sock,char * authreq)1006 static int authdaemon_talk(sasl_conn_t *conn, int sock, char *authreq)
1007 {
1008     char *str;
1009     char buf[8192];
1010 
1011     if (authdaemon_write(sock, authreq, strlen(authreq)))
1012 	goto _err_out;
1013     if (authdaemon_read(sock, buf, sizeof(buf)))
1014 	goto _err_out;
1015     for (str = buf; *str; ) {
1016 	char *sub;
1017 
1018 	for (sub = str; *str; ++str) {
1019 	    if (*str == '\n') {
1020 		*str++ = 0;
1021 		break;
1022 	    }
1023 	}
1024 	if (strcmp(sub, ".") == 0) {
1025 	    /* success */
1026 	    return SASL_OK;
1027 	}
1028 	if (strcmp(sub, "FAIL") == 0) {
1029 	    /* passwords do not match */
1030 	    sasl_seterror(conn, SASL_NOLOG, "authentication failed");
1031 	    return SASL_BADAUTH;
1032 	}
1033     }
1034 _err_out:
1035     /* catchall: authentication error */
1036     sasl_seterror(conn, 0, "could not verify password");
1037     return SASL_FAIL;
1038 }
1039 
authdaemon_verify_password(sasl_conn_t * conn,const char * userid,const char * passwd,const char * service,const char * user_realm)1040 static int authdaemon_verify_password(sasl_conn_t *conn,
1041 				      const char *userid,
1042 				      const char *passwd,
1043 				      const char *service,
1044 				      const char *user_realm __attribute__((unused)))
1045 {
1046     const char *p = NULL;
1047     sasl_getopt_t *getopt;
1048     void *context;
1049     int result = SASL_FAIL;
1050     char *query = NULL;
1051     int sock = -1;
1052 
1053     /* check to see if the user configured a rundir */
1054     if (_sasl_getcallback(conn, SASL_CB_GETOPT,
1055                           (sasl_callback_ft *)&getopt, &context) == SASL_OK) {
1056 	getopt(context, NULL, "authdaemond_path", &p, NULL);
1057     }
1058     if (!p) {
1059 	/*
1060 	 * XXX should we peek at Courier's build-time config ?
1061 	 */
1062 	p = PATH_AUTHDAEMON_SOCKET;
1063     }
1064 
1065     if ((sock = authdaemon_connect(conn, p)) < 0)
1066 	goto out;
1067     if (!(query = authdaemon_build_query(service, "login", userid, passwd)))
1068 	goto out;
1069     result = authdaemon_talk(conn, sock, query);
1070 out:
1071     if (sock >= 0)
1072 	close(sock), sock = -1;
1073     if (query)
1074 	sasl_FREE(query), query = 0;
1075     return result;
1076 }
1077 #endif
1078 
1079 #ifdef HAVE_ALWAYSTRUE
always_true(sasl_conn_t * conn,const char * userstr,const char * passwd,const char * service,const char * user_realm)1080 static int always_true(sasl_conn_t *conn,
1081 		       const char *userstr,
1082 		       const char *passwd __attribute__((unused)),
1083 		       const char *service __attribute__((unused)),
1084 		       const char *user_realm __attribute__((unused)))
1085 {
1086     _sasl_log(conn, SASL_LOG_WARN, "AlwaysTrue Password Verifier Verified: %s",
1087 	      userstr);
1088     return SASL_OK;
1089 }
1090 #endif
1091 
1092 struct sasl_verify_password_s _sasl_verify_password[] = {
1093     { "auxprop", &auxprop_verify_password },
1094 #if 0	/* totally undocumented. wtf is this? */
1095     { "auxprop-hashed", &auxprop_verify_password_hashed },
1096 #endif
1097 #ifdef HAVE_PWCHECK
1098     { "pwcheck", &pwcheck_verify_password },
1099 #endif
1100 #ifdef HAVE_SASLAUTHD
1101     { "saslauthd", &saslauthd_verify_password },
1102 #endif
1103 #ifdef HAVE_AUTHDAEMON
1104     { "authdaemond", &authdaemon_verify_password },
1105 #endif
1106 #ifdef HAVE_ALWAYSTRUE
1107     { "alwaystrue", &always_true },
1108 #endif
1109     { NULL, NULL }
1110 };
1111