xref: /freebsd/contrib/wpa/src/crypto/tls_wolfssl.c (revision 9768746b)
1 /*
2  * SSL/TLS interface functions for wolfSSL TLS case
3  * Copyright (c) 2004-2017, Jouni Malinen <j@w1.fi>
4  *
5  * This software may be distributed under the terms of the BSD license.
6  * See README for more details.
7  */
8 
9 #include "includes.h"
10 
11 #include "common.h"
12 #include "crypto.h"
13 #include "crypto/sha1.h"
14 #include "crypto/sha256.h"
15 #include "tls.h"
16 
17 /* wolfSSL includes */
18 #include <wolfssl/options.h>
19 #include <wolfssl/ssl.h>
20 #include <wolfssl/error-ssl.h>
21 #include <wolfssl/wolfcrypt/asn.h>
22 #include <wolfssl/openssl/x509v3.h>
23 
24 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
25 #define HAVE_AESGCM
26 #include <wolfssl/wolfcrypt/aes.h>
27 #endif
28 
29 #if !defined(CONFIG_FIPS) &&                             \
30     (defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) ||   \
31      defined(EAP_SERVER_FAST))
32 #define WOLFSSL_NEED_EAP_FAST_PRF
33 #endif
34 
35 #define SECRET_LEN          48
36 #define RAN_LEN             32
37 #define SESSION_TICKET_LEN  256
38 
39 static int tls_ref_count = 0;
40 
41 static int tls_ex_idx_session = 0;
42 
43 
44 /* tls input data for wolfSSL Read Callback */
45 struct tls_in_data {
46 	const struct wpabuf *in_data;
47 	size_t consumed; /* how many bytes have we used already */
48 };
49 
50 /* tls output data for wolfSSL Write Callback */
51 struct tls_out_data {
52 	struct wpabuf *out_data;
53 };
54 
55 struct tls_context {
56 	void (*event_cb)(void *ctx, enum tls_event ev,
57 			 union tls_event_data *data);
58 	void *cb_ctx;
59 	int cert_in_cb;
60 	char *ocsp_stapling_response;
61 };
62 
63 static struct tls_context *tls_global = NULL;
64 
65 /* wolfssl tls_connection */
66 struct tls_connection {
67 	struct tls_context *context;
68 	WOLFSSL *ssl;
69 	int read_alerts;
70 	int write_alerts;
71 	int failed;
72 	struct tls_in_data input;
73 	struct tls_out_data output;
74 	char *subject_match;
75 	char *alt_subject_match;
76 	char *suffix_match;
77 	char *domain_match;
78 
79 	u8 srv_cert_hash[32];
80 
81 	unsigned char client_random[RAN_LEN];
82 	unsigned char server_random[RAN_LEN];
83 	unsigned int flags;
84 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
85 	tls_session_ticket_cb session_ticket_cb;
86 	void *session_ticket_cb_ctx;
87 	byte session_ticket[SESSION_TICKET_LEN];
88 #endif
89 	unsigned int ca_cert_verify:1;
90 	unsigned int cert_probe:1;
91 	unsigned int server_cert_only:1;
92 	unsigned int success_data:1;
93 
94 	WOLFSSL_X509 *peer_cert;
95 	WOLFSSL_X509 *peer_issuer;
96 	WOLFSSL_X509 *peer_issuer_issuer;
97 };
98 
99 
100 static struct tls_context * tls_context_new(const struct tls_config *conf)
101 {
102 	struct tls_context *context = os_zalloc(sizeof(*context));
103 
104 	if (!context)
105 		return NULL;
106 
107 	if (conf) {
108 		context->event_cb = conf->event_cb;
109 		context->cb_ctx = conf->cb_ctx;
110 		context->cert_in_cb = conf->cert_in_cb;
111 	}
112 
113 	return context;
114 }
115 
116 
117 static void wolfssl_reset_in_data(struct tls_in_data *in,
118 				  const struct wpabuf *buf)
119 {
120 	/* old one not owned by us so don't free */
121 	in->in_data = buf;
122 	in->consumed = 0;
123 }
124 
125 
126 static void wolfssl_reset_out_data(struct tls_out_data *out)
127 {
128 	/* old one not owned by us so don't free */
129 	out->out_data = wpabuf_alloc_copy("", 0);
130 }
131 
132 
133 /* wolfSSL I/O Receive CallBack */
134 static int wolfssl_receive_cb(WOLFSSL *ssl, char *buf, int sz, void *ctx)
135 {
136 	size_t get = sz;
137 	struct tls_in_data *data = ctx;
138 
139 	if (!data)
140 		return -1;
141 
142 	if (get > (wpabuf_len(data->in_data) - data->consumed))
143 		get = wpabuf_len(data->in_data) - data->consumed;
144 
145 	os_memcpy(buf, wpabuf_head_u8(data->in_data) + data->consumed, get);
146 	data->consumed += get;
147 
148 	if (get == 0)
149 		return -2; /* WANT_READ */
150 
151 	return (int) get;
152 }
153 
154 
155 /* wolfSSL I/O Send CallBack */
156 static int wolfssl_send_cb(WOLFSSL *ssl, char *buf, int sz, void *ctx)
157 {
158 	struct wpabuf *tmp;
159 	struct tls_out_data *data = ctx;
160 
161 	if (!data)
162 		return -1;
163 
164 	wpa_printf(MSG_DEBUG, "SSL: adding %d bytes", sz);
165 
166 	tmp = wpabuf_alloc_copy(buf, sz);
167 	if (!tmp)
168 		return -1;
169 	data->out_data = wpabuf_concat(data->out_data, tmp);
170 	if (!data->out_data)
171 		return -1;
172 
173 	return sz;
174 }
175 
176 
177 static void remove_session_cb(WOLFSSL_CTX *ctx, WOLFSSL_SESSION *sess)
178 {
179 	struct wpabuf *buf;
180 
181 	buf = wolfSSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
182 	if (!buf)
183 		return;
184 	wpa_printf(MSG_DEBUG,
185 		   "wolfSSL: Free application session data %p (sess %p)",
186 		   buf, sess);
187 	wpabuf_free(buf);
188 
189 	wolfSSL_SESSION_set_ex_data(sess, tls_ex_idx_session, NULL);
190 }
191 
192 
193 void * tls_init(const struct tls_config *conf)
194 {
195 	WOLFSSL_CTX *ssl_ctx;
196 	struct tls_context *context;
197 	const char *ciphers;
198 
199 #ifdef DEBUG_WOLFSSL
200 	wolfSSL_Debugging_ON();
201 #endif /* DEBUG_WOLFSSL */
202 
203 	context = tls_context_new(conf);
204 	if (!context)
205 		return NULL;
206 
207 	if (tls_ref_count == 0) {
208 		tls_global = context;
209 
210 		if (wolfSSL_Init() < 0)
211 			return NULL;
212 		/* wolfSSL_Debugging_ON(); */
213 	}
214 
215 	tls_ref_count++;
216 
217 	/* start as client */
218 	ssl_ctx = wolfSSL_CTX_new(wolfSSLv23_client_method());
219 	if (!ssl_ctx) {
220 		tls_ref_count--;
221 		if (context != tls_global)
222 			os_free(context);
223 		if (tls_ref_count == 0) {
224 			os_free(tls_global);
225 			tls_global = NULL;
226 		}
227 	}
228 	wolfSSL_SetIORecv(ssl_ctx, wolfssl_receive_cb);
229 	wolfSSL_SetIOSend(ssl_ctx, wolfssl_send_cb);
230 	wolfSSL_CTX_set_ex_data(ssl_ctx, 0, context);
231 
232 	if (conf->tls_session_lifetime > 0) {
233 		wolfSSL_CTX_set_quiet_shutdown(ssl_ctx, 1);
234 		wolfSSL_CTX_set_session_cache_mode(ssl_ctx,
235 						   SSL_SESS_CACHE_SERVER);
236 		wolfSSL_CTX_set_timeout(ssl_ctx, conf->tls_session_lifetime);
237 		wolfSSL_CTX_sess_set_remove_cb(ssl_ctx, remove_session_cb);
238 	} else {
239 		wolfSSL_CTX_set_session_cache_mode(ssl_ctx,
240 						   SSL_SESS_CACHE_CLIENT);
241 	}
242 
243 	if (conf && conf->openssl_ciphers)
244 		ciphers = conf->openssl_ciphers;
245 	else
246 		ciphers = "ALL";
247 	if (wolfSSL_CTX_set_cipher_list(ssl_ctx, ciphers) != 1) {
248 		wpa_printf(MSG_ERROR,
249 			   "wolfSSL: Failed to set cipher string '%s'",
250 			   ciphers);
251 		tls_deinit(ssl_ctx);
252 		return NULL;
253 	}
254 
255 	return ssl_ctx;
256 }
257 
258 
259 void tls_deinit(void *ssl_ctx)
260 {
261 	struct tls_context *context = wolfSSL_CTX_get_ex_data(ssl_ctx, 0);
262 
263 	if (context != tls_global)
264 		os_free(context);
265 
266 	wolfSSL_CTX_free((WOLFSSL_CTX *) ssl_ctx);
267 
268 	tls_ref_count--;
269 	if (tls_ref_count == 0) {
270 		wolfSSL_Cleanup();
271 		os_free(tls_global);
272 		tls_global = NULL;
273 	}
274 }
275 
276 
277 int tls_get_errors(void *tls_ctx)
278 {
279 #ifdef DEBUG_WOLFSSL
280 #if 0
281 	unsigned long err;
282 
283 	err = wolfSSL_ERR_peek_last_error_line(NULL, NULL);
284 	if (err != 0) {
285 		wpa_printf(MSG_INFO, "TLS - SSL error: %s",
286 			   wolfSSL_ERR_error_string(err, NULL));
287 		return 1;
288 	}
289 #endif
290 #endif /* DEBUG_WOLFSSL */
291 	return 0;
292 }
293 
294 
295 struct tls_connection * tls_connection_init(void *tls_ctx)
296 {
297 	WOLFSSL_CTX *ssl_ctx = tls_ctx;
298 	struct tls_connection *conn;
299 
300 	wpa_printf(MSG_DEBUG, "SSL: connection init");
301 
302 	conn = os_zalloc(sizeof(*conn));
303 	if (!conn)
304 		return NULL;
305 	conn->ssl = wolfSSL_new(ssl_ctx);
306 	if (!conn->ssl) {
307 		os_free(conn);
308 		return NULL;
309 	}
310 
311 	wolfSSL_SetIOReadCtx(conn->ssl,  &conn->input);
312 	wolfSSL_SetIOWriteCtx(conn->ssl, &conn->output);
313 	wolfSSL_set_ex_data(conn->ssl, 0, conn);
314 	conn->context = wolfSSL_CTX_get_ex_data(ssl_ctx, 0);
315 
316 	/* Need randoms post-hanshake for EAP-FAST, export key and deriving
317 	 * session ID in EAP methods. */
318 	wolfSSL_KeepArrays(conn->ssl);
319 	wolfSSL_KeepHandshakeResources(conn->ssl);
320 	wolfSSL_UseClientSuites(conn->ssl);
321 
322 	return conn;
323 }
324 
325 
326 void tls_connection_deinit(void *tls_ctx, struct tls_connection *conn)
327 {
328 	if (!conn)
329 		return;
330 
331 	wpa_printf(MSG_DEBUG, "SSL: connection deinit");
332 
333 	/* parts */
334 	wolfSSL_free(conn->ssl);
335 	os_free(conn->subject_match);
336 	os_free(conn->alt_subject_match);
337 	os_free(conn->suffix_match);
338 	os_free(conn->domain_match);
339 
340 	/* self */
341 	os_free(conn);
342 }
343 
344 
345 int tls_connection_established(void *tls_ctx, struct tls_connection *conn)
346 {
347 	return conn ? wolfSSL_is_init_finished(conn->ssl) : 0;
348 }
349 
350 
351 char * tls_connection_peer_serial_num(void *tls_ctx,
352 				      struct tls_connection *conn)
353 {
354 	/* TODO */
355 	return NULL;
356 }
357 
358 
359 int tls_connection_shutdown(void *tls_ctx, struct tls_connection *conn)
360 {
361 	WOLFSSL_SESSION *session;
362 
363 	if (!conn)
364 		return -1;
365 
366 	wpa_printf(MSG_DEBUG, "SSL: connection shutdown");
367 
368 	/* Set quiet as OpenSSL does */
369 	wolfSSL_set_quiet_shutdown(conn->ssl, 1);
370 	wolfSSL_shutdown(conn->ssl);
371 
372 	session = wolfSSL_get_session(conn->ssl);
373 	if (wolfSSL_clear(conn->ssl) != 1)
374 		return -1;
375 	wolfSSL_set_session(conn->ssl, session);
376 
377 	return 0;
378 }
379 
380 
381 static int tls_connection_set_subject_match(struct tls_connection *conn,
382 					    const char *subject_match,
383 					    const char *alt_subject_match,
384 					    const char *suffix_match,
385 					    const char *domain_match)
386 {
387 	os_free(conn->subject_match);
388 	conn->subject_match = NULL;
389 	if (subject_match) {
390 		conn->subject_match = os_strdup(subject_match);
391 		if (!conn->subject_match)
392 			return -1;
393 	}
394 
395 	os_free(conn->alt_subject_match);
396 	conn->alt_subject_match = NULL;
397 	if (alt_subject_match) {
398 		conn->alt_subject_match = os_strdup(alt_subject_match);
399 		if (!conn->alt_subject_match)
400 			return -1;
401 	}
402 
403 	os_free(conn->suffix_match);
404 	conn->suffix_match = NULL;
405 	if (suffix_match) {
406 		conn->suffix_match = os_strdup(suffix_match);
407 		if (!conn->suffix_match)
408 			return -1;
409 	}
410 
411 	os_free(conn->domain_match);
412 	conn->domain_match = NULL;
413 	if (domain_match) {
414 		conn->domain_match = os_strdup(domain_match);
415 		if (!conn->domain_match)
416 			return -1;
417 	}
418 
419 	return 0;
420 }
421 
422 
423 static int tls_connection_dh(struct tls_connection *conn, const char *dh_file,
424 			     const u8 *dh_blob, size_t blob_len)
425 {
426 	if (!dh_file && !dh_blob)
427 		return 0;
428 
429 	wolfSSL_set_accept_state(conn->ssl);
430 
431 	if (dh_blob) {
432 		if (wolfSSL_SetTmpDH_buffer(conn->ssl, dh_blob, blob_len,
433 					    SSL_FILETYPE_ASN1) < 0) {
434 			wpa_printf(MSG_INFO, "SSL: use DH DER blob failed");
435 			return -1;
436 		}
437 		wpa_printf(MSG_DEBUG, "SSL: use DH blob OK");
438 		return 0;
439 	}
440 
441 	if (dh_file) {
442 		wpa_printf(MSG_INFO, "SSL: use DH PEM file: %s", dh_file);
443 		if (wolfSSL_SetTmpDH_file(conn->ssl, dh_file,
444 					  SSL_FILETYPE_PEM) < 0) {
445 			wpa_printf(MSG_INFO, "SSL: use DH PEM file failed");
446 			if (wolfSSL_SetTmpDH_file(conn->ssl, dh_file,
447 						  SSL_FILETYPE_ASN1) < 0) {
448 				wpa_printf(MSG_INFO,
449 					   "SSL: use DH DER file failed");
450 				return -1;
451 			}
452 		}
453 		wpa_printf(MSG_DEBUG, "SSL: use DH file OK");
454 		return 0;
455 	}
456 
457 	return 0;
458 }
459 
460 
461 static int tls_connection_client_cert(struct tls_connection *conn,
462 				      const char *client_cert,
463 				      const u8 *client_cert_blob,
464 				      size_t blob_len)
465 {
466 	if (!client_cert && !client_cert_blob)
467 		return 0;
468 
469 	if (client_cert_blob) {
470 		if (wolfSSL_use_certificate_chain_buffer_format(
471 			    conn->ssl, client_cert_blob, blob_len,
472 			    SSL_FILETYPE_ASN1) != SSL_SUCCESS) {
473 			wpa_printf(MSG_INFO,
474 				   "SSL: use client cert DER blob failed");
475 			return -1;
476 		}
477 		wpa_printf(MSG_DEBUG, "SSL: use client cert blob OK");
478 		return 0;
479 	}
480 
481 	if (client_cert) {
482 		if (wolfSSL_use_certificate_chain_file(
483 			    conn->ssl, client_cert) != SSL_SUCCESS) {
484 			wpa_printf(MSG_INFO,
485 				   "SSL: use client cert PEM file failed");
486 			if (wolfSSL_use_certificate_chain_file_format(
487 				    conn->ssl, client_cert,
488 				    SSL_FILETYPE_ASN1) != SSL_SUCCESS) {
489 				wpa_printf(MSG_INFO,
490 					   "SSL: use client cert DER file failed");
491 				return -1;
492 			}
493 		}
494 		wpa_printf(MSG_DEBUG, "SSL: use client cert file OK");
495 		return 0;
496 	}
497 
498 	return 0;
499 }
500 
501 
502 static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
503 {
504 	if (!password)
505 		return 0;
506 	os_strlcpy(buf, (char *) password, size);
507 	return os_strlen(buf);
508 }
509 
510 
511 static int tls_connection_private_key(void *tls_ctx,
512 				      struct tls_connection *conn,
513 				      const char *private_key,
514 				      const char *private_key_passwd,
515 				      const u8 *private_key_blob,
516 				      size_t blob_len)
517 {
518 	WOLFSSL_CTX *ctx = tls_ctx;
519 	char *passwd = NULL;
520 	int ok = 0;
521 
522 	if (!private_key && !private_key_blob)
523 		return 0;
524 
525 	if (private_key_passwd) {
526 		passwd = os_strdup(private_key_passwd);
527 		if (!passwd)
528 			return -1;
529 	}
530 
531 	wolfSSL_CTX_set_default_passwd_cb(ctx, tls_passwd_cb);
532 	wolfSSL_CTX_set_default_passwd_cb_userdata(ctx, passwd);
533 
534 	if (private_key_blob) {
535 		if (wolfSSL_use_PrivateKey_buffer(conn->ssl,
536 						  private_key_blob, blob_len,
537 						  SSL_FILETYPE_ASN1) <= 0) {
538 			wpa_printf(MSG_INFO,
539 				   "SSL: use private DER blob failed");
540 		} else {
541 			wpa_printf(MSG_DEBUG, "SSL: use private key blob OK");
542 			ok = 1;
543 		}
544 	}
545 
546 	if (!ok && private_key) {
547 		if (wolfSSL_use_PrivateKey_file(conn->ssl, private_key,
548 						SSL_FILETYPE_PEM) <= 0) {
549 			wpa_printf(MSG_INFO,
550 				   "SSL: use private key PEM file failed");
551 			if (wolfSSL_use_PrivateKey_file(conn->ssl, private_key,
552 							SSL_FILETYPE_ASN1) <= 0)
553 			{
554 				wpa_printf(MSG_INFO,
555 					   "SSL: use private key DER file failed");
556 			} else {
557 				ok = 1;
558 			}
559 		} else {
560 			ok = 1;
561 		}
562 
563 		if (ok)
564 			wpa_printf(MSG_DEBUG, "SSL: use private key file OK");
565 	}
566 
567 	wolfSSL_CTX_set_default_passwd_cb(ctx, NULL);
568 	os_free(passwd);
569 
570 	if (!ok)
571 		return -1;
572 
573 	return 0;
574 }
575 
576 
577 static int tls_match_alt_subject_component(WOLFSSL_X509 *cert, int type,
578 					   const char *value, size_t len)
579 {
580 	WOLFSSL_GENERAL_NAME *gen;
581 	void *ext;
582 	int found = 0;
583 	int i;
584 
585 	ext = wolfSSL_X509_get_ext_d2i(cert, ALT_NAMES_OID, NULL, NULL);
586 
587 	for (i = 0; ext && i < wolfSSL_sk_num(ext); i++) {
588 		gen = wolfSSL_sk_value(ext, i);
589 		if (!gen || gen->type != type)
590 			continue;
591 		if ((size_t) wolfSSL_ASN1_STRING_length(gen->d.ia5) == len &&
592 		    os_memcmp(value, wolfSSL_ASN1_STRING_data(gen->d.ia5),
593 			      len) == 0)
594 			found++;
595 	}
596 
597 	wolfSSL_sk_GENERAL_NAME_free(ext);
598 
599 	return found;
600 }
601 
602 
603 static int tls_match_alt_subject(WOLFSSL_X509 *cert, const char *match)
604 {
605 	int type;
606 	const char *pos, *end;
607 	size_t len;
608 
609 	pos = match;
610 	do {
611 		if (os_strncmp(pos, "EMAIL:", 6) == 0) {
612 			type = GEN_EMAIL;
613 			pos += 6;
614 		} else if (os_strncmp(pos, "DNS:", 4) == 0) {
615 			type = GEN_DNS;
616 			pos += 4;
617 		} else if (os_strncmp(pos, "URI:", 4) == 0) {
618 			type = GEN_URI;
619 			pos += 4;
620 		} else {
621 			wpa_printf(MSG_INFO,
622 				   "TLS: Invalid altSubjectName match '%s'",
623 				   pos);
624 			return 0;
625 		}
626 		end = os_strchr(pos, ';');
627 		while (end) {
628 			if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
629 			    os_strncmp(end + 1, "DNS:", 4) == 0 ||
630 			    os_strncmp(end + 1, "URI:", 4) == 0)
631 				break;
632 			end = os_strchr(end + 1, ';');
633 		}
634 		if (end)
635 			len = end - pos;
636 		else
637 			len = os_strlen(pos);
638 		if (tls_match_alt_subject_component(cert, type, pos, len) > 0)
639 			return 1;
640 		pos = end + 1;
641 	} while (end);
642 
643 	return 0;
644 }
645 
646 
647 static int domain_suffix_match(const char *val, size_t len, const char *match,
648 			       size_t match_len, int full)
649 {
650 	size_t i;
651 
652 	/* Check for embedded nuls that could mess up suffix matching */
653 	for (i = 0; i < len; i++) {
654 		if (val[i] == '\0') {
655 			wpa_printf(MSG_DEBUG,
656 				   "TLS: Embedded null in a string - reject");
657 			return 0;
658 		}
659 	}
660 
661 	if (match_len > len || (full && match_len != len))
662 		return 0;
663 
664 	if (os_strncasecmp(val + len - match_len, match, match_len) != 0)
665 		return 0; /* no match */
666 
667 	if (match_len == len)
668 		return 1; /* exact match */
669 
670 	if (val[len - match_len - 1] == '.')
671 		return 1; /* full label match completes suffix match */
672 
673 	wpa_printf(MSG_DEBUG, "TLS: Reject due to incomplete label match");
674 	return 0;
675 }
676 
677 
678 static int tls_match_suffix_helper(WOLFSSL_X509 *cert, const char *match,
679 				   size_t match_len, int full)
680 {
681 	WOLFSSL_GENERAL_NAME *gen;
682 	void *ext;
683 	int i;
684 	int j;
685 	int dns_name = 0;
686 	WOLFSSL_X509_NAME *name;
687 
688 	wpa_printf(MSG_DEBUG, "TLS: Match domain against %s%s",
689 		   full ? "" : "suffix ", match);
690 
691 	ext = wolfSSL_X509_get_ext_d2i(cert, ALT_NAMES_OID, NULL, NULL);
692 
693 	for (j = 0; ext && j < wolfSSL_sk_num(ext); j++) {
694 		gen = wolfSSL_sk_value(ext, j);
695 		if (!gen || gen->type != ASN_DNS_TYPE)
696 			continue;
697 		dns_name++;
698 		wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate dNSName",
699 				  wolfSSL_ASN1_STRING_data(gen->d.ia5),
700 				  wolfSSL_ASN1_STRING_length(gen->d.ia5));
701 		if (domain_suffix_match(
702 			    (const char *) wolfSSL_ASN1_STRING_data(gen->d.ia5),
703 			    wolfSSL_ASN1_STRING_length(gen->d.ia5), match,
704 			    match_len, full) == 1) {
705 			wpa_printf(MSG_DEBUG, "TLS: %s in dNSName found",
706 				   full ? "Match" : "Suffix match");
707 			wolfSSL_sk_ASN1_OBJECT_free(ext);
708 			return 1;
709 		}
710 	}
711 	wolfSSL_sk_GENERAL_NAME_free(ext);
712 
713 	if (dns_name) {
714 		wpa_printf(MSG_DEBUG, "TLS: None of the dNSName(s) matched");
715 		return 0;
716 	}
717 
718 	name = wolfSSL_X509_get_subject_name(cert);
719 	i = -1;
720 	for (;;) {
721 		WOLFSSL_X509_NAME_ENTRY *e;
722 		WOLFSSL_ASN1_STRING *cn;
723 
724 		i = wolfSSL_X509_NAME_get_index_by_NID(name, ASN_COMMON_NAME,
725 						       i);
726 		if (i == -1)
727 			break;
728 		e = wolfSSL_X509_NAME_get_entry(name, i);
729 		if (!e)
730 			continue;
731 		cn = wolfSSL_X509_NAME_ENTRY_get_data(e);
732 		if (!cn)
733 			continue;
734 		wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate commonName",
735 				  cn->data, cn->length);
736 		if (domain_suffix_match(cn->data, cn->length,
737 					match, match_len, full) == 1) {
738 			wpa_printf(MSG_DEBUG, "TLS: %s in commonName found",
739 				   full ? "Match" : "Suffix match");
740 			return 1;
741 		}
742 	}
743 
744 	wpa_printf(MSG_DEBUG, "TLS: No CommonName %smatch found",
745 		   full ? "" : "suffix ");
746 	return 0;
747 }
748 
749 
750 static int tls_match_suffix(WOLFSSL_X509 *cert, const char *match, int full)
751 {
752 	const char *token, *last = NULL;
753 
754 	/* Process each match alternative separately until a match is found */
755 	while ((token = cstr_token(match, ";", &last))) {
756 		if (tls_match_suffix_helper(cert, token, last - token, full))
757 			return 1;
758 	}
759 
760 	return 0;
761 }
762 
763 
764 static enum tls_fail_reason wolfssl_tls_fail_reason(int err)
765 {
766 	switch (err) {
767 	case X509_V_ERR_CERT_REVOKED:
768 		return TLS_FAIL_REVOKED;
769 	case ASN_BEFORE_DATE_E:
770 	case X509_V_ERR_CERT_NOT_YET_VALID:
771 	case X509_V_ERR_CRL_NOT_YET_VALID:
772 		return TLS_FAIL_NOT_YET_VALID;
773 	case ASN_AFTER_DATE_E:
774 	case X509_V_ERR_CERT_HAS_EXPIRED:
775 	case X509_V_ERR_CRL_HAS_EXPIRED:
776 		return TLS_FAIL_EXPIRED;
777 	case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
778 	case X509_V_ERR_UNABLE_TO_GET_CRL:
779 	case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
780 	case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
781 	case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
782 	case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
783 	case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
784 	case X509_V_ERR_CERT_CHAIN_TOO_LONG:
785 	case X509_V_ERR_PATH_LENGTH_EXCEEDED:
786 	case X509_V_ERR_INVALID_CA:
787 		return TLS_FAIL_UNTRUSTED;
788 	case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
789 	case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
790 	case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
791 	case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
792 	case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
793 	case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
794 	case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
795 	case X509_V_ERR_CERT_UNTRUSTED:
796 	case X509_V_ERR_CERT_REJECTED:
797 		return TLS_FAIL_BAD_CERTIFICATE;
798 	default:
799 		return TLS_FAIL_UNSPECIFIED;
800 	}
801 }
802 
803 
804 static const char * wolfssl_tls_err_string(int err, const char *err_str)
805 {
806 	switch (err) {
807 	case ASN_BEFORE_DATE_E:
808 		return "certificate is not yet valid";
809 	case ASN_AFTER_DATE_E:
810 		return "certificate has expired";
811 	default:
812 		return err_str;
813 	}
814 }
815 
816 
817 static struct wpabuf * get_x509_cert(WOLFSSL_X509 *cert)
818 {
819 	struct wpabuf *buf = NULL;
820 	const u8 *data;
821 	int cert_len;
822 
823 	data = wolfSSL_X509_get_der(cert, &cert_len);
824 	if (!data)
825 		buf = wpabuf_alloc_copy(data, cert_len);
826 
827 	return buf;
828 }
829 
830 
831 static void wolfssl_tls_fail_event(struct tls_connection *conn,
832 				   WOLFSSL_X509 *err_cert, int err, int depth,
833 				   const char *subject, const char *err_str,
834 				   enum tls_fail_reason reason)
835 {
836 	union tls_event_data ev;
837 	struct wpabuf *cert = NULL;
838 	struct tls_context *context = conn->context;
839 
840 	if (!context->event_cb)
841 		return;
842 
843 	cert = get_x509_cert(err_cert);
844 	os_memset(&ev, 0, sizeof(ev));
845 	ev.cert_fail.reason = reason != TLS_FAIL_UNSPECIFIED ?
846 		reason : wolfssl_tls_fail_reason(err);
847 	ev.cert_fail.depth = depth;
848 	ev.cert_fail.subject = subject;
849 	ev.cert_fail.reason_txt = wolfssl_tls_err_string(err, err_str);
850 	ev.cert_fail.cert = cert;
851 	context->event_cb(context->cb_ctx, TLS_CERT_CHAIN_FAILURE, &ev);
852 	wpabuf_free(cert);
853 }
854 
855 
856 static void wolfssl_tls_cert_event(struct tls_connection *conn,
857 				   WOLFSSL_X509 *err_cert, int depth,
858 				   const char *subject)
859 {
860 	struct wpabuf *cert = NULL;
861 	union tls_event_data ev;
862 	struct tls_context *context = conn->context;
863 	char *alt_subject[TLS_MAX_ALT_SUBJECT];
864 	int alt, num_alt_subject = 0;
865 	WOLFSSL_GENERAL_NAME *gen;
866 	void *ext;
867 	int i;
868 #ifdef CONFIG_SHA256
869 	u8 hash[32];
870 #endif /* CONFIG_SHA256 */
871 
872 	if (!context->event_cb)
873 		return;
874 
875 	os_memset(&ev, 0, sizeof(ev));
876 	if (conn->cert_probe || (conn->flags & TLS_CONN_EXT_CERT_CHECK) ||
877 	    context->cert_in_cb) {
878 		cert = get_x509_cert(err_cert);
879 		ev.peer_cert.cert = cert;
880 	}
881 
882 #ifdef CONFIG_SHA256
883 	if (cert) {
884 		const u8 *addr[1];
885 		size_t len[1];
886 
887 		addr[0] = wpabuf_head(cert);
888 		len[0] = wpabuf_len(cert);
889 		if (sha256_vector(1, addr, len, hash) == 0) {
890 			ev.peer_cert.hash = hash;
891 			ev.peer_cert.hash_len = sizeof(hash);
892 		}
893 	}
894 #endif /* CONFIG_SHA256 */
895 
896 	ev.peer_cert.depth = depth;
897 	ev.peer_cert.subject = subject;
898 
899 	ext = wolfSSL_X509_get_ext_d2i(err_cert, ALT_NAMES_OID, NULL, NULL);
900 	for (i = 0; ext && i < wolfSSL_sk_num(ext); i++) {
901 		char *pos;
902 
903 		if (num_alt_subject == TLS_MAX_ALT_SUBJECT)
904 			break;
905 		gen = wolfSSL_sk_value((void *) ext, i);
906 		if (!gen ||
907 		    (gen->type != GEN_EMAIL &&
908 		     gen->type != GEN_DNS &&
909 		     gen->type != GEN_URI))
910 			continue;
911 
912 		pos = os_malloc(10 + wolfSSL_ASN1_STRING_length(gen->d.ia5) +
913 				1);
914 		if (!pos)
915 			break;
916 		alt_subject[num_alt_subject++] = pos;
917 
918 		switch (gen->type) {
919 		case GEN_EMAIL:
920 			os_memcpy(pos, "EMAIL:", 6);
921 			pos += 6;
922 			break;
923 		case GEN_DNS:
924 			os_memcpy(pos, "DNS:", 4);
925 			pos += 4;
926 			break;
927 		case GEN_URI:
928 			os_memcpy(pos, "URI:", 4);
929 			pos += 4;
930 			break;
931 		}
932 
933 		os_memcpy(pos, wolfSSL_ASN1_STRING_data(gen->d.ia5),
934 			  wolfSSL_ASN1_STRING_length(gen->d.ia5));
935 		pos += wolfSSL_ASN1_STRING_length(gen->d.ia5);
936 		*pos = '\0';
937 	}
938 	wolfSSL_sk_GENERAL_NAME_free(ext);
939 
940 	for (alt = 0; alt < num_alt_subject; alt++)
941 		ev.peer_cert.altsubject[alt] = alt_subject[alt];
942 	ev.peer_cert.num_altsubject = num_alt_subject;
943 
944 	context->event_cb(context->cb_ctx, TLS_PEER_CERTIFICATE, &ev);
945 	wpabuf_free(cert);
946 	for (alt = 0; alt < num_alt_subject; alt++)
947 		os_free(alt_subject[alt]);
948 }
949 
950 
951 static int tls_verify_cb(int preverify_ok, WOLFSSL_X509_STORE_CTX *x509_ctx)
952 {
953 	char buf[256];
954 	WOLFSSL_X509 *err_cert;
955 	int err, depth;
956 	WOLFSSL *ssl;
957 	struct tls_connection *conn;
958 	struct tls_context *context;
959 	char *match, *altmatch, *suffix_match, *domain_match;
960 	const char *err_str;
961 
962 	err_cert = wolfSSL_X509_STORE_CTX_get_current_cert(x509_ctx);
963 	if (!err_cert) {
964 		wpa_printf(MSG_DEBUG, "wolfSSL: No Cert");
965 		return 0;
966 	}
967 
968 	err = wolfSSL_X509_STORE_CTX_get_error(x509_ctx);
969 	depth = wolfSSL_X509_STORE_CTX_get_error_depth(x509_ctx);
970 	ssl = wolfSSL_X509_STORE_CTX_get_ex_data(
971 		x509_ctx, wolfSSL_get_ex_data_X509_STORE_CTX_idx());
972 	wolfSSL_X509_NAME_oneline(wolfSSL_X509_get_subject_name(err_cert), buf,
973 				  sizeof(buf));
974 
975 	conn = wolfSSL_get_ex_data(ssl, 0);
976 	if (!conn) {
977 		wpa_printf(MSG_DEBUG, "wolfSSL: No ex_data");
978 		return 0;
979 	}
980 
981 	if (depth == 0)
982 		conn->peer_cert = err_cert;
983 	else if (depth == 1)
984 		conn->peer_issuer = err_cert;
985 	else if (depth == 2)
986 		conn->peer_issuer_issuer = err_cert;
987 
988 	context = conn->context;
989 	match = conn->subject_match;
990 	altmatch = conn->alt_subject_match;
991 	suffix_match = conn->suffix_match;
992 	domain_match = conn->domain_match;
993 
994 	if (!preverify_ok && !conn->ca_cert_verify)
995 		preverify_ok = 1;
996 	if (!preverify_ok && depth > 0 && conn->server_cert_only)
997 		preverify_ok = 1;
998 	if (!preverify_ok && (conn->flags & TLS_CONN_DISABLE_TIME_CHECKS) &&
999 	    (err == X509_V_ERR_CERT_HAS_EXPIRED ||
1000 	     err == ASN_AFTER_DATE_E || err == ASN_BEFORE_DATE_E ||
1001 	     err == X509_V_ERR_CERT_NOT_YET_VALID)) {
1002 		wpa_printf(MSG_DEBUG,
1003 			   "wolfSSL: Ignore certificate validity time mismatch");
1004 		preverify_ok = 1;
1005 	}
1006 
1007 	err_str = wolfSSL_X509_verify_cert_error_string(err);
1008 
1009 #ifdef CONFIG_SHA256
1010 	/*
1011 	 * Do not require preverify_ok so we can explicity allow otherwise
1012 	 * invalid pinned server certificates.
1013 	 */
1014 	if (depth == 0 && conn->server_cert_only) {
1015 		struct wpabuf *cert;
1016 
1017 		cert = get_x509_cert(err_cert);
1018 		if (!cert) {
1019 			wpa_printf(MSG_DEBUG,
1020 				   "wolfSSL: Could not fetch server certificate data");
1021 			preverify_ok = 0;
1022 		} else {
1023 			u8 hash[32];
1024 			const u8 *addr[1];
1025 			size_t len[1];
1026 
1027 			addr[0] = wpabuf_head(cert);
1028 			len[0] = wpabuf_len(cert);
1029 			if (sha256_vector(1, addr, len, hash) < 0 ||
1030 			    os_memcmp(conn->srv_cert_hash, hash, 32) != 0) {
1031 				err_str = "Server certificate mismatch";
1032 				err = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
1033 				preverify_ok = 0;
1034 			} else if (!preverify_ok) {
1035 				/*
1036 				 * Certificate matches pinned certificate, allow
1037 				 * regardless of other problems.
1038 				 */
1039 				wpa_printf(MSG_DEBUG,
1040 					   "wolfSSL: Ignore validation issues for a pinned server certificate");
1041 				preverify_ok = 1;
1042 			}
1043 			wpabuf_free(cert);
1044 		}
1045 	}
1046 #endif /* CONFIG_SHA256 */
1047 
1048 	if (!preverify_ok) {
1049 		wpa_printf(MSG_WARNING,
1050 			   "TLS: Certificate verification failed, error %d (%s) depth %d for '%s'",
1051 			   err, err_str, depth, buf);
1052 		wolfssl_tls_fail_event(conn, err_cert, err, depth, buf,
1053 				       err_str, TLS_FAIL_UNSPECIFIED);
1054 		return preverify_ok;
1055 	}
1056 
1057 	wpa_printf(MSG_DEBUG,
1058 		   "TLS: %s - preverify_ok=%d err=%d (%s) ca_cert_verify=%d depth=%d buf='%s'",
1059 		   __func__, preverify_ok, err, err_str,
1060 		   conn->ca_cert_verify, depth, buf);
1061 	if (depth == 0 && match && os_strstr(buf, match) == NULL) {
1062 		wpa_printf(MSG_WARNING,
1063 			   "TLS: Subject '%s' did not match with '%s'",
1064 			   buf, match);
1065 		preverify_ok = 0;
1066 		wolfssl_tls_fail_event(conn, err_cert, err, depth, buf,
1067 				       "Subject mismatch",
1068 				       TLS_FAIL_SUBJECT_MISMATCH);
1069 	} else if (depth == 0 && altmatch &&
1070 		   !tls_match_alt_subject(err_cert, altmatch)) {
1071 		wpa_printf(MSG_WARNING,
1072 			   "TLS: altSubjectName match '%s' not found",
1073 			   altmatch);
1074 		preverify_ok = 0;
1075 		wolfssl_tls_fail_event(conn, err_cert, err, depth, buf,
1076 				       "AltSubject mismatch",
1077 				       TLS_FAIL_ALTSUBJECT_MISMATCH);
1078 	} else if (depth == 0 && suffix_match &&
1079 		   !tls_match_suffix(err_cert, suffix_match, 0)) {
1080 		wpa_printf(MSG_WARNING,
1081 			   "TLS: Domain suffix match '%s' not found",
1082 			   suffix_match);
1083 		preverify_ok = 0;
1084 		wolfssl_tls_fail_event(conn, err_cert, err, depth, buf,
1085 				       "Domain suffix mismatch",
1086 				       TLS_FAIL_DOMAIN_SUFFIX_MISMATCH);
1087 	} else if (depth == 0 && domain_match &&
1088 		   !tls_match_suffix(err_cert, domain_match, 1)) {
1089 		wpa_printf(MSG_WARNING, "TLS: Domain match '%s' not found",
1090 			   domain_match);
1091 		preverify_ok = 0;
1092 		wolfssl_tls_fail_event(conn, err_cert, err, depth, buf,
1093 				       "Domain mismatch",
1094 				       TLS_FAIL_DOMAIN_MISMATCH);
1095 	} else {
1096 		wolfssl_tls_cert_event(conn, err_cert, depth, buf);
1097 	}
1098 
1099 	if (conn->cert_probe && preverify_ok && depth == 0) {
1100 		wpa_printf(MSG_DEBUG,
1101 			   "wolfSSL: Reject server certificate on probe-only run");
1102 		preverify_ok = 0;
1103 		wolfssl_tls_fail_event(conn, err_cert, err, depth, buf,
1104 				       "Server certificate chain probe",
1105 				       TLS_FAIL_SERVER_CHAIN_PROBE);
1106 	}
1107 
1108 #ifdef HAVE_OCSP_WOLFSSL
1109 	if (depth == 0 && (conn->flags & TLS_CONN_REQUEST_OCSP) &&
1110 	    preverify_ok) {
1111 		enum ocsp_result res;
1112 
1113 		res = check_ocsp_resp(conn->ssl_ctx, conn->ssl, err_cert,
1114 				      conn->peer_issuer,
1115 				      conn->peer_issuer_issuer);
1116 		if (res == OCSP_REVOKED) {
1117 			preverify_ok = 0;
1118 			wolfssl_tls_fail_event(conn, err_cert, err, depth, buf,
1119 					       "certificate revoked",
1120 					       TLS_FAIL_REVOKED);
1121 			if (err == X509_V_OK)
1122 				X509_STORE_CTX_set_error(
1123 					x509_ctx, X509_V_ERR_CERT_REVOKED);
1124 		} else if (res != OCSP_GOOD &&
1125 			   (conn->flags & TLS_CONN_REQUIRE_OCSP)) {
1126 			preverify_ok = 0;
1127 			wolfssl_tls_fail_event(conn, err_cert, err, depth, buf,
1128 					       "bad certificate status response",
1129 					       TLS_FAIL_UNSPECIFIED);
1130 		}
1131 	}
1132 #endif /* HAVE_OCSP_WOLFSSL */
1133 	if (depth == 0 && preverify_ok && context->event_cb != NULL)
1134 		context->event_cb(context->cb_ctx,
1135 				  TLS_CERT_CHAIN_SUCCESS, NULL);
1136 
1137 	return preverify_ok;
1138 }
1139 
1140 
1141 static int tls_connection_ca_cert(void *tls_ctx, struct tls_connection *conn,
1142 				  const char *ca_cert,
1143 				  const u8 *ca_cert_blob, size_t blob_len,
1144 				  const char *ca_path)
1145 {
1146 	WOLFSSL_CTX *ctx = tls_ctx;
1147 
1148 	wolfSSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1149 	conn->ca_cert_verify = 1;
1150 
1151 	if (ca_cert && os_strncmp(ca_cert, "probe://", 8) == 0) {
1152 		wpa_printf(MSG_DEBUG,
1153 			   "wolfSSL: Probe for server certificate chain");
1154 		conn->cert_probe = 1;
1155 		conn->ca_cert_verify = 0;
1156 		return 0;
1157 	}
1158 
1159 	if (ca_cert && os_strncmp(ca_cert, "hash://", 7) == 0) {
1160 #ifdef CONFIG_SHA256
1161 		const char *pos = ca_cert + 7;
1162 
1163 		if (os_strncmp(pos, "server/sha256/", 14) != 0) {
1164 			wpa_printf(MSG_DEBUG,
1165 				   "wolfSSL: Unsupported ca_cert hash value '%s'",
1166 				   ca_cert);
1167 			return -1;
1168 		}
1169 		pos += 14;
1170 		if (os_strlen(pos) != 32 * 2) {
1171 			wpa_printf(MSG_DEBUG,
1172 				   "wolfSSL: Unexpected SHA256 hash length in ca_cert '%s'",
1173 				   ca_cert);
1174 			return -1;
1175 		}
1176 		if (hexstr2bin(pos, conn->srv_cert_hash, 32) < 0) {
1177 			wpa_printf(MSG_DEBUG,
1178 				   "wolfSSL: Invalid SHA256 hash value in ca_cert '%s'",
1179 				   ca_cert);
1180 			return -1;
1181 		}
1182 		conn->server_cert_only = 1;
1183 		wpa_printf(MSG_DEBUG,
1184 			   "wolfSSL: Checking only server certificate match");
1185 		return 0;
1186 #else /* CONFIG_SHA256 */
1187 		wpa_printf(MSG_INFO,
1188 			   "No SHA256 included in the build - cannot validate server certificate hash");
1189 		return -1;
1190 #endif /* CONFIG_SHA256 */
1191 	}
1192 
1193 	if (ca_cert_blob) {
1194 		if (wolfSSL_CTX_load_verify_buffer(ctx, ca_cert_blob, blob_len,
1195 						   SSL_FILETYPE_ASN1) !=
1196 		    SSL_SUCCESS) {
1197 			wpa_printf(MSG_INFO, "SSL: failed to load CA blob");
1198 			return -1;
1199 		}
1200 		wpa_printf(MSG_DEBUG, "SSL: use CA cert blob OK");
1201 		return 0;
1202 	}
1203 
1204 	if (ca_cert || ca_path) {
1205 		WOLFSSL_X509_STORE *cm = wolfSSL_X509_STORE_new();
1206 
1207 		if (!cm) {
1208 			wpa_printf(MSG_INFO,
1209 				   "SSL: failed to create certificate store");
1210 			return -1;
1211 		}
1212 		wolfSSL_CTX_set_cert_store(ctx, cm);
1213 
1214 		if (wolfSSL_CTX_load_verify_locations(ctx, ca_cert, ca_path) !=
1215 		    SSL_SUCCESS) {
1216 			wpa_printf(MSG_INFO,
1217 				   "SSL: failed to load ca_cert as PEM");
1218 
1219 			if (!ca_cert)
1220 				return -1;
1221 
1222 			if (wolfSSL_CTX_der_load_verify_locations(
1223 				    ctx, ca_cert, SSL_FILETYPE_ASN1) !=
1224 			    SSL_SUCCESS) {
1225 				wpa_printf(MSG_INFO,
1226 					   "SSL: failed to load ca_cert as DER");
1227 				return -1;
1228 			}
1229 		}
1230 		return 0;
1231 	}
1232 
1233 	conn->ca_cert_verify = 0;
1234 	return 0;
1235 }
1236 
1237 
1238 static void tls_set_conn_flags(WOLFSSL *ssl, unsigned int flags)
1239 {
1240 #ifdef HAVE_SESSION_TICKET
1241 #if 0
1242 	if (!(flags & TLS_CONN_DISABLE_SESSION_TICKET))
1243 		wolfSSL_UseSessionTicket(ssl);
1244 #endif
1245 #endif /* HAVE_SESSION_TICKET */
1246 
1247 	if (flags & TLS_CONN_DISABLE_TLSv1_0)
1248 		wolfSSL_set_options(ssl, SSL_OP_NO_TLSv1);
1249 	if (flags & TLS_CONN_DISABLE_TLSv1_1)
1250 		wolfSSL_set_options(ssl, SSL_OP_NO_TLSv1_1);
1251 	if (flags & TLS_CONN_DISABLE_TLSv1_2)
1252 		wolfSSL_set_options(ssl, SSL_OP_NO_TLSv1_2);
1253 }
1254 
1255 
1256 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
1257 			      const struct tls_connection_params *params)
1258 {
1259 	wpa_printf(MSG_DEBUG, "SSL: set params");
1260 
1261 	if (tls_connection_set_subject_match(conn, params->subject_match,
1262 					     params->altsubject_match,
1263 					     params->suffix_match,
1264 					     params->domain_match) < 0) {
1265 		wpa_printf(MSG_INFO, "Error setting subject match");
1266 		return -1;
1267 	}
1268 
1269 	if (tls_connection_ca_cert(tls_ctx, conn, params->ca_cert,
1270 				   params->ca_cert_blob,
1271 				   params->ca_cert_blob_len,
1272 				   params->ca_path) < 0) {
1273 		wpa_printf(MSG_INFO, "Error setting CA cert");
1274 		return -1;
1275 	}
1276 
1277 	if (tls_connection_client_cert(conn, params->client_cert,
1278 				       params->client_cert_blob,
1279 				       params->client_cert_blob_len) < 0) {
1280 		wpa_printf(MSG_INFO, "Error setting client cert");
1281 		return -1;
1282 	}
1283 
1284 	if (tls_connection_private_key(tls_ctx, conn, params->private_key,
1285 				       params->private_key_passwd,
1286 				       params->private_key_blob,
1287 				       params->private_key_blob_len) < 0) {
1288 		wpa_printf(MSG_INFO, "Error setting private key");
1289 		return -1;
1290 	}
1291 
1292 	if (tls_connection_dh(conn, params->dh_file, params->dh_blob,
1293 			      params->dh_blob_len) < 0) {
1294 		wpa_printf(MSG_INFO, "Error setting DH");
1295 		return -1;
1296 	}
1297 
1298 	if (params->openssl_ciphers &&
1299 	    wolfSSL_set_cipher_list(conn->ssl, params->openssl_ciphers) != 1) {
1300 		wpa_printf(MSG_INFO,
1301 			   "wolfSSL: Failed to set cipher string '%s'",
1302 			   params->openssl_ciphers);
1303 		return -1;
1304 	}
1305 
1306 	tls_set_conn_flags(conn->ssl, params->flags);
1307 
1308 #ifdef HAVE_CERTIFICATE_STATUS_REQUEST
1309 	if (params->flags & TLS_CONN_REQUEST_OCSP) {
1310 		if (wolfSSL_UseOCSPStapling(conn->ssl, WOLFSSL_CSR_OCSP,
1311 					    WOLFSSL_CSR_OCSP_USE_NONCE) !=
1312 		    SSL_SUCCESS)
1313 			return -1;
1314 		wolfSSL_CTX_EnableOCSP(tls_ctx, 0);
1315 	}
1316 #endif /* HAVE_CERTIFICATE_STATUS_REQUEST */
1317 #ifdef HAVE_CERTIFICATE_STATUS_REQUEST_V2
1318 	if (params->flags & TLS_CONN_REQUEST_OCSP) {
1319 		if (wolfSSL_UseOCSPStaplingV2(conn->ssl,
1320 					      WOLFSSL_CSR2_OCSP_MULTI, 0) !=
1321 		    SSL_SUCCESS)
1322 			return -1;
1323 		wolfSSL_CTX_EnableOCSP(tls_ctx, 0);
1324 	}
1325 #endif /* HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
1326 #if !defined(HAVE_CERTIFICATE_STATUS_REQUEST) && \
1327     !defined(HAVE_CERTIFICATE_STATUS_REQUEST_V2)
1328 #ifdef HAVE_OCSP
1329 	if (params->flags & TLS_CONN_REQUEST_OCSP)
1330 		wolfSSL_CTX_EnableOCSP(ctx, 0);
1331 #else /* HAVE_OCSP */
1332 	if (params->flags & TLS_CONN_REQUIRE_OCSP) {
1333 		wpa_printf(MSG_INFO,
1334 			   "wolfSSL: No OCSP support included - reject configuration");
1335 		return -1;
1336 	}
1337 	if (params->flags & TLS_CONN_REQUEST_OCSP) {
1338 		wpa_printf(MSG_DEBUG,
1339 			   "wolfSSL: No OCSP support included - allow optional OCSP case to continue");
1340 	}
1341 #endif /* HAVE_OCSP */
1342 #endif /* !HAVE_CERTIFICATE_STATUS_REQUEST &&
1343 	* !HAVE_CERTIFICATE_STATUS_REQUEST_V2 */
1344 
1345 	conn->flags = params->flags;
1346 
1347 	return 0;
1348 }
1349 
1350 
1351 static int tls_global_ca_cert(void *ssl_ctx, const char *ca_cert)
1352 {
1353 	WOLFSSL_CTX *ctx = ssl_ctx;
1354 
1355 	if (ca_cert) {
1356 		if (wolfSSL_CTX_load_verify_locations(ctx, ca_cert, NULL) != 1)
1357 		{
1358 			wpa_printf(MSG_WARNING,
1359 				   "Failed to load root certificates");
1360 			return -1;
1361 		}
1362 
1363 		wpa_printf(MSG_DEBUG,
1364 			   "TLS: Trusted root certificate(s) loaded");
1365 	}
1366 
1367 	return 0;
1368 }
1369 
1370 
1371 static int tls_global_client_cert(void *ssl_ctx, const char *client_cert)
1372 {
1373 	WOLFSSL_CTX *ctx = ssl_ctx;
1374 
1375 	if (!client_cert)
1376 		return 0;
1377 
1378 	if (wolfSSL_CTX_use_certificate_chain_file_format(ctx, client_cert,
1379 							  SSL_FILETYPE_ASN1) !=
1380 	    SSL_SUCCESS &&
1381 	    wolfSSL_CTX_use_certificate_chain_file(ctx, client_cert) !=
1382 	    SSL_SUCCESS) {
1383 		wpa_printf(MSG_INFO, "Failed to load client certificate");
1384 		return -1;
1385 	}
1386 
1387 	wpa_printf(MSG_DEBUG, "SSL: Loaded global client certificate: %s",
1388 		   client_cert);
1389 
1390 	return 0;
1391 }
1392 
1393 
1394 static int tls_global_private_key(void *ssl_ctx, const char *private_key,
1395 				  const char *private_key_passwd)
1396 {
1397 	WOLFSSL_CTX *ctx = ssl_ctx;
1398 	char *passwd = NULL;
1399 	int ret = 0;
1400 
1401 	if (!private_key)
1402 		return 0;
1403 
1404 	if (private_key_passwd) {
1405 		passwd = os_strdup(private_key_passwd);
1406 		if (!passwd)
1407 			return -1;
1408 	}
1409 
1410 	wolfSSL_CTX_set_default_passwd_cb(ctx, tls_passwd_cb);
1411 	wolfSSL_CTX_set_default_passwd_cb_userdata(ctx, passwd);
1412 
1413 	if (wolfSSL_CTX_use_PrivateKey_file(ctx, private_key,
1414 					    SSL_FILETYPE_ASN1) != 1 &&
1415 	    wolfSSL_CTX_use_PrivateKey_file(ctx, private_key,
1416 					    SSL_FILETYPE_PEM) != 1) {
1417 		wpa_printf(MSG_INFO, "Failed to load private key");
1418 		ret = -1;
1419 	}
1420 
1421 	wpa_printf(MSG_DEBUG, "SSL: Loaded global private key");
1422 
1423 	os_free(passwd);
1424 	wolfSSL_CTX_set_default_passwd_cb(ctx, NULL);
1425 
1426 	return ret;
1427 }
1428 
1429 
1430 static int tls_global_dh(void *ssl_ctx, const char *dh_file,
1431 			 const u8 *dh_blob, size_t blob_len)
1432 {
1433 	WOLFSSL_CTX *ctx = ssl_ctx;
1434 
1435 	if (!dh_file && !dh_blob)
1436 		return 0;
1437 
1438 	if (dh_blob) {
1439 		if (wolfSSL_CTX_SetTmpDH_buffer(ctx, dh_blob, blob_len,
1440 						SSL_FILETYPE_ASN1) < 0) {
1441 			wpa_printf(MSG_INFO,
1442 				   "SSL: global use DH DER blob failed");
1443 			return -1;
1444 		}
1445 		wpa_printf(MSG_DEBUG, "SSL: global use DH blob OK");
1446 		return 0;
1447 	}
1448 
1449 	if (dh_file) {
1450 		if (wolfSSL_CTX_SetTmpDH_file(ctx, dh_file, SSL_FILETYPE_PEM) <
1451 		    0) {
1452 			wpa_printf(MSG_INFO,
1453 				   "SSL: global use DH PEM file failed");
1454 			if (wolfSSL_CTX_SetTmpDH_file(ctx, dh_file,
1455 						      SSL_FILETYPE_ASN1) < 0) {
1456 				wpa_printf(MSG_INFO,
1457 					   "SSL: global use DH DER file failed");
1458 				return -1;
1459 			}
1460 		}
1461 		wpa_printf(MSG_DEBUG, "SSL: global use DH file OK");
1462 		return 0;
1463 	}
1464 
1465 	return 0;
1466 }
1467 
1468 
1469 #ifdef HAVE_OCSP
1470 
1471 int ocsp_status_cb(void *unused, const char *url, int url_sz,
1472 		   unsigned char *request, int request_sz,
1473 		   unsigned char **response)
1474 {
1475 	size_t len;
1476 
1477 	(void) unused;
1478 
1479 	if (!url) {
1480 		wpa_printf(MSG_DEBUG,
1481 			   "wolfSSL: OCSP status callback - no response configured");
1482 		*response = NULL;
1483 		return 0;
1484 	}
1485 
1486 	*response = (unsigned char *) os_readfile(url, &len);
1487 	if (!*response) {
1488 		wpa_printf(MSG_DEBUG,
1489 			   "wolfSSL: OCSP status callback - could not read response file");
1490 		return -1;
1491 	}
1492 	wpa_printf(MSG_DEBUG,
1493 		   "wolfSSL: OCSP status callback - send cached response");
1494 	return len;
1495 }
1496 
1497 
1498 void ocsp_resp_free_cb(void *ocsp_stapling_response, unsigned char *response)
1499 {
1500 	os_free(response);
1501 }
1502 
1503 #endif /* HAVE_OCSP */
1504 
1505 
1506 int tls_global_set_params(void *tls_ctx,
1507 			  const struct tls_connection_params *params)
1508 {
1509 	wpa_printf(MSG_DEBUG, "SSL: global set params");
1510 
1511 	if (params->check_cert_subject)
1512 		return -1; /* not yet supported */
1513 
1514 	if (tls_global_ca_cert(tls_ctx, params->ca_cert) < 0) {
1515 		wpa_printf(MSG_INFO, "SSL: Failed to load ca cert file '%s'",
1516 			   params->ca_cert);
1517 		return -1;
1518 	}
1519 
1520 	if (tls_global_client_cert(tls_ctx, params->client_cert) < 0) {
1521 		wpa_printf(MSG_INFO,
1522 			   "SSL: Failed to load client cert file '%s'",
1523 			   params->client_cert);
1524 		return -1;
1525 	}
1526 
1527 	if (tls_global_private_key(tls_ctx, params->private_key,
1528 				   params->private_key_passwd) < 0) {
1529 		wpa_printf(MSG_INFO,
1530 			   "SSL: Failed to load private key file '%s'",
1531 			   params->private_key);
1532 		return -1;
1533 	}
1534 
1535 	if (tls_global_dh(tls_ctx, params->dh_file, params->dh_blob,
1536 			  params->dh_blob_len) < 0) {
1537 		wpa_printf(MSG_INFO, "SSL: Failed to load DH file '%s'",
1538 			   params->dh_file);
1539 		return -1;
1540 	}
1541 
1542 	if (params->openssl_ciphers &&
1543 	    wolfSSL_CTX_set_cipher_list(tls_ctx,
1544 					params->openssl_ciphers) != 1) {
1545 		wpa_printf(MSG_INFO,
1546 			   "wolfSSL: Failed to set cipher string '%s'",
1547 			   params->openssl_ciphers);
1548 		return -1;
1549 	}
1550 
1551 	if (params->openssl_ecdh_curves) {
1552 		wpa_printf(MSG_INFO,
1553 			   "wolfSSL: openssl_ecdh_curves not supported");
1554 		return -1;
1555 	}
1556 
1557 #ifdef HAVE_SESSION_TICKET
1558 	/* Session ticket is off by default - can't disable once on. */
1559 	if (!(params->flags & TLS_CONN_DISABLE_SESSION_TICKET))
1560 		wolfSSL_CTX_UseSessionTicket(tls_ctx);
1561 #endif /* HAVE_SESSION_TICKET */
1562 
1563 #ifdef HAVE_OCSP
1564 	if (params->ocsp_stapling_response) {
1565 		wolfSSL_CTX_SetOCSP_OverrideURL(tls_ctx,
1566 						params->ocsp_stapling_response);
1567 		wolfSSL_CTX_SetOCSP_Cb(tls_ctx, ocsp_status_cb,
1568 				       ocsp_resp_free_cb, NULL);
1569 	}
1570 #endif /* HAVE_OCSP */
1571 
1572 	return 0;
1573 }
1574 
1575 
1576 int tls_global_set_verify(void *tls_ctx, int check_crl, int strict)
1577 {
1578 	wpa_printf(MSG_DEBUG, "SSL: global set verify: %d", check_crl);
1579 
1580 	if (check_crl) {
1581 		/* Hack to Enable CRLs. */
1582 		wolfSSL_CTX_LoadCRLBuffer(tls_ctx, NULL, 0, SSL_FILETYPE_PEM);
1583 	}
1584 
1585 	return 0;
1586 }
1587 
1588 
1589 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
1590 			      int verify_peer, unsigned int flags,
1591 			      const u8 *session_ctx, size_t session_ctx_len)
1592 {
1593 	if (!conn)
1594 		return -1;
1595 
1596 	wpa_printf(MSG_DEBUG, "SSL: set verify: %d", verify_peer);
1597 
1598 	if (verify_peer) {
1599 		conn->ca_cert_verify = 1;
1600 		wolfSSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
1601 				   SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1602 				   tls_verify_cb);
1603 	} else {
1604 		conn->ca_cert_verify = 0;
1605 		wolfSSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1606 	}
1607 
1608 	wolfSSL_set_accept_state(conn->ssl);
1609 
1610 	/* TODO: do we need to fake a session like OpenSSL does here? */
1611 
1612 	return 0;
1613 }
1614 
1615 
1616 static struct wpabuf * wolfssl_handshake(struct tls_connection *conn,
1617 					 const struct wpabuf *in_data,
1618 					 int server)
1619 {
1620 	int res;
1621 
1622 	wolfssl_reset_out_data(&conn->output);
1623 
1624 	/* Initiate TLS handshake or continue the existing handshake */
1625 	if (server) {
1626 		wolfSSL_set_accept_state(conn->ssl);
1627 		res = wolfSSL_accept(conn->ssl);
1628 		wpa_printf(MSG_DEBUG, "SSL: wolfSSL_accept: %d", res);
1629 	} else {
1630 		wolfSSL_set_connect_state(conn->ssl);
1631 		res = wolfSSL_connect(conn->ssl);
1632 		wpa_printf(MSG_DEBUG, "SSL: wolfSSL_connect: %d", res);
1633 	}
1634 
1635 	if (res != 1) {
1636 		int err = wolfSSL_get_error(conn->ssl, res);
1637 
1638 		if (err == SSL_ERROR_WANT_READ) {
1639 			wpa_printf(MSG_DEBUG,
1640 				   "SSL: wolfSSL_connect - want more data");
1641 		} else if (err == SSL_ERROR_WANT_WRITE) {
1642 			wpa_printf(MSG_DEBUG,
1643 				   "SSL: wolfSSL_connect - want to write");
1644 		} else {
1645 			char msg[80];
1646 
1647 			wpa_printf(MSG_DEBUG,
1648 				   "SSL: wolfSSL_connect - failed %s",
1649 				   wolfSSL_ERR_error_string(err, msg));
1650 			conn->failed++;
1651 		}
1652 	}
1653 
1654 	return conn->output.out_data;
1655 }
1656 
1657 
1658 static struct wpabuf * wolfssl_get_appl_data(struct tls_connection *conn,
1659 					     size_t max_len)
1660 {
1661 	int res;
1662 	struct wpabuf *appl_data = wpabuf_alloc(max_len + 100);
1663 
1664 	if (!appl_data)
1665 		return NULL;
1666 
1667 	res = wolfSSL_read(conn->ssl, wpabuf_mhead(appl_data),
1668 			   wpabuf_size(appl_data));
1669 	if (res < 0) {
1670 		int err = wolfSSL_get_error(conn->ssl, res);
1671 
1672 		if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
1673 			wpa_printf(MSG_DEBUG,
1674 				   "SSL: No Application Data included");
1675 		} else {
1676 			char msg[80];
1677 
1678 			wpa_printf(MSG_DEBUG,
1679 				   "Failed to read possible Application Data %s",
1680 				   wolfSSL_ERR_error_string(err, msg));
1681 		}
1682 
1683 		wpabuf_free(appl_data);
1684 		return NULL;
1685 	}
1686 
1687 	wpabuf_put(appl_data, res);
1688 	wpa_hexdump_buf_key(MSG_MSGDUMP,
1689 			    "SSL: Application Data in Finished message",
1690 			    appl_data);
1691 	return appl_data;
1692 }
1693 
1694 
1695 static struct wpabuf *
1696 wolfssl_connection_handshake(struct tls_connection *conn,
1697 			     const struct wpabuf *in_data,
1698 			     struct wpabuf **appl_data, int server)
1699 {
1700 	struct wpabuf *out_data;
1701 
1702 	wolfssl_reset_in_data(&conn->input, in_data);
1703 
1704 	if (appl_data)
1705 		*appl_data = NULL;
1706 
1707 	out_data = wolfssl_handshake(conn, in_data, server);
1708 	if (!out_data)
1709 		return NULL;
1710 
1711 	if (wolfSSL_is_init_finished(conn->ssl)) {
1712 		wpa_printf(MSG_DEBUG,
1713 			   "wolfSSL: Handshake finished - resumed=%d",
1714 			   tls_connection_resumed(NULL, conn));
1715 		if (appl_data && in_data)
1716 			*appl_data = wolfssl_get_appl_data(conn,
1717 							   wpabuf_len(in_data));
1718 	}
1719 
1720 	return out_data;
1721 }
1722 
1723 
1724 struct wpabuf * tls_connection_handshake(void *tls_ctx,
1725 					 struct tls_connection *conn,
1726 					 const struct wpabuf *in_data,
1727 					 struct wpabuf **appl_data)
1728 {
1729 	return wolfssl_connection_handshake(conn, in_data, appl_data, 0);
1730 }
1731 
1732 
1733 struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
1734 						struct tls_connection *conn,
1735 						const struct wpabuf *in_data,
1736 						struct wpabuf **appl_data)
1737 {
1738 	return wolfssl_connection_handshake(conn, in_data, appl_data, 1);
1739 }
1740 
1741 
1742 struct wpabuf * tls_connection_encrypt(void *tls_ctx,
1743 				       struct tls_connection *conn,
1744 				       const struct wpabuf *in_data)
1745 {
1746 	int res;
1747 
1748 	if (!conn)
1749 		return NULL;
1750 
1751 	wpa_printf(MSG_DEBUG, "SSL: encrypt: %zu bytes", wpabuf_len(in_data));
1752 
1753 	wolfssl_reset_out_data(&conn->output);
1754 
1755 	res = wolfSSL_write(conn->ssl, wpabuf_head(in_data),
1756 			    wpabuf_len(in_data));
1757 	if (res < 0) {
1758 		int  err = wolfSSL_get_error(conn->ssl, res);
1759 		char msg[80];
1760 
1761 		wpa_printf(MSG_INFO, "Encryption failed - SSL_write: %s",
1762 			   wolfSSL_ERR_error_string(err, msg));
1763 		return NULL;
1764 	}
1765 
1766 	return conn->output.out_data;
1767 }
1768 
1769 
1770 struct wpabuf * tls_connection_decrypt(void *tls_ctx,
1771 				       struct tls_connection *conn,
1772 				       const struct wpabuf *in_data)
1773 {
1774 	int res;
1775 	struct wpabuf *buf;
1776 
1777 	if (!conn)
1778 		return NULL;
1779 
1780 	wpa_printf(MSG_DEBUG, "SSL: decrypt");
1781 
1782 	wolfssl_reset_in_data(&conn->input, in_data);
1783 
1784 	/* Read decrypted data for further processing */
1785 	/*
1786 	 * Even though we try to disable TLS compression, it is possible that
1787 	 * this cannot be done with all TLS libraries. Add extra buffer space
1788 	 * to handle the possibility of the decrypted data being longer than
1789 	 * input data.
1790 	 */
1791 	buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
1792 	if (!buf)
1793 		return NULL;
1794 	res = wolfSSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
1795 	if (res < 0) {
1796 		wpa_printf(MSG_INFO, "Decryption failed - SSL_read");
1797 		wpabuf_free(buf);
1798 		return NULL;
1799 	}
1800 	wpabuf_put(buf, res);
1801 
1802 	wpa_printf(MSG_DEBUG, "SSL: decrypt: %zu bytes", wpabuf_len(buf));
1803 
1804 	return buf;
1805 }
1806 
1807 
1808 int tls_connection_resumed(void *tls_ctx, struct tls_connection *conn)
1809 {
1810 	return conn ? wolfSSL_session_reused(conn->ssl) : 0;
1811 }
1812 
1813 
1814 int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
1815 				   u8 *ciphers)
1816 {
1817 	char buf[128], *pos, *end;
1818 	u8 *c;
1819 	int ret;
1820 
1821 	if (!conn || !conn->ssl || !ciphers)
1822 		return -1;
1823 
1824 	buf[0] = '\0';
1825 	pos = buf;
1826 	end = pos + sizeof(buf);
1827 
1828 	c = ciphers;
1829 	while (*c != TLS_CIPHER_NONE) {
1830 		const char *suite;
1831 
1832 		switch (*c) {
1833 		case TLS_CIPHER_RC4_SHA:
1834 			suite = "RC4-SHA";
1835 			break;
1836 		case TLS_CIPHER_AES128_SHA:
1837 			suite = "AES128-SHA";
1838 			break;
1839 		case TLS_CIPHER_RSA_DHE_AES128_SHA:
1840 			suite = "DHE-RSA-AES128-SHA";
1841 			break;
1842 		case TLS_CIPHER_ANON_DH_AES128_SHA:
1843 			suite = "ADH-AES128-SHA";
1844 			break;
1845 		case TLS_CIPHER_RSA_DHE_AES256_SHA:
1846 			suite = "DHE-RSA-AES256-SHA";
1847 			break;
1848 		case TLS_CIPHER_AES256_SHA:
1849 			suite = "AES256-SHA";
1850 			break;
1851 		default:
1852 			wpa_printf(MSG_DEBUG,
1853 				   "TLS: Unsupported cipher selection: %d", *c);
1854 			return -1;
1855 		}
1856 		ret = os_snprintf(pos, end - pos, ":%s", suite);
1857 		if (os_snprintf_error(end - pos, ret))
1858 			break;
1859 		pos += ret;
1860 
1861 		c++;
1862 	}
1863 
1864 	wpa_printf(MSG_DEBUG, "wolfSSL: cipher suites: %s", buf + 1);
1865 
1866 	if (wolfSSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
1867 		wpa_printf(MSG_DEBUG, "Cipher suite configuration failed");
1868 		return -1;
1869 	}
1870 
1871 	return 0;
1872 }
1873 
1874 
1875 int tls_get_cipher(void *tls_ctx, struct tls_connection *conn,
1876 		   char *buf, size_t buflen)
1877 {
1878 	WOLFSSL_CIPHER *cipher;
1879 	const char *name;
1880 
1881 	if (!conn || !conn->ssl)
1882 		return -1;
1883 
1884 	cipher = wolfSSL_get_current_cipher(conn->ssl);
1885 	if (!cipher)
1886 		return -1;
1887 
1888 	name = wolfSSL_CIPHER_get_name(cipher);
1889 	if (!name)
1890 		return -1;
1891 
1892 	if (os_strcmp(name, "SSL_RSA_WITH_RC4_128_SHA") == 0)
1893 		os_strlcpy(buf, "RC4-SHA", buflen);
1894 	else if (os_strcmp(name, "TLS_RSA_WITH_AES_128_CBC_SHA") == 0)
1895 		os_strlcpy(buf, "AES128-SHA", buflen);
1896 	else if (os_strcmp(name, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA") == 0)
1897 		os_strlcpy(buf, "DHE-RSA-AES128-SHA", buflen);
1898 	else if (os_strcmp(name, "TLS_DH_anon_WITH_AES_128_CBC_SHA") == 0)
1899 		os_strlcpy(buf, "ADH-AES128-SHA", buflen);
1900 	else if (os_strcmp(name, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA") == 0)
1901 		os_strlcpy(buf, "DHE-RSA-AES256-SHA", buflen);
1902 	else if (os_strcmp(name, "TLS_RSA_WITH_AES_256_CBC_SHA") == 0)
1903 		os_strlcpy(buf, "AES256-SHA", buflen);
1904 	else
1905 		os_strlcpy(buf, name, buflen);
1906 
1907 	return 0;
1908 }
1909 
1910 
1911 int tls_connection_enable_workaround(void *tls_ctx,
1912 				     struct tls_connection *conn)
1913 {
1914 	/* no empty fragments in wolfSSL for now */
1915 	return 0;
1916 }
1917 
1918 
1919 int tls_connection_get_failed(void *tls_ctx, struct tls_connection *conn)
1920 {
1921 	if (!conn)
1922 		return -1;
1923 
1924 	return conn->failed;
1925 }
1926 
1927 
1928 int tls_connection_get_read_alerts(void *tls_ctx, struct tls_connection *conn)
1929 {
1930 	if (!conn)
1931 		return -1;
1932 
1933 	/* TODO: this is not incremented anywhere */
1934 	return conn->read_alerts;
1935 }
1936 
1937 
1938 int tls_connection_get_write_alerts(void *tls_ctx,
1939 				    struct tls_connection *conn)
1940 {
1941 	if (!conn)
1942 		return -1;
1943 
1944 	/* TODO: this is not incremented anywhere */
1945 	return conn->write_alerts;
1946 }
1947 
1948 
1949 
1950 int tls_get_library_version(char *buf, size_t buf_len)
1951 {
1952 	return os_snprintf(buf, buf_len, "wolfSSL build=%s run=%s",
1953 			   WOLFSSL_VERSION, wolfSSL_lib_version());
1954 }
1955 
1956 int tls_get_version(void *ssl_ctx, struct tls_connection *conn,
1957 		    char *buf, size_t buflen)
1958 {
1959 	const char *name;
1960 
1961 	if (!conn || !conn->ssl)
1962 		return -1;
1963 
1964 	name = wolfSSL_get_version(conn->ssl);
1965 	if (!name)
1966 		return -1;
1967 
1968 	os_strlcpy(buf, name, buflen);
1969 	return 0;
1970 }
1971 
1972 
1973 int tls_connection_get_random(void *ssl_ctx, struct tls_connection *conn,
1974 			      struct tls_random *keys)
1975 {
1976 	WOLFSSL *ssl;
1977 
1978 	if (!conn || !keys)
1979 		return -1;
1980 	ssl = conn->ssl;
1981 	if (!ssl)
1982 		return -1;
1983 
1984 	os_memset(keys, 0, sizeof(*keys));
1985 	keys->client_random = conn->client_random;
1986 	keys->client_random_len = wolfSSL_get_client_random(
1987 		ssl, conn->client_random, sizeof(conn->client_random));
1988 	keys->server_random = conn->server_random;
1989 	keys->server_random_len = wolfSSL_get_server_random(
1990 		ssl, conn->server_random, sizeof(conn->server_random));
1991 
1992 	return 0;
1993 }
1994 
1995 
1996 int tls_connection_export_key(void *tls_ctx, struct tls_connection *conn,
1997 			      const char *label, const u8 *context,
1998 			      size_t context_len, u8 *out, size_t out_len)
1999 {
2000 	if (context)
2001 		return -1;
2002 	if (!conn || wolfSSL_make_eap_keys(conn->ssl, out, out_len, label) != 0)
2003 		return -1;
2004 	return 0;
2005 }
2006 
2007 
2008 #define SEED_LEN	(RAN_LEN + RAN_LEN)
2009 
2010 int tls_connection_get_eap_fast_key(void *tls_ctx, struct tls_connection *conn,
2011 				    u8 *out, size_t out_len)
2012 {
2013 	byte seed[SEED_LEN];
2014 	int ret = -1;
2015 	WOLFSSL *ssl;
2016 	byte *tmp_out;
2017 	byte *_out;
2018 	int skip = 0;
2019 	byte *master_key;
2020 	unsigned int master_key_len;
2021 	byte *server_random;
2022 	unsigned int server_len;
2023 	byte *client_random;
2024 	unsigned int client_len;
2025 
2026 	if (!conn || !conn->ssl)
2027 		return -1;
2028 	ssl = conn->ssl;
2029 
2030 	skip = 2 * (wolfSSL_GetKeySize(ssl) + wolfSSL_GetHmacSize(ssl) +
2031 		    wolfSSL_GetIVSize(ssl));
2032 
2033 	tmp_out = os_malloc(skip + out_len);
2034 	if (!tmp_out)
2035 		return -1;
2036 	_out = tmp_out;
2037 
2038 	wolfSSL_get_keys(ssl, &master_key, &master_key_len, &server_random,
2039 			 &server_len, &client_random, &client_len);
2040 	os_memcpy(seed, server_random, RAN_LEN);
2041 	os_memcpy(seed + RAN_LEN, client_random, RAN_LEN);
2042 
2043 	if (wolfSSL_GetVersion(ssl) == WOLFSSL_TLSV1_2) {
2044 		tls_prf_sha256(master_key, master_key_len,
2045 			       "key expansion", seed, sizeof(seed),
2046 			       _out, skip + out_len);
2047 		ret = 0;
2048 	} else {
2049 		ret = tls_prf_sha1_md5(master_key, master_key_len,
2050 				       "key expansion", seed, sizeof(seed),
2051 				       _out, skip + out_len);
2052 	}
2053 
2054 	forced_memzero(master_key, master_key_len);
2055 	if (ret == 0)
2056 		os_memcpy(out, _out + skip, out_len);
2057 	bin_clear_free(tmp_out, skip + out_len);
2058 
2059 	return ret;
2060 }
2061 
2062 
2063 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
2064 
2065 int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
2066 				    int ext_type, const u8 *data,
2067 				    size_t data_len)
2068 {
2069 	(void) ssl_ctx;
2070 
2071 	if (!conn || !conn->ssl || ext_type != 35)
2072 		return -1;
2073 
2074 	if (wolfSSL_set_SessionTicket(conn->ssl, data,
2075 				      (unsigned int) data_len) != 1)
2076 		return -1;
2077 
2078 	return 0;
2079 }
2080 
2081 
2082 static int tls_sess_sec_cb(WOLFSSL *s, void *secret, int *secret_len, void *arg)
2083 {
2084 	struct tls_connection *conn = arg;
2085 	int ret;
2086 	unsigned char client_random[RAN_LEN];
2087 	unsigned char server_random[RAN_LEN];
2088 	word32 ticket_len = sizeof(conn->session_ticket);
2089 
2090 	if (!conn || !conn->session_ticket_cb)
2091 		return 1;
2092 
2093 	if (wolfSSL_get_client_random(s, client_random,
2094 				      sizeof(client_random)) == 0 ||
2095 	    wolfSSL_get_server_random(s, server_random,
2096 				      sizeof(server_random)) == 0 ||
2097 	    wolfSSL_get_SessionTicket(s, conn->session_ticket,
2098 				      &ticket_len) != 1)
2099 		return 1;
2100 
2101 	if (ticket_len == 0)
2102 		return 0;
2103 
2104 	ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
2105 				      conn->session_ticket, ticket_len,
2106 				      client_random, server_random, secret);
2107 	if (ret <= 0)
2108 		return 1;
2109 
2110 	*secret_len = SECRET_LEN;
2111 	return 0;
2112 }
2113 
2114 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
2115 
2116 
2117 int tls_connection_set_session_ticket_cb(void *tls_ctx,
2118 					 struct tls_connection *conn,
2119 					 tls_session_ticket_cb cb,
2120 					 void *ctx)
2121 {
2122 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
2123 	conn->session_ticket_cb = cb;
2124 	conn->session_ticket_cb_ctx = ctx;
2125 
2126 	if (cb) {
2127 		if (wolfSSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
2128 						  conn) != 1)
2129 			return -1;
2130 	} else {
2131 		if (wolfSSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
2132 			return -1;
2133 	}
2134 
2135 	return 0;
2136 #else /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
2137 	return -1;
2138 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
2139 }
2140 
2141 
2142 void tls_connection_set_success_data_resumed(struct tls_connection *conn)
2143 {
2144 	wpa_printf(MSG_DEBUG,
2145 		   "wolfSSL: Success data accepted for resumed session");
2146 }
2147 
2148 
2149 void tls_connection_remove_session(struct tls_connection *conn)
2150 {
2151 	WOLFSSL_SESSION *sess;
2152 
2153 	sess = wolfSSL_get_session(conn->ssl);
2154 	if (!sess)
2155 		return;
2156 
2157 	wolfSSL_SSL_SESSION_set_timeout(sess, 0);
2158 	wpa_printf(MSG_DEBUG,
2159 		   "wolfSSL: Removed cached session to disable session resumption");
2160 }
2161 
2162 
2163 void tls_connection_set_success_data(struct tls_connection *conn,
2164 				     struct wpabuf *data)
2165 {
2166 	WOLFSSL_SESSION *sess;
2167 	struct wpabuf *old;
2168 
2169 	wpa_printf(MSG_DEBUG, "wolfSSL: Set success data");
2170 
2171 	sess = wolfSSL_get_session(conn->ssl);
2172 	if (!sess) {
2173 		wpa_printf(MSG_DEBUG,
2174 			   "wolfSSL: No session found for success data");
2175 		goto fail;
2176 	}
2177 
2178 	old = wolfSSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
2179 	if (old) {
2180 		wpa_printf(MSG_DEBUG, "wolfSSL: Replacing old success data %p",
2181 			   old);
2182 		wpabuf_free(old);
2183 	}
2184 	if (wolfSSL_SESSION_set_ex_data(sess, tls_ex_idx_session, data) != 1)
2185 		goto fail;
2186 
2187 	wpa_printf(MSG_DEBUG, "wolfSSL: Stored success data %p", data);
2188 	conn->success_data = 1;
2189 	return;
2190 
2191 fail:
2192 	wpa_printf(MSG_INFO, "wolfSSL: Failed to store success data");
2193 	wpabuf_free(data);
2194 }
2195 
2196 
2197 const struct wpabuf *
2198 tls_connection_get_success_data(struct tls_connection *conn)
2199 {
2200 	WOLFSSL_SESSION *sess;
2201 
2202 	wpa_printf(MSG_DEBUG, "wolfSSL: Get success data");
2203 
2204 	sess = wolfSSL_get_session(conn->ssl);
2205 	if (!sess)
2206 		return NULL;
2207 	return wolfSSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
2208 }
2209