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