3 * netsec.c -- Network security routines for handling protocols that
4 * require SASL and/or TLS.
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.
16 #include <sys/select.h>
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 */
29 static int netsec_get_user(void *context
, int id
, const char **result
,
31 static int netsec_get_password(sasl_conn_t
*conn
, void *context
, int id
,
32 sasl_secret_t
**psecret
);
34 static int sasl_initialized
= 0;
36 #define SASL_MAXRECVBUF 65536
37 #endif /* CYRUS_SASL */
40 #include <openssl/ssl.h>
41 #include <openssl/err.h>
43 static int tls_initialized
= 0;
44 static SSL_CTX
*sslctx
= NULL
; /* SSL Context */
46 #endif /* TLS_SUPPORT */
48 /* I'm going to hardcode this for now; maybe make it adjustable later? */
49 #define NETSEC_BUFSIZE 65536
52 * Our context structure, which holds all of the relevant information
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 */
74 char *oauth_service
; /* OAuth2 service name */
75 #endif /* OAUTH_SUPPORT */
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 */
90 BIO
*ssl_io
; /* BIO used for connection I/O */
91 int tls_active
; /* If true, TLS is running */
92 #endif /* TLS_SUPPORT */
96 * Function to read data from the actual network socket
99 static int netsec_fillread(netsec_context
*ns_context
, char **errstr
);
102 * How this code works, in general.
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.
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.
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).
118 * Allocate and initialize our security context
124 netsec_context
*nsc
= mh_xmalloc(sizeof(*nsc
));
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
;
143 nsc
->oauth_service
= NULL
;
144 #endif /* OAUTH_SUPPORT */
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
;
153 nsc
->sasl_seclayer
= 0;
154 nsc
->sasl_tmpbuf
= NULL
;
155 nsc
->sasl_maxbufsize
= 0;
156 #endif /* CYRUS_SASL */
160 #endif /* TLS_SUPPORT */
165 * Shutdown the connection completely and free all resources.
166 * The connection is only closed if the flag is given.
170 netsec_shutdown(netsec_context
*nsc
, int closeflag
)
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
);
179 free(nsc
->sasl_mech
);
181 if (nsc
->oauth_service
)
182 free(nsc
->oauth_service
);
183 #endif /* OAUTH_SERVICE */
186 sasl_dispose(&nsc
->sasl_conn
);
187 if (nsc
->sasl_hostname
)
188 free(nsc
->sasl_hostname
);
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
);
197 if (nsc
->sasl_secret
) {
198 if (nsc
->sasl_secret
->len
> 0) {
199 memset(nsc
->sasl_secret
->data
, 0, nsc
->sasl_secret
->len
);
201 free(nsc
->sasl_secret
);
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 */
211 * I checked; BIO_free_all() will cause SSL_shutdown to be called
212 * on the SSL object in the chain.
214 BIO_free_all(nsc
->ssl_io
);
215 #endif /* TLS_SUPPORT */
217 if (closeflag
&& nsc
->ns_fd
!= -1)
224 * Set the file descriptor for our context
228 netsec_set_fd(netsec_context
*nsc
, int fd
)
234 * Set the userid used for authentication for this context
238 netsec_set_userid(netsec_context
*nsc
, const char *userid
)
240 nsc
->ns_userid
= getcpy(userid
);
244 * Get the snoop flag for this connection
248 netsec_get_snoop(netsec_context
*nsc
)
250 return nsc
->ns_snoop
;
254 * Set the snoop flag for this connection
258 netsec_set_snoop(netsec_context
*nsc
, int snoop
)
260 nsc
->ns_snoop
= snoop
;
264 * Set the snoop callback for this connection.
267 void netsec_set_snoop_callback(netsec_context
*nsc
,
268 netsec_snoop_callback callback
, void *context
)
270 nsc
->ns_snoop_cb
= callback
;
271 nsc
->ns_snoop_context
= context
;
275 * A base64-decoding snoop callback
279 netsec_b64_snoop_decoder(netsec_context
*nsc
, const char *string
, size_t len
,
285 int offset
= context
? *((int *) context
) : 0;
289 * Output non-base64 data first.
291 fprintf(stderr
, "%.*s", offset
, string
);
296 if (decodeBase64(string
, &decoded
, &decodedlen
, 1, NULL
) == OK
) {
298 hexify((const unsigned char *) decoded
, decodedlen
, &hexified
);
299 fprintf(stderr
, "b64<%s>\n", hexified
);
301 free((char *) decoded
);
303 fprintf(stderr
, "%.*s\n", (int) len
, string
);
308 * Set the read timeout for this connection
312 netsec_set_timeout(netsec_context
*nsc
, int timeout
)
314 nsc
->ns_timeout
= timeout
;
318 * Read data from the network. Basically, return anything in our buffer,
319 * otherwise fill from the network.
323 netsec_read(netsec_context
*nsc
, void *buffer
, size_t size
, char **errstr
)
328 * If our buffer is empty, then we should fill it now
331 if (nsc
->ns_inbuflen
== 0) {
332 if (netsec_fillread(nsc
, errstr
) != OK
)
337 * netsec_fillread only returns if the buffer is full, so we can
338 * assume here that this has something in it.
341 retlen
= size
> nsc
->ns_inbuflen
? nsc
->ns_inbuflen
: size
;
343 memcpy(buffer
, nsc
->ns_inptr
, retlen
);
345 if (retlen
== (int) nsc
->ns_inbuflen
) {
347 * We've emptied our buffer, so reset everything.
349 nsc
->ns_inptr
= nsc
->ns_inbuffer
;
350 nsc
->ns_inbuflen
= 0;
352 nsc
->ns_inptr
+= size
;
353 nsc
->ns_inbuflen
-= size
;
360 * Get a "line" (CR/LF) terminated from the network.
362 * Okay, we play some games here, so pay attention:
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
370 * - If your data may contain embedded NULs, this won't work.
374 netsec_readline(netsec_context
*nsc
, size_t *len
, char **errstr
)
376 unsigned char *ptr
= nsc
->ns_inptr
;
377 size_t count
= 0, offset
;
381 * Search through our existing buffer for a LF
384 while (count
< nsc
->ns_inbuflen
) {
386 if (*ptr
++ == '\n') {
387 char *sptr
= (char *) nsc
->ns_inptr
;
388 if (count
> 1 && *(ptr
- 2) == '\r')
392 *len
= ptr
- nsc
->ns_inptr
;
393 nsc
->ns_inptr
+= count
;
394 nsc
->ns_inbuflen
-= count
;
397 if (nsc
->sasl_seclayer
)
398 fprintf(stderr
, "(sasl-encrypted) ");
399 #endif /* CYRUS_SASL */
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
);
409 fprintf(stderr
, "%s\n", sptr
);
416 * Hm, we didn't find a \n. If we've already searched half of the input
417 * buffer, return an error.
420 if (count
>= nsc
->ns_inbufsize
/ 2) {
421 netsec_err(errstr
, "Unable to find a line terminator after %d bytes",
427 * Okay, get some more network data. This may move inptr, so regenerate
431 offset
= ptr
- nsc
->ns_inptr
;
433 if (netsec_fillread(nsc
, errstr
) != OK
)
436 ptr
= nsc
->ns_inptr
+ offset
;
440 return NULL
; /* Should never reach this */
444 * Fill our read buffer with some data from the network.
448 netsec_fillread(netsec_context
*nsc
, char **errstr
)
452 size_t readbufsize
, remaining
, startoffset
;
456 * If inbuflen is zero, that means the buffer has been emptied
457 * completely. In that case move inptr back to the start.
460 if (nsc
->ns_inbuflen
== 0) {
461 nsc
->ns_inptr
= nsc
->ns_inbuffer
;
466 * If we are using TLS and there's anything pending, then skip the
470 if (!nsc
->tls_active
|| BIO_pending(nsc
->ssl_io
) == 0)
471 #endif /* TLS_SUPPORT */
477 FD_SET(nsc
->ns_fd
, &rfds
);
479 tv
.tv_sec
= nsc
->ns_timeout
;
482 rc
= select(nsc
->ns_fd
+ 1, &rfds
, NULL
, NULL
, &tv
);
485 netsec_err(errstr
, "select() while reading failed: %s",
491 netsec_err(errstr
, "read() timed out after %d seconds",
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.
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
;
507 * If we are using TLS, then just read via the BIO. But we still
508 * use our local buffer.
511 if (nsc
->tls_active
) {
512 rc
= BIO_read(nsc
->ssl_io
, end
, remaining
);
515 * Either EOF, or possibly an error. Either way, it was probably
516 * unexpected, so treat as error.
518 netsec_err(errstr
, "TLS peer aborted connection");
521 /* Definitely an error */
522 netsec_err(errstr
, "Read on TLS connection failed: %s",
523 ERR_error_string(ERR_get_error(), NULL
));
527 nsc
->ns_inbuflen
+= rc
;
531 #endif /* TLS_SUPPORT */
534 * Okay, time to read some data. Either we're just doing it straight
535 * or we're passing it through sasl_decode() first.
539 if (nsc
->sasl_seclayer
) {
540 readbuf
= nsc
->sasl_tmpbuf
;
541 readbufsize
= nsc
->sasl_maxbufsize
;
543 #endif /* CYRUS_SASL */
545 readbuf
= (char *) end
;
546 readbufsize
= remaining
;
550 * At this point, we should have active data on the connection (see
551 * select() above) so this read SHOULDN'T block. Hopefully.
554 rc
= read(nsc
->ns_fd
, readbuf
, readbufsize
);
557 netsec_err(errstr
, "Received EOF on network read");
562 netsec_err(errstr
, "Network read failed: %s", strerror(errno
));
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.
574 if (nsc
->sasl_seclayer
) {
576 unsigned int tmpoutlen
;
578 rc
= sasl_decode(nsc
->sasl_conn
, nsc
->sasl_tmpbuf
, rc
,
579 &tmpout
, &tmpoutlen
);
582 netsec_err(errstr
, "Unable to decode SASL network data: %s",
583 sasl_errdetail(nsc
->sasl_conn
));
594 if (tmpoutlen
> remaining
) {
595 netsec_err(errstr
, "Internal error: SASL decode buffer overflow!");
599 memcpy(end
, tmpout
, tmpoutlen
);
601 nsc
->ns_inbuflen
+= tmpoutlen
;
603 #endif /* CYRUS_SASL */
604 nsc
->ns_inbuflen
+= rc
;
607 * If we're past the halfway point in our read buffers, shuffle everything
608 * back to the beginning.
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
;
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
626 netsec_write(netsec_context
*nsc
, const void *buffer
, size_t size
,
629 const unsigned char *bufptr
= buffer
;
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.
643 if (nsc
->tls_active
) {
644 rc
= BIO_write(nsc
->ssl_io
, buffer
, size
);
647 netsec_err(errstr
, "Error writing to TLS connection: %s",
648 ERR_error_string(ERR_get_error(), NULL
));
654 #endif /* TLS_SUPPORT */
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.
661 while ((int) size
>= (remaining
= nsc
->ns_outbufsize
- nsc
->ns_outbuflen
)) {
662 memcpy(nsc
->ns_outptr
, bufptr
, remaining
);
665 * In theory I should increment outptr, but netsec_flush just resets
668 nsc
->ns_outbuflen
= nsc
->ns_outbufsize
;
670 rc
= netsec_flush(nsc
, errstr
);
680 * Copy any leftover data into the buffer.
684 memcpy(nsc
->ns_outptr
, bufptr
, size
);
685 nsc
->ns_outptr
+= size
;
686 nsc
->ns_outbuflen
+= size
;
693 * Our network printf() routine, which really just calls netsec_vprintf().
697 netsec_printf(netsec_context
*nsc
, char **errstr
, const char *format
, ...)
702 va_start(ap
, format
);
703 rc
= netsec_vprintf(nsc
, errstr
, format
, ap
);
710 * Write bytes to the network using printf()-style formatting.
712 * Again, for the most part copy stuff into our buffer to be flushed
717 netsec_vprintf(netsec_context
*nsc
, char **errstr
, const char *format
,
723 * Again, if we're using TLS, then bypass our local buffering
726 if (nsc
->tls_active
) {
727 rc
= BIO_vprintf(nsc
->ssl_io
, format
, ap
);
730 netsec_err(errstr
, "Error writing to TLS connection: %s",
731 ERR_error_string(ERR_get_error(), NULL
));
737 #endif /* TLS_SUPPORT */
740 * Cheat a little. If we can fit the data into our outgoing buffer,
741 * great! If not, generate a flush and retry once.
745 rc
= vsnprintf((char *) nsc
->ns_outptr
,
746 nsc
->ns_outbufsize
- nsc
->ns_outbuflen
, format
, ap
);
748 if (rc
>= (int) (nsc
->ns_outbufsize
- nsc
->ns_outbuflen
)) {
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.
755 if (nsc
->ns_outbuffer
== nsc
->ns_outptr
) {
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.
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
);
767 * Generate a flush (which may be inefficient, but hopefully
768 * it isn't) and then try again.
770 if (netsec_flush(nsc
, errstr
) != OK
)
773 * After this, outbuffer should == outptr, so we shouldn't
774 * hit this next time around.
782 if (outlen
> 0 && nsc
->ns_outptr
[outlen
- 1] == '\n') {
784 if (outlen
> 0 && nsc
->ns_outptr
[outlen
- 1] == '\r')
787 nsc
->ns_snoop_noend
= 1;
789 if (outlen
> 0 || nsc
->ns_snoop_noend
== 0) {
791 if (nsc
->sasl_seclayer
)
792 fprintf(stderr
, "(sasl-encrypted) ");
793 #endif /* CYRUS_SASL */
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
);
803 fprintf(stderr
, "%.*s\n", outlen
, nsc
->ns_outptr
);
805 nsc
->ns_snoop_noend
= 0;
809 nsc
->ns_outptr
+= rc
;
810 nsc
->ns_outbuflen
+= rc
;
816 * Flush out any buffered data in our output buffers. This routine is
817 * actually where the real network writes take place.
821 netsec_flush(netsec_context
*nsc
, char **errstr
)
823 const char *netoutbuf
= (const char *) nsc
->ns_outbuffer
;
824 unsigned int netoutlen
= nsc
->ns_outbuflen
;
828 * For TLS connections, just call BIO_flush(); we'll let TLS handle
829 * all of our output buffering.
832 if (nsc
->tls_active
) {
833 rc
= BIO_flush(nsc
->ssl_io
);
836 netsec_err(errstr
, "Error flushing TLS connection: %s",
837 ERR_error_string(ERR_get_error(), NULL
));
843 #endif /* TLS_SUPPORT */
853 * If SASL security layers are in effect, run the data through
854 * sasl_encode() first and then write it.
857 if (nsc
->sasl_seclayer
) {
858 rc
= sasl_encode(nsc
->sasl_conn
, (const char *) nsc
->ns_outbuffer
,
859 nsc
->ns_outbuflen
, &netoutbuf
, &netoutlen
);
862 netsec_err(errstr
, "SASL data encoding failed: %s",
863 sasl_errdetail(nsc
->sasl_conn
));
868 #endif /* CYRUS_SASL */
869 rc
= write(nsc
->ns_fd
, netoutbuf
, netoutlen
);
872 netsec_err(errstr
, "write() failed: %s", strerror(errno
));
876 nsc
->ns_outptr
= nsc
->ns_outbuffer
;
877 nsc
->ns_outbuflen
= 0;
883 * Set various SASL protocol parameters
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
)
892 sasl_callback_t
*sasl_cbs
;
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
));
906 * Allocate an array of SASL callbacks for this connection.
907 * Right now we just allocate an array of four callbacks.
910 sasl_cbs
= mh_xmalloc(sizeof(*sasl_cbs
) * 4);
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
;
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
;
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
;
924 sasl_cbs
[3].id
= SASL_CB_LIST_END
;
925 sasl_cbs
[3].proc
= NULL
;
926 sasl_cbs
[3].context
= NULL
;
928 nsc
->sasl_cbs
= sasl_cbs
;
930 retval
= sasl_client_new(service
, hostname
, NULL
, NULL
, nsc
->sasl_cbs
, 0,
934 netsec_err(errstr
, "SASL new client allocation failed: %s",
935 sasl_errstring(retval
, NULL
, NULL
));
939 nsc
->sasl_mech
= mechanism
? getcpy(mechanism
) : NULL
;
940 nsc
->sasl_proto_cb
= callback
;
941 nsc
->sasl_hostname
= getcpy(hostname
);
944 #else /* CYRUS_SASL */
945 netsec_err(errstr
, "SASL is not supported");
948 #endif /* CYRUS_SASL */
953 * Our userid callback; return the specified username to the SASL
954 * library when asked.
957 int netsec_get_user(void *context
, int id
, const char **result
,
960 netsec_context
*nsc
= (netsec_context
*) context
;
962 if (! result
|| (id
!= SASL_CB_USER
&& id
!= SASL_CB_AUTHNAME
))
963 return SASL_BADPARAM
;
965 if (nsc
->ns_userid
== NULL
) {
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.
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
;
980 if (nmh_get_credentials(nsc
->sasl_hostname
, nsc
->ns_userid
, 1,
981 nsc
->sasl_creds
) != OK
)
982 return SASL_BADPARAM
;
984 if (nsc
->ns_userid
!= nsc
->sasl_creds
->user
) {
986 free(nsc
->ns_userid
);
987 nsc
->ns_userid
= getcpy(nsc
->sasl_creds
->user
);
991 *result
= nsc
->ns_userid
;
993 *len
= strlen(nsc
->ns_userid
);
999 * Retrieve a password and return it to SASL
1003 netsec_get_password(sasl_conn_t
*conn
, void *context
, int id
,
1004 sasl_secret_t
**psecret
)
1006 netsec_context
*nsc
= (netsec_context
*) context
;
1011 if (! psecret
|| id
!= SASL_CB_PASS
)
1012 return SASL_BADPARAM
;
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
;
1020 if (nsc
->sasl_creds
->password
== NULL
) {
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.
1028 if (nmh_get_credentials(nsc
->sasl_hostname
, nsc
->ns_userid
, 0,
1029 nsc
->sasl_creds
) != OK
) {
1030 return SASL_BADPARAM
;
1034 len
= strlen(nsc
->sasl_creds
->password
);
1037 * sasl_secret_t includes 1 bytes for "data" already, so that leaves
1038 * us room for a terminating NUL
1041 *psecret
= (sasl_secret_t
*) malloc(sizeof(sasl_secret_t
) + len
);
1046 (*psecret
)->len
= len
;
1047 strcpy((char *) (*psecret
)->data
, nsc
->sasl_creds
->password
);
1049 nsc
->sasl_secret
= *psecret
;
1053 #endif /* CYRUS_SASL */
1056 * Negotiate SASL on this connection
1060 netsec_negotiate_sasl(netsec_context
*nsc
, const char *mechlist
, char **errstr
)
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
;
1071 #ifdef OAUTH_SUPPORT
1072 unsigned char *xoauth_client_res
;
1073 size_t xoauth_client_res_len
;
1074 #endif /* OAUTH_SUPPORT */
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.
1082 if (nsc
->sasl_mech
) {
1083 char **str
, *mlist
= getcpy(mechlist
);
1086 str
= brkstring(mlist
, " ", NULL
);
1088 for (i
= 0; str
[i
] != NULL
; i
++) {
1089 if (strcasecmp(nsc
->sasl_mech
, str
[i
]) == 0) {
1094 i
= (str
[i
] == NULL
);
1100 netsec_err(errstr
, "Chosen mechanism %s not supported by server",
1106 #ifdef OAUTH_SUPPORT
1107 if (nsc
->sasl_mech
&& strcasecmp(nsc
->sasl_mech
, "XOAUTH2") == 0) {
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
1116 if (! nsc
->oauth_service
) {
1117 netsec_err(errstr
, "Internal error: OAuth2 service name not given");
1121 nsc
->sasl_chosen_mech
= getcpy(nsc
->sasl_mech
);
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 "
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
);
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
1145 rc
= nsc
->sasl_proto_cb(NETSEC_SASL_FINISH
, NULL
, 0, NULL
, 0, errstr
);
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
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,
1158 netsec_err(errstr
, "Unexpected success after OAuth failure!");
1164 #endif /* OAUTH_SUPPORT */
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
1174 memset(&secprops
, 0, sizeof(secprops
));
1175 secprops
.maxbufsize
= SASL_MAXRECVBUF
;
1178 * If we're using TLS, do not negotiate a security layer
1183 nsc
->tls_active
? 0 :
1184 #endif /* TLS_SUPPORT */
1187 rc
= sasl_setprop(nsc
->sasl_conn
, SASL_SEC_PROPS
, &secprops
);
1189 if (rc
!= SASL_OK
) {
1190 netsec_err(errstr
, "SASL security property initialization failed: %s",
1191 sasl_errstring(rc
, NULL
, NULL
));
1196 * Start the actual protocol negotiation, and go through the
1197 * sasl_client_step() loop (after sasl_client_start, of course).
1200 rc
= sasl_client_start(nsc
->sasl_conn
,
1201 nsc
->sasl_mech
? nsc
->sasl_mech
: mechlist
, NULL
,
1202 (const char **) &saslbuf
, &saslbuflen
,
1205 if (rc
!= SASL_OK
&& rc
!= SASL_CONTINUE
) {
1206 netsec_err(errstr
, "SASL client start failed: %s",
1207 sasl_errdetail(nsc
->sasl_conn
));
1211 nsc
->sasl_chosen_mech
= getcpy(chosen_mech
);
1213 if (nsc
->sasl_proto_cb(NETSEC_SASL_START
, saslbuf
, saslbuflen
, NULL
, 0,
1218 * We've written out our first message; enter in the step loop
1221 while (rc
== SASL_CONTINUE
) {
1223 * Call our SASL callback, which will handle the details of
1224 * reading data from the network.
1227 if (nsc
->sasl_proto_cb(NETSEC_SASL_READ
, NULL
, 0, &outbuf
, &outbuflen
,
1229 nsc
->sasl_proto_cb(NETSEC_SASL_CANCEL
, NULL
, 0, NULL
, 0, NULL
);
1233 rc
= sasl_client_step(nsc
->sasl_conn
, (char *) outbuf
, outbuflen
, NULL
,
1234 (const char **) &saslbuf
, &saslbuflen
);
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
);
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
);
1254 * SASL exchanges should be complete, process the final response message
1258 if (nsc
->sasl_proto_cb(NETSEC_SASL_FINISH
, NULL
, 0, NULL
, 0,
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.
1269 * At this point, SASL should be complete. Get a few properties
1270 * from the authentication exchange.
1273 rc
= sasl_getprop(nsc
->sasl_conn
, SASL_SSF
, (const void **) &ssf
);
1275 if (rc
!= SASL_OK
) {
1276 netsec_err(errstr
, "Cannot retrieve SASL negotiated security "
1277 "strength factor: %s", sasl_errstring(rc
, NULL
, NULL
));
1281 nsc
->sasl_ssf
= *ssf
;
1283 if (nsc
->sasl_ssf
> 0) {
1284 rc
= sasl_getprop(nsc
->sasl_conn
, SASL_MAXOUTBUF
,
1285 (const void **) &outbufmax
);
1287 if (rc
!= SASL_OK
) {
1288 netsec_err(errstr
, "Cannot retrieve SASL negotiated output "
1289 "buffer size: %s", sasl_errstring(rc
, NULL
, NULL
));
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).
1299 nsc
->sasl_maxbufsize
= *outbufmax
;
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
);
1306 * There shouldn't be any data in the buffer, but for
1307 * consistency's sake discard it.
1309 nsc
->ns_outptr
= nsc
->ns_outbuffer
;
1310 nsc
->ns_outbuflen
= 0;
1314 * Allocate a buffer to do temporary reads into, before we
1315 * call sasl_decode()
1318 nsc
->sasl_tmpbuf
= mh_xmalloc(nsc
->sasl_maxbufsize
);
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
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
;
1335 nsc
->sasl_seclayer
= 1;
1340 netsec_err(errstr
, "SASL not supported");
1343 #endif /* CYRUS_SASL */
1347 * Retrieve our chosen SASL mechanism
1351 netsec_get_sasl_mechanism(netsec_context
*nsc
)
1354 return nsc
->sasl_chosen_mech
;
1355 #else /* CYRUS_SASL */
1357 #endif /* CYRUS_SASL */
1361 * Set an OAuth2 service name, if we support it.
1365 netsec_set_oauth_service(netsec_context
*nsc
, const char *service
)
1367 #ifdef OAUTH_SUPPORT
1368 nsc
->oauth_service
= getcpy(service
);
1370 #else /* OAUTH_SUPPORT */
1372 #endif /* OAUTH_SUPPORT */
1376 * Initialize (and enable) TLS for this connection
1380 netsec_set_tls(netsec_context
*nsc
, int tls
, char **errstr
)
1385 BIO
*sbio
, *ssl_bio
;;
1387 if (! tls_initialized
) {
1389 SSL_load_error_strings();
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.
1397 sslctx
= SSL_CTX_new(SSLv23_client_method());
1400 netsec_err(errstr
, "Unable to initialize OpenSSL context: %s",
1401 ERR_error_string(ERR_get_error(), NULL
));
1405 SSL_CTX_set_options(sslctx
, SSL_OP_NO_SSLv2
| SSL_OP_NO_SSLv3
|
1411 if (nsc
->ns_fd
== -1) {
1412 netsec_err(errstr
, "Invalid file descriptor in netsec context");
1417 * Create the SSL structure which holds the data for a single
1421 ssl
= SSL_new(sslctx
);
1424 netsec_err(errstr
, "Unable to create SSL connection: %s",
1425 ERR_error_string(ERR_get_error(), NULL
));
1430 * Never bother us, since we are using blocking sockets.
1433 SSL_set_mode(ssl
, SSL_MODE_AUTO_RETRY
);
1436 * This is a bit weird, so pay attention.
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
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:
1446 * buffer BIO -> SSL BIO -> socket BIO.
1448 * So writes and reads are buffered (we mostly care about writes).
1451 sbio
= BIO_new_socket(nsc
->ns_fd
, BIO_NOCLOSE
);
1454 netsec_err(errstr
, "Unable to create a socket BIO: %s",
1455 ERR_error_string(ERR_get_error(), NULL
));
1460 SSL_set_bio(ssl
, sbio
, sbio
);
1461 SSL_set_connect_state(ssl
);
1463 nsc
->ssl_io
= BIO_new(BIO_f_buffer());
1465 if (! nsc
->ssl_io
) {
1466 netsec_err(errstr
, "Unable to create a buffer BIO: %s",
1467 ERR_error_string(ERR_get_error(), NULL
));
1472 ssl_bio
= BIO_new(BIO_f_ssl());
1475 netsec_err(errstr
, "Unable to create a SSL BIO: %s",
1476 ERR_error_string(ERR_get_error(), NULL
));
1481 BIO_set_ssl(ssl_bio
, ssl
, BIO_CLOSE
);
1482 BIO_push(nsc
->ssl_io
, ssl_bio
);
1486 BIO_free_all(nsc
->ssl_io
);
1491 #else /* TLS_SUPPORT */
1492 netsec_err(errstr
, "TLS is not supported");
1496 #endif /* TLS_SUPPORT */
1500 * Start TLS negotiation on this connection
1504 netsec_negotiate_tls(netsec_context
*nsc
, char **errstr
)
1507 if (! nsc
->ssl_io
) {
1508 netsec_err(errstr
, "TLS has not been configured for this connection");
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
));
1518 if (nsc
->ns_snoop
) {
1521 if (BIO_get_ssl(nsc
->ssl_io
, &ssl
) < 1) {
1522 fprintf(stderr
, "WARNING: cannot determine SSL ciphers\n");
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
));
1532 nsc
->tls_active
= 1;
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.
1539 if (nsc
->ns_outbuffer
) {
1540 free(nsc
->ns_outbuffer
);
1541 nsc
->ns_outbuffer
= NULL
;
1545 #else /* TLS_SUPPORT */
1546 netsec_err(errstr
, "TLS not supported");
1549 #endif /* TLS_SUPPORT */
1553 * Generate an (allocated) error string
1557 netsec_err(char **errstr
, const char *fmt
, ...)
1561 char *errbuf
= NULL
;
1568 errbufsize
= rc
+ 1;
1569 errbuf
= mh_xrealloc(errbuf
, errbufsize
);
1571 rc
= vsnprintf(errbuf
, errbufsize
, fmt
, ap
);
1573 } while (rc
>= (int) errbufsize
);