xref: /titanic_52/usr/src/uts/common/inet/kssl/ksslrec.c (revision 8d61a337e3509e92fccb0fdeb26db712c21d43cd)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  */
24 
25 #include <sys/types.h>
26 #include <sys/stream.h>
27 #include <sys/strsubr.h>
28 #include <sys/stropts.h>
29 #include <sys/strsun.h>
30 #define	_SUN_TPI_VERSION 2
31 #include <sys/ddi.h>
32 #include <sys/sunddi.h>
33 #include <sys/debug.h>
34 #include <sys/vtrace.h>
35 #include <sys/kmem.h>
36 #include <sys/cpuvar.h>
37 #include <sys/atomic.h>
38 #include <sys/sysmacros.h>
39 
40 #include <sys/errno.h>
41 #include <sys/isa_defs.h>
42 #include <sys/md5.h>
43 #include <sys/sha1.h>
44 #include <sys/random.h>
45 #include <inet/common.h>
46 #include <netinet/in.h>
47 
48 #include <sys/systm.h>
49 #include <sys/param.h>
50 
51 #include "ksslimpl.h"
52 #include "ksslapi.h"
53 #include "ksslproto.h"
54 
55 static ssl3CipherSuiteDef cipher_suite_defs[] = {
56 	/* 2 X 16 byte keys +  2 x 20 byte MAC secrets, no IVs */
57 	{SSL_RSA_WITH_RC4_128_SHA,	cipher_rc4,	mac_sha,	72},
58 
59 	/* 2 X 16 byte keys +  2 x 16 byte MAC secrets, no IVs */
60 	{SSL_RSA_WITH_RC4_128_MD5,	cipher_rc4,	mac_md5,	64},
61 
62 	/* 2 X 8 byte keys +  2 x 20 byte MAC secrets, 2 x 8 byte IVs */
63 	{SSL_RSA_WITH_DES_CBC_SHA,	cipher_des,	mac_sha,	72},
64 
65 	/* 2 X 24 byte keys +  2 x 20 byte MAC secrets, 2 x 8 byte IVs */
66 	{SSL_RSA_WITH_3DES_EDE_CBC_SHA,	cipher_3des,	mac_sha,	104},
67 
68 	/* 2 X 16 byte keys +  2 x 20 byte MAC secrets, 2 x 16 byte IVs */
69 	{TLS_RSA_WITH_AES_128_CBC_SHA,	cipher_aes128,	mac_sha,	104},
70 
71 	/* 2 X 32 byte keys +  2 x 20 byte MAC secrets, 2 x 16 byte IVs */
72 	{TLS_RSA_WITH_AES_256_CBC_SHA,	cipher_aes256,	mac_sha,	136},
73 
74 	{SSL_RSA_WITH_NULL_SHA,		cipher_null,	mac_sha,	40}
75 };
76 
77 static int cipher_suite_defs_nentries =
78     sizeof (cipher_suite_defs) / sizeof (cipher_suite_defs[0]);
79 
80 static KSSLMACDef mac_defs[] = { /* indexed by SSL3MACAlgorithm */
81 	/* macsz padsz HashInit HashUpdate HashFinal */
82 
83 	{MD5_HASH_LEN, SSL3_MD5_PAD_LEN,
84 	    (hashinit_func_t)MD5Init, (hashupdate_func_t)MD5Update,
85 	    (hashfinal_func_t)MD5Final},
86 
87 	{SHA1_HASH_LEN, SSL3_SHA1_PAD_LEN,
88 	    (hashinit_func_t)SHA1Init, (hashupdate_func_t)SHA1Update,
89 	    (hashfinal_func_t)SHA1Final},
90 };
91 
92 static uchar_t kssl_pad_1[60] = {
93     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
94     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
95     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
96     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
97     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
98     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
99     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
100     0x36, 0x36, 0x36, 0x36
101 };
102 static uchar_t kssl_pad_2[60] = {
103     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
104     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
105     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
106     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
107     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
108     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
109     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
110     0x5c, 0x5c, 0x5c, 0x5c
111 };
112 
113 int kssl_cache_count;
114 static boolean_t kssl_synchronous = B_FALSE;
115 
116 static void kssl_update_handshake_hashes(ssl_t *, uchar_t *, uint_t);
117 static int kssl_compute_handshake_hashes(ssl_t *, SSL3Hashes *, uint32_t);
118 static int kssl_handle_client_hello(ssl_t *, mblk_t *, int);
119 static int kssl_handle_client_key_exchange(ssl_t *, mblk_t *, int,
120     kssl_callback_t, void *);
121 static int kssl_send_server_hello(ssl_t *);
122 static int kssl_send_certificate_and_server_hello_done(ssl_t *);
123 static int kssl_send_change_cipher_specs(ssl_t *);
124 static int kssl_send_finished(ssl_t *, int);
125 static int kssl_handle_finished(ssl_t *, mblk_t *, int);
126 static void kssl_get_hello_random(uchar_t *);
127 static uchar_t *kssl_rsa_unwrap(uchar_t *, size_t *);
128 static void kssl_cache_sid(sslSessionID *, kssl_entry_t *);
129 static void kssl_lookup_sid(sslSessionID *, uchar_t *, in6_addr_t *,
130     kssl_entry_t *);
131 static int kssl_generate_tls_ms(ssl_t *, uchar_t *, size_t);
132 static void kssl_generate_ssl_ms(ssl_t *, uchar_t *, size_t);
133 static int kssl_generate_tls_keyblock(ssl_t *);
134 static void kssl_generate_keyblock(ssl_t *);
135 static void kssl_ssl3_key_material_derive_step(ssl_t *, uchar_t *, size_t,
136     int, uchar_t *, int);
137 static int kssl_tls_PRF(ssl_t *, uchar_t *, size_t,
138     uchar_t *, size_t, uchar_t *, size_t, uchar_t *, size_t);
139 static int kssl_tls_P_hash(crypto_mechanism_t *, crypto_key_t *,
140     size_t, uchar_t *, size_t, uchar_t *, size_t, uchar_t *, size_t);
141 static void kssl_cke_done(void *, int);
142 
143 #define	HMAC_INIT(m, k, c) \
144 	rv = crypto_mac_init(m, k, NULL, c, NULL); if (CRYPTO_ERR(rv)) goto end;
145 
146 #define	HMAC_UPDATE(c, d, l) \
147 	dd.cd_raw.iov_base = (char *)d; \
148 	dd.cd_length = dd.cd_raw.iov_len = l; \
149 	rv = crypto_mac_update(c, &dd, NULL); if (CRYPTO_ERR(rv)) goto end;
150 
151 #define	HMAC_FINAL(c, d, l) \
152 	mac.cd_raw.iov_base = (char *)d; \
153 	mac.cd_length = mac.cd_raw.iov_len = l; \
154 	rv = crypto_mac_final(c, &mac, NULL); if (CRYPTO_ERR(rv)) goto end;
155 
156 /*
157  * This hack can go away once we have SSL3 MAC support by KCF
158  * software providers (See 4873559).
159  */
160 extern int kcf_md5_threshold;
161 
162 int
163 kssl_compute_record_mac(
164 	ssl_t *ssl,
165 	int direction,
166 	uint64_t seq_num,
167 	SSL3ContentType ct,
168 	uchar_t *versionp,
169 	uchar_t *buf,
170 	int len,
171 	uchar_t *digest)
172 {
173 	KSSL_HASHCTX mac_ctx;
174 	KSSL_HASHCTX *ctx = &mac_ctx;
175 	uchar_t temp[16], *p;
176 	KSSLCipherSpec *spec;
177 	boolean_t hash_use_ok = B_FALSE;
178 	int rv = 0;
179 
180 	spec = &ssl->spec[direction];
181 
182 	if (spec->mac_hashsz == 0) {
183 		return (1);
184 	}
185 
186 	p = temp;
187 
188 	*p++ = (seq_num >> 56) & 0xff;
189 	*p++ = (seq_num >> 48) & 0xff;
190 	*p++ = (seq_num >> 40) & 0xff;
191 	*p++ = (seq_num >> 32) & 0xff;
192 	*p++ = (seq_num >> 24) & 0xff;
193 	*p++ = (seq_num >> 16) & 0xff;
194 	*p++ = (seq_num >> 8) & 0xff;
195 	*p++ = (seq_num) & 0xff;
196 	*p++ = (uchar_t)ct;
197 	if (IS_TLS(ssl)) {
198 		*p++ = versionp[0];
199 		*p++ = versionp[1];
200 	}
201 	*p++ = (len >> 8) & 0xff;
202 	*p++ = (len) & 0xff;
203 
204 	if (IS_TLS(ssl) || (spec->hmac_mech.cm_type != CRYPTO_MECH_INVALID &&
205 	    len >= kcf_md5_threshold)) {
206 		crypto_data_t dd, mac;
207 		struct uio uio_pt;
208 		struct iovec iovarray_pt[2];
209 
210 		/* init the array of iovecs for use in the uio struct */
211 		iovarray_pt[0].iov_base = (char *)temp;
212 		iovarray_pt[0].iov_len = (p - temp);
213 		iovarray_pt[1].iov_base = (char *)buf;
214 		iovarray_pt[1].iov_len = len;
215 
216 		/* init the uio struct for use in the crypto_data_t struct */
217 		bzero(&uio_pt, sizeof (uio_pt));
218 		uio_pt.uio_iov = iovarray_pt;
219 		uio_pt.uio_iovcnt = 2;
220 		uio_pt.uio_segflg = UIO_SYSSPACE;
221 
222 		dd.cd_format = CRYPTO_DATA_UIO;
223 		dd.cd_offset = 0;
224 		dd.cd_length =  (p - temp) + len;
225 		dd.cd_miscdata = NULL;
226 		dd.cd_uio = &uio_pt;
227 
228 		mac.cd_format = CRYPTO_DATA_RAW;
229 		mac.cd_offset = 0;
230 		mac.cd_raw.iov_base = (char *)digest;
231 		mac.cd_length = mac.cd_raw.iov_len = spec->mac_hashsz;
232 
233 		/*
234 		 * The calling context can tolerate a blocking call here.
235 		 * For outgoing traffic, we are in user context
236 		 * when called from strsock_kssl_output(). For incoming
237 		 * traffic past the SSL handshake, we are in user
238 		 * context when called from strsock_kssl_input(). During the
239 		 * SSL handshake, we are called for client_finished message
240 		 * handling from a squeue worker thread that gets scheduled
241 		 * by an SQ_FILL call. This thread is not in interrupt
242 		 * context and so can block.
243 		 */
244 		rv = crypto_mac(&spec->hmac_mech, &dd, &spec->hmac_key,
245 		    NULL, &mac, NULL);
246 
247 		if (CRYPTO_ERR(rv)) {
248 			hash_use_ok = (rv == CRYPTO_MECH_NOT_SUPPORTED &&
249 			    !IS_TLS(ssl));
250 			if (!hash_use_ok) {
251 				DTRACE_PROBE1(kssl_err__crypto_mac_error,
252 				    int, rv);
253 				KSSL_COUNTER(compute_mac_failure, 1);
254 			}
255 		}
256 	} else
257 		hash_use_ok = B_TRUE;
258 
259 	if (hash_use_ok) {
260 		bcopy(&(ssl->mac_ctx[direction][0]), ctx,
261 		    sizeof (KSSL_HASHCTX));
262 		spec->MAC_HashUpdate((void *)ctx, temp, p - temp);
263 		spec->MAC_HashUpdate((void *)ctx, buf, len);
264 		spec->MAC_HashFinal(digest, (void *)ctx);
265 
266 		bcopy(&(ssl->mac_ctx[direction][1]), ctx,
267 		    sizeof (KSSL_HASHCTX));
268 		spec->MAC_HashUpdate((void *)ctx, digest, spec->mac_hashsz);
269 		spec->MAC_HashFinal(digest, (void *)ctx);
270 	}
271 
272 	return (rv);
273 }
274 
275 /*
276  * Handles handshake messages.
277  * Messages to be replied are returned in handshake_sendbuf.
278  */
279 int
280 kssl_handle_handshake_message(ssl_t *ssl, mblk_t *mp, int *err,
281     kssl_callback_t cbfn, void *arg)
282 {
283 	uint32_t msglen;
284 	uchar_t msghdr[4];
285 
286 	ASSERT(ssl->msg.state == MSG_BODY);
287 	ASSERT(ssl->msg.msglen_bytes == 3);
288 	ASSERT(mp->b_wptr >= mp->b_rptr + ssl->msg.msglen);
289 
290 	ssl->sslcnt++;
291 	msglen = ssl->msg.msglen;
292 
293 	if (ssl->msg.type == client_hello) {
294 		MD5Init(&ssl->hs_md5);
295 		SHA1Init(&ssl->hs_sha1);
296 	}
297 
298 	if (ssl->msg.type == finished && ssl->resumed == B_FALSE) {
299 		if (kssl_compute_handshake_hashes(ssl, &ssl->hs_hashes,
300 		    sender_client) != 0) {
301 			*err = SSL_MISS;
302 			return (0);
303 		}
304 	}
305 
306 	if (ssl->msg.type != finished || ssl->resumed == B_FALSE) {
307 		msghdr[0] = (uchar_t)ssl->msg.type;
308 
309 		msghdr[1] = (uchar_t)(msglen >> 16);
310 		msghdr[2] = (uchar_t)(msglen >> 8);
311 		msghdr[3] = (uchar_t)(msglen);
312 		kssl_update_handshake_hashes(ssl, msghdr, 4);
313 		kssl_update_handshake_hashes(ssl, mp->b_rptr, msglen);
314 	}
315 
316 	ssl->msg.state = MSG_INIT;
317 	ssl->msg.msglen = 0;
318 	ssl->msg.msglen_bytes = 0;
319 
320 	switch (ssl->msg.type) {
321 	case client_hello:
322 		if (ssl->hs_waitstate != wait_client_hello) {
323 			kssl_send_alert(ssl, alert_fatal,
324 			    unexpected_message);
325 			*err = EBADMSG;
326 			ssl->activeinput = B_FALSE;
327 			return (1);
328 		}
329 		*err = kssl_handle_client_hello(ssl, mp, msglen);
330 		if (*err == SSL_MISS) {
331 			ssl->activeinput = B_FALSE;
332 			return (0);
333 		}
334 		return (1);
335 	case client_key_exchange:
336 		if (ssl->hs_waitstate != wait_client_key) {
337 			kssl_send_alert(ssl, alert_fatal,
338 			    unexpected_message);
339 			*err = EBADMSG;
340 			ssl->activeinput = B_FALSE;
341 			return (1);
342 		}
343 		*err = kssl_handle_client_key_exchange(ssl, mp,
344 		    msglen, cbfn, arg);
345 		return (1);
346 	case finished:
347 		if (ssl->hs_waitstate != wait_finished) {
348 			kssl_send_alert(ssl, alert_fatal,
349 			    unexpected_message);
350 			*err = EBADMSG;
351 			ssl->activeinput = B_FALSE;
352 			return (1);
353 		}
354 		*err = kssl_handle_finished(ssl, mp, msglen);
355 		return (1);
356 	default:
357 		kssl_send_alert(ssl, alert_fatal, unexpected_message);
358 		ssl->activeinput = B_FALSE;
359 		*err = EBADMSG;
360 		return (1);
361 	}
362 }
363 
364 static void
365 kssl_update_handshake_hashes(ssl_t *ssl, uchar_t *buf, uint_t len)
366 {
367 	MD5Update(&ssl->hs_md5, buf, len);
368 	SHA1Update(&ssl->hs_sha1, buf, len);
369 }
370 
371 static int
372 kssl_compute_handshake_hashes(
373 	ssl_t *ssl,
374 	SSL3Hashes *hashes,
375 	uint32_t sender)
376 {
377 	MD5_CTX md5 = ssl->hs_md5;	/* clone md5 context */
378 	SHA1_CTX sha1 = ssl->hs_sha1;	/* clone sha1 context */
379 	MD5_CTX *md5ctx = &md5;
380 	SHA1_CTX *sha1ctx = &sha1;
381 
382 	if (IS_TLS(ssl)) {
383 		uchar_t seed[MD5_HASH_LEN + SHA1_HASH_LEN];
384 		char *label;
385 
386 		/*
387 		 * Do not take another hash step here.
388 		 * Just complete the operation.
389 		 */
390 		MD5Final(hashes->md5, md5ctx);
391 		SHA1Final(hashes->sha1, sha1ctx);
392 
393 		bcopy(hashes->md5, seed, MD5_HASH_LEN);
394 		bcopy(hashes->sha1, seed + MD5_HASH_LEN, SHA1_HASH_LEN);
395 
396 		if (sender == sender_client)
397 			label = TLS_CLIENT_FINISHED_LABEL;
398 		else
399 			label = TLS_SERVER_FINISHED_LABEL;
400 
401 		return (kssl_tls_PRF(ssl,
402 		    ssl->sid.master_secret,
403 		    (size_t)SSL3_MASTER_SECRET_LEN,
404 		    (uchar_t *)label, strlen(label),
405 		    seed, (size_t)(MD5_HASH_LEN + SHA1_HASH_LEN),
406 		    hashes->tlshash, (size_t)TLS_FINISHED_SIZE));
407 	} else {
408 		uchar_t s[4];
409 		s[0] = (sender >> 24) & 0xff;
410 		s[1] = (sender >> 16) & 0xff;
411 		s[2] = (sender >> 8) & 0xff;
412 		s[3] = (sender) & 0xff;
413 
414 		MD5Update(md5ctx, s, 4);
415 		MD5Update(md5ctx, ssl->sid.master_secret,
416 		    SSL3_MASTER_SECRET_LEN);
417 		MD5Update(md5ctx, kssl_pad_1, SSL3_MD5_PAD_LEN);
418 		MD5Final(hashes->md5, md5ctx);
419 
420 		MD5Init(md5ctx);
421 		MD5Update(md5ctx, ssl->sid.master_secret,
422 		    SSL3_MASTER_SECRET_LEN);
423 		MD5Update(md5ctx, kssl_pad_2, SSL3_MD5_PAD_LEN);
424 		MD5Update(md5ctx, hashes->md5, MD5_HASH_LEN);
425 		MD5Final(hashes->md5, md5ctx);
426 
427 		SHA1Update(sha1ctx, s, 4);
428 		SHA1Update(sha1ctx, ssl->sid.master_secret,
429 		    SSL3_MASTER_SECRET_LEN);
430 		SHA1Update(sha1ctx, kssl_pad_1, SSL3_SHA1_PAD_LEN);
431 		SHA1Final(hashes->sha1, sha1ctx);
432 
433 		SHA1Init(sha1ctx);
434 		SHA1Update(sha1ctx, ssl->sid.master_secret,
435 		    SSL3_MASTER_SECRET_LEN);
436 		SHA1Update(sha1ctx, kssl_pad_2, SSL3_SHA1_PAD_LEN);
437 		SHA1Update(sha1ctx, hashes->sha1, SHA1_HASH_LEN);
438 		SHA1Final(hashes->sha1, sha1ctx);
439 		return (0);
440 	}
441 }
442 
443 
444 /*
445  * Minimum message length for a client hello =
446  * 2-byte client_version +
447  * 32-byte random +
448  * 1-byte session_id length +
449  * 2-byte cipher_suites length +
450  * 1-byte compression_methods length +
451  * 1-byte CompressionMethod.null
452  */
453 #define	KSSL_SSL3_CH_MIN_MSGLEN	(39)
454 
455 /*
456  * Process SSL/TLS Client Hello message. Return 0 on success, errno value
457  * or SSL_MISS if no cipher suite of the server matches the list received
458  * in the message.
459  */
460 static int
461 kssl_handle_client_hello(ssl_t *ssl, mblk_t *mp, int msglen)
462 {
463 	uchar_t *msgend;
464 	int err;
465 	SSL3AlertDescription desc = illegal_parameter;
466 	uint_t sidlen, cslen, cmlen;
467 	uchar_t *suitesp;
468 	uint_t i, j;
469 	uint16_t suite, selected_suite;
470 	int ch_msglen = KSSL_SSL3_CH_MIN_MSGLEN;
471 	boolean_t suite_found = B_FALSE;
472 
473 	ASSERT(mp->b_wptr >= mp->b_rptr + msglen);
474 	ASSERT(ssl->msg.type == client_hello);
475 	ASSERT(ssl->hs_waitstate == wait_client_hello);
476 	ASSERT(ssl->resumed == B_FALSE);
477 
478 	if (msglen < ch_msglen) {
479 		DTRACE_PROBE2(kssl_err__msglen_less_than_minimum,
480 		    int, msglen, int, ch_msglen);
481 		goto falert;
482 	}
483 
484 	msgend = mp->b_rptr + msglen;
485 
486 	/* Support SSLv3 (version == 3.0) or TLS (version == 3.1) */
487 	if (ssl->major_version != 3 || (ssl->major_version == 3 &&
488 	    ssl->minor_version != 0 && ssl->minor_version != 1)) {
489 		DTRACE_PROBE2(kssl_err__SSL_version_not_supported,
490 		    uchar_t, ssl->major_version,
491 		    uchar_t, ssl->minor_version);
492 		desc = handshake_failure;
493 		goto falert;
494 	}
495 	mp->b_rptr += 2; /* skip the version bytes */
496 
497 	/* read client random field */
498 	bcopy(mp->b_rptr, ssl->client_random, SSL3_RANDOM_LENGTH);
499 	mp->b_rptr += SSL3_RANDOM_LENGTH;
500 
501 	/* read session ID length */
502 	ASSERT(ssl->sid.cached == B_FALSE);
503 	sidlen = *mp->b_rptr++;
504 	ch_msglen += sidlen;
505 	if (msglen < ch_msglen) {
506 		DTRACE_PROBE2(kssl_err__invalid_message_length_after_ver,
507 		    int, msglen, int, ch_msglen);
508 		goto falert;
509 	}
510 	if (sidlen != SSL3_SESSIONID_BYTES) {
511 		mp->b_rptr += sidlen;
512 	} else {
513 		kssl_lookup_sid(&ssl->sid, mp->b_rptr, &ssl->faddr,
514 		    ssl->kssl_entry);
515 		mp->b_rptr += SSL3_SESSIONID_BYTES;
516 	}
517 
518 	/* read cipher suite length */
519 	cslen = ((uint_t)mp->b_rptr[0] << 8) + (uint_t)mp->b_rptr[1];
520 	mp->b_rptr += 2;
521 	ch_msglen += cslen;
522 
523 	/*
524 	 * This check can't be a "!=" since there can be
525 	 * compression methods other than CompressionMethod.null.
526 	 * Also, there can be extra data (TLS extensions) after the
527 	 * compression methods field.
528 	 */
529 	if (msglen < ch_msglen) {
530 		DTRACE_PROBE2(kssl_err__invalid_message_length_after_cslen,
531 		    int, msglen, int, ch_msglen);
532 		goto falert;
533 	}
534 
535 	/* The length has to be even since a cipher suite is 2-byte long. */
536 	if (cslen & 0x1) {
537 		DTRACE_PROBE1(kssl_err__uneven_cipher_suite_length,
538 		    uint_t, cslen);
539 		goto falert;
540 	}
541 	suitesp = mp->b_rptr;
542 
543 	/* session resumption checks */
544 	if (ssl->sid.cached == B_TRUE) {
545 		suite = ssl->sid.cipher_suite;
546 		for (j = 0; j < cslen; j += 2) {
547 			DTRACE_PROBE2(kssl_cipher_suite_check_resumpt,
548 			    uint16_t, suite,
549 			    uint16_t,
550 			    (uint16_t)((suitesp[j] << 8) + suitesp[j+1]));
551 			/* Check for regular (true) cipher suite. */
552 			if (suitesp[j] == ((suite >> 8) & 0xff) &&
553 			    suitesp[j + 1] == (suite & 0xff)) {
554 				DTRACE_PROBE1(kssl_cipher_suite_found_resumpt,
555 				    uint16_t, suite);
556 				suite_found = B_TRUE;
557 				selected_suite = suite;
558 			}
559 
560 			/* Check for SCSV. */
561 			if (suitesp[j] ==  ((SSL_SCSV >> 8) & 0xff) &&
562 			    suitesp[j + 1] == (SSL_SCSV & 0xff)) {
563 				DTRACE_PROBE(kssl_scsv_found_resumpt);
564 				ssl->secure_renegotiation = B_TRUE;
565 			}
566 
567 			/*
568 			 * If we got cipher suite match and SCSV we can
569 			 * terminate the cycle now.
570 			 */
571 			if (suite_found && ssl->secure_renegotiation)
572 				break;
573 		}
574 		if (suite_found)
575 			goto suite_found;
576 		kssl_uncache_sid(&ssl->sid, ssl->kssl_entry);
577 	}
578 
579 	/* Check if this server is capable of the cipher suite. */
580 	for (i = 0; i < ssl->kssl_entry->kssl_cipherSuites_nentries; i++) {
581 		suite = ssl->kssl_entry->kssl_cipherSuites[i];
582 		for (j = 0; j < cslen; j += 2) {
583 			DTRACE_PROBE2(kssl_cipher_suite_check, uint16_t, suite,
584 			    uint16_t,
585 			    (uint16_t)((suitesp[j] << 8) + suitesp[j+1]));
586 			/* Check for regular (true) cipher suite. */
587 			if (suitesp[j] == ((suite >> 8) & 0xff) &&
588 			    suitesp[j + 1] == (suite & 0xff)) {
589 				DTRACE_PROBE1(kssl_cipher_suite_found,
590 				    uint16_t, suite);
591 				suite_found = B_TRUE;
592 				selected_suite = suite;
593 			}
594 
595 			/* Check for SCSV. */
596 			if (suitesp[j] ==  ((SSL_SCSV >> 8) & 0xff) &&
597 			    suitesp[j + 1] == (SSL_SCSV & 0xff)) {
598 				DTRACE_PROBE(kssl_scsv_found);
599 				ssl->secure_renegotiation = B_TRUE;
600 			}
601 
602 			/*
603 			 * If we got cipher suite match and SCSV or went
604 			 * through the whole list of client cipher suites
605 			 * (hence we know if SCSV was present or not) we
606 			 * can terminate the cycle now.
607 			 */
608 			if (suite_found &&
609 			    (ssl->secure_renegotiation || (i > 0)))
610 				break;
611 		}
612 		if (suite_found)
613 			break;
614 	}
615 	if (!suite_found) {
616 		if (ssl->sslcnt == 1) {
617 			DTRACE_PROBE(kssl_no_cipher_suite_found);
618 			KSSL_COUNTER(no_suite_found, 1);
619 			/*
620 			 * If there is no fallback point terminate the
621 			 * handshake with SSL alert otherwise return with
622 			 * SSL_MISS.
623 			 */
624 			if (ssl->kssl_entry->ke_fallback_head == NULL) {
625 				DTRACE_PROBE(kssl_no_fallback);
626 				desc = handshake_failure;
627 				goto falert;
628 			} else {
629 				return (SSL_MISS);
630 			}
631 		}
632 		desc = handshake_failure;
633 		DTRACE_PROBE(kssl_err__no_cipher_suites_found);
634 		goto falert;
635 	}
636 
637 suite_found:
638 	mp->b_rptr += cslen;
639 
640 	/*
641 	 * Check for the mandatory CompressionMethod.null. We do not
642 	 * support any other compression methods.
643 	 */
644 	cmlen = *mp->b_rptr++;
645 	ch_msglen += cmlen - 1;	/* -1 accounts for the null method */
646 	if (msglen < ch_msglen) {
647 		DTRACE_PROBE2(kssl_err__invalid_message_length_after_complen,
648 		    int, msglen, int, ch_msglen);
649 		goto falert;
650 	}
651 
652 	/*
653 	 * Search for null compression method (encoded as 0 byte) in the
654 	 * compression methods field.
655 	 */
656 	while (cmlen >= 1) {
657 		if (*mp->b_rptr++ == 0)
658 			break;
659 		cmlen--;
660 	}
661 
662 	if (cmlen == 0) {
663 		desc = handshake_failure;
664 		DTRACE_PROBE(kssl_err__no_null_compression_method);
665 		goto falert;
666 	}
667 
668 	/* Find the suite in the internal cipher suite table. */
669 	for (i = 0; i < cipher_suite_defs_nentries; i++) {
670 		if (selected_suite == cipher_suite_defs[i].suite) {
671 			break;
672 		}
673 	}
674 
675 	/* Get past the remaining compression methods (minus null method). */
676 	mp->b_rptr += cmlen - 1;
677 
678 	ASSERT(i < cipher_suite_defs_nentries);
679 
680 	ssl->pending_cipher_suite = selected_suite;
681 	ssl->pending_malg = cipher_suite_defs[i].malg;
682 	ssl->pending_calg = cipher_suite_defs[i].calg;
683 	ssl->pending_keyblksz = cipher_suite_defs[i].keyblksz;
684 
685 	/* Parse TLS extensions (if any). */
686 	if (ch_msglen + 2 < msglen) {
687 		/* Get the length of the extensions. */
688 		uint16_t ext_total_len = ((uint_t)mp->b_rptr[0] << 8) +
689 		    (uint_t)mp->b_rptr[1];
690 		DTRACE_PROBE1(kssl_total_length_extensions, uint16_t,
691 		    ext_total_len);
692 		/*
693 		 * Consider zero extensions length as invalid extension
694 		 * encoding.
695 		 */
696 		if (ext_total_len == 0) {
697 			DTRACE_PROBE1(kssl_err__zero_extensions_length,
698 			    mblk_t *, mp);
699 			goto falert;
700 		}
701 		ch_msglen += 2;
702 		if (ch_msglen + ext_total_len > msglen) {
703 			DTRACE_PROBE2(kssl_err__invalid_extensions_length,
704 			    int, msglen, int, ch_msglen);
705 			goto falert;
706 		}
707 		mp->b_rptr += 2;
708 
709 		/*
710 		 * Go through the TLS extensions. This is only done to check
711 		 * for the presence of renegotiation_info extension. We do not
712 		 * support any other TLS extensions and hence ignore them.
713 		 */
714 		while (mp->b_rptr < msgend) {
715 			uint16_t ext_len, ext_type;
716 
717 			/*
718 			 * Check that the extension has at least type and
719 			 * length (2 + 2 bytes).
720 			 */
721 			if (ch_msglen + 4 > msglen) {
722 				DTRACE_PROBE(kssl_err__invalid_ext_format);
723 				goto falert;
724 			}
725 
726 			/* Get extension type and length */
727 			ext_type = ((uint_t)mp->b_rptr[0] << 8) +
728 			    (uint_t)mp->b_rptr[1];
729 			mp->b_rptr += 2;
730 			ext_len = ((uint_t)mp->b_rptr[0] << 8) +
731 			    (uint_t)mp->b_rptr[1];
732 			mp->b_rptr += 2;
733 			ch_msglen += 4;
734 			DTRACE_PROBE3(kssl_ext_detected, uint16_t, ext_type,
735 			    uint16_t, ext_len, mblk_t *, mp);
736 
737 			/*
738 			 * Make sure the contents of the extension are
739 			 * accessible.
740 			 */
741 			if (ch_msglen + ext_len > msglen) {
742 				DTRACE_PROBE1(
743 				    kssl_err__invalid_ext_len,
744 				    uint16_t, ext_len);
745 				goto falert;
746 			}
747 
748 			switch (ext_type) {
749 			case TLSEXT_RENEGOTIATION_INFO:
750 				/*
751 				 * Search for empty "renegotiation_info"
752 				 * extension (encoded as ff 01 00 01 00).
753 				 */
754 				DTRACE_PROBE(kssl_reneg_info_found);
755 				if ((ext_len != 1) ||
756 				    (*mp->b_rptr != 0)) {
757 					DTRACE_PROBE2(
758 					    kssl_err__non_empty_reneg_info,
759 					    uint16_t, ext_len,
760 					    mblk_t *, mp);
761 					goto falert;
762 				}
763 				ssl->secure_renegotiation = B_TRUE;
764 				break;
765 			default:
766 				/* FALLTHRU */
767 				break;
768 			}
769 
770 			/* jump to the next extension */
771 			ch_msglen += ext_len;
772 			mp->b_rptr += ext_len;
773 		}
774 	}
775 
776 	mp->b_rptr = msgend;
777 
778 	if (ssl->sid.cached == B_TRUE) {
779 		err = kssl_send_server_hello(ssl);
780 		if (err != 0) {
781 			return (err);
782 		}
783 		if (IS_TLS(ssl))
784 			err = kssl_generate_tls_keyblock(ssl);
785 		else
786 			kssl_generate_keyblock(ssl);
787 
788 		err = kssl_send_change_cipher_specs(ssl);
789 		if (err != 0) {
790 			return (err);
791 		}
792 
793 		err = kssl_send_finished(ssl, 1);
794 		if (err != 0)
795 			return (err);
796 
797 		err = kssl_compute_handshake_hashes(ssl, &ssl->hs_hashes,
798 		    sender_client);
799 		if (err != 0)
800 			return (err);
801 
802 		ssl->hs_waitstate = wait_change_cipher;
803 		ssl->resumed = B_TRUE;
804 		ssl->activeinput = B_FALSE;
805 		KSSL_COUNTER(resumed_sessions, 1);
806 		return (0);
807 	}
808 
809 	(void) random_get_pseudo_bytes(ssl->sid.session_id,
810 	    SSL3_SESSIONID_BYTES);
811 	ssl->sid.client_addr = ssl->faddr;
812 	ssl->sid.cipher_suite = selected_suite;
813 
814 	err = kssl_send_server_hello(ssl);
815 	if (err != 0) {
816 		return (err);
817 	}
818 	err = kssl_send_certificate_and_server_hello_done(ssl);
819 	if (err != 0) {
820 		return (err);
821 	}
822 	KSSL_COUNTER(full_handshakes, 1);
823 	ssl->hs_waitstate = wait_client_key;
824 	ssl->activeinput = B_FALSE;
825 	return (0);
826 
827 falert:
828 	kssl_send_alert(ssl, alert_fatal, desc);
829 	return (EBADMSG);
830 }
831 
832 #define	SET_HASH_INDEX(index, s, clnt_addr) {				\
833 	int addr;							\
834 									\
835 	IN6_V4MAPPED_TO_IPADDR(clnt_addr, addr);			\
836 	index = addr ^ (((int)(s)[0] << 24) | ((int)(s)[1] << 16) |	\
837 	    ((int)(s)[2] << 8) | (int)(s)[SSL3_SESSIONID_BYTES - 1]);	\
838 }
839 
840 /*
841  * Creates a cache entry. Sets the sid->cached flag
842  * and sid->time fields. So, the caller should not set them.
843  */
844 static void
845 kssl_cache_sid(sslSessionID *sid, kssl_entry_t *kssl_entry)
846 {
847 	uint_t index;
848 	uchar_t *s = sid->session_id;
849 	kmutex_t *lock;
850 
851 	ASSERT(sid->cached == B_FALSE);
852 
853 	/* set the values before creating the cache entry */
854 	sid->cached = B_TRUE;
855 	sid->time = ddi_get_lbolt();
856 
857 	SET_HASH_INDEX(index, s, &sid->client_addr);
858 	index %= kssl_entry->sid_cache_nentries;
859 
860 	lock = &(kssl_entry->sid_cache[index].se_lock);
861 	mutex_enter(lock);
862 	kssl_entry->sid_cache[index].se_used++;
863 	bcopy(sid, &(kssl_entry->sid_cache[index].se_sid), sizeof (*sid));
864 	mutex_exit(lock);
865 
866 	KSSL_COUNTER(sid_cached, 1);
867 }
868 
869 /*
870  * Invalidates the cache entry, if any. Clears the sid->cached flag
871  * as a side effect.
872  */
873 void
874 kssl_uncache_sid(sslSessionID *sid, kssl_entry_t *kssl_entry)
875 {
876 	uint_t index;
877 	uchar_t *s = sid->session_id;
878 	sslSessionID *csid;
879 	kmutex_t *lock;
880 
881 	ASSERT(sid->cached == B_TRUE);
882 	sid->cached = B_FALSE;
883 
884 	SET_HASH_INDEX(index, s, &sid->client_addr);
885 	index %= kssl_entry->sid_cache_nentries;
886 
887 	lock = &(kssl_entry->sid_cache[index].se_lock);
888 	mutex_enter(lock);
889 	csid = &(kssl_entry->sid_cache[index].se_sid);
890 	if (!(IN6_ARE_ADDR_EQUAL(&csid->client_addr, &sid->client_addr)) ||
891 	    bcmp(csid->session_id, s, SSL3_SESSIONID_BYTES)) {
892 		mutex_exit(lock);
893 		return;
894 	}
895 	csid->cached = B_FALSE;
896 	mutex_exit(lock);
897 
898 	KSSL_COUNTER(sid_uncached, 1);
899 }
900 
901 static void
902 kssl_lookup_sid(sslSessionID *sid, uchar_t *s, in6_addr_t *faddr,
903     kssl_entry_t *kssl_entry)
904 {
905 	uint_t index;
906 	kmutex_t *lock;
907 	sslSessionID *csid;
908 
909 	KSSL_COUNTER(sid_cache_lookups, 1);
910 
911 	SET_HASH_INDEX(index, s, faddr);
912 	index %= kssl_entry->sid_cache_nentries;
913 
914 	lock = &(kssl_entry->sid_cache[index].se_lock);
915 	mutex_enter(lock);
916 	csid = &(kssl_entry->sid_cache[index].se_sid);
917 	if (csid->cached == B_FALSE ||
918 	    !IN6_ARE_ADDR_EQUAL(&csid->client_addr, faddr) ||
919 	    bcmp(csid->session_id, s, SSL3_SESSIONID_BYTES)) {
920 		mutex_exit(lock);
921 		return;
922 	}
923 
924 	if (TICK_TO_SEC(ddi_get_lbolt() - csid->time) >
925 	    kssl_entry->sid_cache_timeout) {
926 		csid->cached = B_FALSE;
927 		mutex_exit(lock);
928 		return;
929 	}
930 
931 	bcopy(csid, sid, sizeof (*sid));
932 	mutex_exit(lock);
933 	ASSERT(sid->cached == B_TRUE);
934 
935 	KSSL_COUNTER(sid_cache_hits, 1);
936 }
937 
938 static uchar_t *
939 kssl_rsa_unwrap(uchar_t *buf, size_t *lenp)
940 {
941 	size_t len = *lenp;
942 	int i = 2;
943 
944 	if (buf[0] != 0 || buf[1] != 2) {
945 		return (NULL);
946 	}
947 
948 	while (i < len) {
949 		if (buf[i++] == 0) {
950 			*lenp = len - i;
951 			break;
952 		}
953 	}
954 
955 	if (i == len) {
956 		return (NULL);
957 	}
958 
959 	return (buf + i);
960 }
961 
962 
963 #define	KSSL_SSL3_SH_RECLEN	(74)
964 #define	KSSL_SSL3_FIN_MSGLEN	(36)
965 #define	KSSL_EMPTY_RENEG_INFO_LEN	(7)
966 
967 #define	KSSL_SSL3_MAX_CCP_FIN_MSGLEN	(128)	/* comfortable upper bound */
968 
969 /*
970  * Send ServerHello record to the client.
971  */
972 static int
973 kssl_send_server_hello(ssl_t *ssl)
974 {
975 	mblk_t *mp;
976 	uchar_t *buf;
977 	uchar_t *msgstart;
978 	uint16_t reclen = KSSL_SSL3_SH_RECLEN;
979 
980 	mp = allocb(ssl->tcp_mss, BPRI_HI);
981 	if (mp == NULL) {
982 		KSSL_COUNTER(alloc_fails, 1);
983 		return (ENOMEM);
984 	}
985 	ssl->handshake_sendbuf = mp;
986 	buf = mp->b_wptr;
987 
988 	if (ssl->secure_renegotiation)
989 		reclen += KSSL_EMPTY_RENEG_INFO_LEN;
990 
991 	/* 5 byte record header */
992 	buf[0] = content_handshake;
993 	buf[1] = ssl->major_version;
994 	buf[2] = ssl->minor_version;
995 	buf[3] = reclen >> 8;
996 	buf[4] = reclen & 0xff;
997 	buf += SSL3_HDR_LEN;
998 
999 	msgstart = buf;
1000 
1001 	/* 6 byte message header */
1002 	buf[0] = (uchar_t)server_hello;			/* message type */
1003 	buf[1] = 0;					/* message len byte 0 */
1004 	buf[2] = ((reclen - 4) >> 8) &
1005 	    0xff;					/* message len byte 1 */
1006 	buf[3] = (reclen - 4) & 0xff;	/* message len byte 2 */
1007 
1008 	buf[4] = ssl->major_version;	/* version byte 0 */
1009 	buf[5] = ssl->minor_version;	/* version byte 1 */
1010 
1011 	buf += 6;
1012 
1013 	kssl_get_hello_random(ssl->server_random);
1014 	bcopy(ssl->server_random, buf, SSL3_RANDOM_LENGTH);
1015 	buf += SSL3_RANDOM_LENGTH;
1016 
1017 	buf[0] = SSL3_SESSIONID_BYTES;
1018 	bcopy(ssl->sid.session_id, buf + 1, SSL3_SESSIONID_BYTES);
1019 	buf += SSL3_SESSIONID_BYTES + 1;
1020 
1021 	buf[0] = (ssl->pending_cipher_suite >> 8) & 0xff;
1022 	buf[1] = ssl->pending_cipher_suite & 0xff;
1023 
1024 	buf[2] = 0;	/* No compression */
1025 	buf += 3;
1026 
1027 	/*
1028 	 * Add "renegotiation_info" extension if the ClientHello message
1029 	 * contained either SCSV value in cipher suite list or
1030 	 * "renegotiation_info" extension. This is per RFC 5746, section 3.6.
1031 	 */
1032 	if (ssl->secure_renegotiation) {
1033 		/* Extensions length */
1034 		buf[0] = 0x00;
1035 		buf[1] = 0x05;
1036 		/* empty renegotiation_info extension encoding (section 3.2) */
1037 		buf[2] = 0xff;
1038 		buf[3] = 0x01;
1039 		buf[4] = 0x00;
1040 		buf[5] = 0x01;
1041 		buf[6] = 0x00;
1042 		buf += KSSL_EMPTY_RENEG_INFO_LEN;
1043 	}
1044 
1045 	mp->b_wptr = buf;
1046 	ASSERT(mp->b_wptr < mp->b_datap->db_lim);
1047 
1048 	kssl_update_handshake_hashes(ssl, msgstart, reclen);
1049 	return (0);
1050 }
1051 
1052 static void
1053 kssl_get_hello_random(uchar_t *buf)
1054 {
1055 	timestruc_t ts;
1056 	time_t sec;
1057 
1058 	gethrestime(&ts);
1059 	sec = ts.tv_sec;
1060 
1061 	buf[0] = (sec >> 24) & 0xff;
1062 	buf[1] = (sec >> 16) & 0xff;
1063 	buf[2] = (sec >> 8) & 0xff;
1064 	buf[3] = (sec) & 0xff;
1065 
1066 	(void) random_get_pseudo_bytes(&buf[4], SSL3_RANDOM_LENGTH - 4);
1067 
1068 	/* Should this be caching? */
1069 }
1070 
1071 static int
1072 kssl_tls_P_hash(crypto_mechanism_t *mech, crypto_key_t *key,
1073 	size_t hashlen,
1074 	uchar_t *label, size_t label_len,
1075 	uchar_t *seed, size_t seedlen,
1076 	uchar_t *data, size_t datalen)
1077 {
1078 	int rv = 0;
1079 	uchar_t A1[MAX_HASH_LEN], result[MAX_HASH_LEN];
1080 	int bytes_left = datalen;
1081 	crypto_data_t dd, mac;
1082 	crypto_context_t ctx;
1083 
1084 	dd.cd_format = CRYPTO_DATA_RAW;
1085 	dd.cd_offset = 0;
1086 	mac.cd_format = CRYPTO_DATA_RAW;
1087 	mac.cd_offset = 0;
1088 
1089 	/*
1090 	 * A(i) = HMAC_hash(secret, seed + A(i-1));
1091 	 * A(0) = seed;
1092 	 *
1093 	 * Compute A(1):
1094 	 * A(1) = HMAC_hash(secret, label + seed)
1095 	 *
1096 	 */
1097 	HMAC_INIT(mech, key, &ctx);
1098 	HMAC_UPDATE(ctx, label, label_len);
1099 	HMAC_UPDATE(ctx, seed, seedlen);
1100 	HMAC_FINAL(ctx, A1, hashlen);
1101 
1102 	/* Compute A(2) ... A(n) */
1103 	while (bytes_left > 0) {
1104 		HMAC_INIT(mech, key, &ctx);
1105 		HMAC_UPDATE(ctx, A1, hashlen);
1106 		HMAC_UPDATE(ctx, label, label_len);
1107 		HMAC_UPDATE(ctx, seed, seedlen);
1108 		HMAC_FINAL(ctx, result, hashlen);
1109 
1110 		/*
1111 		 * The A(i) value is stored in "result".
1112 		 * Save the results of the MAC so it can be input to next
1113 		 * iteration.
1114 		 */
1115 		if (bytes_left > hashlen) {
1116 			/* Store the chunk result */
1117 			bcopy(result, data, hashlen);
1118 			data += hashlen;
1119 
1120 			bytes_left -= hashlen;
1121 
1122 			/* Update A1 for next iteration */
1123 			HMAC_INIT(mech, key, &ctx);
1124 			HMAC_UPDATE(ctx, A1, hashlen);
1125 			HMAC_FINAL(ctx, A1, hashlen);
1126 
1127 		} else {
1128 			bcopy(result, data, bytes_left);
1129 			data += bytes_left;
1130 			bytes_left = 0;
1131 		}
1132 	}
1133 end:
1134 	if (CRYPTO_ERR(rv)) {
1135 		DTRACE_PROBE1(kssl_err__crypto_mac_error, int, rv);
1136 		KSSL_COUNTER(compute_mac_failure, 1);
1137 	}
1138 	return (rv);
1139 }
1140 
1141 /* ARGSUSED */
1142 static int
1143 kssl_tls_PRF(ssl_t *ssl,
1144 	uchar_t *secret, size_t secret_len,
1145 	uchar_t *label, size_t label_len,
1146 	uchar_t *seed, size_t seed_len,
1147 	uchar_t *prfresult, size_t prfresult_len)
1148 {
1149 	/*
1150 	 * RFC 2246:
1151 	 *  PRF(secret, label, seed) = P_MD5(S1, label + seed) XOR
1152 	 *				P_SHA1(S2, label + seed);
1153 	 * S1 = 1st half of secret.
1154 	 * S1 = 2nd half of secret.
1155 	 *
1156 	 */
1157 
1158 	int rv, i;
1159 	uchar_t psha1[MAX_KEYBLOCK_LENGTH];
1160 	crypto_key_t S1, S2;
1161 
1162 	/* length of secret keys is ceil(length/2) */
1163 	size_t slen = roundup(secret_len, 2) / 2;
1164 
1165 	if (prfresult_len >  MAX_KEYBLOCK_LENGTH) {
1166 		DTRACE_PROBE1(kssl_err__unexpected_keyblock_size,
1167 		    size_t, prfresult_len);
1168 		return (CRYPTO_ARGUMENTS_BAD);
1169 	}
1170 
1171 	ASSERT(prfresult != NULL);
1172 	ASSERT(label != NULL);
1173 	ASSERT(seed != NULL);
1174 
1175 	S1.ck_data   = secret;
1176 	S1.ck_length = slen * 8; /* bits */
1177 	S1.ck_format = CRYPTO_KEY_RAW;
1178 
1179 	S2.ck_data   = secret + slen;
1180 	S2.ck_length = slen * 8; /* bits */
1181 	S2.ck_format = CRYPTO_KEY_RAW;
1182 
1183 	rv = kssl_tls_P_hash(&hmac_md5_mech, &S1, MD5_HASH_LEN,
1184 	    label, label_len,
1185 	    seed, seed_len,
1186 	    prfresult, prfresult_len);
1187 	if (CRYPTO_ERR(rv))
1188 		goto end;
1189 
1190 	rv = kssl_tls_P_hash(&hmac_sha1_mech, &S2, SHA1_HASH_LEN,
1191 	    label, label_len,
1192 	    seed, seed_len,
1193 	    psha1, prfresult_len);
1194 	if (CRYPTO_ERR(rv))
1195 		goto end;
1196 
1197 	for (i = 0; i < prfresult_len; i++)
1198 		prfresult[i] ^= psha1[i];
1199 
1200 end:
1201 	if (CRYPTO_ERR(rv))
1202 		bzero(prfresult, prfresult_len);
1203 
1204 	return (rv);
1205 }
1206 
1207 #define	IS_BAD_PRE_MASTER_SECRET(pms, pmslen, ssl)			\
1208 	(pms == NULL || pmslen != SSL3_PRE_MASTER_SECRET_LEN ||		\
1209 	pms[0] != ssl->major_version || pms[1] != ssl->minor_version)
1210 
1211 #define	FAKE_PRE_MASTER_SECRET(pms, pmslen, ssl, buf) {			\
1212 		KSSL_COUNTER(bad_pre_master_secret, 1);			\
1213 		pms = buf;						\
1214 		pmslen = SSL3_PRE_MASTER_SECRET_LEN;			\
1215 		pms[0] = ssl->major_version;				\
1216 		pms[1] = ssl->minor_version;				\
1217 		(void) random_get_pseudo_bytes(&buf[2], pmslen - 2);	\
1218 }
1219 
1220 static int
1221 kssl_generate_tls_ms(ssl_t *ssl, uchar_t *pms, size_t pmslen)
1222 {
1223 	uchar_t buf[SSL3_PRE_MASTER_SECRET_LEN];
1224 	uchar_t seed[SSL3_RANDOM_LENGTH * 2];
1225 
1226 	/*
1227 	 * Computing the master secret:
1228 	 * ----------------------------
1229 	 * master_secret = PRF (pms, "master secret",
1230 	 *		ClientHello.random + ServerHello.random);
1231 	 */
1232 	bcopy(ssl->client_random, seed, SSL3_RANDOM_LENGTH);
1233 	bcopy(ssl->server_random, seed + SSL3_RANDOM_LENGTH,
1234 	    SSL3_RANDOM_LENGTH);
1235 
1236 	/* if pms is bad fake it to thwart Bleichenbacher attack */
1237 	if (IS_BAD_PRE_MASTER_SECRET(pms, pmslen, ssl)) {
1238 		DTRACE_PROBE(kssl_err__under_Bleichenbacher_attack);
1239 		FAKE_PRE_MASTER_SECRET(pms, pmslen, ssl, buf);
1240 	}
1241 
1242 	return (kssl_tls_PRF(ssl,
1243 	    pms, pmslen,
1244 	    (uchar_t *)TLS_MASTER_SECRET_LABEL,
1245 	    (size_t)strlen(TLS_MASTER_SECRET_LABEL),
1246 	    seed, sizeof (seed),
1247 	    ssl->sid.master_secret,
1248 	    (size_t)sizeof (ssl->sid.master_secret)));
1249 }
1250 
1251 
1252 static void
1253 kssl_generate_ssl_ms(ssl_t *ssl, uchar_t *pms, size_t pmslen)
1254 {
1255 	uchar_t buf[SSL3_PRE_MASTER_SECRET_LEN];
1256 	uchar_t *ms;
1257 	int hlen = MD5_HASH_LEN;
1258 
1259 	ms = ssl->sid.master_secret;
1260 
1261 	/* if pms is bad fake it to thwart Bleichenbacher attack */
1262 	if (IS_BAD_PRE_MASTER_SECRET(pms, pmslen, ssl)) {
1263 		DTRACE_PROBE(kssl_err__under_Bleichenbacher_attack);
1264 		FAKE_PRE_MASTER_SECRET(pms, pmslen, ssl, buf);
1265 	}
1266 
1267 	kssl_ssl3_key_material_derive_step(ssl, pms, pmslen, 1, ms, 0);
1268 	kssl_ssl3_key_material_derive_step(ssl, pms, pmslen, 2, ms + hlen, 0);
1269 	kssl_ssl3_key_material_derive_step(ssl, pms, pmslen, 3, ms + 2 * hlen,
1270 	    0);
1271 }
1272 
1273 static int
1274 kssl_generate_tls_keyblock(ssl_t *ssl)
1275 {
1276 	uchar_t seed[2 * SSL3_RANDOM_LENGTH];
1277 
1278 	bcopy(ssl->server_random, seed, SSL3_RANDOM_LENGTH);
1279 	bcopy(ssl->client_random, seed + SSL3_RANDOM_LENGTH,
1280 	    SSL3_RANDOM_LENGTH);
1281 
1282 	return (kssl_tls_PRF(ssl, ssl->sid.master_secret,
1283 	    (size_t)SSL3_MASTER_SECRET_LEN,
1284 	    (uchar_t *)TLS_KEY_EXPANSION_LABEL,
1285 	    (size_t)strlen(TLS_KEY_EXPANSION_LABEL),
1286 	    seed, (size_t)sizeof (seed),
1287 	    ssl->pending_keyblock,
1288 	    (size_t)ssl->pending_keyblksz));
1289 
1290 }
1291 
1292 static void
1293 kssl_generate_keyblock(ssl_t *ssl)
1294 {
1295 	uchar_t *ms;
1296 	size_t mslen = SSL3_MASTER_SECRET_LEN;
1297 	int hlen = MD5_HASH_LEN;
1298 	uchar_t *keys = ssl->pending_keyblock;
1299 	int steps = howmany(ssl->pending_keyblksz, hlen);
1300 	int i;
1301 
1302 	ms = ssl->sid.master_secret;
1303 
1304 	ASSERT(hlen * steps <= MAX_KEYBLOCK_LENGTH);
1305 
1306 	for (i = 1; i <= steps; i++) {
1307 		kssl_ssl3_key_material_derive_step(ssl, ms, mslen, i, keys, 1);
1308 		keys += hlen;
1309 	}
1310 }
1311 
1312 static char *ssl3_key_derive_seeds[9] = {"A", "BB", "CCC", "DDDD", "EEEEE",
1313 	"FFFFFF", "GGGGGGG", "HHHHHHHH", "IIIIIIIII"};
1314 
1315 static void
1316 kssl_ssl3_key_material_derive_step(
1317 	ssl_t *ssl,
1318 	uchar_t *secret,
1319 	size_t secretlen,
1320 	int step,
1321 	uchar_t *dst,
1322 	int sr_first)
1323 {
1324 	SHA1_CTX sha1, *sha1ctx;
1325 	MD5_CTX md5, *md5ctx;
1326 	uchar_t sha1_hash[SHA1_HASH_LEN];
1327 
1328 	sha1ctx = &sha1;
1329 	md5ctx = &md5;
1330 
1331 	ASSERT(step <=
1332 	    sizeof (ssl3_key_derive_seeds) /
1333 	    sizeof (ssl3_key_derive_seeds[0]));
1334 	step--;
1335 
1336 	SHA1Init(sha1ctx);
1337 	SHA1Update(sha1ctx, (uchar_t *)ssl3_key_derive_seeds[step],
1338 	    step + 1);
1339 	SHA1Update(sha1ctx, secret, secretlen);
1340 	if (sr_first) {
1341 		SHA1Update(sha1ctx, ssl->server_random, SSL3_RANDOM_LENGTH);
1342 		SHA1Update(sha1ctx, ssl->client_random, SSL3_RANDOM_LENGTH);
1343 	} else {
1344 		SHA1Update(sha1ctx, ssl->client_random, SSL3_RANDOM_LENGTH);
1345 		SHA1Update(sha1ctx, ssl->server_random, SSL3_RANDOM_LENGTH);
1346 	}
1347 	SHA1Final(sha1_hash, sha1ctx);
1348 
1349 	MD5Init(md5ctx);
1350 	MD5Update(md5ctx, secret, secretlen);
1351 	MD5Update(md5ctx, sha1_hash, SHA1_HASH_LEN);
1352 	MD5Final(dst, md5ctx);
1353 }
1354 
1355 static int
1356 kssl_send_certificate_and_server_hello_done(ssl_t *ssl)
1357 {
1358 	int cur_reclen;
1359 	int mss;
1360 	int len, copylen;
1361 	mblk_t *mp;
1362 	uchar_t *cert_buf;
1363 	int cert_len;
1364 	uchar_t *msgbuf;
1365 	Certificate_t *cert;
1366 	uint16_t reclen = KSSL_SSL3_SH_RECLEN;
1367 
1368 	cert = ssl->kssl_entry->ke_server_certificate;
1369 	if (cert == NULL) {
1370 		return (ENOENT);
1371 	}
1372 	cert_buf = cert->msg;
1373 	cert_len = cert->len;
1374 
1375 	if (ssl->secure_renegotiation)
1376 		reclen += KSSL_EMPTY_RENEG_INFO_LEN;
1377 
1378 	mp = ssl->handshake_sendbuf;
1379 	mss = ssl->tcp_mss;
1380 	ASSERT(mp != NULL);
1381 	cur_reclen = mp->b_wptr - mp->b_rptr - SSL3_HDR_LEN;
1382 	ASSERT(cur_reclen == reclen);
1383 	/* Assume MSS is at least 80 bytes */
1384 	ASSERT(mss > cur_reclen + SSL3_HDR_LEN);
1385 	ASSERT(cur_reclen < SSL3_MAX_RECORD_LENGTH); /* XXX */
1386 
1387 	copylen = mss - (cur_reclen + SSL3_HDR_LEN);
1388 	len = cert_len;
1389 	copylen = MIN(copylen, len);
1390 	copylen = MIN(copylen, SSL3_MAX_RECORD_LENGTH - cur_reclen);
1391 
1392 	/* new record always starts in a new mblk for simplicity */
1393 	msgbuf = cert_buf;
1394 	for (;;) {
1395 		ASSERT(mp->b_wptr + copylen <= mp->b_datap->db_lim);
1396 		bcopy(msgbuf, mp->b_wptr, copylen);
1397 		msgbuf += copylen;
1398 		mp->b_wptr += copylen;
1399 		cur_reclen += copylen;
1400 		len -= copylen;
1401 		if (len == 0) {
1402 			break;
1403 		}
1404 		if (cur_reclen == SSL3_MAX_RECORD_LENGTH) {
1405 			cur_reclen = 0;
1406 		}
1407 		copylen = MIN(len, mss);
1408 		copylen = MIN(copylen, SSL3_MAX_RECORD_LENGTH - cur_reclen);
1409 		mp->b_cont = allocb(copylen, BPRI_HI);
1410 		if (mp->b_cont == NULL) {
1411 			KSSL_COUNTER(alloc_fails, 1);
1412 			freemsg(ssl->handshake_sendbuf);
1413 			ssl->handshake_sendbuf = NULL;
1414 			return (ENOMEM);
1415 		}
1416 		mp = mp->b_cont;
1417 		if (cur_reclen == 0) {
1418 			mp->b_wptr[0] = content_handshake;
1419 			mp->b_wptr[1] = ssl->major_version;
1420 			mp->b_wptr[2] = ssl->minor_version;
1421 			cur_reclen = MIN(len, reclen);
1422 			mp->b_wptr[3] = (cur_reclen >> 8) & 0xff;
1423 			mp->b_wptr[4] = (cur_reclen) & 0xff;
1424 			mp->b_wptr += SSL3_HDR_LEN;
1425 			cur_reclen = 0;
1426 			copylen = MIN(copylen, mss - SSL3_HDR_LEN);
1427 		}
1428 	}
1429 
1430 	/* adjust the record length field for the first record */
1431 	mp = ssl->handshake_sendbuf;
1432 	cur_reclen = MIN(reclen + cert_len, SSL3_MAX_RECORD_LENGTH);
1433 	mp->b_rptr[3] = (cur_reclen >> 8) & 0xff;
1434 	mp->b_rptr[4] = (cur_reclen) & 0xff;
1435 
1436 	kssl_update_handshake_hashes(ssl, cert_buf, cert_len);
1437 
1438 	return (0);
1439 }
1440 
1441 static int
1442 kssl_send_change_cipher_specs(ssl_t *ssl)
1443 {
1444 	mblk_t *mp, *newmp;
1445 	uchar_t *buf;
1446 
1447 	mp = ssl->handshake_sendbuf;
1448 
1449 	/* We're most likely to hit the fast path for resumed sessions */
1450 	if ((mp != NULL) &&
1451 	    (mp->b_datap->db_lim - mp->b_wptr > KSSL_SSL3_MAX_CCP_FIN_MSGLEN)) {
1452 		buf = mp->b_wptr;
1453 	} else {
1454 		newmp = allocb(KSSL_SSL3_MAX_CCP_FIN_MSGLEN, BPRI_HI);
1455 
1456 		if (newmp == NULL)
1457 			return (ENOMEM);	/* need to do better job! */
1458 
1459 		if (mp == NULL) {
1460 			ssl->handshake_sendbuf = newmp;
1461 		} else {
1462 			linkb(ssl->handshake_sendbuf, newmp);
1463 		}
1464 		mp = newmp;
1465 		buf = mp->b_rptr;
1466 	}
1467 
1468 	/* 5 byte record header */
1469 	buf[0] = content_change_cipher_spec;
1470 	buf[1] = ssl->major_version;
1471 	buf[2] = ssl->minor_version;
1472 	buf[3] = 0;
1473 	buf[4] = 1;
1474 	buf += SSL3_HDR_LEN;
1475 
1476 	buf[0] = 1;
1477 
1478 	mp->b_wptr = buf + 1;
1479 	ASSERT(mp->b_wptr < mp->b_datap->db_lim);
1480 
1481 	ssl->seq_num[KSSL_WRITE] = 0;
1482 	return (kssl_spec_init(ssl, KSSL_WRITE));
1483 }
1484 
1485 int
1486 kssl_spec_init(ssl_t *ssl, int dir)
1487 {
1488 	KSSL_HASHCTX *ctx;
1489 	KSSLCipherSpec *spec = &ssl->spec[dir];
1490 	int ret = 0;
1491 
1492 	spec->mac_hashsz = mac_defs[ssl->pending_malg].hashsz;
1493 	spec->mac_padsz = mac_defs[ssl->pending_malg].padsz;
1494 
1495 	spec->MAC_HashInit = mac_defs[ssl->pending_malg].HashInit;
1496 	spec->MAC_HashUpdate = mac_defs[ssl->pending_malg].HashUpdate;
1497 	spec->MAC_HashFinal = mac_defs[ssl->pending_malg].HashFinal;
1498 
1499 	if (dir == KSSL_READ) {
1500 		bcopy(ssl->pending_keyblock, ssl->mac_secret[dir],
1501 		    spec->mac_hashsz);
1502 	} else {
1503 		bcopy(&(ssl->pending_keyblock[spec->mac_hashsz]),
1504 		    ssl->mac_secret[dir], spec->mac_hashsz);
1505 	}
1506 
1507 	/* Pre-compute these here. will save cycles on each record later */
1508 	if (!IS_TLS(ssl)) {
1509 		ctx = &ssl->mac_ctx[dir][0];
1510 		spec->MAC_HashInit((void *)ctx);
1511 		spec->MAC_HashUpdate((void *)ctx, ssl->mac_secret[dir],
1512 		    spec->mac_hashsz);
1513 		spec->MAC_HashUpdate((void *)ctx, kssl_pad_1,
1514 		    spec->mac_padsz);
1515 
1516 		ctx = &ssl->mac_ctx[dir][1];
1517 		spec->MAC_HashInit((void *)ctx);
1518 		spec->MAC_HashUpdate((void *)ctx, ssl->mac_secret[dir],
1519 		    spec->mac_hashsz);
1520 		spec->MAC_HashUpdate((void *)ctx, kssl_pad_2,
1521 		    spec->mac_padsz);
1522 	}
1523 
1524 	spec->cipher_type = cipher_defs[ssl->pending_calg].type;
1525 	spec->cipher_mech.cm_type = cipher_defs[ssl->pending_calg].mech_type;
1526 	spec->cipher_bsize = cipher_defs[ssl->pending_calg].bsize;
1527 	spec->cipher_keysz = cipher_defs[ssl->pending_calg].keysz;
1528 
1529 	if (spec->cipher_ctx != NULL) {
1530 		crypto_cancel_ctx(spec->cipher_ctx);
1531 		spec->cipher_ctx = 0;
1532 	}
1533 
1534 	/*
1535 	 * Initialize HMAC keys for TLS and SSL3 HMAC keys
1536 	 * for SSL 3.0.
1537 	 */
1538 	if (IS_TLS(ssl)) {
1539 		if (ssl->pending_malg == mac_md5) {
1540 			spec->hmac_mech = hmac_md5_mech;
1541 		} else if (ssl->pending_malg == mac_sha) {
1542 			spec->hmac_mech = hmac_sha1_mech;
1543 		}
1544 
1545 		spec->hmac_key.ck_format = CRYPTO_KEY_RAW;
1546 		spec->hmac_key.ck_data = ssl->mac_secret[dir];
1547 		spec->hmac_key.ck_length = spec->mac_hashsz * 8;
1548 	} else {
1549 		static uint32_t param;
1550 
1551 		spec->hmac_mech.cm_type = CRYPTO_MECH_INVALID;
1552 		spec->hmac_mech.cm_param = (caddr_t)&param;
1553 		spec->hmac_mech.cm_param_len = sizeof (param);
1554 		if (ssl->pending_malg == mac_md5) {
1555 			spec->hmac_mech.cm_type =
1556 			    crypto_mech2id("CKM_SSL3_MD5_MAC");
1557 			param = MD5_HASH_LEN;
1558 		} else if (ssl->pending_malg == mac_sha) {
1559 			spec->hmac_mech.cm_type =
1560 			    crypto_mech2id("CKM_SSL3_SHA1_MAC");
1561 			param = SHA1_HASH_LEN;
1562 		}
1563 
1564 		spec->hmac_key.ck_format = CRYPTO_KEY_RAW;
1565 		spec->hmac_key.ck_data = ssl->mac_secret[dir];
1566 		spec->hmac_key.ck_length = spec->mac_hashsz * 8;
1567 	}
1568 
1569 	/* We're done if this is the nil cipher */
1570 	if (spec->cipher_keysz == 0) {
1571 		return (0);
1572 	}
1573 
1574 	/* Initialize the key and the active context */
1575 	spec->cipher_key.ck_format = CRYPTO_KEY_RAW;
1576 	spec->cipher_key.ck_length = 8 * spec->cipher_keysz; /* in bits */
1577 
1578 	if (cipher_defs[ssl->pending_calg].bsize > 0) {
1579 		/* client_write_IV */
1580 		spec->cipher_mech.cm_param =
1581 		    (caddr_t)&(ssl->pending_keyblock[2 * spec->mac_hashsz +
1582 		    2 * spec->cipher_keysz]);
1583 		spec->cipher_mech.cm_param_len = spec->cipher_bsize;
1584 	}
1585 	spec->cipher_data.cd_format = CRYPTO_DATA_RAW;
1586 	if (dir == KSSL_READ) {
1587 		spec->cipher_mech.cm_param_len =
1588 		    cipher_defs[ssl->pending_calg].bsize;
1589 
1590 		/* client_write_key */
1591 		spec->cipher_key.ck_data =
1592 		    &(ssl->pending_keyblock[2 * spec->mac_hashsz]);
1593 
1594 		ret = crypto_decrypt_init(&(spec->cipher_mech),
1595 		    &(spec->cipher_key), NULL, &spec->cipher_ctx, NULL);
1596 		if (CRYPTO_ERR(ret)) {
1597 			DTRACE_PROBE1(kssl_err__crypto_decrypt_init_read,
1598 			    int, ret);
1599 		}
1600 	} else {
1601 		if (cipher_defs[ssl->pending_calg].bsize > 0) {
1602 			/* server_write_IV */
1603 			spec->cipher_mech.cm_param += spec->cipher_bsize;
1604 		}
1605 
1606 		/* server_write_key */
1607 		spec->cipher_key.ck_data =
1608 		    &(ssl->pending_keyblock[2 * spec->mac_hashsz +
1609 		    spec->cipher_keysz]);
1610 
1611 		ret = crypto_encrypt_init(&(spec->cipher_mech),
1612 		    &(spec->cipher_key), NULL, &spec->cipher_ctx, NULL);
1613 		if (CRYPTO_ERR(ret))
1614 			DTRACE_PROBE1(kssl_err__crypto_encrypt_init_non_read,
1615 			    int, ret);
1616 	}
1617 	return (ret);
1618 }
1619 
1620 static int
1621 kssl_send_finished(ssl_t *ssl, int update_hsh)
1622 {
1623 	mblk_t *mp;
1624 	uchar_t *buf;
1625 	uchar_t *rstart;
1626 	uchar_t *versionp;
1627 	SSL3Hashes ssl3hashes;
1628 	size_t finish_len;
1629 	int ret;
1630 	uint16_t adj_len = 0;
1631 
1632 	mp = ssl->handshake_sendbuf;
1633 	ASSERT(mp != NULL);
1634 	buf = mp->b_wptr;
1635 	if (ssl->secure_renegotiation)
1636 		adj_len = KSSL_EMPTY_RENEG_INFO_LEN;
1637 	/*
1638 	 * It should be either a message with Server Hello record or just plain
1639 	 * SSL header (data packet).
1640 	 */
1641 	ASSERT(buf - mp->b_rptr ==
1642 	    SSL3_HDR_LEN + KSSL_SSL3_SH_RECLEN + SSL3_HDR_LEN + 1 + adj_len ||
1643 	    buf - mp->b_rptr == SSL3_HDR_LEN + 1);
1644 
1645 	rstart = buf;
1646 
1647 	if (IS_TLS(ssl))
1648 		finish_len = TLS_FINISHED_SIZE;
1649 	else
1650 		finish_len = KSSL_SSL3_FIN_MSGLEN;
1651 
1652 	/* 5 byte record header */
1653 	buf[0] = content_handshake;
1654 	buf[1] = ssl->major_version;
1655 	buf[2] = ssl->minor_version;
1656 	buf[3] = 0;
1657 	buf[4] = 4 + finish_len;
1658 
1659 	versionp = &buf[1];
1660 
1661 	buf += SSL3_HDR_LEN;
1662 
1663 	/* 4 byte message header */
1664 	buf[0] = (uchar_t)finished;	/* message type */
1665 	buf[1] = 0;			/* message len byte 0 */
1666 	buf[2] = 0;			/* message len byte 1 */
1667 	buf[3] = finish_len;	/* message len byte 2 */
1668 	buf += 4;
1669 
1670 	if (IS_TLS(ssl)) {
1671 		bcopy(ssl->hs_hashes.md5, ssl3hashes.md5,
1672 		    sizeof (ssl3hashes.md5));
1673 		bcopy(ssl->hs_hashes.sha1, ssl3hashes.sha1,
1674 		    sizeof (ssl3hashes.sha1));
1675 	}
1676 
1677 	/* Compute hashes for the SENDER side */
1678 	ret = kssl_compute_handshake_hashes(ssl, &ssl3hashes, sender_server);
1679 	if (ret != 0)
1680 		return (ret);
1681 
1682 	if (IS_TLS(ssl)) {
1683 		bcopy(ssl3hashes.tlshash, buf, sizeof (ssl3hashes.tlshash));
1684 	} else {
1685 		bcopy(ssl3hashes.md5, buf, MD5_HASH_LEN);
1686 		bcopy(ssl3hashes.sha1, buf + MD5_HASH_LEN, SHA1_HASH_LEN);
1687 	}
1688 
1689 	if (update_hsh) {
1690 		kssl_update_handshake_hashes(ssl, buf - 4, finish_len + 4);
1691 	}
1692 
1693 	mp->b_wptr = buf + finish_len;
1694 
1695 	ret = kssl_mac_encrypt_record(ssl, content_handshake, versionp,
1696 	    rstart, mp);
1697 	ASSERT(mp->b_wptr <= mp->b_datap->db_lim);
1698 
1699 	return (ret);
1700 }
1701 
1702 int
1703 kssl_mac_encrypt_record(ssl_t *ssl,
1704 	SSL3ContentType ct,
1705 	uchar_t *versionp,
1706 	uchar_t *rstart,
1707 	mblk_t *mp)
1708 {
1709 	KSSLCipherSpec *spec;
1710 	int mac_sz;
1711 	int ret = 0;
1712 	uint16_t rec_sz;
1713 	int pad_sz;
1714 	int i;
1715 
1716 	ASSERT(ssl != NULL);
1717 	ASSERT(rstart >= mp->b_rptr);
1718 	ASSERT(rstart < mp->b_wptr);
1719 
1720 	spec = &ssl->spec[KSSL_WRITE];
1721 	mac_sz = spec->mac_hashsz;
1722 
1723 	rec_sz = (mp->b_wptr - rstart) - SSL3_HDR_LEN;
1724 	ASSERT(rec_sz > 0);
1725 
1726 	if (mac_sz != 0) {
1727 		ASSERT(mp->b_wptr + mac_sz <= mp->b_datap->db_lim);
1728 		ret = kssl_compute_record_mac(ssl, KSSL_WRITE,
1729 		    ssl->seq_num[KSSL_WRITE], ct, versionp,
1730 		    rstart + SSL3_HDR_LEN, rec_sz, mp->b_wptr);
1731 		if (ret == CRYPTO_SUCCESS) {
1732 			ssl->seq_num[KSSL_WRITE]++;
1733 			mp->b_wptr += mac_sz;
1734 			rec_sz += mac_sz;
1735 		} else {
1736 			return (ret);
1737 		}
1738 	}
1739 
1740 	if (spec->cipher_type == type_block) {
1741 		pad_sz = spec->cipher_bsize -
1742 		    (rec_sz & (spec->cipher_bsize - 1));
1743 		ASSERT(mp->b_wptr + pad_sz <= mp->b_datap->db_lim);
1744 		for (i = 0; i < pad_sz; i++) {
1745 			mp->b_wptr[i] = pad_sz - 1;
1746 		}
1747 		mp->b_wptr += pad_sz;
1748 		rec_sz += pad_sz;
1749 	}
1750 
1751 	ASSERT(rec_sz <= SSL3_MAX_RECORD_LENGTH);
1752 
1753 	U16_TO_BE16(rec_sz, rstart + 3);
1754 
1755 	if (spec->cipher_ctx == 0)
1756 		return (ret);
1757 
1758 	spec->cipher_data.cd_length = rec_sz;
1759 	spec->cipher_data.cd_raw.iov_base = (char *)(rstart + SSL3_HDR_LEN);
1760 	spec->cipher_data.cd_raw.iov_len = rec_sz;
1761 	/* One record at a time. Otherwise, gotta allocate the crypt_data_t */
1762 	ret = crypto_encrypt_update(spec->cipher_ctx, &spec->cipher_data,
1763 	    NULL, NULL);
1764 	if (CRYPTO_ERR(ret)) {
1765 		DTRACE_PROBE1(kssl_err__crypto_encrypt_update,
1766 		    int, ret);
1767 	}
1768 	return (ret);
1769 }
1770 
1771 /*
1772  * Produce SSL alert message (SSLv3/TLS) or error message (SSLv2). For SSLv2
1773  * it is only done to tear down the SSL connection so it has fixed encoding.
1774  */
1775 void
1776 kssl_send_alert(ssl_t *ssl, SSL3AlertLevel level, SSL3AlertDescription desc)
1777 {
1778 	mblk_t *mp;
1779 	uchar_t *buf;
1780 	KSSLCipherSpec *spec;
1781 	size_t len;
1782 
1783 	ASSERT(ssl != NULL);
1784 
1785 	ssl->sendalert_level = level;
1786 	ssl->sendalert_desc = desc;
1787 
1788 	if (level == alert_fatal) {
1789 		DTRACE_PROBE2(kssl_sending_alert,
1790 		    SSL3AlertLevel, level, SSL3AlertDescription, desc);
1791 		if (ssl->sid.cached == B_TRUE) {
1792 			kssl_uncache_sid(&ssl->sid, ssl->kssl_entry);
1793 		}
1794 		ssl->fatal_alert = B_TRUE;
1795 		KSSL_COUNTER(fatal_alerts, 1);
1796 	} else
1797 		KSSL_COUNTER(warning_alerts, 1);
1798 
1799 	spec = &ssl->spec[KSSL_WRITE];
1800 
1801 	ASSERT(ssl->alert_sendbuf == NULL);
1802 	if (ssl->major_version == 0x03)
1803 		len = 7;
1804 	else
1805 		len = 5;
1806 	ssl->alert_sendbuf = mp = allocb(len + spec->mac_hashsz +
1807 	    spec->cipher_bsize, BPRI_HI);
1808 	if (mp == NULL) {
1809 		KSSL_COUNTER(alloc_fails, 1);
1810 		return;
1811 	}
1812 	buf = mp->b_wptr;
1813 
1814 	/* SSLv3/TLS */
1815 	if (ssl->major_version == 0x03) {
1816 		/* 5 byte record header */
1817 		buf[0] = content_alert;
1818 		buf[1] = ssl->major_version;
1819 		buf[2] = ssl->minor_version;
1820 		buf[3] = 0;
1821 		buf[4] = 2;
1822 		buf += SSL3_HDR_LEN;
1823 
1824 		/* alert contents */
1825 		buf[0] = (uchar_t)level;
1826 		buf[1] = (uchar_t)desc;
1827 		buf += 2;
1828 	} else {
1829 	/* SSLv2 has different encoding. */
1830 		/* 2-byte encoding of the length */
1831 		buf[0] = 0x80;
1832 		buf[1] = 0x03;
1833 		buf += 2;
1834 
1835 		/* Protocol Message Code = Error */
1836 		buf[0] = 0;
1837 		/* Error Message Code = Undefined Error */
1838 		buf[1] = 0;
1839 		buf[2] = 0;
1840 		buf += 3;
1841 	}
1842 
1843 	mp->b_wptr = buf;
1844 }
1845 
1846 /* Assumes RSA encryption */
1847 static int
1848 kssl_handle_client_key_exchange(ssl_t *ssl, mblk_t *mp, int msglen,
1849     kssl_callback_t cbfn, void *arg)
1850 {
1851 	char *buf;
1852 	uchar_t *pms;
1853 	size_t pmslen;
1854 	int allocated;
1855 	int err, rverr = ENOMEM;
1856 	kssl_entry_t *ep;
1857 	crypto_key_t *privkey;
1858 	crypto_data_t *wrapped_pms_data, *pms_data;
1859 	crypto_call_req_t creq, *creqp;
1860 
1861 	ep = ssl->kssl_entry;
1862 	privkey = ep->ke_private_key;
1863 	if (privkey == NULL) {
1864 		return (ENOENT);
1865 	}
1866 
1867 	ASSERT(ssl->msg.type == client_key_exchange);
1868 	ASSERT(ssl->hs_waitstate == wait_client_key);
1869 
1870 	/*
1871 	 * TLS adds an extra 2 byte length field before the data.
1872 	 */
1873 	if (IS_TLS(ssl)) {
1874 		msglen = (mp->b_rptr[0] << 8) | mp->b_rptr[1];
1875 		mp->b_rptr += 2;
1876 	}
1877 
1878 	/*
1879 	 * Allocate all we need in one shot. about 300 bytes total, for
1880 	 * 1024 bit RSA modulus.
1881 	 * The buffer layout will be: pms_data, wrapped_pms_data, the
1882 	 * value of the wrapped pms from the client, then room for the
1883 	 * resulting decrypted premaster secret.
1884 	 */
1885 	allocated = 2 * (sizeof (crypto_data_t) + msglen);
1886 	buf = kmem_alloc(allocated, KM_NOSLEEP);
1887 	if (buf == NULL) {
1888 		return (ENOMEM);
1889 	}
1890 
1891 	pms_data = (crypto_data_t *)buf;
1892 	wrapped_pms_data = &(((crypto_data_t *)buf)[1]);
1893 
1894 	wrapped_pms_data->cd_format = pms_data->cd_format = CRYPTO_DATA_RAW;
1895 	wrapped_pms_data->cd_offset = pms_data->cd_offset = 0;
1896 	wrapped_pms_data->cd_length = pms_data->cd_length = msglen;
1897 	wrapped_pms_data->cd_miscdata = pms_data->cd_miscdata = NULL;
1898 	wrapped_pms_data->cd_raw.iov_len = pms_data->cd_raw.iov_len = msglen;
1899 	wrapped_pms_data->cd_raw.iov_base = buf + 2 * sizeof (crypto_data_t);
1900 	pms_data->cd_raw.iov_base = wrapped_pms_data->cd_raw.iov_base + msglen;
1901 
1902 	bcopy(mp->b_rptr, wrapped_pms_data->cd_raw.iov_base, msglen);
1903 	mp->b_rptr += msglen;
1904 
1905 	/* Proceed synchronously if out of interrupt and configured to do so */
1906 	if ((kssl_synchronous) && (!servicing_interrupt())) {
1907 		creqp = NULL;
1908 	} else {
1909 		ssl->cke_callback_func = cbfn;
1910 		ssl->cke_callback_arg = arg;
1911 		creq.cr_flag = kssl_call_flag;
1912 		creq.cr_callback_func = kssl_cke_done;
1913 		creq.cr_callback_arg = ssl;
1914 
1915 		/* The callback routine will release this one */
1916 		KSSL_SSL_REFHOLD(ssl);
1917 
1918 		creqp = &creq;
1919 	}
1920 
1921 	if (ep->ke_is_nxkey) {
1922 		kssl_session_info_t *s;
1923 
1924 		s = ep->ke_sessinfo;
1925 		err = CRYPTO_SUCCESS;
1926 		if (!s->is_valid_handle) {
1927 			/* Reauthenticate to the provider */
1928 			if (s->do_reauth) {
1929 				err = kssl_get_obj_handle(ep);
1930 				if (err == CRYPTO_SUCCESS) {
1931 					s->is_valid_handle = B_TRUE;
1932 					s->do_reauth = B_FALSE;
1933 				}
1934 			} else
1935 				err = CRYPTO_FAILED;
1936 		}
1937 
1938 		if (err == CRYPTO_SUCCESS) {
1939 			ASSERT(s->is_valid_handle);
1940 			err = crypto_decrypt_prov(s->prov, s->sid,
1941 			    &rsa_x509_mech, wrapped_pms_data, &s->key,
1942 			    NULL, pms_data, creqp);
1943 		}
1944 
1945 		/*
1946 		 * Deal with session specific errors. We translate to
1947 		 * the closest errno.
1948 		 */
1949 		switch (err) {
1950 		case CRYPTO_KEY_HANDLE_INVALID:
1951 		case CRYPTO_SESSION_HANDLE_INVALID:
1952 			s->is_valid_handle = B_FALSE;
1953 			s->do_reauth = B_TRUE;
1954 			rverr = EINVAL;
1955 			break;
1956 		case CRYPTO_PIN_EXPIRED:
1957 		case CRYPTO_PIN_LOCKED:
1958 			rverr = EACCES;
1959 			break;
1960 		case CRYPTO_UNKNOWN_PROVIDER:
1961 			rverr = ENXIO;
1962 			break;
1963 		}
1964 	} else {
1965 		err = crypto_decrypt(&rsa_x509_mech, wrapped_pms_data,
1966 		    privkey, NULL, pms_data, creqp);
1967 	}
1968 
1969 	switch (err) {
1970 	case CRYPTO_SUCCESS:
1971 		break;
1972 
1973 	case CRYPTO_QUEUED:
1974 		/*
1975 		 * Finish the master secret then the rest of key material
1976 		 * derivation later.
1977 		 */
1978 		ssl->job.kjob = creq.cr_reqid;
1979 		ssl->job.buf = buf;
1980 		ssl->job.buflen = allocated;
1981 		ssl->hs_waitstate = wait_client_key_done;
1982 		return (0);
1983 	default:
1984 		DTRACE_PROBE1(kssl_err__crypto_decrypt, int, err);
1985 		kmem_free(buf, allocated);
1986 		return (rverr);
1987 	}
1988 
1989 	pmslen = pms_data->cd_length;
1990 	pms = kssl_rsa_unwrap((uchar_t *)pms_data->cd_raw.iov_base, &pmslen);
1991 
1992 	/* generate master key and save it in the ssl sid structure */
1993 	if (IS_TLS(ssl)) {
1994 		err = kssl_generate_tls_ms(ssl, pms, pmslen);
1995 		if (!CRYPTO_ERR(err))
1996 			err = kssl_generate_tls_keyblock(ssl);
1997 	} else {
1998 		kssl_generate_ssl_ms(ssl, pms, pmslen);
1999 		kssl_generate_keyblock(ssl);
2000 	}
2001 
2002 	if (err == CRYPTO_SUCCESS)
2003 		ssl->hs_waitstate = wait_change_cipher;
2004 
2005 	ssl->activeinput = B_FALSE;
2006 
2007 	kmem_free(buf, allocated);
2008 
2009 	return (0);
2010 }
2011 
2012 static int
2013 kssl_handle_finished(ssl_t *ssl, mblk_t *mp, int msglen)
2014 {
2015 	int err;
2016 	size_t finish_len;
2017 	int hashcompare;
2018 
2019 	ASSERT(ssl->msg.type == finished);
2020 	ASSERT(ssl->hs_waitstate == wait_finished);
2021 
2022 	if (IS_TLS(ssl))
2023 		finish_len = TLS_FINISHED_SIZE;
2024 	else
2025 		finish_len = KSSL_SSL3_FIN_MSGLEN;
2026 
2027 	if (msglen != finish_len) {
2028 		kssl_send_alert(ssl, alert_fatal, illegal_parameter);
2029 		return (EBADMSG);
2030 	}
2031 
2032 	if (IS_TLS(ssl)) {
2033 		hashcompare = bcmp(mp->b_rptr, ssl->hs_hashes.tlshash,
2034 		    finish_len);
2035 	} else {
2036 		hashcompare = bcmp(mp->b_rptr, &ssl->hs_hashes, finish_len);
2037 	}
2038 
2039 	/* The handshake hashes should be computed by now */
2040 	if (hashcompare != 0) {
2041 		kssl_send_alert(ssl, alert_fatal, handshake_failure);
2042 		return (EBADMSG);
2043 	}
2044 
2045 	mp->b_rptr += msglen;
2046 
2047 	ssl->hs_waitstate = idle_handshake;
2048 
2049 	if (ssl->resumed == B_TRUE) {
2050 		ssl->activeinput = B_FALSE;
2051 		return (0);
2052 	}
2053 
2054 	err = kssl_send_change_cipher_specs(ssl);
2055 	if (err != 0) {
2056 		return (err);
2057 	}
2058 	err = kssl_send_finished(ssl, 0);
2059 	if (err != 0) {
2060 		return (err);
2061 	}
2062 
2063 	kssl_cache_sid(&ssl->sid, ssl->kssl_entry);
2064 	ssl->activeinput = B_FALSE;
2065 
2066 	return (0);
2067 }
2068 
2069 #define	KSSL2_CH_MIN_RECSZ	(9)
2070 
2071 /*
2072  * This method is needed to handle clients which send the
2073  * SSLv2/SSLv3 handshake for backwards compat with SSLv2 servers.
2074  * We are not really doing SSLv2 here, just handling the header
2075  * and then switching to SSLv3.
2076  */
2077 int
2078 kssl_handle_v2client_hello(ssl_t *ssl, mblk_t *mp, int recsz)
2079 {
2080 	uchar_t *recend;
2081 	int err;
2082 	SSL3AlertDescription desc = illegal_parameter;
2083 	uint_t randlen;
2084 	uint_t sidlen;
2085 	uint_t cslen;
2086 	uchar_t *suitesp;
2087 	uchar_t *rand;
2088 	uint_t i, j;
2089 	uint16_t suite, selected_suite;
2090 	int ch_recsz = KSSL2_CH_MIN_RECSZ;
2091 	boolean_t suite_found = B_FALSE;
2092 
2093 	ASSERT(mp->b_wptr >= mp->b_rptr + recsz);
2094 	ASSERT(ssl->hs_waitstate == wait_client_hello);
2095 	ASSERT(ssl->resumed == B_FALSE);
2096 
2097 	if (recsz < ch_recsz) {
2098 		DTRACE_PROBE2(kssl_err__reclen_less_than_minimum,
2099 		    int, recsz, int, ch_recsz);
2100 		goto falert;
2101 	}
2102 
2103 	MD5Init(&ssl->hs_md5);
2104 	SHA1Init(&ssl->hs_sha1);
2105 
2106 	kssl_update_handshake_hashes(ssl, mp->b_rptr, recsz);
2107 
2108 	recend = mp->b_rptr + recsz;
2109 
2110 	if (*mp->b_rptr != 1) {
2111 		DTRACE_PROBE1(kssl_err__invalid_version, uint_t, *mp->b_rptr);
2112 		goto falert;
2113 	}
2114 	mp->b_rptr += 3;
2115 
2116 	cslen = ((uint_t)mp->b_rptr[0] << 8) + (uint_t)mp->b_rptr[1];
2117 	sidlen = ((uint_t)mp->b_rptr[2] << 8) + (uint_t)mp->b_rptr[3];
2118 	randlen = ((uint_t)mp->b_rptr[4] << 8) + (uint_t)mp->b_rptr[5];
2119 	if (cslen % 3 != 0) {
2120 		DTRACE_PROBE1(kssl_err__cipher_suites_len_error, uint_t, cslen);
2121 		goto falert;
2122 	}
2123 	if (randlen < SSL_MIN_CHALLENGE_BYTES ||
2124 	    randlen > SSL_MAX_CHALLENGE_BYTES) {
2125 		DTRACE_PROBE1(kssl_err__randlen_out_of_range,
2126 		    uint_t, randlen);
2127 		goto falert;
2128 	}
2129 	mp->b_rptr += 6;
2130 	ch_recsz += cslen + sidlen + randlen;
2131 	if (recsz != ch_recsz) {
2132 		DTRACE_PROBE2(kssl_err__invalid_message_len_sum,
2133 		    int, recsz, int, ch_recsz);
2134 		goto falert;
2135 	}
2136 	suitesp = mp->b_rptr;
2137 	rand = suitesp + cslen + sidlen;
2138 	if (randlen < SSL3_RANDOM_LENGTH) {
2139 		bzero(ssl->client_random, SSL3_RANDOM_LENGTH);
2140 	}
2141 	bcopy(rand, &ssl->client_random[SSL3_RANDOM_LENGTH - randlen],
2142 	    randlen);
2143 
2144 	for (i = 0; i < ssl->kssl_entry->kssl_cipherSuites_nentries; i++) {
2145 		suite = ssl->kssl_entry->kssl_cipherSuites[i];
2146 		for (j = 0; j < cslen; j += 3) {
2147 			DTRACE_PROBE2(kssl_cipher_suite_check_v2,
2148 			    uint16_t, suite,
2149 			    uint16_t,
2150 			    (uint16_t)((suitesp[j+1] << 8) + suitesp[j+2]));
2151 			if (suitesp[j] != 0) {
2152 				continue;
2153 			}
2154 
2155 			/* Check for regular (true) cipher suite. */
2156 			if (suitesp[j + 1] == ((suite >> 8) & 0xff) &&
2157 			    suitesp[j + 2] == (suite & 0xff)) {
2158 				DTRACE_PROBE1(kssl_cipher_suite_found,
2159 				    uint16_t, suite);
2160 				suite_found = B_TRUE;
2161 				selected_suite = suite;
2162 			}
2163 
2164 			/* Check for SCSV. */
2165 			if (suitesp[j + 1] ==  ((SSL_SCSV >> 8) & 0xff) &&
2166 			    suitesp[j + 2] == (SSL_SCSV & 0xff)) {
2167 				DTRACE_PROBE(kssl_scsv_found);
2168 				ssl->secure_renegotiation = B_TRUE;
2169 			}
2170 			/*
2171 			 * If we got cipher suite match and SCSV or went
2172 			 * through the whole list of client cipher suites
2173 			 * (hence we know if SCSV was present or not) we
2174 			 * can terminate the cycle now.
2175 			 */
2176 			if (suite_found &&
2177 			    (ssl->secure_renegotiation || (i > 0)))
2178 				break;
2179 		}
2180 		if (suite_found)
2181 			break;
2182 	}
2183 	if (!suite_found) {
2184 		DTRACE_PROBE(kssl_err__no_SSLv2_cipher_suite);
2185 		ssl->activeinput = B_FALSE;
2186 		/*
2187 		 * If there is no fallback point terminate the handshake with
2188 		 * SSL alert otherwise return with SSL_MISS.
2189 		 */
2190 		if (ssl->kssl_entry->ke_fallback_head == NULL) {
2191 			DTRACE_PROBE(kssl_no_fallback);
2192 			desc = handshake_failure;
2193 			goto falert;
2194 		} else {
2195 			return (SSL_MISS);
2196 		}
2197 	}
2198 
2199 	mp->b_rptr = recend;
2200 
2201 	for (i = 0; i < cipher_suite_defs_nentries; i++) {
2202 		if (selected_suite == cipher_suite_defs[i].suite) {
2203 			break;
2204 		}
2205 	}
2206 
2207 	ASSERT(i < cipher_suite_defs_nentries);
2208 
2209 	ssl->pending_cipher_suite = selected_suite;
2210 	ssl->pending_malg = cipher_suite_defs[i].malg;
2211 	ssl->pending_calg = cipher_suite_defs[i].calg;
2212 	ssl->pending_keyblksz = cipher_suite_defs[i].keyblksz;
2213 
2214 	ASSERT(ssl->sid.cached == B_FALSE);
2215 
2216 	(void) random_get_pseudo_bytes(ssl->sid.session_id,
2217 	    SSL3_SESSIONID_BYTES);
2218 	ssl->sid.client_addr = ssl->faddr;
2219 	ssl->sid.cipher_suite = selected_suite;
2220 
2221 	err = kssl_send_server_hello(ssl);
2222 	if (err != 0) {
2223 		return (err);
2224 	}
2225 	err = kssl_send_certificate_and_server_hello_done(ssl);
2226 	if (err != 0) {
2227 		return (err);
2228 	}
2229 	KSSL_COUNTER(full_handshakes, 1);
2230 	ssl->hs_waitstate = wait_client_key;
2231 	ssl->activeinput = B_FALSE;
2232 	return (0);
2233 
2234 falert:
2235 	kssl_send_alert(ssl, alert_fatal, desc);
2236 	ssl->activeinput = B_FALSE;
2237 	return (EBADMSG);
2238 }
2239 
2240 /*
2241  * Call back routine for asynchronously submitted RSA decryption jobs.
2242  * This routine retrieves the pre-master secret, and proceeds to generate
2243  * the remaining key materials.
2244  */
2245 static void
2246 kssl_cke_done(void *arg, int status)
2247 {
2248 	int ret = 0;
2249 	uchar_t *pms;
2250 	size_t pmslen;
2251 	crypto_data_t *pms_data;
2252 	kssl_cmd_t kssl_cmd = KSSL_CMD_NONE;
2253 	ssl_t *ssl = (ssl_t *)arg;
2254 	mblk_t *alertmp;
2255 	kssl_callback_t cbfn;
2256 	void *cbarg;
2257 
2258 	mutex_enter(&ssl->kssl_lock);
2259 
2260 	ASSERT(ssl->msg.type == client_key_exchange);
2261 	ASSERT(ssl->hs_waitstate == wait_client_key_done);
2262 
2263 	if (status != CRYPTO_SUCCESS) {
2264 		kssl_send_alert(ssl, alert_fatal, decrypt_error);
2265 		kssl_cmd = KSSL_CMD_SEND;
2266 		goto out;
2267 	}
2268 
2269 	pms_data = (crypto_data_t *)(ssl->job.buf);
2270 
2271 	ASSERT(pms_data != NULL);
2272 
2273 	pmslen = pms_data->cd_length;
2274 	pms = kssl_rsa_unwrap((uchar_t *)pms_data->cd_raw.iov_base, &pmslen);
2275 
2276 	/* generate master key and save it in the ssl sid structure */
2277 	if (IS_TLS(ssl)) {
2278 		ret = kssl_generate_tls_ms(ssl, pms, pmslen);
2279 		if (!CRYPTO_ERR(ret))
2280 			ret = kssl_generate_tls_keyblock(ssl);
2281 	} else {
2282 		kssl_generate_ssl_ms(ssl, pms, pmslen);
2283 		kssl_generate_keyblock(ssl);
2284 	}
2285 
2286 	if (ret == CRYPTO_SUCCESS)
2287 		ssl->hs_waitstate = wait_change_cipher;
2288 
2289 out:
2290 	kmem_free(ssl->job.buf, ssl->job.buflen);
2291 
2292 	ssl->job.kjob = 0;
2293 	ssl->job.buf = NULL;
2294 	ssl->job.buflen = 0;
2295 
2296 	ssl->activeinput = B_FALSE;
2297 
2298 	/* If we're the only ones left, then we won't callback */
2299 	if (ssl->kssl_refcnt == 1) {
2300 		mutex_exit(&ssl->kssl_lock);
2301 		KSSL_SSL_REFRELE(ssl);
2302 		return;
2303 	}
2304 
2305 	cbfn = ssl->cke_callback_func;
2306 	cbarg = ssl->cke_callback_arg;
2307 	alertmp = ssl->alert_sendbuf;
2308 	ssl->alert_sendbuf = NULL;
2309 
2310 	mutex_exit(&ssl->kssl_lock);
2311 
2312 	KSSL_SSL_REFRELE(ssl);
2313 
2314 	/* Now call the callback routine */
2315 	(*(cbfn))(cbarg, alertmp, kssl_cmd);
2316 }
2317 
2318 /*
2319  * Returns the first complete contiguous record out of rec_ass_head
2320  * The record is returned in a separate contiguous mblk, rec_ass_head is
2321  * left pointing to the next record in the queue.
2322  *
2323  * The output looks as follows:
2324  *
2325  * |--------|---------- .... -----|<---------->|<----------->|--- ... ---|
2326  * ^        ^                     ^  mac_size     pad_size               ^
2327  * |        |___ b_rptr  b_wptr __|                                      |
2328  * |                                                                     |
2329  * |___ db_base                                                db_lim ___|
2330  */
2331 mblk_t *
2332 kssl_get_next_record(ssl_t *ssl)
2333 {
2334 	mblk_t *mp, *retmp;
2335 	int rhsz = SSL3_HDR_LEN;
2336 	uint16_t rec_sz;
2337 	int mpsz, total_size;
2338 	SSL3ContentType content_type;
2339 
2340 	ASSERT(MUTEX_HELD(&ssl->kssl_lock));
2341 
2342 	mp = ssl->rec_ass_head;
2343 	if (mp == NULL)
2344 		return (NULL);
2345 
2346 	/* Fast path: when mp has at least a complete record */
2347 	if (MBLKL(mp) < rhsz) {
2348 		DTRACE_PROBE1(kssl_mblk__incomplete_header,
2349 		    mblk_t *, mp);
2350 		/* Not even a complete header in there yet */
2351 		if (msgdsize(mp) < rhsz) {
2352 			return (NULL);
2353 		}
2354 
2355 		if (!pullupmsg(mp, rhsz)) {
2356 			kssl_send_alert(ssl, alert_fatal, internal_error);
2357 			freemsg(mp);
2358 			ssl->rec_ass_head = ssl->rec_ass_tail = NULL;
2359 			return (NULL);
2360 		}
2361 	}
2362 	content_type = (SSL3ContentType)mp->b_rptr[0];
2363 	if (content_type == content_handshake_v2) {
2364 		DTRACE_PROBE1(kssl_mblk__ssl_v2, mblk_t *, mp);
2365 		rec_sz = (uint16_t)mp->b_rptr[1];
2366 		rhsz = 2;
2367 	} else {
2368 		DTRACE_PROBE1(kssl_mblk__ssl_v3, mblk_t *, mp);
2369 		uint8_t *rec_sz_p = (uint8_t *)mp->b_rptr + 3;
2370 		rec_sz = BE16_TO_U16(rec_sz_p);
2371 	}
2372 
2373 	/*
2374 	 * same tests as above. Only rare very fragmented cases will
2375 	 * incur the cost of msgdsize() and msgpullup(). Well formed
2376 	 * packets will fall in the most frequent fast path.
2377 	 */
2378 	total_size = rhsz + rec_sz;
2379 
2380 	/*
2381 	 * Missing: defensive against record fabricated with longer than
2382 	 * MAX record length.
2383 	 */
2384 	if (MBLKL(mp) < total_size) {
2385 		DTRACE_PROBE2(kssl_mblk__smaller_than_total_size,
2386 		    mblk_t *, mp, int, total_size);
2387 		/* Not a complete record yet. Keep accumulating */
2388 		if (msgdsize(mp) < total_size) {
2389 			return (NULL);
2390 		}
2391 
2392 		if (!pullupmsg(mp, total_size)) {
2393 			kssl_send_alert(ssl, alert_fatal, internal_error);
2394 			freemsg(mp);
2395 			ssl->rec_ass_head = ssl->rec_ass_tail = NULL;
2396 			return (NULL);
2397 		}
2398 	}
2399 	mpsz = MBLKL(mp);	/* could've changed after the pullup */
2400 
2401 	if (mpsz > total_size) {
2402 		DTRACE_PROBE2(kssl_mblk__bigger_than_total_size,
2403 		    mblk_t *, mp, int, total_size);
2404 		/* gotta allocate a new block */
2405 		if ((retmp = dupb(mp)) == NULL) {
2406 			kssl_send_alert(ssl, alert_fatal, internal_error);
2407 			freemsg(mp);
2408 			ssl->rec_ass_head = ssl->rec_ass_tail = NULL;
2409 			return (NULL);
2410 		}
2411 
2412 		retmp->b_wptr = retmp->b_rptr + total_size;
2413 		mp->b_rptr += total_size;
2414 		ssl->rec_ass_head = mp;
2415 	} else {
2416 		DTRACE_PROBE2(kssl_mblk__equal_to_total_size,
2417 		    mblk_t *, mp, int, total_size);
2418 		ASSERT(mpsz == total_size);
2419 		ssl->rec_ass_head = mp->b_cont;
2420 		mp->b_cont = NULL;
2421 		retmp = mp;
2422 	}
2423 	/* Adjust the tail */
2424 	if ((mp = ssl->rec_ass_tail = ssl->rec_ass_head) != NULL) {
2425 		for (; mp->b_cont != NULL; mp = mp->b_cont) {
2426 			ssl->rec_ass_tail = mp->b_cont;
2427 		}
2428 	}
2429 
2430 	return (retmp);
2431 }
2432 
2433 
2434 static void
2435 kssl_mblksfree(ssl_t *ssl)
2436 {
2437 
2438 	ASSERT(ssl != NULL);
2439 
2440 	if (ssl->rec_ass_head != NULL) {
2441 		freemsg(ssl->rec_ass_head);
2442 	}
2443 	ssl->rec_ass_head = NULL;
2444 	ssl->rec_ass_tail = NULL;
2445 
2446 	if (ssl->msg.head != NULL) {
2447 		freemsg(ssl->msg.head);
2448 	}
2449 	ssl->msg.head = NULL;
2450 	ssl->msg.tail = NULL;
2451 
2452 	if (ssl->handshake_sendbuf != NULL) {
2453 		freemsg(ssl->handshake_sendbuf);
2454 		ssl->handshake_sendbuf = NULL;
2455 	}
2456 	if (ssl->alert_sendbuf != NULL) {
2457 		freemsg(ssl->alert_sendbuf);
2458 		ssl->alert_sendbuf = NULL;
2459 	}
2460 }
2461 
2462 static void
2463 kssl_specsfree(ssl_t *ssl)
2464 {
2465 	KSSLCipherSpec *spec = &ssl->spec[KSSL_READ];
2466 
2467 	if (spec->cipher_ctx != NULL) {
2468 		crypto_cancel_ctx(spec->cipher_ctx);
2469 		spec->cipher_ctx = 0;
2470 	}
2471 
2472 	spec = &ssl->spec[KSSL_WRITE];
2473 
2474 	if (spec->cipher_ctx != NULL) {
2475 		crypto_cancel_ctx(spec->cipher_ctx);
2476 		spec->cipher_ctx = 0;
2477 	}
2478 }
2479 
2480 /*
2481  * Frees the ssl structure (aka the context of an SSL session).
2482  * Any pending crypto jobs are cancelled.
2483  * Any initiated crypto contexts are freed as well.
2484  */
2485 void
2486 kssl_free_context(ssl_t *ssl)
2487 {
2488 	ASSERT(ssl != NULL);
2489 	if (!(MUTEX_HELD(&ssl->kssl_lock))) {
2490 		/* we're coming from an external API entry point */
2491 		mutex_enter(&ssl->kssl_lock);
2492 	}
2493 
2494 	if (ssl->job.kjob != NULL) {
2495 		crypto_cancel_req(ssl->job.kjob);
2496 		kmem_free(ssl->job.buf, ssl->job.buflen);
2497 
2498 		ssl->job.kjob = 0;
2499 		ssl->job.buf = NULL;
2500 		ssl->job.buflen = 0;
2501 	}
2502 
2503 	kssl_mblksfree(ssl);
2504 	kssl_specsfree(ssl);
2505 
2506 	KSSL_ENTRY_REFRELE(ssl->kssl_entry);
2507 	ssl->kssl_entry = NULL;
2508 
2509 	mutex_exit(&ssl->kssl_lock);
2510 
2511 	kmem_cache_free(kssl_cache, ssl);
2512 	kssl_cache_count--;
2513 }
2514