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.
17 #include <sasl/sasl.h>
18 #include <sasl/saslutil.h>
19 # if SASL_VERSION_FULL < 0x020125
20 /* Cyrus SASL 2.1.25 introduced the sasl_callback_ft prototype,
21 which has an explicit void parameter list, according to best
22 practice. So we need to cast to avoid compile warnings.
23 Provide this prototype for earlier versions. */
24 typedef int (*sasl_callback_ft
)();
25 # endif /* SASL_VERSION_FULL < 0x020125 */
27 static int netsec_get_user(void *context
, int id
, const char **result
,
29 static int netsec_get_password(sasl_conn_t
*conn
, void *context
, int id
,
30 sasl_secret_t
**psecret
);
32 static int sasl_initialized
= 0;
34 #define SASL_MAXRECVBUF 65536
35 #endif /* CYRUS_SASL */
38 #include <openssl/ssl.h>
39 #include <openssl/err.h>
41 static int tls_initialized
= 0;
42 static SSL_CTX
*sslctx
= NULL
; /* SSL Context */
44 #endif /* TLS_SUPPORT */
47 * Our context structure, which holds all of the relevant information
51 struct _netsec_context
{
52 int ns_fd
; /* Descriptor for network connection */
53 int ns_snoop
; /* If true, display network data */
54 char *ns_userid
; /* Userid for authentication */
55 unsigned char *ns_inbuffer
; /* Our read input buffer */
56 unsigned char *ns_inptr
; /* Our read buffer input pointer */
57 unsigned int ns_inbuflen
; /* Length of data in input buffer */
58 unsigned int ns_inbufsize
; /* Size of input buffer */
59 unsigned char *ns_outbuffer
;/* Output buffer */
60 unsigned char *ns_outptr
; /* Output buffer pointer */
61 unsigned int ns_outbuflen
; /* Output buffer data length */
62 unsigned int ns_outbufsize
; /* Output buffer size */
64 char *sasl_hostname
; /* Hostname we've connected to */
65 char *sasl_mech
; /* User-requested mechanism */
66 sasl_conn_t
*sasl_conn
; /* SASL connection context */
67 sasl_ssf_t sasl_ssf
; /* SASL Security Strength Factor */
68 netsec_sasl_callback sasl_proto_cb
; /* SASL callback we use */
69 sasl_callback_t
*sasl_cbs
; /* Callbacks used by SASL */
70 nmh_creds_t sasl_creds
; /* Credentials (username/password) */
71 sasl_secret_t
*sasl_secret
; /* SASL password structure */
72 char *sasl_chosen_mech
; /* Mechanism chosen by SASL */
73 int sasl_enabled
; /* If true, SASL is enabled */
74 #endif /* CYRUS_SASL */
76 BIO
*ssl_io
; /* BIO used for connection I/O */
77 int tls_active
; /* If true, TLS is running */
78 #endif /* TLS_SUPPORT */
82 * Function to allocate error message strings
85 static void netsec_err(char **errstr
, const char *format
, ...);
88 * How this code works, in general.
90 * _If_ we are using no encryption or SASL encryption, then we buffer the
91 * network data through ns_inbuffer and ns_outbuffer. That should be
92 * relatively self-explanatory.
94 * If we are using SSL for encryption, then use a buffering BIO for output
95 * (that just easier). Still do buffering for reads; when we need more
96 * data we call the BIO_read() function to fill our local buffer.
98 * For SASL, we make use of (for now) the Cyrus-SASL library. For some
99 * mechanisms, we implement those mechanisms directly since the Cyrus SASL
100 * library doesn't support them (like OAuth).
104 * Allocate and initialize our security context
110 netsec_context
*nsc
= mh_xmalloc(sizeof(*nsc
));
114 nsc
->ns_userid
= NULL
;
115 nsc
->ns_inbuffer
= nsc
->ns_inptr
= NULL
;
116 nsc
->ns_inbuflen
= nsc
->ns_inbufsize
= 0;
117 nsc
->ns_outbuffer
= nsc
->ns_outptr
= NULL
;
118 nsc
->ns_outbuflen
= nsc
->ns_outbufsize
= 0;
120 nsc
->sasl_conn
= NULL
;
121 nsc
->sasl_hostname
= NULL
;
122 nsc
->sasl_mech
= NULL
;
123 nsc
->sasl_cbs
= NULL
;
124 nsc
->sasl_creds
= NULL
;
125 nsc
->sasl_secret
= NULL
;
126 nsc
->sasl_chosen_mech
= NULL
;
127 #endif /* CYRUS_SASL */
131 #endif /* TLS_SUPPORT */
136 * Shutdown the connection completely and free all resources.
137 * The connection is not closed, however.
141 netsec_shutdown(netsec_context
*nsc
)
144 free(nsc
->ns_userid
);
145 if (nsc
->ns_inbuffer
)
146 free(nsc
->ns_inbuffer
);
147 if (nsc
->ns_outbuffer
)
148 free(nsc
->ns_outbuffer
);
151 sasl_dispose(&nsc
->sasl_conn
);
152 if (nsc
->sasl_hostname
)
153 free(nsc
->sasl_hostname
);
155 free(nsc
->sasl_mech
);
158 if (nsc
->sasl_creds
) {
159 if (nsc
->sasl_creds
->password
)
160 memset(nsc
->sasl_creds
->password
, 0,
161 strlen(nsc
->sasl_creds
->password
));
162 free(nsc
->sasl_creds
);
164 if (nsc
->sasl_secret
) {
165 if (nsc
->sasl_secret
->len
> 0) {
166 memset(nsc
->sasl_secret
->data
, 0, nsc
->sasl_secret
->len
);
168 free(nsc
->sasl_secret
);
170 if (nsc
->sasl_chosen_mech
)
171 free(nsc
->sasl_chosen_mech
);
172 #endif /* CYRUS_SASL */
176 * I checked; BIO_free_all() will cause SSL_shutdown to be called
177 * on the SSL object in the chain.
179 BIO_free_all(nsc
->ssl_io
);
180 #endif /* TLS_SUPPORT */
186 * Set the file descriptor for our context
190 netsec_set_fd(netsec_context
*nsc
, int fd
)
196 * Set the userid used for authentication for this context
200 netsec_set_userid(netsec_context
*nsc
, const char *userid
)
202 nsc
->ns_userid
= getcpy(userid
);
206 * Set the snoop flag for this connection
210 netsec_set_snoop(netsec_context
*nsc
, int snoop
)
212 nsc
->ns_snoop
= snoop
;
216 * Set various SASL protocol parameters
220 netsec_set_sasl_params(netsec_context
*nsc
, const char *hostname
,
221 const char *service
, const char *mechanism
,
222 netsec_sasl_callback callback
, char **errstr
)
225 sasl_callback_t
*sasl_cbs
;
228 if (! sasl_initialized
) {
229 retval
= sasl_client_init(NULL
);
230 if (retval
!= SASL_OK
) {
231 netsec_err(errstr
, "SASL client initialization failed: %s",
232 sasl_errstring(retval
, NULL
, NULL
));
239 * Allocate an array of SASL callbacks for this connection.
240 * Right now we just allocate an array of four callbacks.
243 sasl_cbs
= mh_xmalloc(sizeof(*sasl_cbs
) * 4);
245 sasl_cbs
[0].id
= SASL_CB_USER
;
246 sasl_cbs
[0].proc
= (sasl_callback_ft
) netsec_get_user
;
247 sasl_cbs
[0].context
= nsc
;
249 sasl_cbs
[1].id
= SASL_CB_AUTHNAME
;
250 sasl_cbs
[1].proc
= (sasl_callback_ft
) netsec_get_user
;
251 sasl_cbs
[1].context
= nsc
;
253 sasl_cbs
[2].id
= SASL_CB_PASS
;
254 sasl_cbs
[2].proc
= (sasl_callback_ft
) netsec_get_password
;
255 sasl_cbs
[2].context
= nsc
;
257 sasl_cbs
[3].id
= SASL_CB_LIST_END
;
258 sasl_cbs
[3].proc
= NULL
;
259 sasl_cbs
[3].context
= NULL
;
261 nsc
->sasl_cbs
= sasl_cbs
;
263 retval
= sasl_client_new(service
, hostname
, NULL
, NULL
, nsc
->sasl_cbs
, 0,
267 netsec_err(errstr
, "SASL new client allocation failed: %s",
268 sasl_errstring(retval
, NULL
, NULL
));
272 nsc
->sasl_mech
= mechanism
? getcpy(mechanism
) : NULL
;
273 nsc
->sasl_proto_cb
= callback
;
274 nsc
->sasl_hostname
= getcpy(hostname
);
277 #else /* CYRUS_SASL */
278 netsec_err(errstr
, "SASL is not supported");
281 #endif /* CYRUS_SASL */
286 * Our userid callback; return the specified username to the SASL
287 * library when asked.
290 int netsec_get_user(void *context
, int id
, const char **result
,
293 netsec_context
*nsc
= (netsec_context
*) context
;
295 if (! result
|| (id
!= SASL_CB_USER
&& id
!= SASL_CB_AUTHNAME
))
296 return SASL_BADPARAM
;
298 if (nsc
->ns_userid
== NULL
) {
300 * Pass the 1 third argument to nmh_get_credentials() so that
301 * a defauly user if the -user switch wasn't supplied, and so
302 * that a default password will be supplied. That's used when
303 * those values really don't matter, and only with legacy/.netrc,
304 * i.e., with a credentials profile entry.
307 if (nsc
->sasl_creds
== NULL
) {
308 nsc
->sasl_creds
= mh_xmalloc(sizeof(*nsc
->sasl_creds
));
309 nsc
->sasl_creds
->user
= NULL
;
310 nsc
->sasl_creds
->password
= NULL
;
313 if (nmh_get_credentials(nsc
->sasl_hostname
, nsc
->ns_userid
, 1,
314 nsc
->sasl_creds
) != OK
)
315 return SASL_BADPARAM
;
317 if (nsc
->ns_userid
!= nsc
->sasl_creds
->user
) {
319 free(nsc
->ns_userid
);
320 nsc
->ns_userid
= getcpy(nsc
->sasl_creds
->user
);
324 *result
= nsc
->ns_userid
;
326 *len
= strlen(nsc
->ns_userid
);
332 * Retrieve a password and return it to SASL
336 netsec_get_password(sasl_conn_t
*conn
, void *context
, int id
,
337 sasl_secret_t
**psecret
)
339 netsec_context
*nsc
= (netsec_context
*) context
;
344 if (! psecret
|| id
!= SASL_CB_PASS
)
345 return SASL_BADPARAM
;
347 if (nsc
->sasl_creds
== NULL
) {
348 nsc
->sasl_creds
= mh_xmalloc(sizeof(*nsc
->sasl_creds
));
349 nsc
->sasl_creds
->user
= NULL
;
350 nsc
->sasl_creds
->password
= NULL
;
353 if (nsc
->sasl_creds
->password
== NULL
) {
355 * Pass the 0 third argument to nmh_get_credentials() so
356 * that the default password isn't used. With legacy/.netrc
357 * credentials support, we'll only get here if the -user
358 * switch to send(1)/post(8) wasn't used.
361 if (nmh_get_credentials(nsc
->sasl_hostname
, nsc
->ns_userid
, 0,
362 nsc
->sasl_creds
) != OK
) {
363 return SASL_BADPARAM
;
367 len
= strlen(nsc
->sasl_creds
->password
);
370 * sasl_secret_t includes 1 bytes for "data" already, so that leaves
371 * us room for a terminating NUL
374 *psecret
= (sasl_secret_t
*) malloc(sizeof(sasl_secret_t
) + len
);
379 (*psecret
)->len
= len
;
380 strcpy((char *) (*psecret
)->data
, nsc
->sasl_creds
->password
);
382 nsc
->sasl_secret
= *psecret
;
386 #endif /* CYRUS_SASL */
389 * Negotiate SASL on this connection
393 netsec_negotiate_sasl(netsec_context
*nsc
, const char *mechlist
, char **errstr
)
396 sasl_security_properties_t secprops
;
397 const char *chosen_mech
;
398 const unsigned char *saslbuf
;
399 unsigned char *outbuf
;
400 unsigned int saslbuflen
, outbuflen
;
405 * In netsec_set_sasl_params, we've already done all of our setup with
406 * sasl_client_init() and sasl_client_new(). So time to set security
407 * properties, call sasl_client_start(), and generate the protocol
411 memset(&secprops
, 0, sizeof(secprops
));
412 secprops
.maxbufsize
= SASL_MAXRECVBUF
;
415 * If we're using TLS, do not negotiate a security layer
420 nsc
->tls_active
? 0 :
421 #endif /* TLS_SUPPORT */
424 rc
= sasl_setprop(nsc
->sasl_conn
, SASL_SEC_PROPS
, &secprops
);
427 netsec_err(errstr
, "SASL security property initialization failed: %s",
428 sasl_errstring(rc
, NULL
, NULL
));
433 * Start the actual protocol negotiation, and go through the
434 * sasl_client_step() loop (after sasl_client_start, of course).
437 rc
= sasl_client_start(nsc
->sasl_conn
, mechlist
, NULL
,
438 (const unsigned char **) &saslbuf
, &saslbuflen
,
441 if (rc
!= SASL_OK
&& rc
!= SASL_CONTINUE
) {
442 netsec_err(errstr
, "SASL client start failed: %s",
443 sasl_errdetail(nsc
->sasl_conn
));
447 nsc
->sasl_chosen_mech
= getcpy(chosen_mech
);
449 if (nsc
->sasl_proto_cb(NETSEC_SASL_START
, saslbuf
, saslbuflen
, &outbuf
,
450 &outbuflen
, nsc
->ns_snoop
, errstr
) != OK
)
453 if (netsec_write(nsc
, outbuf
, outbuflen
, errstr
) != OK
) {
460 if (netsec_flush(nsc
, errstr
) != OK
)
464 * We've written out our first message; enter in the step loop
467 while (rc
== SASL_CONTINUE
) {
469 * Call our SASL callback, which will handle the details of
470 * reading data from the network.
473 if (nsc
->sasl_proto_cb(NETSEC_SASL_READ
, NULL
, 0, &outbuf
, &outbuflen
,
474 nsc
->ns_snoop
, errstr
) != OK
) {
475 if (nsc
->sasl_proto_cb(NETSEC_SASL_CANCEL
, NULL
, 0, &outbuf
,
476 &outbuflen
, nsc
->ns_snoop
, NULL
) == OK
) {
477 netsec_write(nsc
, outbuf
, outbuflen
, NULL
);
478 netsec_flush(nsc
, NULL
);
483 rc
= sasl_client_step(nsc
->sasl_conn
, outbuf
, outbuflen
, NULL
,
484 &saslbuf
, &saslbuflen
);
489 netsec_err(errstr
, "SASL not supported");
492 #endif /* CYRUS_SASL */
496 * Retrieve our chosen SASL mechanism
500 netsec_get_sasl_mechanism(netsec_context
*nsc
)
503 return nsc
->sasl_chosen_mech
;
504 #else /* CYRUS_SASL */
506 #endif /* CYRUS_SASL */
510 * Initialize (and enable) TLS for this connection
514 netsec_set_tls(netsec_context
*nsc
, int tls
, char **errstr
)
519 BIO
*sbio
, *ssl_bio
;;
521 if (! tls_initialized
) {
523 SSL_load_error_strings();
526 * Create the SSL context; this has the properties for all
527 * SSL connections (we are only doing one), though. Make sure
528 * we only support secure (known as of now) TLS protocols.
531 sslctx
= SSL_CTX_new(SSLv23_client_method());
534 netsec_err(errstr
, "Unable to initialize OpenSSL context: %s",
535 ERR_error_string(ERR_get_error(), NULL
));
539 SSL_CTX_set_options(sslctx
, SSL_OP_NO_SSLv2
| SSL_OP_NO_SSLv3
|
545 if (nsc
->ns_fd
== -1) {
546 netsec_err(errstr
, "Invalid file descriptor in netsec context");
551 * Create the SSL structure which holds the data for a single
555 ssl
= SSL_new(sslctx
);
558 netsec_err(errstr
, "Unable to create SSL connection: %s",
559 ERR_error_string(ERR_get_error(), NULL
));
564 * This is a bit weird, so pay attention.
566 * We create a socket BIO, and bind it to our SSL connection.
567 * That means reads and writes to the SSL connection will use our
570 * Then we create an SSL BIO, and assign our current SSL connection
571 * to it. We then create a buffer BIO and push it in front of our
572 * SSL BIO. So the chain looks like:
574 * buffer BIO -> SSL BIO -> socket BIO.
576 * So writes and reads are buffered (we mostly care about writes).
579 sbio
= BIO_new_socket(nsc
->ns_fd
, BIO_NOCLOSE
);
582 netsec_err(errstr
, "Unable to create a socket BIO: %s",
583 ERR_error_string(ERR_get_error(), NULL
));
588 SSL_set_bio(ssl
, sbio
, sbio
);
589 SSL_set_connect_state(ssl
);
591 nsc
->ssl_io
= BIO_new(BIO_f_buffer());
594 netsec_err(errstr
, "Unable to create a buffer BIO: %s",
595 ERR_error_string(ERR_get_error(), NULL
));
600 ssl_bio
= BIO_new(BIO_f_ssl());
603 netsec_err(errstr
, "Unable to create a SSL BIO: %s",
604 ERR_error_string(ERR_get_error(), NULL
));
609 BIO_set_ssl(ssl_bio
, ssl
, BIO_CLOSE
);
610 BIO_push(nsc
->ssl_io
, ssl_bio
);
614 BIO_free_all(nsc
->ssl_io
);
619 #else /* TLS_SUPPORT */
620 netsec_err(errstr
, "TLS is not supported");
624 #endif /* TLS_SUPPORT */
628 * Start TLS negotiation on this connection
632 netsec_negotiate_tls(netsec_context
*nsc
, char **errstr
)
636 netsec_err(errstr
, "TLS has not been configured for this connection");
640 if (BIO_do_handshake(nsc
->ssl_io
) < 1) {
641 netsec_err(errstr
, "TLS negotiation failed: %s",
642 ERR_error_string(ERR_get_error(), NULL
));
649 if (BIO_get_ssl(nsc
->ssl_io
, &ssl
) < 1) {
650 fprintf(stderr
, "WARNING: cannot determine SSL ciphers\n");
652 const SSL_CIPHER
*cipher
= SSL_get_current_cipher(ssl
);
653 fprintf(stderr
, "TLS negotation successful: %s(%d) %s\n",
654 SSL_CIPHER_get_name(cipher
),
655 SSL_CIPHER_get_bits(cipher
, NULL
),
656 SSL_CIPHER_get_version(cipher
));
663 #else /* TLS_SUPPORT */
664 netsec_err(errstr
, "TLS not supported");
667 #endif /* TLS_SUPPORT */
671 * Generate an (allocated) error string
675 netsec_err(char **errstr
, const char *fmt
, ...)
687 errbuf
= mh_xrealloc(errbuf
, errbufsize
);
689 rc
= vsnprintf(errbuf
, errbufsize
, fmt
, ap
);
691 } while (rc
>= (int) errbufsize
);