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