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_timeout
; /* Network read timeout, in seconds */
60 char *ns_userid
; /* Userid for authentication */
61 unsigned char *ns_inbuffer
; /* Our read input buffer */
62 unsigned char *ns_inptr
; /* Our read buffer input pointer */
63 unsigned int ns_inbuflen
; /* Length of data in input buffer */
64 unsigned int ns_inbufsize
; /* Size of input buffer */
65 unsigned char *ns_outbuffer
;/* Output buffer */
66 unsigned char *ns_outptr
; /* Output buffer pointer */
67 unsigned int ns_outbuflen
; /* Output buffer data length */
68 unsigned int ns_outbufsize
; /* Output buffer size */
69 char *sasl_mech
; /* User-requested mechanism */
71 char *oauth_service
; /* OAuth2 service name */
72 #endif /* OAUTH_SUPPORT */
74 char *sasl_hostname
; /* Hostname we've connected to */
75 sasl_conn_t
*sasl_conn
; /* SASL connection context */
76 sasl_ssf_t sasl_ssf
; /* SASL Security Strength Factor */
77 netsec_sasl_callback sasl_proto_cb
; /* SASL callback we use */
78 sasl_callback_t
*sasl_cbs
; /* Callbacks used by SASL */
79 nmh_creds_t sasl_creds
; /* Credentials (username/password) */
80 sasl_secret_t
*sasl_secret
; /* SASL password structure */
81 char *sasl_chosen_mech
; /* Mechanism chosen by SASL */
82 int sasl_seclayer
; /* If true, SASL security layer is enabled */
83 char *sasl_tmpbuf
; /* Temporary read buffer for decodes */
84 size_t sasl_maxbufsize
; /* Maximum negotiated SASL buffer size */
85 #endif /* CYRUS_SASL */
87 BIO
*ssl_io
; /* BIO used for connection I/O */
88 int tls_active
; /* If true, TLS is running */
89 #endif /* TLS_SUPPORT */
93 * Function to read data from the actual network socket
96 static int netsec_fillread(netsec_context
*ns_context
, char **errstr
);
99 * How this code works, in general.
101 * _If_ we are using no encryption or SASL encryption, then we buffer the
102 * network data through ns_inbuffer and ns_outbuffer. That should be
103 * relatively self-explanatory.
105 * If we are using SSL for encryption, then use a buffering BIO for output
106 * (that just easier). Still do buffering for reads; when we need more
107 * data we call the BIO_read() function to fill our local buffer.
109 * For SASL, we make use of (for now) the Cyrus-SASL library. For some
110 * mechanisms, we implement those mechanisms directly since the Cyrus SASL
111 * library doesn't support them (like OAuth).
115 * Allocate and initialize our security context
121 netsec_context
*nsc
= mh_xmalloc(sizeof(*nsc
));
125 nsc
->ns_userid
= NULL
;
126 nsc
->ns_timeout
= 60; /* Our default */
127 nsc
->ns_inbufsize
= NETSEC_BUFSIZE
;
128 nsc
->ns_inbuffer
= mh_xmalloc(nsc
->ns_inbufsize
);
129 nsc
->ns_inptr
= nsc
->ns_inbuffer
;
130 nsc
->ns_inbuflen
= 0;
131 nsc
->ns_outbufsize
= NETSEC_BUFSIZE
;
132 nsc
->ns_outbuffer
= mh_xmalloc(nsc
->ns_outbufsize
);
133 nsc
->ns_outptr
= nsc
->ns_outbuffer
;
134 nsc
->ns_outbuflen
= 0;
135 nsc
->sasl_mech
= NULL
;
137 nsc
->oauth_service
= NULL
;
138 #endif /* OAUTH_SUPPORT */
140 nsc
->sasl_conn
= NULL
;
141 nsc
->sasl_hostname
= NULL
;
142 nsc
->sasl_cbs
= NULL
;
143 nsc
->sasl_creds
= NULL
;
144 nsc
->sasl_secret
= NULL
;
145 nsc
->sasl_chosen_mech
= NULL
;
147 nsc
->sasl_seclayer
= 0;
148 nsc
->sasl_tmpbuf
= NULL
;
149 nsc
->sasl_maxbufsize
= 0;
150 #endif /* CYRUS_SASL */
154 #endif /* TLS_SUPPORT */
159 * Shutdown the connection completely and free all resources.
160 * The connection is only closed if the flag is given.
164 netsec_shutdown(netsec_context
*nsc
, int closeflag
)
167 free(nsc
->ns_userid
);
168 if (nsc
->ns_inbuffer
)
169 free(nsc
->ns_inbuffer
);
170 if (nsc
->ns_outbuffer
)
171 free(nsc
->ns_outbuffer
);
173 free(nsc
->sasl_mech
);
175 if (nsc
->oauth_service
)
176 free(nsc
->oauth_service
);
177 #endif /* OAUTH_SERVICE */
180 sasl_dispose(&nsc
->sasl_conn
);
181 if (nsc
->sasl_hostname
)
182 free(nsc
->sasl_hostname
);
185 if (nsc
->sasl_creds
) {
186 if (nsc
->sasl_creds
->password
)
187 memset(nsc
->sasl_creds
->password
, 0,
188 strlen(nsc
->sasl_creds
->password
));
189 free(nsc
->sasl_creds
);
191 if (nsc
->sasl_secret
) {
192 if (nsc
->sasl_secret
->len
> 0) {
193 memset(nsc
->sasl_secret
->data
, 0, nsc
->sasl_secret
->len
);
195 free(nsc
->sasl_secret
);
197 if (nsc
->sasl_chosen_mech
)
198 free(nsc
->sasl_chosen_mech
);
199 if (nsc
->sasl_tmpbuf
)
200 free(nsc
->sasl_tmpbuf
);
201 #endif /* CYRUS_SASL */
205 * I checked; BIO_free_all() will cause SSL_shutdown to be called
206 * on the SSL object in the chain.
208 BIO_free_all(nsc
->ssl_io
);
209 #endif /* TLS_SUPPORT */
211 if (closeflag
&& nsc
->ns_fd
!= -1)
218 * Set the file descriptor for our context
222 netsec_set_fd(netsec_context
*nsc
, int fd
)
228 * Set the userid used for authentication for this context
232 netsec_set_userid(netsec_context
*nsc
, const char *userid
)
234 nsc
->ns_userid
= getcpy(userid
);
238 * Get the snoop flag for this connection
242 netsec_get_snoop(netsec_context
*nsc
)
244 return nsc
->ns_snoop
;
248 * Set the snoop flag for this connection
252 netsec_set_snoop(netsec_context
*nsc
, int snoop
)
254 nsc
->ns_snoop
= snoop
;
258 * Set the read timeout for this connection
262 netsec_set_timeout(netsec_context
*nsc
, int timeout
)
264 nsc
->ns_timeout
= timeout
;
268 * Read data from the network. Basically, return anything in our buffer,
269 * otherwise fill from the network.
273 netsec_read(netsec_context
*nsc
, void *buffer
, size_t size
, char **errstr
)
278 * If our buffer is empty, then we should fill it now
281 if (nsc
->ns_inbuflen
== 0) {
282 if (netsec_fillread(nsc
, errstr
) != OK
)
287 * netsec_fillread only returns if the buffer is full, so we can
288 * assume here that this has something in it.
291 retlen
= size
> nsc
->ns_inbuflen
? nsc
->ns_inbuflen
: size
;
293 memcpy(buffer
, nsc
->ns_inptr
, retlen
);
295 if (retlen
== (int) nsc
->ns_inbuflen
) {
297 * We've emptied our buffer, so reset everything.
299 nsc
->ns_inptr
= nsc
->ns_inbuffer
;
300 nsc
->ns_inbuflen
= 0;
302 nsc
->ns_inptr
+= size
;
303 nsc
->ns_inbuflen
-= size
;
310 * Get a "line" (CR/LF) terminated from the network.
312 * Okay, we play some games here, so pay attention:
314 * - Unlike every other function, we return a pointer to the
315 * existing buffer. This pointer is valid until you call another
316 * read functiona again.
317 * - We NUL-terminated the buffer right at the end, before the terminator.
318 * - Technically we look for a LF; if we find a CR right before it, then
320 * - If your data may contain embedded NULs, this won't work.
324 netsec_readline(netsec_context
*nsc
, size_t *len
, char **errstr
)
326 unsigned char *ptr
= nsc
->ns_inptr
;
327 size_t count
= 0, offset
;
331 * Search through our existing buffer for a LF
334 while (count
< nsc
->ns_inbuflen
) {
336 if (*ptr
++ == '\n') {
337 char *sptr
= (char *) nsc
->ns_inptr
;
338 if (count
> 1 && *(ptr
- 2) == '\r')
342 *len
= ptr
- nsc
->ns_inptr
;
343 nsc
->ns_inptr
+= count
;
344 nsc
->ns_inbuflen
-= count
;
350 * Hm, we didn't find a \n. If we've already searched half of the input
351 * buffer, return an error.
354 if (count
>= nsc
->ns_inbufsize
/ 2) {
355 netsec_err(errstr
, "Unable to find a line terminator after %d bytes",
361 * Okay, get some more network data. This may move inptr, so regenerate
365 offset
= ptr
- nsc
->ns_inptr
;
367 if (netsec_fillread(nsc
, errstr
) != OK
)
370 ptr
= nsc
->ns_inptr
+ offset
;
374 return NULL
; /* Should never reach this */
378 * Fill our read buffer with some data from the network.
382 netsec_fillread(netsec_context
*nsc
, char **errstr
)
386 size_t readbufsize
, remaining
, startoffset
;
390 * If inbuflen is zero, that means the buffer has been emptied
391 * completely. In that case move inptr back to the start.
394 if (nsc
->ns_inbuflen
== 0) {
395 nsc
->ns_inptr
= nsc
->ns_inbuffer
;
400 * If we are using TLS and there's anything pending, then skip the
404 if (!nsc
->tls_active
|| BIO_pending(nsc
->ssl_io
) == 0)
405 #endif /* TLS_SUPPORT */
411 FD_SET(nsc
->ns_fd
, &rfds
);
413 tv
.tv_sec
= nsc
->ns_timeout
;
416 rc
= select(nsc
->ns_fd
+ 1, &rfds
, NULL
, NULL
, &tv
);
419 netsec_err(errstr
, "select() while reading failed: %s",
425 netsec_err(errstr
, "read() timed out after %d seconds",
431 * At this point, we know that rc is 1, so there's not even any
432 * point to check to see if our descriptor is set in rfds.
436 startoffset
= nsc
->ns_inptr
- nsc
->ns_inbuffer
;
437 remaining
= nsc
->ns_inbufsize
- (startoffset
+ nsc
->ns_inbuflen
);
438 end
= nsc
->ns_inptr
+ nsc
->ns_inbuflen
;
441 * If we are using TLS, then just read via the BIO. But we still
442 * use our local buffer.
445 if (nsc
->tls_active
) {
446 rc
= BIO_read(nsc
->ssl_io
, end
, remaining
);
449 * Either EOF, or possibly an error. Either way, it was probably
450 * unexpected, so treat as error.
452 netsec_err(errstr
, "TLS peer aborted connection");
455 /* Definitely an error */
456 netsec_err(errstr
, "Read on TLS connection failed: %s",
457 ERR_error_string(ERR_get_error(), NULL
));
461 nsc
->ns_inbuflen
+= rc
;
465 #endif /* TLS_SUPPORT */
468 * Okay, time to read some data. Either we're just doing it straight
469 * or we're passing it through sasl_decode() first.
473 if (nsc
->sasl_seclayer
) {
474 readbuf
= nsc
->sasl_tmpbuf
;
475 readbufsize
= nsc
->sasl_maxbufsize
;
477 #endif /* CYRUS_SASL */
479 readbuf
= (char *) end
;
480 readbufsize
= remaining
;
484 * At this point, we should have active data on the connection (see
485 * select() above) so this read SHOULDN'T block. Hopefully.
488 rc
= read(nsc
->ns_fd
, readbuf
, readbufsize
);
491 netsec_err(errstr
, "Received EOF on network read");
496 netsec_err(errstr
, "Network read failed: %s", strerror(errno
));
501 * Okay, so we've had a successful read. If we are doing SASL security
502 * layers, pass this through sasl_decode(). sasl_decode() can return
503 * 0 bytes decoded; if that happens, jump back to the beginning. Otherwise
504 * we can just update our length pointer.
508 if (nsc
->sasl_seclayer
) {
510 unsigned int tmpoutlen
;
512 rc
= sasl_decode(nsc
->sasl_conn
, nsc
->sasl_tmpbuf
, rc
,
513 &tmpout
, &tmpoutlen
);
516 netsec_err(errstr
, "Unable to decode SASL network data: %s",
517 sasl_errdetail(nsc
->sasl_conn
));
528 if (tmpoutlen
> remaining
) {
529 netsec_err(errstr
, "Internal error: SASL decode buffer overflow!");
533 memcpy(end
, tmpout
, tmpoutlen
);
535 nsc
->ns_inbuflen
+= tmpoutlen
;
537 #endif /* CYRUS_SASL */
538 nsc
->ns_inbuflen
+= rc
;
541 * If we're past the halfway point in our read buffers, shuffle everything
542 * back to the beginning.
545 if (startoffset
> nsc
->ns_inbufsize
/ 2) {
546 memmove(nsc
->ns_inbuffer
, nsc
->ns_inptr
, nsc
->ns_inbuflen
);
547 nsc
->ns_inptr
= nsc
->ns_inbuffer
;
554 * Write data to our network connection. Really, fill up the buffer as
555 * much as we can, and flush it out if necessary. netsec_flush() does
560 netsec_write(netsec_context
*nsc
, const void *buffer
, size_t size
,
563 const unsigned char *bufptr
= buffer
;
572 * If TLS is active, then bypass all of our buffering logic; just
573 * write it directly to our BIO. We have a buffering BIO first in
574 * our stack, so buffering will take place there.
577 if (nsc
->tls_active
) {
578 rc
= BIO_write(nsc
->ssl_io
, buffer
, size
);
581 netsec_err(errstr
, "Error writing to TLS connection: %s",
582 ERR_error_string(ERR_get_error(), NULL
));
588 #endif /* TLS_SUPPORT */
591 * Run a loop copying in data to our local buffer; when we're done with
592 * any buffer overflows then just copy any remaining data in.
595 while ((int) size
>= (remaining
= nsc
->ns_outbufsize
- nsc
->ns_outbuflen
)) {
596 memcpy(nsc
->ns_outptr
, bufptr
, remaining
);
599 * In theory I should increment outptr, but netsec_flush just resets
602 nsc
->ns_outbuflen
= nsc
->ns_outbufsize
;
604 rc
= netsec_flush(nsc
, errstr
);
614 * Copy any leftover data into the buffer.
618 memcpy(nsc
->ns_outptr
, bufptr
, size
);
619 nsc
->ns_outptr
+= size
;
620 nsc
->ns_outbuflen
+= size
;
627 * Our network printf() routine, which really just calls netsec_vprintf().
631 netsec_printf(netsec_context
*nsc
, char **errstr
, const char *format
, ...)
636 va_start(ap
, format
);
637 rc
= netsec_vprintf(nsc
, errstr
, format
, ap
);
644 * Write bytes to the network using printf()-style formatting.
646 * Again, for the most part copy stuff into our buffer to be flushed
651 netsec_vprintf(netsec_context
*nsc
, char **errstr
, const char *format
,
657 * Again, if we're using TLS, then bypass our local buffering
660 if (nsc
->tls_active
) {
661 rc
= BIO_vprintf(nsc
->ssl_io
, format
, ap
);
664 netsec_err(errstr
, "Error writing to TLS connection: %s",
665 ERR_error_string(ERR_get_error(), NULL
));
671 #endif /* TLS_SUPPORT */
674 * Cheat a little. If we can fit the data into our outgoing buffer,
675 * great! If not, generate a flush and retry once.
679 rc
= vsnprintf((char *) nsc
->ns_outptr
,
680 nsc
->ns_outbufsize
- nsc
->ns_outbuflen
, format
, ap
);
682 if (rc
>= (int) (nsc
->ns_outbufsize
- nsc
->ns_outbuflen
)) {
684 * This means we have an overflow. Note that we don't actually
685 * make use of the terminating NUL, but according to the spec
686 * vsnprintf() won't write to the last byte in the string; that's
687 * why we have to use >= in the comparison above.
689 if (nsc
->ns_outbuffer
== nsc
->ns_outptr
) {
691 * Whoops, if the buffer pointer was the same as the start of the
692 * buffer, that means we overflowed the internal buffer.
693 * At that point, just give up.
695 netsec_err(errstr
, "Internal error: wanted to printf() a total of "
696 "%d bytes, but our buffer size was only %d bytes",
697 rc
, nsc
->ns_outbufsize
);
701 * Generate a flush (which may be inefficient, but hopefully
702 * it isn't) and then try again.
704 if (netsec_flush(nsc
, errstr
) != OK
)
707 * After this, outbuffer should == outptr, so we shouldn't
708 * hit this next time around.
714 nsc
->ns_outptr
+= rc
;
715 nsc
->ns_outbuflen
+= rc
;
721 * Flush out any buffered data in our output buffers. This routine is
722 * actually where the real network writes take place.
726 netsec_flush(netsec_context
*nsc
, char **errstr
)
728 const char *netoutbuf
= (const char *) nsc
->ns_outbuffer
;
729 unsigned int netoutlen
= nsc
->ns_outbuflen
;
733 * For TLS connections, just call BIO_flush(); we'll let TLS handle
734 * all of our output buffering.
737 if (nsc
->tls_active
) {
738 rc
= BIO_flush(nsc
->ssl_io
);
741 netsec_err(errstr
, "Error flushing TLS connection: %s",
742 ERR_error_string(ERR_get_error(), NULL
));
748 #endif /* TLS_SUPPORT */
758 * If SASL security layers are in effect, run the data through
759 * sasl_encode() first and then write it.
762 if (nsc
->sasl_seclayer
) {
763 rc
= sasl_encode(nsc
->sasl_conn
, (const char *) nsc
->ns_outbuffer
,
764 nsc
->ns_outbuflen
, &netoutbuf
, &netoutlen
);
767 netsec_err(errstr
, "SASL data encoding failed: %s",
768 sasl_errdetail(nsc
->sasl_conn
));
773 #endif /* CYRUS_SASL */
774 rc
= write(nsc
->ns_fd
, netoutbuf
, netoutlen
);
777 netsec_err(errstr
, "write() failed: %s", strerror(errno
));
781 nsc
->ns_outptr
= nsc
->ns_outbuffer
;
782 nsc
->ns_outbuflen
= 0;
788 * Set various SASL protocol parameters
792 netsec_set_sasl_params(netsec_context
*nsc
, const char *hostname
,
793 const char *service
, const char *mechanism
,
794 netsec_sasl_callback callback
, char **errstr
)
797 sasl_callback_t
*sasl_cbs
;
800 if (! sasl_initialized
) {
801 retval
= sasl_client_init(NULL
);
802 if (retval
!= SASL_OK
) {
803 netsec_err(errstr
, "SASL client initialization failed: %s",
804 sasl_errstring(retval
, NULL
, NULL
));
811 * Allocate an array of SASL callbacks for this connection.
812 * Right now we just allocate an array of four callbacks.
815 sasl_cbs
= mh_xmalloc(sizeof(*sasl_cbs
) * 4);
817 sasl_cbs
[0].id
= SASL_CB_USER
;
818 sasl_cbs
[0].proc
= (sasl_callback_ft
) netsec_get_user
;
819 sasl_cbs
[0].context
= nsc
;
821 sasl_cbs
[1].id
= SASL_CB_AUTHNAME
;
822 sasl_cbs
[1].proc
= (sasl_callback_ft
) netsec_get_user
;
823 sasl_cbs
[1].context
= nsc
;
825 sasl_cbs
[2].id
= SASL_CB_PASS
;
826 sasl_cbs
[2].proc
= (sasl_callback_ft
) netsec_get_password
;
827 sasl_cbs
[2].context
= nsc
;
829 sasl_cbs
[3].id
= SASL_CB_LIST_END
;
830 sasl_cbs
[3].proc
= NULL
;
831 sasl_cbs
[3].context
= NULL
;
833 nsc
->sasl_cbs
= sasl_cbs
;
835 retval
= sasl_client_new(service
, hostname
, NULL
, NULL
, nsc
->sasl_cbs
, 0,
839 netsec_err(errstr
, "SASL new client allocation failed: %s",
840 sasl_errstring(retval
, NULL
, NULL
));
844 nsc
->sasl_mech
= mechanism
? getcpy(mechanism
) : NULL
;
845 nsc
->sasl_proto_cb
= callback
;
846 nsc
->sasl_hostname
= getcpy(hostname
);
849 #else /* CYRUS_SASL */
850 netsec_err(errstr
, "SASL is not supported");
853 #endif /* CYRUS_SASL */
858 * Our userid callback; return the specified username to the SASL
859 * library when asked.
862 int netsec_get_user(void *context
, int id
, const char **result
,
865 netsec_context
*nsc
= (netsec_context
*) context
;
867 if (! result
|| (id
!= SASL_CB_USER
&& id
!= SASL_CB_AUTHNAME
))
868 return SASL_BADPARAM
;
870 if (nsc
->ns_userid
== NULL
) {
872 * Pass the 1 third argument to nmh_get_credentials() so that
873 * a defauly user if the -user switch wasn't supplied, and so
874 * that a default password will be supplied. That's used when
875 * those values really don't matter, and only with legacy/.netrc,
876 * i.e., with a credentials profile entry.
879 if (nsc
->sasl_creds
== NULL
) {
880 nsc
->sasl_creds
= mh_xmalloc(sizeof(*nsc
->sasl_creds
));
881 nsc
->sasl_creds
->user
= NULL
;
882 nsc
->sasl_creds
->password
= NULL
;
885 if (nmh_get_credentials(nsc
->sasl_hostname
, nsc
->ns_userid
, 1,
886 nsc
->sasl_creds
) != OK
)
887 return SASL_BADPARAM
;
889 if (nsc
->ns_userid
!= nsc
->sasl_creds
->user
) {
891 free(nsc
->ns_userid
);
892 nsc
->ns_userid
= getcpy(nsc
->sasl_creds
->user
);
896 *result
= nsc
->ns_userid
;
898 *len
= strlen(nsc
->ns_userid
);
904 * Retrieve a password and return it to SASL
908 netsec_get_password(sasl_conn_t
*conn
, void *context
, int id
,
909 sasl_secret_t
**psecret
)
911 netsec_context
*nsc
= (netsec_context
*) context
;
916 if (! psecret
|| id
!= SASL_CB_PASS
)
917 return SASL_BADPARAM
;
919 if (nsc
->sasl_creds
== NULL
) {
920 nsc
->sasl_creds
= mh_xmalloc(sizeof(*nsc
->sasl_creds
));
921 nsc
->sasl_creds
->user
= NULL
;
922 nsc
->sasl_creds
->password
= NULL
;
925 if (nsc
->sasl_creds
->password
== NULL
) {
927 * Pass the 0 third argument to nmh_get_credentials() so
928 * that the default password isn't used. With legacy/.netrc
929 * credentials support, we'll only get here if the -user
930 * switch to send(1)/post(8) wasn't used.
933 if (nmh_get_credentials(nsc
->sasl_hostname
, nsc
->ns_userid
, 0,
934 nsc
->sasl_creds
) != OK
) {
935 return SASL_BADPARAM
;
939 len
= strlen(nsc
->sasl_creds
->password
);
942 * sasl_secret_t includes 1 bytes for "data" already, so that leaves
943 * us room for a terminating NUL
946 *psecret
= (sasl_secret_t
*) malloc(sizeof(sasl_secret_t
) + len
);
951 (*psecret
)->len
= len
;
952 strcpy((char *) (*psecret
)->data
, nsc
->sasl_creds
->password
);
954 nsc
->sasl_secret
= *psecret
;
958 #endif /* CYRUS_SASL */
961 * Negotiate SASL on this connection
965 netsec_negotiate_sasl(netsec_context
*nsc
, const char *mechlist
, char **errstr
)
968 sasl_security_properties_t secprops
;
969 const char *chosen_mech
;
970 const unsigned char *saslbuf
;
971 unsigned char *outbuf
;
972 unsigned int saslbuflen
, outbuflen
;
977 unsigned char *xoauth_client_res
;
978 size_t xoauth_client_res_len
;
979 #endif /* OAUTH_SUPPORT */
983 * If we've been passed a requested mechanism, check our mechanism
984 * list from the protocol. If it's not supported, return an error.
987 if (nsc
->sasl_mech
) {
988 char **str
, *mlist
= getcpy(mechlist
);
991 str
= brkstring(mlist
, " ", NULL
);
993 for (i
= 0; str
[i
] != NULL
; i
++) {
994 if (strcasecmp(nsc
->sasl_mech
, str
[i
]) == 0) {
999 i
= (str
[i
] == NULL
);
1005 netsec_err(errstr
, "Chosen mechanism %s not supported by server",
1011 #ifdef OAUTH_SUPPORT
1012 if (nsc
->sasl_mech
&& strcasecmp(nsc
->sasl_mech
, "XOAUTH2") == 0) {
1014 * This should be relatively straightforward, but requires some
1015 * help from the plugin. Basically, if XOAUTH2 is a success,
1016 * the callback has to return success, but no output data. If
1017 * there is output data, it will be assumed that it is the JSON
1021 if (! nsc
->oauth_service
) {
1022 netsec_err(errstr
, "Internal error: OAuth2 service name not given");
1026 nsc
->sasl_chosen_mech
= getcpy(nsc
->sasl_mech
);
1028 if (mh_oauth_do_xoauth(nsc
->ns_userid
, nsc
->oauth_service
,
1029 &xoauth_client_res
, &xoauth_client_res_len
,
1030 nsc
->ns_snoop
? stderr
: NULL
) != OK
) {
1031 netsec_err(errstr
, "Internal error: Unable to get OAuth2 "
1036 rc
= nsc
->sasl_proto_cb(NETSEC_SASL_START
, xoauth_client_res
,
1037 xoauth_client_res_len
, NULL
, 0, errstr
);
1038 free(xoauth_client_res
);
1044 * Okay, we need to do a NETSEC_SASL_FINISH now. If we return
1045 * success, we indicate that with no output data. But if we
1046 * fail, then send a blank message and get the resulting
1050 rc
= nsc
->sasl_proto_cb(NETSEC_SASL_FINISH
, NULL
, 0, NULL
, 0, errstr
);
1054 * We're going to assume the error here is a JSON response;
1055 * we ignore it and send a blank message in response. We should
1056 * then get either an +OK or -ERR
1059 nsc
->sasl_proto_cb(NETSEC_SASL_WRITE
, NULL
, 0, NULL
, 0, NULL
);
1060 rc
= nsc
->sasl_proto_cb(NETSEC_SASL_FINISH
, NULL
, 0, NULL
, 0,
1063 netsec_err(errstr
, "Unexpected success after OAuth failure!");
1068 #endif /* OAUTH_SUPPORT */
1072 * In netsec_set_sasl_params, we've already done all of our setup with
1073 * sasl_client_init() and sasl_client_new(). So time to set security
1074 * properties, call sasl_client_start(), and generate the protocol
1078 memset(&secprops
, 0, sizeof(secprops
));
1079 secprops
.maxbufsize
= SASL_MAXRECVBUF
;
1082 * If we're using TLS, do not negotiate a security layer
1087 nsc
->tls_active
? 0 :
1088 #endif /* TLS_SUPPORT */
1091 rc
= sasl_setprop(nsc
->sasl_conn
, SASL_SEC_PROPS
, &secprops
);
1093 if (rc
!= SASL_OK
) {
1094 netsec_err(errstr
, "SASL security property initialization failed: %s",
1095 sasl_errstring(rc
, NULL
, NULL
));
1100 * Start the actual protocol negotiation, and go through the
1101 * sasl_client_step() loop (after sasl_client_start, of course).
1104 rc
= sasl_client_start(nsc
->sasl_conn
,
1105 nsc
->sasl_mech
? nsc
->sasl_mech
: mechlist
, NULL
,
1106 (const char **) &saslbuf
, &saslbuflen
,
1109 if (rc
!= SASL_OK
&& rc
!= SASL_CONTINUE
) {
1110 netsec_err(errstr
, "SASL client start failed: %s",
1111 sasl_errdetail(nsc
->sasl_conn
));
1115 nsc
->sasl_chosen_mech
= getcpy(chosen_mech
);
1117 if (nsc
->sasl_proto_cb(NETSEC_SASL_START
, saslbuf
, saslbuflen
, NULL
, 0,
1122 * We've written out our first message; enter in the step loop
1125 while (rc
== SASL_CONTINUE
) {
1127 * Call our SASL callback, which will handle the details of
1128 * reading data from the network.
1131 if (nsc
->sasl_proto_cb(NETSEC_SASL_READ
, NULL
, 0, &outbuf
, &outbuflen
,
1133 nsc
->sasl_proto_cb(NETSEC_SASL_CANCEL
, NULL
, 0, NULL
, 0, NULL
);
1137 rc
= sasl_client_step(nsc
->sasl_conn
, (char *) outbuf
, outbuflen
, NULL
,
1138 (const char **) &saslbuf
, &saslbuflen
);
1143 if (rc
!= SASL_OK
&& rc
!= SASL_CONTINUE
) {
1144 netsec_err(errstr
, "SASL client negotiation failed: %s",
1145 sasl_errdetail(nsc
->sasl_conn
));
1146 nsc
->sasl_proto_cb(NETSEC_SASL_CANCEL
, NULL
, 0, NULL
, 0, NULL
);
1150 if (nsc
->sasl_proto_cb(NETSEC_SASL_WRITE
, saslbuf
, saslbuflen
,
1151 NULL
, 0, errstr
) != OK
) {
1152 nsc
->sasl_proto_cb(NETSEC_SASL_CANCEL
, NULL
, 0, NULL
, 0, NULL
);
1158 * SASL exchanges should be complete, process the final response message
1162 if (nsc
->sasl_proto_cb(NETSEC_SASL_FINISH
, NULL
, 0, NULL
, 0,
1165 * At this point we can't really send an abort since the SASL dialog
1166 * has completed, so just bubble back up the error message.
1173 * At this point, SASL should be complete. Get a few properties
1174 * from the authentication exchange.
1177 rc
= sasl_getprop(nsc
->sasl_conn
, SASL_SSF
, (const void **) &ssf
);
1179 if (rc
!= SASL_OK
) {
1180 netsec_err(errstr
, "Cannot retrieve SASL negotiated security "
1181 "strength factor: %s", sasl_errstring(rc
, NULL
, NULL
));
1185 nsc
->sasl_ssf
= *ssf
;
1187 if (nsc
->sasl_ssf
> 0) {
1188 rc
= sasl_getprop(nsc
->sasl_conn
, SASL_MAXOUTBUF
,
1189 (const void **) &outbufmax
);
1191 if (rc
!= SASL_OK
) {
1192 netsec_err(errstr
, "Cannot retrieve SASL negotiated output "
1193 "buffer size: %s", sasl_errstring(rc
, NULL
, NULL
));
1198 * If our output buffer isn't the same size as the input buffer,
1199 * reallocate it and set the new size (since we won't encode any
1200 * data larger than that).
1203 nsc
->sasl_maxbufsize
= *outbufmax
;
1205 if (nsc
->ns_outbufsize
!= nsc
->sasl_maxbufsize
) {
1206 nsc
->ns_outbufsize
= nsc
->sasl_maxbufsize
;
1207 nsc
->ns_outbuffer
= mh_xrealloc(nsc
->ns_outbuffer
,
1208 nsc
->ns_outbufsize
);
1210 * There shouldn't be any data in the buffer, but for
1211 * consistency's sake discard it.
1213 nsc
->ns_outptr
= nsc
->ns_outbuffer
;
1214 nsc
->ns_outbuflen
= 0;
1218 * Allocate a buffer to do temporary reads into, before we
1219 * call sasl_decode()
1222 nsc
->sasl_tmpbuf
= mh_xmalloc(nsc
->sasl_maxbufsize
);
1225 * Okay, this is a bit weird. Make sure that the input buffer
1226 * is at least TWICE the size of the max buffer size. That's
1227 * because if we're consuming data but want to extend the current
1228 * buffer, we want to be sure there's room for another full buffer's
1232 if (nsc
->ns_inbufsize
< nsc
->sasl_maxbufsize
* 2) {
1233 size_t offset
= nsc
->ns_inptr
- nsc
->ns_inbuffer
;
1234 nsc
->ns_inbufsize
= nsc
->sasl_maxbufsize
* 2;
1235 nsc
->ns_inbuffer
= mh_xrealloc(nsc
->ns_inbuffer
, nsc
->ns_inbufsize
);
1236 nsc
->ns_inptr
= nsc
->ns_inbuffer
+ offset
;
1239 nsc
->sasl_seclayer
= 1;
1244 netsec_err(errstr
, "SASL not supported");
1247 #endif /* CYRUS_SASL */
1251 * Retrieve our chosen SASL mechanism
1255 netsec_get_sasl_mechanism(netsec_context
*nsc
)
1258 return nsc
->sasl_chosen_mech
;
1259 #else /* CYRUS_SASL */
1261 #endif /* CYRUS_SASL */
1265 * Set an OAuth2 service name, if we support it.
1269 netsec_set_oauth_service(netsec_context
*nsc
, const char *service
)
1271 #ifdef OAUTH_SUPPORT
1272 nsc
->oauth_service
= getcpy(service
);
1274 #else /* OAUTH_SUPPORT */
1276 #endif /* OAUTH_SUPPORT */
1280 * Initialize (and enable) TLS for this connection
1284 netsec_set_tls(netsec_context
*nsc
, int tls
, char **errstr
)
1289 BIO
*sbio
, *ssl_bio
;;
1291 if (! tls_initialized
) {
1293 SSL_load_error_strings();
1296 * Create the SSL context; this has the properties for all
1297 * SSL connections (we are only doing one), though. Make sure
1298 * we only support secure (known as of now) TLS protocols.
1301 sslctx
= SSL_CTX_new(SSLv23_client_method());
1304 netsec_err(errstr
, "Unable to initialize OpenSSL context: %s",
1305 ERR_error_string(ERR_get_error(), NULL
));
1309 SSL_CTX_set_options(sslctx
, SSL_OP_NO_SSLv2
| SSL_OP_NO_SSLv3
|
1315 if (nsc
->ns_fd
== -1) {
1316 netsec_err(errstr
, "Invalid file descriptor in netsec context");
1321 * Create the SSL structure which holds the data for a single
1325 ssl
= SSL_new(sslctx
);
1328 netsec_err(errstr
, "Unable to create SSL connection: %s",
1329 ERR_error_string(ERR_get_error(), NULL
));
1334 * Never bother us, since we are using blocking sockets.
1337 SSL_set_mode(ssl
, SSL_MODE_AUTO_RETRY
);
1340 * This is a bit weird, so pay attention.
1342 * We create a socket BIO, and bind it to our SSL connection.
1343 * That means reads and writes to the SSL connection will use our
1346 * Then we create an SSL BIO, and assign our current SSL connection
1347 * to it. We then create a buffer BIO and push it in front of our
1348 * SSL BIO. So the chain looks like:
1350 * buffer BIO -> SSL BIO -> socket BIO.
1352 * So writes and reads are buffered (we mostly care about writes).
1355 sbio
= BIO_new_socket(nsc
->ns_fd
, BIO_NOCLOSE
);
1358 netsec_err(errstr
, "Unable to create a socket BIO: %s",
1359 ERR_error_string(ERR_get_error(), NULL
));
1364 SSL_set_bio(ssl
, sbio
, sbio
);
1365 SSL_set_connect_state(ssl
);
1367 nsc
->ssl_io
= BIO_new(BIO_f_buffer());
1369 if (! nsc
->ssl_io
) {
1370 netsec_err(errstr
, "Unable to create a buffer BIO: %s",
1371 ERR_error_string(ERR_get_error(), NULL
));
1376 ssl_bio
= BIO_new(BIO_f_ssl());
1379 netsec_err(errstr
, "Unable to create a SSL BIO: %s",
1380 ERR_error_string(ERR_get_error(), NULL
));
1385 BIO_set_ssl(ssl_bio
, ssl
, BIO_CLOSE
);
1386 BIO_push(nsc
->ssl_io
, ssl_bio
);
1390 BIO_free_all(nsc
->ssl_io
);
1395 #else /* TLS_SUPPORT */
1396 netsec_err(errstr
, "TLS is not supported");
1400 #endif /* TLS_SUPPORT */
1404 * Start TLS negotiation on this connection
1408 netsec_negotiate_tls(netsec_context
*nsc
, char **errstr
)
1411 if (! nsc
->ssl_io
) {
1412 netsec_err(errstr
, "TLS has not been configured for this connection");
1416 if (BIO_do_handshake(nsc
->ssl_io
) < 1) {
1417 netsec_err(errstr
, "TLS negotiation failed: %s",
1418 ERR_error_string(ERR_get_error(), NULL
));
1422 if (nsc
->ns_snoop
) {
1425 if (BIO_get_ssl(nsc
->ssl_io
, &ssl
) < 1) {
1426 fprintf(stderr
, "WARNING: cannot determine SSL ciphers\n");
1428 const SSL_CIPHER
*cipher
= SSL_get_current_cipher(ssl
);
1429 fprintf(stderr
, "TLS negotation successful: %s(%d) %s\n",
1430 SSL_CIPHER_get_name(cipher
),
1431 SSL_CIPHER_get_bits(cipher
, NULL
),
1432 SSL_CIPHER_get_version(cipher
));
1436 nsc
->tls_active
= 1;
1439 * At this point, TLS has been activated; we're not going to use
1440 * the output buffer, so free it now to save a little bit of memory.
1443 if (nsc
->ns_outbuffer
) {
1444 free(nsc
->ns_outbuffer
);
1445 nsc
->ns_outbuffer
= NULL
;
1449 #else /* TLS_SUPPORT */
1450 netsec_err(errstr
, "TLS not supported");
1453 #endif /* TLS_SUPPORT */
1457 * Generate an (allocated) error string
1461 netsec_err(char **errstr
, const char *fmt
, ...)
1465 char *errbuf
= NULL
;
1472 errbufsize
= rc
+ 1;
1473 errbuf
= mh_xrealloc(errbuf
, errbufsize
);
1475 rc
= vsnprintf(errbuf
, errbufsize
, fmt
, ap
);
1477 } while (rc
>= (int) errbufsize
);