]> diplodocus.org Git - nmh/blob - sbr/netsec.c
3a1f60d441aab8636337312e199aa11ca8f129dc
[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 <stdarg.h>
15
16 #ifdef CYRUS_SASL
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 */
26
27 static int netsec_get_user(void *context, int id, const char **result,
28 unsigned int *len);
29 static int netsec_get_password(sasl_conn_t *conn, void *context, int id,
30 sasl_secret_t **psecret);
31
32 static int sasl_initialized = 0;
33
34 #define SASL_MAXRECVBUF 65536
35 #endif /* CYRUS_SASL */
36
37 #ifdef TLS_SUPPORT
38 #include <openssl/ssl.h>
39 #include <openssl/err.h>
40
41 static int tls_initialized = 0;
42 static SSL_CTX *sslctx = NULL; /* SSL Context */
43
44 #endif /* TLS_SUPPORT */
45
46 /*
47 * Our context structure, which holds all of the relevant information
48 * about a connection.
49 */
50
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 */
63 #ifdef CYRUS_SASL
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 */
75 #ifdef TLS_SUPPORT
76 BIO *ssl_io; /* BIO used for connection I/O */
77 int tls_active; /* If true, TLS is running */
78 #endif /* TLS_SUPPORT */
79 };
80
81 /*
82 * Function to allocate error message strings
83 */
84
85 static void netsec_err(char **errstr, const char *format, ...);
86
87 /*
88 * How this code works, in general.
89 *
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.
93 *
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.
97 *
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).
101 */
102
103 /*
104 * Allocate and initialize our security context
105 */
106
107 netsec_context *
108 netsec_init(void)
109 {
110 netsec_context *nsc = mh_xmalloc(sizeof(*nsc));
111
112 nsc->ns_fd = -1;
113 nsc->ns_snoop = 0;
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;
119 #ifdef CYRUS_SASL
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 */
128 #ifdef TLS_SUPPORT
129 nsc->ssl_io = NULL;
130 nsc->tls_active = 0;
131 #endif /* TLS_SUPPORT */
132 return nsc;
133 }
134
135 /*
136 * Shutdown the connection completely and free all resources.
137 * The connection is not closed, however.
138 */
139
140 void
141 netsec_shutdown(netsec_context *nsc)
142 {
143 if (nsc->ns_userid)
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);
149 #ifdef CYRUS_SASL
150 if (nsc->sasl_conn)
151 sasl_dispose(&nsc->sasl_conn);
152 if (nsc->sasl_hostname)
153 free(nsc->sasl_hostname);
154 if (nsc->sasl_mech)
155 free(nsc->sasl_mech);
156 if (nsc->sasl_cbs)
157 free(nsc->sasl_cbs);
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);
163 }
164 if (nsc->sasl_secret) {
165 if (nsc->sasl_secret->len > 0) {
166 memset(nsc->sasl_secret->data, 0, nsc->sasl_secret->len);
167 }
168 free(nsc->sasl_secret);
169 }
170 if (nsc->sasl_chosen_mech)
171 free(nsc->sasl_chosen_mech);
172 #endif /* CYRUS_SASL */
173 #ifdef TLS_SUPPORT
174 if (nsc->ssl_io)
175 /*
176 * I checked; BIO_free_all() will cause SSL_shutdown to be called
177 * on the SSL object in the chain.
178 */
179 BIO_free_all(nsc->ssl_io);
180 #endif /* TLS_SUPPORT */
181
182 free(nsc);
183 }
184
185 /*
186 * Set the file descriptor for our context
187 */
188
189 void
190 netsec_set_fd(netsec_context *nsc, int fd)
191 {
192 nsc->ns_fd = fd;
193 }
194
195 /*
196 * Set the userid used for authentication for this context
197 */
198
199 void
200 netsec_set_userid(netsec_context *nsc, const char *userid)
201 {
202 nsc->ns_userid = getcpy(userid);
203 }
204
205 /*
206 * Set the snoop flag for this connection
207 */
208
209 void
210 netsec_set_snoop(netsec_context *nsc, int snoop)
211 {
212 nsc->ns_snoop = snoop;
213 }
214
215 /*
216 * Set various SASL protocol parameters
217 */
218
219 int
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)
223 {
224 #ifdef CYRUS_SASL
225 sasl_callback_t *sasl_cbs;
226 int retval;
227
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));
233 return NOTOK;
234 }
235 sasl_initialized++;
236 }
237
238 /*
239 * Allocate an array of SASL callbacks for this connection.
240 * Right now we just allocate an array of four callbacks.
241 */
242
243 sasl_cbs = mh_xmalloc(sizeof(*sasl_cbs) * 4);
244
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;
248
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;
252
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;
256
257 sasl_cbs[3].id = SASL_CB_LIST_END;
258 sasl_cbs[3].proc = NULL;
259 sasl_cbs[3].context = NULL;
260
261 nsc->sasl_cbs = sasl_cbs;
262
263 retval = sasl_client_new(service, hostname, NULL, NULL, nsc->sasl_cbs, 0,
264 &nsc->sasl_conn);
265
266 if (retval) {
267 netsec_err(errstr, "SASL new client allocation failed: %s",
268 sasl_errstring(retval, NULL, NULL));
269 return NOTOK;
270 }
271
272 nsc->sasl_mech = mechanism ? getcpy(mechanism) : NULL;
273 nsc->sasl_proto_cb = callback;
274 nsc->sasl_hostname = getcpy(hostname);
275
276 return OK;
277 #else /* CYRUS_SASL */
278 netsec_err(errstr, "SASL is not supported");
279
280 return NOTOK;
281 #endif /* CYRUS_SASL */
282 }
283
284 #ifdef CYRUS_SASL
285 /*
286 * Our userid callback; return the specified username to the SASL
287 * library when asked.
288 */
289
290 int netsec_get_user(void *context, int id, const char **result,
291 unsigned int *len)
292 {
293 netsec_context *nsc = (netsec_context *) context;
294
295 if (! result || (id != SASL_CB_USER && id != SASL_CB_AUTHNAME))
296 return SASL_BADPARAM;
297
298 if (nsc->ns_userid == NULL) {
299 /*
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.
305 */
306
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;
311 }
312
313 if (nmh_get_credentials(nsc->sasl_hostname, nsc->ns_userid, 1,
314 nsc->sasl_creds) != OK)
315 return SASL_BADPARAM;
316
317 if (nsc->ns_userid != nsc->sasl_creds->user) {
318 if (nsc->ns_userid)
319 free(nsc->ns_userid);
320 nsc->ns_userid = getcpy(nsc->sasl_creds->user);
321 }
322 }
323
324 *result = nsc->ns_userid;
325 if (len)
326 *len = strlen(nsc->ns_userid);
327
328 return SASL_OK;
329 }
330
331 /*
332 * Retrieve a password and return it to SASL
333 */
334
335 static int
336 netsec_get_password(sasl_conn_t *conn, void *context, int id,
337 sasl_secret_t **psecret)
338 {
339 netsec_context *nsc = (netsec_context *) context;
340 int len;
341
342 NMH_UNUSED(conn);
343
344 if (! psecret || id != SASL_CB_PASS)
345 return SASL_BADPARAM;
346
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;
351 }
352
353 if (nsc->sasl_creds->password == NULL) {
354 /*
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.
359 */
360
361 if (nmh_get_credentials(nsc->sasl_hostname, nsc->ns_userid, 0,
362 nsc->sasl_creds) != OK) {
363 return SASL_BADPARAM;
364 }
365 }
366
367 len = strlen(nsc->sasl_creds->password);
368
369 /*
370 * sasl_secret_t includes 1 bytes for "data" already, so that leaves
371 * us room for a terminating NUL
372 */
373
374 *psecret = (sasl_secret_t *) malloc(sizeof(sasl_secret_t) + len);
375
376 if (! *psecret)
377 return SASL_NOMEM;
378
379 (*psecret)->len = len;
380 strcpy((char *) (*psecret)->data, nsc->sasl_creds->password);
381
382 nsc->sasl_secret = *psecret;
383
384 return SASL_OK;
385 }
386 #endif /* CYRUS_SASL */
387
388 /*
389 * Negotiate SASL on this connection
390 */
391
392 int
393 netsec_negotiate_sasl(netsec_context *nsc, const char *mechlist, char **errstr)
394 {
395 #ifdef CYRUS_SASL
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;
401 sasl_ssf_t *ssf;
402 int rc;
403
404 /*
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
408 * messages.
409 */
410
411 memset(&secprops, 0, sizeof(secprops));
412 secprops.maxbufsize = SASL_MAXRECVBUF;
413
414 /*
415 * If we're using TLS, do not negotiate a security layer
416 */
417
418 secprops.max_ssf =
419 #ifdef TLS_SUPPORT
420 nsc->tls_active ? 0 :
421 #endif /* TLS_SUPPORT */
422 UINT_MAX;
423
424 rc = sasl_setprop(nsc->sasl_conn, SASL_SEC_PROPS, &secprops);
425
426 if (rc != SASL_OK) {
427 netsec_err(errstr, "SASL security property initialization failed: %s",
428 sasl_errstring(rc, NULL, NULL));
429 return NOTOK;
430 }
431
432 /*
433 * Start the actual protocol negotiation, and go through the
434 * sasl_client_step() loop (after sasl_client_start, of course).
435 */
436
437 rc = sasl_client_start(nsc->sasl_conn, mechlist, NULL,
438 (const unsigned char **) &saslbuf, &saslbuflen,
439 &chosen_mech);
440
441 if (rc != SASL_OK && rc != SASL_CONTINUE) {
442 netsec_err(errstr, "SASL client start failed: %s",
443 sasl_errdetail(nsc->sasl_conn));
444 return NOTOK;
445 }
446
447 nsc->sasl_chosen_mech = getcpy(chosen_mech);
448
449 if (nsc->sasl_proto_cb(NETSEC_SASL_START, saslbuf, saslbuflen, &outbuf,
450 &outbuflen, nsc->ns_snoop, errstr) != OK)
451 return NOTOK;
452
453 if (netsec_write(nsc, outbuf, outbuflen, errstr) != OK) {
454 free(outbuf);
455 return NOTOK;
456 }
457
458 free(outbuf);
459
460 if (netsec_flush(nsc, errstr) != OK)
461 return NOTOK;
462
463 /*
464 * We've written out our first message; enter in the step loop
465 */
466
467 while (rc == SASL_CONTINUE) {
468 /*
469 * Call our SASL callback, which will handle the details of
470 * reading data from the network.
471 */
472
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);
479 }
480 return NOTOK;
481 }
482
483 rc = sasl_client_step(nsc->sasl_conn, outbuf, outbuflen, NULL,
484 &saslbuf, &saslbuflen);
485 }
486
487 return OK;
488 #else
489 netsec_err(errstr, "SASL not supported");
490
491 return NOTOK;
492 #endif /* CYRUS_SASL */
493 }
494
495 /*
496 * Retrieve our chosen SASL mechanism
497 */
498
499 char *
500 netsec_get_sasl_mechanism(netsec_context *nsc)
501 {
502 #ifdef CYRUS_SASL
503 return nsc->sasl_chosen_mech;
504 #else /* CYRUS_SASL */
505 return NULL;
506 #endif /* CYRUS_SASL */
507 }
508
509 /*
510 * Initialize (and enable) TLS for this connection
511 */
512
513 int
514 netsec_set_tls(netsec_context *nsc, int tls, char **errstr)
515 {
516 if (tls) {
517 #ifdef TLS_SUPPORT
518 SSL *ssl;
519 BIO *sbio, *ssl_bio;;
520
521 if (! tls_initialized) {
522 SSL_library_init();
523 SSL_load_error_strings();
524
525 /*
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.
529 */
530
531 sslctx = SSL_CTX_new(SSLv23_client_method());
532
533 if (! sslctx) {
534 netsec_err(errstr, "Unable to initialize OpenSSL context: %s",
535 ERR_error_string(ERR_get_error(), NULL));
536 return NOTOK;
537 }
538
539 SSL_CTX_set_options(sslctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
540 SSL_OP_NO_TLSv1);
541
542 tls_initialized++;
543 }
544
545 if (nsc->ns_fd == -1) {
546 netsec_err(errstr, "Invalid file descriptor in netsec context");
547 return NOTOK;
548 }
549
550 /*
551 * Create the SSL structure which holds the data for a single
552 * TLS connection.
553 */
554
555 ssl = SSL_new(sslctx);
556
557 if (! ssl) {
558 netsec_err(errstr, "Unable to create SSL connection: %s",
559 ERR_error_string(ERR_get_error(), NULL));
560 return NOTOK;
561 }
562
563 /*
564 * This is a bit weird, so pay attention.
565 *
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
568 * supplied socket.
569 *
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:
573 *
574 * buffer BIO -> SSL BIO -> socket BIO.
575 *
576 * So writes and reads are buffered (we mostly care about writes).
577 */
578
579 sbio = BIO_new_socket(nsc->ns_fd, BIO_NOCLOSE);
580
581 if (! sbio) {
582 netsec_err(errstr, "Unable to create a socket BIO: %s",
583 ERR_error_string(ERR_get_error(), NULL));
584 SSL_free(ssl);
585 return NOTOK;
586 }
587
588 SSL_set_bio(ssl, sbio, sbio);
589 SSL_set_connect_state(ssl);
590
591 nsc->ssl_io = BIO_new(BIO_f_buffer());
592
593 if (! nsc->ssl_io) {
594 netsec_err(errstr, "Unable to create a buffer BIO: %s",
595 ERR_error_string(ERR_get_error(), NULL));
596 SSL_free(ssl);
597 return NOTOK;
598 }
599
600 ssl_bio = BIO_new(BIO_f_ssl());
601
602 if (! ssl_bio) {
603 netsec_err(errstr, "Unable to create a SSL BIO: %s",
604 ERR_error_string(ERR_get_error(), NULL));
605 SSL_free(ssl);
606 return NOTOK;
607 }
608
609 BIO_set_ssl(ssl_bio, ssl, BIO_CLOSE);
610 BIO_push(nsc->ssl_io, ssl_bio);
611
612 return OK;
613 } else {
614 BIO_free_all(nsc->ssl_io);
615 nsc->ssl_io = NULL;
616
617 return OK;
618 }
619 #else /* TLS_SUPPORT */
620 netsec_err(errstr, "TLS is not supported");
621
622 return NOTOK;
623 }
624 #endif /* TLS_SUPPORT */
625 }
626
627 /*
628 * Start TLS negotiation on this connection
629 */
630
631 int
632 netsec_negotiate_tls(netsec_context *nsc, char **errstr)
633 {
634 #ifdef TLS_SUPPORT
635 if (! nsc->ssl_io) {
636 netsec_err(errstr, "TLS has not been configured for this connection");
637 return NOTOK;
638 }
639
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));
643 return NOTOK;
644 }
645
646 if (nsc->ns_snoop) {
647 SSL *ssl;
648
649 if (BIO_get_ssl(nsc->ssl_io, &ssl) < 1) {
650 fprintf(stderr, "WARNING: cannot determine SSL ciphers\n");
651 } else {
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));
657 }
658 }
659
660 nsc->tls_active = 1;
661
662 return OK;
663 #else /* TLS_SUPPORT */
664 netsec_err(errstr, "TLS not supported");
665
666 return NOTOK;
667 #endif /* TLS_SUPPORT */
668 }
669
670 /*
671 * Generate an (allocated) error string
672 */
673
674 static void
675 netsec_err(char **errstr, const char *fmt, ...)
676 {
677 va_list ap;
678 size_t errbufsize;
679 char *errbuf = NULL;
680 int rc = 127;
681
682 if (! errstr)
683 return;
684
685 do {
686 errbufsize = rc + 1;
687 errbuf = mh_xrealloc(errbuf, errbufsize);
688 va_start(ap, fmt);
689 rc = vsnprintf(errbuf, errbufsize, fmt, ap);
690 va_end(ap);
691 } while (rc >= (int) errbufsize);
692
693 *errstr = errbuf;
694 }