]> diplodocus.org Git - nmh/blob - sbr/netsec.c
c5dfef01bbdca10311cf6ca4f507fb2f483ddfab
[nmh] / sbr / netsec.c
1
2 /*
3 * netsec.c -- Network security routines for handling protocols that
4 * require SASL and/or TLS.
5 *
6 * This code is Copyright (c) 2016, by the authors of nmh. See the
7 * COPYRIGHT file in the root directory of the nmh distribution for
8 * complete copyright information.
9 */
10
11 #include <h/mh.h>
12 #include <h/utils.h>
13 #include <h/netsec.h>
14 #include <h/oauth.h>
15 #include <stdarg.h>
16 #include <sys/select.h>
17
18 #ifdef CYRUS_SASL
19 #include <sasl/sasl.h>
20 #include <sasl/saslutil.h>
21 # if SASL_VERSION_FULL < 0x020125
22 /* Cyrus SASL 2.1.25 introduced the sasl_callback_ft prototype,
23 which has an explicit void parameter list, according to best
24 practice. So we need to cast to avoid compile warnings.
25 Provide this prototype for earlier versions. */
26 typedef int (*sasl_callback_ft)();
27 # endif /* SASL_VERSION_FULL < 0x020125 */
28
29 static int netsec_get_user(void *context, int id, const char **result,
30 unsigned int *len);
31 static int netsec_get_password(sasl_conn_t *conn, void *context, int id,
32 sasl_secret_t **psecret);
33
34 static int sasl_initialized = 0;
35
36 #define SASL_MAXRECVBUF 65536
37 #endif /* CYRUS_SASL */
38
39 #ifdef TLS_SUPPORT
40 #include <openssl/ssl.h>
41 #include <openssl/err.h>
42
43 static int tls_initialized = 0;
44 static SSL_CTX *sslctx = NULL; /* SSL Context */
45
46 #endif /* TLS_SUPPORT */
47
48 /* I'm going to hardcode this for now; maybe make it adjustable later? */
49 #define NETSEC_BUFSIZE 65536
50
51 /*
52 * Our context structure, which holds all of the relevant information
53 * about a connection.
54 */
55
56 struct _netsec_context {
57 int ns_fd; /* Descriptor for network connection */
58 int ns_snoop; /* If true, display network data */
59 int ns_timeout; /* Network read timeout, in seconds */
60 char *ns_userid; /* Userid for authentication */
61 unsigned char *ns_inbuffer; /* Our read input buffer */
62 unsigned char *ns_inptr; /* Our read buffer input pointer */
63 unsigned int ns_inbuflen; /* Length of data in input buffer */
64 unsigned int ns_inbufsize; /* Size of input buffer */
65 unsigned char *ns_outbuffer;/* Output buffer */
66 unsigned char *ns_outptr; /* Output buffer pointer */
67 unsigned int ns_outbuflen; /* Output buffer data length */
68 unsigned int ns_outbufsize; /* Output buffer size */
69 char *sasl_mech; /* User-requested mechanism */
70 #ifdef OAUTH_SUPPORT
71 char *oauth_service; /* OAuth2 service name */
72 #endif /* OAUTH_SUPPORT */
73 #ifdef CYRUS_SASL
74 char *sasl_hostname; /* Hostname we've connected to */
75 sasl_conn_t *sasl_conn; /* SASL connection context */
76 sasl_ssf_t sasl_ssf; /* SASL Security Strength Factor */
77 netsec_sasl_callback sasl_proto_cb; /* SASL callback we use */
78 sasl_callback_t *sasl_cbs; /* Callbacks used by SASL */
79 nmh_creds_t sasl_creds; /* Credentials (username/password) */
80 sasl_secret_t *sasl_secret; /* SASL password structure */
81 char *sasl_chosen_mech; /* Mechanism chosen by SASL */
82 int sasl_seclayer; /* If true, SASL security layer is enabled */
83 char *sasl_tmpbuf; /* Temporary read buffer for decodes */
84 size_t sasl_maxbufsize; /* Maximum negotiated SASL buffer size */
85 #endif /* CYRUS_SASL */
86 #ifdef TLS_SUPPORT
87 BIO *ssl_io; /* BIO used for connection I/O */
88 int tls_active; /* If true, TLS is running */
89 #endif /* TLS_SUPPORT */
90 };
91
92 /*
93 * Function to read data from the actual network socket
94 */
95
96 static int netsec_fillread(netsec_context *ns_context, char **errstr);
97
98 /*
99 * How this code works, in general.
100 *
101 * _If_ we are using no encryption or SASL encryption, then we buffer the
102 * network data through ns_inbuffer and ns_outbuffer. That should be
103 * relatively self-explanatory.
104 *
105 * If we are using SSL for encryption, then use a buffering BIO for output
106 * (that just easier). Still do buffering for reads; when we need more
107 * data we call the BIO_read() function to fill our local buffer.
108 *
109 * For SASL, we make use of (for now) the Cyrus-SASL library. For some
110 * mechanisms, we implement those mechanisms directly since the Cyrus SASL
111 * library doesn't support them (like OAuth).
112 */
113
114 /*
115 * Allocate and initialize our security context
116 */
117
118 netsec_context *
119 netsec_init(void)
120 {
121 netsec_context *nsc = mh_xmalloc(sizeof(*nsc));
122
123 nsc->ns_fd = -1;
124 nsc->ns_snoop = 0;
125 nsc->ns_userid = NULL;
126 nsc->ns_timeout = 60; /* Our default */
127 nsc->ns_inbufsize = NETSEC_BUFSIZE;
128 nsc->ns_inbuffer = mh_xmalloc(nsc->ns_inbufsize);
129 nsc->ns_inptr = nsc->ns_inbuffer;
130 nsc->ns_inbuflen = 0;
131 nsc->ns_outbufsize = NETSEC_BUFSIZE;
132 nsc->ns_outbuffer = mh_xmalloc(nsc->ns_outbufsize);
133 nsc->ns_outptr = nsc->ns_outbuffer;
134 nsc->ns_outbuflen = 0;
135 nsc->sasl_mech = NULL;
136 #ifdef OAUTH_SUPPORT
137 nsc->oauth_service = NULL;
138 #endif /* OAUTH_SUPPORT */
139 #ifdef CYRUS_SASL
140 nsc->sasl_conn = NULL;
141 nsc->sasl_hostname = NULL;
142 nsc->sasl_cbs = NULL;
143 nsc->sasl_creds = NULL;
144 nsc->sasl_secret = NULL;
145 nsc->sasl_chosen_mech = NULL;
146 nsc->sasl_ssf = 0;
147 nsc->sasl_seclayer = 0;
148 nsc->sasl_tmpbuf = NULL;
149 nsc->sasl_maxbufsize = 0;
150 #endif /* CYRUS_SASL */
151 #ifdef TLS_SUPPORT
152 nsc->ssl_io = NULL;
153 nsc->tls_active = 0;
154 #endif /* TLS_SUPPORT */
155 return nsc;
156 }
157
158 /*
159 * Shutdown the connection completely and free all resources.
160 * The connection is only closed if the flag is given.
161 */
162
163 void
164 netsec_shutdown(netsec_context *nsc, int closeflag)
165 {
166 if (nsc->ns_userid)
167 free(nsc->ns_userid);
168 if (nsc->ns_inbuffer)
169 free(nsc->ns_inbuffer);
170 if (nsc->ns_outbuffer)
171 free(nsc->ns_outbuffer);
172 if (nsc->sasl_mech)
173 free(nsc->sasl_mech);
174 #ifdef OAUTH_SERVICE
175 if (nsc->oauth_service)
176 free(nsc->oauth_service);
177 #endif /* OAUTH_SERVICE */
178 #ifdef CYRUS_SASL
179 if (nsc->sasl_conn)
180 sasl_dispose(&nsc->sasl_conn);
181 if (nsc->sasl_hostname)
182 free(nsc->sasl_hostname);
183 if (nsc->sasl_cbs)
184 free(nsc->sasl_cbs);
185 if (nsc->sasl_creds) {
186 if (nsc->sasl_creds->password)
187 memset(nsc->sasl_creds->password, 0,
188 strlen(nsc->sasl_creds->password));
189 free(nsc->sasl_creds);
190 }
191 if (nsc->sasl_secret) {
192 if (nsc->sasl_secret->len > 0) {
193 memset(nsc->sasl_secret->data, 0, nsc->sasl_secret->len);
194 }
195 free(nsc->sasl_secret);
196 }
197 if (nsc->sasl_chosen_mech)
198 free(nsc->sasl_chosen_mech);
199 if (nsc->sasl_tmpbuf)
200 free(nsc->sasl_tmpbuf);
201 #endif /* CYRUS_SASL */
202 #ifdef TLS_SUPPORT
203 if (nsc->ssl_io)
204 /*
205 * I checked; BIO_free_all() will cause SSL_shutdown to be called
206 * on the SSL object in the chain.
207 */
208 BIO_free_all(nsc->ssl_io);
209 #endif /* TLS_SUPPORT */
210
211 if (closeflag && nsc->ns_fd != -1)
212 close(nsc->ns_fd);
213
214 free(nsc);
215 }
216
217 /*
218 * Set the file descriptor for our context
219 */
220
221 void
222 netsec_set_fd(netsec_context *nsc, int fd)
223 {
224 nsc->ns_fd = fd;
225 }
226
227 /*
228 * Set the userid used for authentication for this context
229 */
230
231 void
232 netsec_set_userid(netsec_context *nsc, const char *userid)
233 {
234 nsc->ns_userid = getcpy(userid);
235 }
236
237 /*
238 * Get the snoop flag for this connection
239 */
240
241 int
242 netsec_get_snoop(netsec_context *nsc)
243 {
244 return nsc->ns_snoop;
245 }
246
247 /*
248 * Set the snoop flag for this connection
249 */
250
251 void
252 netsec_set_snoop(netsec_context *nsc, int snoop)
253 {
254 nsc->ns_snoop = snoop;
255 }
256
257 /*
258 * Set the read timeout for this connection
259 */
260
261 void
262 netsec_set_timeout(netsec_context *nsc, int timeout)
263 {
264 nsc->ns_timeout = timeout;
265 }
266
267 /*
268 * Read data from the network. Basically, return anything in our buffer,
269 * otherwise fill from the network.
270 */
271
272 ssize_t
273 netsec_read(netsec_context *nsc, void *buffer, size_t size, char **errstr)
274 {
275 int retlen;
276
277 /*
278 * If our buffer is empty, then we should fill it now
279 */
280
281 if (nsc->ns_inbuflen == 0) {
282 if (netsec_fillread(nsc, errstr) != OK)
283 return NOTOK;
284 }
285
286 /*
287 * netsec_fillread only returns if the buffer is full, so we can
288 * assume here that this has something in it.
289 */
290
291 retlen = size > nsc->ns_inbuflen ? nsc->ns_inbuflen : size;
292
293 memcpy(buffer, nsc->ns_inptr, retlen);
294
295 if (retlen == (int) nsc->ns_inbuflen) {
296 /*
297 * We've emptied our buffer, so reset everything.
298 */
299 nsc->ns_inptr = nsc->ns_inbuffer;
300 nsc->ns_inbuflen = 0;
301 } else {
302 nsc->ns_inptr += size;
303 nsc->ns_inbuflen -= size;
304 }
305
306 return OK;
307 }
308
309 /*
310 * Get a "line" (CR/LF) terminated from the network.
311 *
312 * Okay, we play some games here, so pay attention:
313 *
314 * - Unlike every other function, we return a pointer to the
315 * existing buffer. This pointer is valid until you call another
316 * read functiona again.
317 * - We NUL-terminated the buffer right at the end, before the terminator.
318 * - Technically we look for a LF; if we find a CR right before it, then
319 * we back up one.
320 * - If your data may contain embedded NULs, this won't work.
321 */
322
323 char *
324 netsec_readline(netsec_context *nsc, size_t *len, char **errstr)
325 {
326 unsigned char *ptr = nsc->ns_inptr;
327 size_t count = 0, offset;
328
329 retry:
330 /*
331 * Search through our existing buffer for a LF
332 */
333
334 while (count < nsc->ns_inbuflen) {
335 count++;
336 if (*ptr++ == '\n') {
337 char *sptr = (char *) nsc->ns_inptr;
338 if (count > 1 && *(ptr - 2) == '\r')
339 ptr--;
340 *--ptr = '\0';
341 if (len)
342 *len = ptr - nsc->ns_inptr;
343 nsc->ns_inptr += count;
344 nsc->ns_inbuflen -= count;
345 return sptr;
346 }
347 }
348
349 /*
350 * Hm, we didn't find a \n. If we've already searched half of the input
351 * buffer, return an error.
352 */
353
354 if (count >= nsc->ns_inbufsize / 2) {
355 netsec_err(errstr, "Unable to find a line terminator after %d bytes",
356 count);
357 return NULL;
358 }
359
360 /*
361 * Okay, get some more network data. This may move inptr, so regenerate
362 * our ptr value;
363 */
364
365 offset = ptr - nsc->ns_inptr;
366
367 if (netsec_fillread(nsc, errstr) != OK)
368 return NULL;
369
370 ptr = nsc->ns_inptr + offset;
371
372 goto retry;
373
374 return NULL; /* Should never reach this */
375 }
376
377 /*
378 * Fill our read buffer with some data from the network.
379 */
380
381 static int
382 netsec_fillread(netsec_context *nsc, char **errstr)
383 {
384 unsigned char *end;
385 char *readbuf;
386 size_t readbufsize, remaining, startoffset;
387 int rc;
388
389 /*
390 * If inbuflen is zero, that means the buffer has been emptied
391 * completely. In that case move inptr back to the start.
392 */
393
394 if (nsc->ns_inbuflen == 0) {
395 nsc->ns_inptr = nsc->ns_inbuffer;
396 }
397
398 retry:
399 /*
400 * If we are using TLS and there's anything pending, then skip the
401 * select call
402 */
403 #ifdef TLS_SUPPORT
404 if (!nsc->tls_active || BIO_pending(nsc->ssl_io) == 0)
405 #endif /* TLS_SUPPORT */
406 {
407 struct timeval tv;
408 fd_set rfds;
409
410 FD_ZERO(&rfds);
411 FD_SET(nsc->ns_fd, &rfds);
412
413 tv.tv_sec = nsc->ns_timeout;
414 tv.tv_usec = 0;
415
416 rc = select(nsc->ns_fd + 1, &rfds, NULL, NULL, &tv);
417
418 if (rc == -1) {
419 netsec_err(errstr, "select() while reading failed: %s",
420 strerror(errno));
421 return NOTOK;
422 }
423
424 if (rc == 0) {
425 netsec_err(errstr, "read() timed out after %d seconds",
426 nsc->ns_timeout);
427 return NOTOK;
428 }
429
430 /*
431 * At this point, we know that rc is 1, so there's not even any
432 * point to check to see if our descriptor is set in rfds.
433 */
434 }
435
436 startoffset = nsc->ns_inptr - nsc->ns_inbuffer;
437 remaining = nsc->ns_inbufsize - (startoffset + nsc->ns_inbuflen);
438 end = nsc->ns_inptr + nsc->ns_inbuflen;
439
440 /*
441 * If we are using TLS, then just read via the BIO. But we still
442 * use our local buffer.
443 */
444 #ifdef TLS_SUPPORT
445 if (nsc->tls_active) {
446 rc = BIO_read(nsc->ssl_io, end, remaining);
447 if (rc == 0) {
448 /*
449 * Either EOF, or possibly an error. Either way, it was probably
450 * unexpected, so treat as error.
451 */
452 netsec_err(errstr, "TLS peer aborted connection");
453 return NOTOK;
454 } else if (rc < 0) {
455 /* Definitely an error */
456 netsec_err(errstr, "Read on TLS connection failed: %s",
457 ERR_error_string(ERR_get_error(), NULL));
458 return NOTOK;
459 }
460
461 nsc->ns_inbuflen += rc;
462
463 return OK;
464 }
465 #endif /* TLS_SUPPORT */
466
467 /*
468 * Okay, time to read some data. Either we're just doing it straight
469 * or we're passing it through sasl_decode() first.
470 */
471
472 #ifdef CYRUS_SASL
473 if (nsc->sasl_seclayer) {
474 readbuf = nsc->sasl_tmpbuf;
475 readbufsize = nsc->sasl_maxbufsize;
476 } else
477 #endif /* CYRUS_SASL */
478 {
479 readbuf = (char *) end;
480 readbufsize = remaining;
481 }
482
483 /*
484 * At this point, we should have active data on the connection (see
485 * select() above) so this read SHOULDN'T block. Hopefully.
486 */
487
488 rc = read(nsc->ns_fd, readbuf, readbufsize);
489
490 if (rc == 0) {
491 netsec_err(errstr, "Received EOF on network read");
492 return NOTOK;
493 }
494
495 if (rc < 0) {
496 netsec_err(errstr, "Network read failed: %s", strerror(errno));
497 return NOTOK;
498 }
499
500 /*
501 * Okay, so we've had a successful read. If we are doing SASL security
502 * layers, pass this through sasl_decode(). sasl_decode() can return
503 * 0 bytes decoded; if that happens, jump back to the beginning. Otherwise
504 * we can just update our length pointer.
505 */
506
507 #ifdef CYRUS_SASL
508 if (nsc->sasl_seclayer) {
509 const char *tmpout;
510 unsigned int tmpoutlen;
511
512 rc = sasl_decode(nsc->sasl_conn, nsc->sasl_tmpbuf, rc,
513 &tmpout, &tmpoutlen);
514
515 if (rc != SASL_OK) {
516 netsec_err(errstr, "Unable to decode SASL network data: %s",
517 sasl_errdetail(nsc->sasl_conn));
518 return NOTOK;
519 }
520
521 if (tmpoutlen == 0)
522 goto retry;
523
524 /*
525 * Just in case ...
526 */
527
528 if (tmpoutlen > remaining) {
529 netsec_err(errstr, "Internal error: SASL decode buffer overflow!");
530 return NOTOK;
531 }
532
533 memcpy(end, tmpout, tmpoutlen);
534
535 nsc->ns_inbuflen += tmpoutlen;
536 } else
537 #endif /* CYRUS_SASL */
538 nsc->ns_inbuflen += rc;
539
540 /*
541 * If we're past the halfway point in our read buffers, shuffle everything
542 * back to the beginning.
543 */
544
545 if (startoffset > nsc->ns_inbufsize / 2) {
546 memmove(nsc->ns_inbuffer, nsc->ns_inptr, nsc->ns_inbuflen);
547 nsc->ns_inptr = nsc->ns_inbuffer;
548 }
549
550 return OK;
551 }
552
553 /*
554 * Write data to our network connection. Really, fill up the buffer as
555 * much as we can, and flush it out if necessary. netsec_flush() does
556 * the real work.
557 */
558
559 int
560 netsec_write(netsec_context *nsc, const void *buffer, size_t size,
561 char **errstr)
562 {
563 const unsigned char *bufptr = buffer;
564 int rc, remaining;
565
566 /* Just in case */
567
568 if (size == 0)
569 return OK;
570
571 /*
572 * If TLS is active, then bypass all of our buffering logic; just
573 * write it directly to our BIO. We have a buffering BIO first in
574 * our stack, so buffering will take place there.
575 */
576 #ifdef TLS_SUPPORT
577 if (nsc->tls_active) {
578 rc = BIO_write(nsc->ssl_io, buffer, size);
579
580 if (rc <= 0) {
581 netsec_err(errstr, "Error writing to TLS connection: %s",
582 ERR_error_string(ERR_get_error(), NULL));
583 return NOTOK;
584 }
585
586 return OK;
587 }
588 #endif /* TLS_SUPPORT */
589
590 /*
591 * Run a loop copying in data to our local buffer; when we're done with
592 * any buffer overflows then just copy any remaining data in.
593 */
594
595 while ((int) size >= (remaining = nsc->ns_outbufsize - nsc->ns_outbuflen)) {
596 memcpy(nsc->ns_outptr, bufptr, remaining);
597
598 /*
599 * In theory I should increment outptr, but netsec_flush just resets
600 * it anyway.
601 */
602 nsc->ns_outbuflen = nsc->ns_outbufsize;
603
604 rc = netsec_flush(nsc, errstr);
605
606 if (rc != OK)
607 return NOTOK;
608
609 bufptr += remaining;
610 size -= remaining;
611 }
612
613 /*
614 * Copy any leftover data into the buffer.
615 */
616
617 if (size > 0) {
618 memcpy(nsc->ns_outptr, bufptr, size);
619 nsc->ns_outptr += size;
620 nsc->ns_outbuflen += size;
621 }
622
623 return OK;
624 }
625
626 /*
627 * Our network printf() routine, which really just calls netsec_vprintf().
628 */
629
630 int
631 netsec_printf(netsec_context *nsc, char **errstr, const char *format, ...)
632 {
633 va_list ap;
634 int rc;
635
636 va_start(ap, format);
637 rc = netsec_vprintf(nsc, errstr, format, ap);
638 va_end(ap);
639
640 return rc;
641 }
642
643 /*
644 * Write bytes to the network using printf()-style formatting.
645 *
646 * Again, for the most part copy stuff into our buffer to be flushed
647 * out later.
648 */
649
650 int
651 netsec_vprintf(netsec_context *nsc, char **errstr, const char *format,
652 va_list ap)
653 {
654 int rc;
655
656 /*
657 * Again, if we're using TLS, then bypass our local buffering
658 */
659 #ifdef TLS_SUPPORT
660 if (nsc->tls_active) {
661 rc = BIO_vprintf(nsc->ssl_io, format, ap);
662
663 if (rc <= 0) {
664 netsec_err(errstr, "Error writing to TLS connection: %s",
665 ERR_error_string(ERR_get_error(), NULL));
666 return NOTOK;
667 }
668
669 return OK;
670 }
671 #endif /* TLS_SUPPORT */
672
673 /*
674 * Cheat a little. If we can fit the data into our outgoing buffer,
675 * great! If not, generate a flush and retry once.
676 */
677
678 retry:
679 rc = vsnprintf((char *) nsc->ns_outptr,
680 nsc->ns_outbufsize - nsc->ns_outbuflen, format, ap);
681
682 if (rc >= (int) (nsc->ns_outbufsize - nsc->ns_outbuflen)) {
683 /*
684 * This means we have an overflow. Note that we don't actually
685 * make use of the terminating NUL, but according to the spec
686 * vsnprintf() won't write to the last byte in the string; that's
687 * why we have to use >= in the comparison above.
688 */
689 if (nsc->ns_outbuffer == nsc->ns_outptr) {
690 /*
691 * Whoops, if the buffer pointer was the same as the start of the
692 * buffer, that means we overflowed the internal buffer.
693 * At that point, just give up.
694 */
695 netsec_err(errstr, "Internal error: wanted to printf() a total of "
696 "%d bytes, but our buffer size was only %d bytes",
697 rc, nsc->ns_outbufsize);
698 return NOTOK;
699 } else {
700 /*
701 * Generate a flush (which may be inefficient, but hopefully
702 * it isn't) and then try again.
703 */
704 if (netsec_flush(nsc, errstr) != OK)
705 return NOTOK;
706 /*
707 * After this, outbuffer should == outptr, so we shouldn't
708 * hit this next time around.
709 */
710 goto retry;
711 }
712 }
713
714 nsc->ns_outptr += rc;
715 nsc->ns_outbuflen += rc;
716
717 return OK;
718 }
719
720 /*
721 * Flush out any buffered data in our output buffers. This routine is
722 * actually where the real network writes take place.
723 */
724
725 int
726 netsec_flush(netsec_context *nsc, char **errstr)
727 {
728 const char *netoutbuf = (const char *) nsc->ns_outbuffer;
729 unsigned int netoutlen = nsc->ns_outbuflen;
730 int rc;
731
732 /*
733 * For TLS connections, just call BIO_flush(); we'll let TLS handle
734 * all of our output buffering.
735 */
736 #ifdef TLS_SUPPORT
737 if (nsc->tls_active) {
738 rc = BIO_flush(nsc->ssl_io);
739
740 if (rc <= 0) {
741 netsec_err(errstr, "Error flushing TLS connection: %s",
742 ERR_error_string(ERR_get_error(), NULL));
743 return NOTOK;
744 }
745
746 return OK;
747 }
748 #endif /* TLS_SUPPORT */
749
750 /*
751 * Small optimization
752 */
753
754 if (netoutlen == 0)
755 return OK;
756
757 /*
758 * If SASL security layers are in effect, run the data through
759 * sasl_encode() first and then write it.
760 */
761 #ifdef CYRUS_SASL
762 if (nsc->sasl_seclayer) {
763 rc = sasl_encode(nsc->sasl_conn, (const char *) nsc->ns_outbuffer,
764 nsc->ns_outbuflen, &netoutbuf, &netoutlen);
765
766 if (rc != SASL_OK) {
767 netsec_err(errstr, "SASL data encoding failed: %s",
768 sasl_errdetail(nsc->sasl_conn));
769 return NOTOK;
770 }
771
772 }
773 #endif /* CYRUS_SASL */
774 rc = write(nsc->ns_fd, netoutbuf, netoutlen);
775
776 if (rc < 0) {
777 netsec_err(errstr, "write() failed: %s", strerror(errno));
778 return NOTOK;
779 }
780
781 nsc->ns_outptr = nsc->ns_outbuffer;
782 nsc->ns_outbuflen = 0;
783
784 return OK;
785 }
786
787 /*
788 * Set various SASL protocol parameters
789 */
790
791 int
792 netsec_set_sasl_params(netsec_context *nsc, const char *hostname,
793 const char *service, const char *mechanism,
794 netsec_sasl_callback callback, char **errstr)
795 {
796 #ifdef CYRUS_SASL
797 sasl_callback_t *sasl_cbs;
798 int retval;
799
800 if (! sasl_initialized) {
801 retval = sasl_client_init(NULL);
802 if (retval != SASL_OK) {
803 netsec_err(errstr, "SASL client initialization failed: %s",
804 sasl_errstring(retval, NULL, NULL));
805 return NOTOK;
806 }
807 sasl_initialized++;
808 }
809
810 /*
811 * Allocate an array of SASL callbacks for this connection.
812 * Right now we just allocate an array of four callbacks.
813 */
814
815 sasl_cbs = mh_xmalloc(sizeof(*sasl_cbs) * 4);
816
817 sasl_cbs[0].id = SASL_CB_USER;
818 sasl_cbs[0].proc = (sasl_callback_ft) netsec_get_user;
819 sasl_cbs[0].context = nsc;
820
821 sasl_cbs[1].id = SASL_CB_AUTHNAME;
822 sasl_cbs[1].proc = (sasl_callback_ft) netsec_get_user;
823 sasl_cbs[1].context = nsc;
824
825 sasl_cbs[2].id = SASL_CB_PASS;
826 sasl_cbs[2].proc = (sasl_callback_ft) netsec_get_password;
827 sasl_cbs[2].context = nsc;
828
829 sasl_cbs[3].id = SASL_CB_LIST_END;
830 sasl_cbs[3].proc = NULL;
831 sasl_cbs[3].context = NULL;
832
833 nsc->sasl_cbs = sasl_cbs;
834
835 retval = sasl_client_new(service, hostname, NULL, NULL, nsc->sasl_cbs, 0,
836 &nsc->sasl_conn);
837
838 if (retval) {
839 netsec_err(errstr, "SASL new client allocation failed: %s",
840 sasl_errstring(retval, NULL, NULL));
841 return NOTOK;
842 }
843
844 nsc->sasl_mech = mechanism ? getcpy(mechanism) : NULL;
845 nsc->sasl_proto_cb = callback;
846 nsc->sasl_hostname = getcpy(hostname);
847
848 return OK;
849 #else /* CYRUS_SASL */
850 netsec_err(errstr, "SASL is not supported");
851
852 return NOTOK;
853 #endif /* CYRUS_SASL */
854 }
855
856 #ifdef CYRUS_SASL
857 /*
858 * Our userid callback; return the specified username to the SASL
859 * library when asked.
860 */
861
862 int netsec_get_user(void *context, int id, const char **result,
863 unsigned int *len)
864 {
865 netsec_context *nsc = (netsec_context *) context;
866
867 if (! result || (id != SASL_CB_USER && id != SASL_CB_AUTHNAME))
868 return SASL_BADPARAM;
869
870 if (nsc->ns_userid == NULL) {
871 /*
872 * Pass the 1 third argument to nmh_get_credentials() so that
873 * a defauly user if the -user switch wasn't supplied, and so
874 * that a default password will be supplied. That's used when
875 * those values really don't matter, and only with legacy/.netrc,
876 * i.e., with a credentials profile entry.
877 */
878
879 if (nsc->sasl_creds == NULL) {
880 nsc->sasl_creds = mh_xmalloc(sizeof(*nsc->sasl_creds));
881 nsc->sasl_creds->user = NULL;
882 nsc->sasl_creds->password = NULL;
883 }
884
885 if (nmh_get_credentials(nsc->sasl_hostname, nsc->ns_userid, 1,
886 nsc->sasl_creds) != OK)
887 return SASL_BADPARAM;
888
889 if (nsc->ns_userid != nsc->sasl_creds->user) {
890 if (nsc->ns_userid)
891 free(nsc->ns_userid);
892 nsc->ns_userid = getcpy(nsc->sasl_creds->user);
893 }
894 }
895
896 *result = nsc->ns_userid;
897 if (len)
898 *len = strlen(nsc->ns_userid);
899
900 return SASL_OK;
901 }
902
903 /*
904 * Retrieve a password and return it to SASL
905 */
906
907 static int
908 netsec_get_password(sasl_conn_t *conn, void *context, int id,
909 sasl_secret_t **psecret)
910 {
911 netsec_context *nsc = (netsec_context *) context;
912 int len;
913
914 NMH_UNUSED(conn);
915
916 if (! psecret || id != SASL_CB_PASS)
917 return SASL_BADPARAM;
918
919 if (nsc->sasl_creds == NULL) {
920 nsc->sasl_creds = mh_xmalloc(sizeof(*nsc->sasl_creds));
921 nsc->sasl_creds->user = NULL;
922 nsc->sasl_creds->password = NULL;
923 }
924
925 if (nsc->sasl_creds->password == NULL) {
926 /*
927 * Pass the 0 third argument to nmh_get_credentials() so
928 * that the default password isn't used. With legacy/.netrc
929 * credentials support, we'll only get here if the -user
930 * switch to send(1)/post(8) wasn't used.
931 */
932
933 if (nmh_get_credentials(nsc->sasl_hostname, nsc->ns_userid, 0,
934 nsc->sasl_creds) != OK) {
935 return SASL_BADPARAM;
936 }
937 }
938
939 len = strlen(nsc->sasl_creds->password);
940
941 /*
942 * sasl_secret_t includes 1 bytes for "data" already, so that leaves
943 * us room for a terminating NUL
944 */
945
946 *psecret = (sasl_secret_t *) malloc(sizeof(sasl_secret_t) + len);
947
948 if (! *psecret)
949 return SASL_NOMEM;
950
951 (*psecret)->len = len;
952 strcpy((char *) (*psecret)->data, nsc->sasl_creds->password);
953
954 nsc->sasl_secret = *psecret;
955
956 return SASL_OK;
957 }
958 #endif /* CYRUS_SASL */
959
960 /*
961 * Negotiate SASL on this connection
962 */
963
964 int
965 netsec_negotiate_sasl(netsec_context *nsc, const char *mechlist, char **errstr)
966 {
967 #ifdef CYRUS_SASL
968 sasl_security_properties_t secprops;
969 const char *chosen_mech;
970 const unsigned char *saslbuf;
971 unsigned char *outbuf;
972 unsigned int saslbuflen, outbuflen;
973 sasl_ssf_t *ssf;
974 int *outbufmax;
975 #endif
976 #ifdef OAUTH_SUPPORT
977 unsigned char *xoauth_client_res;
978 size_t xoauth_client_res_len;
979 #endif /* OAUTH_SUPPORT */
980 int rc;
981
982 /*
983 * If we've been passed a requested mechanism, check our mechanism
984 * list from the protocol. If it's not supported, return an error.
985 */
986
987 if (nsc->sasl_mech) {
988 char **str, *mlist = getcpy(mechlist);
989 int i;
990
991 str = brkstring(mlist, " ", NULL);
992
993 for (i = 0; str[i] != NULL; i++) {
994 if (strcasecmp(nsc->sasl_mech, str[i]) == 0) {
995 break;
996 }
997 }
998
999 i = (str[i] == NULL);
1000
1001 free(str);
1002 free(mlist);
1003
1004 if (i) {
1005 netsec_err(errstr, "Chosen mechanism %s not supported by server",
1006 nsc->sasl_mech);
1007 return NOTOK;
1008 }
1009 }
1010
1011 #ifdef OAUTH_SUPPORT
1012 if (nsc->sasl_mech && strcasecmp(nsc->sasl_mech, "XOAUTH2") == 0) {
1013 /*
1014 * This should be relatively straightforward, but requires some
1015 * help from the plugin. Basically, if XOAUTH2 is a success,
1016 * the callback has to return success, but no output data. If
1017 * there is output data, it will be assumed that it is the JSON
1018 * error message.
1019 */
1020
1021 if (! nsc->oauth_service) {
1022 netsec_err(errstr, "Internal error: OAuth2 service name not given");
1023 return NOTOK;
1024 }
1025
1026 nsc->sasl_chosen_mech = getcpy(nsc->sasl_mech);
1027
1028 if (mh_oauth_do_xoauth(nsc->ns_userid, nsc->oauth_service,
1029 &xoauth_client_res, &xoauth_client_res_len,
1030 nsc->ns_snoop ? stderr : NULL) != OK) {
1031 netsec_err(errstr, "Internal error: Unable to get OAuth2 "
1032 "bearer token");
1033 return NOTOK;
1034 }
1035
1036 rc = nsc->sasl_proto_cb(NETSEC_SASL_START, xoauth_client_res,
1037 xoauth_client_res_len, NULL, 0, errstr);
1038 free(xoauth_client_res);
1039
1040 if (rc != OK)
1041 return NOTOK;
1042
1043 /*
1044 * Okay, we need to do a NETSEC_SASL_FINISH now. If we return
1045 * success, we indicate that with no output data. But if we
1046 * fail, then send a blank message and get the resulting
1047 * error.
1048 */
1049
1050 rc = nsc->sasl_proto_cb(NETSEC_SASL_FINISH, NULL, 0, NULL, 0, errstr);
1051
1052 if (rc != OK) {
1053 /*
1054 * We're going to assume the error here is a JSON response;
1055 * we ignore it and send a blank message in response. We should
1056 * then get either an +OK or -ERR
1057 */
1058 free(errstr);
1059 nsc->sasl_proto_cb(NETSEC_SASL_WRITE, NULL, 0, NULL, 0, NULL);
1060 rc = nsc->sasl_proto_cb(NETSEC_SASL_FINISH, NULL, 0, NULL, 0,
1061 errstr);
1062 if (rc == 0) {
1063 netsec_err(errstr, "Unexpected success after OAuth failure!");
1064 }
1065 return NOTOK;
1066 }
1067 }
1068 #endif /* OAUTH_SUPPORT */
1069
1070 #ifdef CYRUS_SASL
1071 /*
1072 * In netsec_set_sasl_params, we've already done all of our setup with
1073 * sasl_client_init() and sasl_client_new(). So time to set security
1074 * properties, call sasl_client_start(), and generate the protocol
1075 * messages.
1076 */
1077
1078 memset(&secprops, 0, sizeof(secprops));
1079 secprops.maxbufsize = SASL_MAXRECVBUF;
1080
1081 /*
1082 * If we're using TLS, do not negotiate a security layer
1083 */
1084
1085 secprops.max_ssf =
1086 #ifdef TLS_SUPPORT
1087 nsc->tls_active ? 0 :
1088 #endif /* TLS_SUPPORT */
1089 UINT_MAX;
1090
1091 rc = sasl_setprop(nsc->sasl_conn, SASL_SEC_PROPS, &secprops);
1092
1093 if (rc != SASL_OK) {
1094 netsec_err(errstr, "SASL security property initialization failed: %s",
1095 sasl_errstring(rc, NULL, NULL));
1096 return NOTOK;
1097 }
1098
1099 /*
1100 * Start the actual protocol negotiation, and go through the
1101 * sasl_client_step() loop (after sasl_client_start, of course).
1102 */
1103
1104 rc = sasl_client_start(nsc->sasl_conn,
1105 nsc->sasl_mech ? nsc->sasl_mech : mechlist, NULL,
1106 (const char **) &saslbuf, &saslbuflen,
1107 &chosen_mech);
1108
1109 if (rc != SASL_OK && rc != SASL_CONTINUE) {
1110 netsec_err(errstr, "SASL client start failed: %s",
1111 sasl_errdetail(nsc->sasl_conn));
1112 return NOTOK;
1113 }
1114
1115 nsc->sasl_chosen_mech = getcpy(chosen_mech);
1116
1117 if (nsc->sasl_proto_cb(NETSEC_SASL_START, saslbuf, saslbuflen, NULL, 0,
1118 errstr) != OK)
1119 return NOTOK;
1120
1121 /*
1122 * We've written out our first message; enter in the step loop
1123 */
1124
1125 while (rc == SASL_CONTINUE) {
1126 /*
1127 * Call our SASL callback, which will handle the details of
1128 * reading data from the network.
1129 */
1130
1131 if (nsc->sasl_proto_cb(NETSEC_SASL_READ, NULL, 0, &outbuf, &outbuflen,
1132 errstr) != OK) {
1133 nsc->sasl_proto_cb(NETSEC_SASL_CANCEL, NULL, 0, NULL, 0, NULL);
1134 return NOTOK;
1135 }
1136
1137 rc = sasl_client_step(nsc->sasl_conn, (char *) outbuf, outbuflen, NULL,
1138 (const char **) &saslbuf, &saslbuflen);
1139
1140 if (outbuf)
1141 free(outbuf);
1142
1143 if (rc != SASL_OK && rc != SASL_CONTINUE) {
1144 netsec_err(errstr, "SASL client negotiation failed: %s",
1145 sasl_errdetail(nsc->sasl_conn));
1146 nsc->sasl_proto_cb(NETSEC_SASL_CANCEL, NULL, 0, NULL, 0, NULL);
1147 return NOTOK;
1148 }
1149
1150 if (nsc->sasl_proto_cb(NETSEC_SASL_WRITE, saslbuf, saslbuflen,
1151 NULL, 0, errstr) != OK) {
1152 nsc->sasl_proto_cb(NETSEC_SASL_CANCEL, NULL, 0, NULL, 0, NULL);
1153 return NOTOK;
1154 }
1155 }
1156
1157 /*
1158 * SASL exchanges should be complete, process the final response message
1159 * from the server.
1160 */
1161
1162 if (nsc->sasl_proto_cb(NETSEC_SASL_FINISH, NULL, 0, NULL, 0,
1163 errstr) != OK) {
1164 /*
1165 * At this point we can't really send an abort since the SASL dialog
1166 * has completed, so just bubble back up the error message.
1167 */
1168
1169 return NOTOK;
1170 }
1171
1172 /*
1173 * At this point, SASL should be complete. Get a few properties
1174 * from the authentication exchange.
1175 */
1176
1177 rc = sasl_getprop(nsc->sasl_conn, SASL_SSF, (const void **) &ssf);
1178
1179 if (rc != SASL_OK) {
1180 netsec_err(errstr, "Cannot retrieve SASL negotiated security "
1181 "strength factor: %s", sasl_errstring(rc, NULL, NULL));
1182 return NOTOK;
1183 }
1184
1185 nsc->sasl_ssf = *ssf;
1186
1187 if (nsc->sasl_ssf > 0) {
1188 rc = sasl_getprop(nsc->sasl_conn, SASL_MAXOUTBUF,
1189 (const void **) &outbufmax);
1190
1191 if (rc != SASL_OK) {
1192 netsec_err(errstr, "Cannot retrieve SASL negotiated output "
1193 "buffer size: %s", sasl_errstring(rc, NULL, NULL));
1194 return NOTOK;
1195 }
1196
1197 /*
1198 * If our output buffer isn't the same size as the input buffer,
1199 * reallocate it and set the new size (since we won't encode any
1200 * data larger than that).
1201 */
1202
1203 nsc->sasl_maxbufsize = *outbufmax;
1204
1205 if (nsc->ns_outbufsize != nsc->sasl_maxbufsize) {
1206 nsc->ns_outbufsize = nsc->sasl_maxbufsize;
1207 nsc->ns_outbuffer = mh_xrealloc(nsc->ns_outbuffer,
1208 nsc->ns_outbufsize);
1209 /*
1210 * There shouldn't be any data in the buffer, but for
1211 * consistency's sake discard it.
1212 */
1213 nsc->ns_outptr = nsc->ns_outbuffer;
1214 nsc->ns_outbuflen = 0;
1215 }
1216
1217 /*
1218 * Allocate a buffer to do temporary reads into, before we
1219 * call sasl_decode()
1220 */
1221
1222 nsc->sasl_tmpbuf = mh_xmalloc(nsc->sasl_maxbufsize);
1223
1224 /*
1225 * Okay, this is a bit weird. Make sure that the input buffer
1226 * is at least TWICE the size of the max buffer size. That's
1227 * because if we're consuming data but want to extend the current
1228 * buffer, we want to be sure there's room for another full buffer's
1229 * worth of data.
1230 */
1231
1232 if (nsc->ns_inbufsize < nsc->sasl_maxbufsize * 2) {
1233 size_t offset = nsc->ns_inptr - nsc->ns_inbuffer;
1234 nsc->ns_inbufsize = nsc->sasl_maxbufsize * 2;
1235 nsc->ns_inbuffer = mh_xrealloc(nsc->ns_inbuffer, nsc->ns_inbufsize);
1236 nsc->ns_inptr = nsc->ns_inbuffer + offset;
1237 }
1238
1239 nsc->sasl_seclayer = 1;
1240 }
1241
1242 return OK;
1243 #else
1244 netsec_err(errstr, "SASL not supported");
1245
1246 return NOTOK;
1247 #endif /* CYRUS_SASL */
1248 }
1249
1250 /*
1251 * Retrieve our chosen SASL mechanism
1252 */
1253
1254 char *
1255 netsec_get_sasl_mechanism(netsec_context *nsc)
1256 {
1257 #ifdef CYRUS_SASL
1258 return nsc->sasl_chosen_mech;
1259 #else /* CYRUS_SASL */
1260 return NULL;
1261 #endif /* CYRUS_SASL */
1262 }
1263
1264 /*
1265 * Set an OAuth2 service name, if we support it.
1266 */
1267
1268 int
1269 netsec_set_oauth_service(netsec_context *nsc, const char *service)
1270 {
1271 #ifdef OAUTH_SUPPORT
1272 nsc->oauth_service = getcpy(service);
1273 return OK;
1274 #else /* OAUTH_SUPPORT */
1275 return NOTOK;
1276 #endif /* OAUTH_SUPPORT */
1277 }
1278
1279 /*
1280 * Initialize (and enable) TLS for this connection
1281 */
1282
1283 int
1284 netsec_set_tls(netsec_context *nsc, int tls, char **errstr)
1285 {
1286 if (tls) {
1287 #ifdef TLS_SUPPORT
1288 SSL *ssl;
1289 BIO *sbio, *ssl_bio;;
1290
1291 if (! tls_initialized) {
1292 SSL_library_init();
1293 SSL_load_error_strings();
1294
1295 /*
1296 * Create the SSL context; this has the properties for all
1297 * SSL connections (we are only doing one), though. Make sure
1298 * we only support secure (known as of now) TLS protocols.
1299 */
1300
1301 sslctx = SSL_CTX_new(SSLv23_client_method());
1302
1303 if (! sslctx) {
1304 netsec_err(errstr, "Unable to initialize OpenSSL context: %s",
1305 ERR_error_string(ERR_get_error(), NULL));
1306 return NOTOK;
1307 }
1308
1309 SSL_CTX_set_options(sslctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
1310 SSL_OP_NO_TLSv1);
1311
1312 tls_initialized++;
1313 }
1314
1315 if (nsc->ns_fd == -1) {
1316 netsec_err(errstr, "Invalid file descriptor in netsec context");
1317 return NOTOK;
1318 }
1319
1320 /*
1321 * Create the SSL structure which holds the data for a single
1322 * TLS connection.
1323 */
1324
1325 ssl = SSL_new(sslctx);
1326
1327 if (! ssl) {
1328 netsec_err(errstr, "Unable to create SSL connection: %s",
1329 ERR_error_string(ERR_get_error(), NULL));
1330 return NOTOK;
1331 }
1332
1333 /*
1334 * Never bother us, since we are using blocking sockets.
1335 */
1336
1337 SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
1338
1339 /*
1340 * This is a bit weird, so pay attention.
1341 *
1342 * We create a socket BIO, and bind it to our SSL connection.
1343 * That means reads and writes to the SSL connection will use our
1344 * supplied socket.
1345 *
1346 * Then we create an SSL BIO, and assign our current SSL connection
1347 * to it. We then create a buffer BIO and push it in front of our
1348 * SSL BIO. So the chain looks like:
1349 *
1350 * buffer BIO -> SSL BIO -> socket BIO.
1351 *
1352 * So writes and reads are buffered (we mostly care about writes).
1353 */
1354
1355 sbio = BIO_new_socket(nsc->ns_fd, BIO_NOCLOSE);
1356
1357 if (! sbio) {
1358 netsec_err(errstr, "Unable to create a socket BIO: %s",
1359 ERR_error_string(ERR_get_error(), NULL));
1360 SSL_free(ssl);
1361 return NOTOK;
1362 }
1363
1364 SSL_set_bio(ssl, sbio, sbio);
1365 SSL_set_connect_state(ssl);
1366
1367 nsc->ssl_io = BIO_new(BIO_f_buffer());
1368
1369 if (! nsc->ssl_io) {
1370 netsec_err(errstr, "Unable to create a buffer BIO: %s",
1371 ERR_error_string(ERR_get_error(), NULL));
1372 SSL_free(ssl);
1373 return NOTOK;
1374 }
1375
1376 ssl_bio = BIO_new(BIO_f_ssl());
1377
1378 if (! ssl_bio) {
1379 netsec_err(errstr, "Unable to create a SSL BIO: %s",
1380 ERR_error_string(ERR_get_error(), NULL));
1381 SSL_free(ssl);
1382 return NOTOK;
1383 }
1384
1385 BIO_set_ssl(ssl_bio, ssl, BIO_CLOSE);
1386 BIO_push(nsc->ssl_io, ssl_bio);
1387
1388 return OK;
1389 } else {
1390 BIO_free_all(nsc->ssl_io);
1391 nsc->ssl_io = NULL;
1392
1393 return OK;
1394 }
1395 #else /* TLS_SUPPORT */
1396 netsec_err(errstr, "TLS is not supported");
1397
1398 return NOTOK;
1399 }
1400 #endif /* TLS_SUPPORT */
1401 }
1402
1403 /*
1404 * Start TLS negotiation on this connection
1405 */
1406
1407 int
1408 netsec_negotiate_tls(netsec_context *nsc, char **errstr)
1409 {
1410 #ifdef TLS_SUPPORT
1411 if (! nsc->ssl_io) {
1412 netsec_err(errstr, "TLS has not been configured for this connection");
1413 return NOTOK;
1414 }
1415
1416 if (BIO_do_handshake(nsc->ssl_io) < 1) {
1417 netsec_err(errstr, "TLS negotiation failed: %s",
1418 ERR_error_string(ERR_get_error(), NULL));
1419 return NOTOK;
1420 }
1421
1422 if (nsc->ns_snoop) {
1423 SSL *ssl;
1424
1425 if (BIO_get_ssl(nsc->ssl_io, &ssl) < 1) {
1426 fprintf(stderr, "WARNING: cannot determine SSL ciphers\n");
1427 } else {
1428 const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
1429 fprintf(stderr, "TLS negotation successful: %s(%d) %s\n",
1430 SSL_CIPHER_get_name(cipher),
1431 SSL_CIPHER_get_bits(cipher, NULL),
1432 SSL_CIPHER_get_version(cipher));
1433 }
1434 }
1435
1436 nsc->tls_active = 1;
1437
1438 /*
1439 * At this point, TLS has been activated; we're not going to use
1440 * the output buffer, so free it now to save a little bit of memory.
1441 */
1442
1443 if (nsc->ns_outbuffer) {
1444 free(nsc->ns_outbuffer);
1445 nsc->ns_outbuffer = NULL;
1446 }
1447
1448 return OK;
1449 #else /* TLS_SUPPORT */
1450 netsec_err(errstr, "TLS not supported");
1451
1452 return NOTOK;
1453 #endif /* TLS_SUPPORT */
1454 }
1455
1456 /*
1457 * Generate an (allocated) error string
1458 */
1459
1460 void
1461 netsec_err(char **errstr, const char *fmt, ...)
1462 {
1463 va_list ap;
1464 size_t errbufsize;
1465 char *errbuf = NULL;
1466 int rc = 127;
1467
1468 if (! errstr)
1469 return;
1470
1471 do {
1472 errbufsize = rc + 1;
1473 errbuf = mh_xrealloc(errbuf, errbufsize);
1474 va_start(ap, fmt);
1475 rc = vsnprintf(errbuf, errbufsize, fmt, ap);
1476 va_end(ap);
1477 } while (rc >= (int) errbufsize);
1478
1479 *errstr = errbuf;
1480 }