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