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