xref: /titanic_41/usr/src/uts/common/inet/kssl/ksslrec.c (revision 3db86aab554edbb4244c8d1a1c90f152eee768af)
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 		/* cilent_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;
1524 	crypto_key_t *privkey;
1525 	crypto_data_t *wrapped_pms_data, *pms_data;
1526 	crypto_call_req_t creq, *creqp;
1527 
1528 	privkey = ssl->kssl_entry->ke_private_key;
1529 	if (privkey == NULL) {
1530 	    return (ENOENT);
1531 	}
1532 
1533 	ASSERT(ssl->msg.type == client_key_exchange);
1534 	ASSERT(ssl->hs_waitstate == wait_client_key);
1535 
1536 	/*
1537 	 * TLS adds an extra 2 byte length field before the data.
1538 	 */
1539 	if (IS_TLS(ssl)) {
1540 		msglen = (mp->b_rptr[0] << 8) | mp->b_rptr[1];
1541 		mp->b_rptr += 2;
1542 	}
1543 
1544 	/*
1545 	 * Allocate all we need in one shot. about 300 bytes total, for
1546 	 * 1024 bit RSA modulus.
1547 	 * The buffer layout will be: pms_data, wrapped_pms_data, the
1548 	 * value of the wrapped pms from the client, then room for the
1549 	 * resulting decrypted premaster secret.
1550 	 */
1551 	allocated = 2 * (sizeof (crypto_data_t) + msglen);
1552 	buf = kmem_alloc(allocated, KM_NOSLEEP);
1553 	if (buf == NULL) {
1554 		return (ENOMEM);
1555 	}
1556 
1557 	pms_data = (crypto_data_t *)buf;
1558 	wrapped_pms_data = &(((crypto_data_t *)buf)[1]);
1559 
1560 	wrapped_pms_data->cd_format = pms_data->cd_format = CRYPTO_DATA_RAW;
1561 	wrapped_pms_data->cd_offset = pms_data->cd_offset = 0;
1562 	wrapped_pms_data->cd_length = pms_data->cd_length = msglen;
1563 	wrapped_pms_data->cd_miscdata = pms_data->cd_miscdata = NULL;
1564 	wrapped_pms_data->cd_raw.iov_len = pms_data->cd_raw.iov_len = msglen;
1565 	wrapped_pms_data->cd_raw.iov_base = buf + 2 * sizeof (crypto_data_t);
1566 	pms_data->cd_raw.iov_base = wrapped_pms_data->cd_raw.iov_base + msglen;
1567 
1568 	bcopy(mp->b_rptr, wrapped_pms_data->cd_raw.iov_base, msglen);
1569 	mp->b_rptr += msglen;
1570 
1571 	/* Proceed synchronously if out of interrupt and configured to do so */
1572 	if ((kssl_synchronous) && (!servicing_interrupt())) {
1573 		creqp = NULL;
1574 	} else {
1575 		ssl->cke_callback_func = cbfn;
1576 		ssl->cke_callback_arg = arg;
1577 		creq.cr_flag = kssl_call_flag;
1578 		creq.cr_callback_func = kssl_cke_done;
1579 		creq.cr_callback_arg = ssl;
1580 
1581 		/* The callback routine will release this one */
1582 		KSSL_SSL_REFHOLD(ssl);
1583 
1584 		creqp = &creq;
1585 	}
1586 
1587 	err = crypto_decrypt(&rsa_x509_mech, wrapped_pms_data,
1588 		privkey, NULL, pms_data, creqp);
1589 
1590 	switch (err) {
1591 	case CRYPTO_SUCCESS:
1592 		break;
1593 
1594 	case CRYPTO_QUEUED:
1595 		/*
1596 		 * Finish the master secret then the rest of key material
1597 		 * derivation later.
1598 		 */
1599 		ssl->job.kjob = creq.cr_reqid;
1600 		ssl->job.buf = buf;
1601 		ssl->job.buflen = allocated;
1602 		ssl->hs_waitstate = wait_client_key_done;
1603 		return (0);
1604 	default:
1605 #ifdef	DEBUG
1606 		cmn_err(CE_WARN, "kssl_handle_client_key_exchange: "
1607 			"crypto_decrypt error 0x%02X", err);
1608 #endif	/* DEBUG */
1609 		kmem_free(buf, allocated);
1610 		return (ENOMEM);
1611 	}
1612 
1613 	pmslen = pms_data->cd_length;
1614 	pms = kssl_rsa_unwrap((uchar_t *)pms_data->cd_raw.iov_base, &pmslen);
1615 
1616 	/* generate master key and save it in the ssl sid structure */
1617 	if (IS_TLS(ssl)) {
1618 		err = kssl_generate_tls_ms(ssl, pms, pmslen);
1619 		if (!CRYPTO_ERR(err))
1620 			err = kssl_generate_tls_keyblock(ssl);
1621 	} else {
1622 		kssl_generate_ssl_ms(ssl, pms, pmslen);
1623 		kssl_generate_keyblock(ssl);
1624 	}
1625 
1626 	if (err == CRYPTO_SUCCESS)
1627 		ssl->hs_waitstate = wait_change_cipher;
1628 
1629 	ssl->activeinput = B_FALSE;
1630 
1631 	kmem_free(buf, allocated);
1632 
1633 	return (0);
1634 }
1635 
1636 static int
1637 kssl_handle_finished(ssl_t *ssl, mblk_t *mp, int msglen)
1638 {
1639 	int err;
1640 	size_t finish_len;
1641 	int hashcompare;
1642 
1643 	ASSERT(ssl->msg.type == finished);
1644 	ASSERT(ssl->hs_waitstate == wait_finished);
1645 
1646 	if (IS_TLS(ssl))
1647 		finish_len = TLS_FINISHED_SIZE;
1648 	else
1649 		finish_len = KSSL_SSL3_FIN_MSGLEN;
1650 
1651 	if (msglen != finish_len) {
1652 		kssl_send_alert(ssl, alert_fatal, illegal_parameter);
1653 		return (EBADMSG);
1654 	}
1655 
1656 	if (IS_TLS(ssl)) {
1657 		hashcompare = bcmp(mp->b_rptr, ssl->hs_hashes.tlshash,
1658 			finish_len);
1659 	} else {
1660 		hashcompare = bcmp(mp->b_rptr, &ssl->hs_hashes, finish_len);
1661 	}
1662 
1663 	/* The handshake hashes should be computed by now */
1664 	if (hashcompare != 0) {
1665 		kssl_send_alert(ssl, alert_fatal, handshake_failure);
1666 		return (EBADMSG);
1667 	}
1668 
1669 	mp->b_rptr += msglen;
1670 
1671 	ssl->hs_waitstate = idle_handshake;
1672 
1673 	if (ssl->resumed == B_TRUE) {
1674 		ssl->activeinput = B_FALSE;
1675 		return (0);
1676 	}
1677 
1678 	err = kssl_send_change_cipher_specs(ssl);
1679 	if (err != 0) {
1680 		return (err);
1681 	}
1682 	err = kssl_send_finished(ssl, 0);
1683 	if (err != 0) {
1684 		return (err);
1685 	}
1686 
1687 	ASSERT(ssl->sid.cached == B_FALSE);
1688 	ssl->sid.cached = B_TRUE;
1689 	kssl_cache_sid(&ssl->sid, ssl->kssl_entry);
1690 	ssl->activeinput = B_FALSE;
1691 
1692 	return (0);
1693 }
1694 
1695 #define	KSSL2_CH_MIN_RECSZ	(9)
1696 
1697 /*
1698  * This method is needed to handle clients which send the
1699  * SSLv2/SSLv3 handshake for backwards compat with SSLv2 servers.
1700  * We are not really doing SSLv2 here, just handling the header
1701  * and then switching to SSLv3.
1702  */
1703 int
1704 kssl_handle_v2client_hello(ssl_t *ssl, mblk_t *mp, int recsz)
1705 {
1706 	uchar_t *recend;
1707 	int err;
1708 	SSL3AlertDescription desc = illegal_parameter;
1709 	uint_t randlen;
1710 	uint_t sidlen;
1711 	uint_t nsuites;
1712 	uchar_t *suitesp;
1713 	uchar_t *rand;
1714 	uint_t i, j;
1715 	uint16_t suite;
1716 	int ch_recsz = KSSL2_CH_MIN_RECSZ;
1717 
1718 	ASSERT(mp->b_wptr >= mp->b_rptr + recsz);
1719 	ASSERT(ssl->hs_waitstate == wait_client_hello);
1720 	ASSERT(ssl->resumed == B_FALSE);
1721 
1722 	if (recsz < ch_recsz) {
1723 		goto falert;
1724 	}
1725 
1726 	MD5Init(&ssl->hs_md5);
1727 	SHA1Init(&ssl->hs_sha1);
1728 
1729 	kssl_update_handshake_hashes(ssl, mp->b_rptr, recsz);
1730 
1731 	recend = mp->b_rptr + recsz;
1732 
1733 	if (*mp->b_rptr != 1) {
1734 		goto falert;
1735 	}
1736 	mp->b_rptr += 3;
1737 
1738 	nsuites = ((uint_t)mp->b_rptr[0] << 8) + (uint_t)mp->b_rptr[1];
1739 	sidlen = ((uint_t)mp->b_rptr[2] << 8) + (uint_t)mp->b_rptr[3];
1740 	randlen = ((uint_t)mp->b_rptr[4] << 8) + (uint_t)mp->b_rptr[5];
1741 	if (nsuites % 3 != 0) {
1742 		KSSL_DEBUG2_IF(kssl_debug,
1743 			"kssl_handle_v2client_hello nsuites = %d, error.",
1744 			nsuites);
1745 		goto falert;
1746 	}
1747 	if (randlen < SSL_MIN_CHALLENGE_BYTES ||
1748 	    randlen > SSL_MAX_CHALLENGE_BYTES) {
1749 		KSSL_DEBUG2_IF(kssl_debug,
1750 			"kssl_handle_v2client_hello randlen out of range: %d",
1751 			randlen);
1752 		goto falert;
1753 	}
1754 	mp->b_rptr += 6;
1755 	ch_recsz += nsuites + sidlen + randlen;
1756 	if (recsz != ch_recsz) {
1757 		goto falert;
1758 	}
1759 	suitesp = mp->b_rptr;
1760 	rand = suitesp + nsuites + sidlen;
1761 	if (randlen < SSL3_RANDOM_LENGTH) {
1762 		bzero(ssl->client_random, SSL3_RANDOM_LENGTH);
1763 	}
1764 	bcopy(rand, &ssl->client_random[SSL3_RANDOM_LENGTH - randlen],
1765 	    randlen);
1766 
1767 	for (i = 0; i < ssl->kssl_entry->kssl_cipherSuites_nentries; i++) {
1768 		suite = ssl->kssl_entry->kssl_cipherSuites[i];
1769 		for (j = 0; j < nsuites; j += 3) {
1770 			if (suitesp[j] != 0) {
1771 				continue;
1772 			}
1773 
1774 			if (suitesp[j + 1] == ((suite >> 8) & 0xff) &&
1775 			    suitesp[j + 2] == (suite & 0xff)) {
1776 				break;
1777 			}
1778 		}
1779 		if (j < nsuites) {
1780 			break;
1781 		}
1782 	}
1783 	if (i == ssl->kssl_entry->kssl_cipherSuites_nentries) {
1784 		KSSL_DEBUG1_IF(kssl_debug, "kssl_handle_v2client_hello - "
1785 			"cannot find SSLv2 cipher suite");
1786 		ssl->activeinput = B_FALSE;
1787 		return (SSL_MISS);
1788 	}
1789 
1790 	mp->b_rptr = recend;
1791 
1792 	for (i = 0; i < cipher_suite_defs_nentries; i++) {
1793 		if (suite == cipher_suite_defs[i].suite) {
1794 			break;
1795 		}
1796 	}
1797 
1798 	ASSERT(i < cipher_suite_defs_nentries);
1799 
1800 	ssl->pending_cipher_suite = suite;
1801 	ssl->pending_malg = cipher_suite_defs[i].malg;
1802 	ssl->pending_calg = cipher_suite_defs[i].calg;
1803 	ssl->pending_keyblksz = cipher_suite_defs[i].keyblksz;
1804 
1805 	ASSERT(ssl->sid.cached == B_FALSE);
1806 
1807 	(void) random_get_pseudo_bytes(ssl->sid.session_id,
1808 	    SSL3_SESSIONID_BYTES);
1809 	ssl->sid.client_addr = ssl->faddr;
1810 	ssl->sid.cipher_suite = suite;
1811 
1812 	err = kssl_send_server_hello(ssl);
1813 	if (err != 0) {
1814 		return (err);
1815 	}
1816 	err = kssl_send_certificate_and_server_hello_done(ssl);
1817 	if (err != 0) {
1818 		return (err);
1819 	}
1820 	KSSL_COUNTER(full_handshakes, 1);
1821 	ssl->hs_waitstate = wait_client_key;
1822 	ssl->activeinput = B_FALSE;
1823 	return (0);
1824 
1825 falert:
1826 	kssl_send_alert(ssl, alert_fatal, desc);
1827 	ssl->activeinput = B_FALSE;
1828 	return (EBADMSG);
1829 }
1830 
1831 /*
1832  * Call back routine for asynchronously submitted RSA decryption jobs.
1833  * The routine retreived the pre-master secret, and proceeds to generate
1834  * the remaining key materials.
1835  */
1836 static void
1837 kssl_cke_done(void *arg, int status)
1838 {
1839 	int ret = 0;
1840 	uchar_t *pms;
1841 	size_t pmslen;
1842 	crypto_data_t *pms_data;
1843 	kssl_cmd_t kssl_cmd = KSSL_CMD_NONE;
1844 	ssl_t *ssl = (ssl_t *)arg;
1845 	mblk_t *alertmp;
1846 	kssl_callback_t cbfn;
1847 	void *cbarg;
1848 
1849 	mutex_enter(&ssl->kssl_lock);
1850 
1851 	ASSERT(ssl->msg.type == client_key_exchange);
1852 	ASSERT(ssl->hs_waitstate == wait_client_key_done);
1853 
1854 	if (status != CRYPTO_SUCCESS) {
1855 		kssl_send_alert(ssl, alert_fatal, decrypt_error);
1856 		kssl_cmd = KSSL_CMD_SEND;
1857 		goto out;
1858 	}
1859 
1860 	pms_data = (crypto_data_t *)(ssl->job.buf);
1861 
1862 	ASSERT(pms_data != NULL);
1863 
1864 	pmslen = pms_data->cd_length;
1865 	pms = kssl_rsa_unwrap((uchar_t *)pms_data->cd_raw.iov_base, &pmslen);
1866 
1867 	/* generate master key and save it in the ssl sid structure */
1868 	if (IS_TLS(ssl)) {
1869 		ret = kssl_generate_tls_ms(ssl, pms, pmslen);
1870 		if (!CRYPTO_ERR(ret))
1871 			ret = kssl_generate_tls_keyblock(ssl);
1872 	} else {
1873 		kssl_generate_ssl_ms(ssl, pms, pmslen);
1874 		kssl_generate_keyblock(ssl);
1875 	}
1876 
1877 	if (ret == CRYPTO_SUCCESS)
1878 		ssl->hs_waitstate = wait_change_cipher;
1879 
1880 out:
1881 	kmem_free(ssl->job.buf, ssl->job.buflen);
1882 
1883 	ssl->job.kjob = 0;
1884 	ssl->job.buf = NULL;
1885 	ssl->job.buflen = 0;
1886 
1887 	ssl->activeinput = B_FALSE;
1888 
1889 	/* If we're the only ones left, then we won't callback */
1890 	if (ssl->kssl_refcnt == 1) {
1891 		mutex_exit(&ssl->kssl_lock);
1892 		KSSL_SSL_REFRELE(ssl);
1893 		return;
1894 	}
1895 
1896 	cbfn = ssl->cke_callback_func;
1897 	cbarg = ssl->cke_callback_arg;
1898 	alertmp = ssl->alert_sendbuf;
1899 	ssl->alert_sendbuf = NULL;
1900 
1901 	mutex_exit(&ssl->kssl_lock);
1902 
1903 	KSSL_SSL_REFRELE(ssl);
1904 
1905 	/* Now call the callback routine */
1906 	(*(cbfn))(cbarg, alertmp, kssl_cmd);
1907 }
1908 
1909 /*
1910  * Returns the first complete contiguous record out of rec_ass_head
1911  * The record is returned in a separate contiguous mblk, rec_ass_head is
1912  * left pointing to the next record in the queue.
1913  *
1914  * The output looks as follows:
1915  *
1916  * |--------|---------- .... -----|<---------->|<----------->|--- ... ---|
1917  * ^        ^                     ^  mac_size     pad_size               ^
1918  * |        |___ b_rptr  b_wptr __|                                      |
1919  * |                                                                     |
1920  * |___ db_base                                                db_lim ___|
1921  */
1922 mblk_t *
1923 kssl_get_next_record(ssl_t *ssl)
1924 {
1925 	mblk_t *mp, *retmp;
1926 	int rhsz = SSL3_HDR_LEN;
1927 	uint16_t rec_sz;
1928 	int mpsz, total_size;
1929 	SSL3ContentType content_type;
1930 
1931 	ASSERT(MUTEX_HELD(&ssl->kssl_lock));
1932 
1933 	mp = ssl->rec_ass_head;
1934 	if (mp == NULL)
1935 		return (NULL);
1936 
1937 	/* Fast path: when mp has at least a complete record */
1938 	if (MBLKL(mp) < rhsz) {
1939 		/* Not even a complete header in there yet */
1940 		if (msgdsize(mp) < rhsz) {
1941 			return (NULL);
1942 		}
1943 
1944 		if (!pullupmsg(mp, rhsz)) {
1945 			kssl_send_alert(ssl, alert_fatal, internal_error);
1946 			freemsg(mp);
1947 			ssl->rec_ass_head = ssl->rec_ass_tail = NULL;
1948 			return (NULL);
1949 		}
1950 	}
1951 	content_type = (SSL3ContentType)mp->b_rptr[0];
1952 	if (content_type == content_handshake_v2) {
1953 		rec_sz = (uint16_t)mp->b_rptr[1];
1954 		rhsz = 2;
1955 	} else {
1956 		uint8_t *rec_sz_p = (uint8_t *)mp->b_rptr + 3;
1957 		rec_sz = BE16_TO_U16(rec_sz_p);
1958 	}
1959 
1960 	/*
1961 	 * same tests as above. Only rare very fragmented cases will
1962 	 * incur the cost of msgdsize() and msgpullup(). Well formed
1963 	 * packets will fall in the most frequent fast path.
1964 	 */
1965 	total_size = rhsz + rec_sz;
1966 
1967 	/*
1968 	 * Missing: defensive against record fabricated with longer than
1969 	 * MAX record length.
1970 	 */
1971 	if (MBLKL(mp) < total_size) {
1972 		/* Not a complete record yet. Keep accumulating */
1973 		if (msgdsize(mp) < total_size) {
1974 			return (NULL);
1975 		}
1976 
1977 		if (!pullupmsg(mp, total_size)) {
1978 			kssl_send_alert(ssl, alert_fatal, internal_error);
1979 			freemsg(mp);
1980 			ssl->rec_ass_head = ssl->rec_ass_tail = NULL;
1981 			return (NULL);
1982 		}
1983 	}
1984 	mpsz = MBLKL(mp);	/* could've changed after the pullup */
1985 
1986 	if (mpsz > total_size) {
1987 		/* gotta allocate a new block */
1988 		if ((retmp = dupb(mp)) == NULL) {
1989 			kssl_send_alert(ssl, alert_fatal, internal_error);
1990 			freemsg(mp);
1991 			ssl->rec_ass_head = ssl->rec_ass_tail = NULL;
1992 			return (NULL);
1993 		}
1994 
1995 		retmp->b_wptr = retmp->b_rptr + total_size;
1996 		mp->b_rptr += total_size;
1997 		ssl->rec_ass_head = mp;
1998 	} else {
1999 		ASSERT(mpsz == total_size);
2000 		ssl->rec_ass_head = mp->b_cont;
2001 		mp->b_cont = NULL;
2002 		retmp = mp;
2003 	}
2004 	/* Adjust the tail */
2005 	if ((mp = ssl->rec_ass_tail = ssl->rec_ass_head) != NULL) {
2006 		for (; mp->b_cont != NULL; mp = mp->b_cont) {
2007 			ssl->rec_ass_tail = mp->b_cont;
2008 		}
2009 	}
2010 
2011 	return (retmp);
2012 }
2013 
2014 
2015 static void
2016 kssl_mblksfree(ssl_t *ssl)
2017 {
2018 
2019 	ASSERT(ssl != NULL);
2020 
2021 	if (ssl->rec_ass_head != NULL) {
2022 		freemsg(ssl->rec_ass_head);
2023 	}
2024 	ssl->rec_ass_head = NULL;
2025 	ssl->rec_ass_tail = NULL;
2026 
2027 	if (ssl->msg.head != NULL) {
2028 		freemsg(ssl->msg.head);
2029 	}
2030 	ssl->msg.head = NULL;
2031 	ssl->msg.tail = NULL;
2032 
2033 	if (ssl->handshake_sendbuf != NULL) {
2034 		freemsg(ssl->handshake_sendbuf);
2035 		ssl->handshake_sendbuf = NULL;
2036 	}
2037 	if (ssl->alert_sendbuf != NULL) {
2038 		freemsg(ssl->alert_sendbuf);
2039 		ssl->alert_sendbuf = NULL;
2040 	}
2041 }
2042 
2043 static void
2044 kssl_specsfree(ssl_t *ssl)
2045 {
2046 	KSSLCipherSpec *spec = &ssl->spec[KSSL_READ];
2047 
2048 	if (spec->cipher_ctx != NULL) {
2049 		crypto_cancel_ctx(spec->cipher_ctx);
2050 		spec->cipher_ctx = 0;
2051 	}
2052 
2053 	spec = &ssl->spec[KSSL_WRITE];
2054 
2055 	if (spec->cipher_ctx != NULL) {
2056 		crypto_cancel_ctx(spec->cipher_ctx);
2057 		spec->cipher_ctx = 0;
2058 	}
2059 }
2060 
2061 /*
2062  * Frees the ssl structure (aka the context of an SSL session).
2063  * Any pending crypto jobs are cancelled.
2064  * Any initiated crypto contexts are freed as well.
2065  */
2066 void
2067 kssl_free_context(ssl_t *ssl)
2068 {
2069 	ASSERT(ssl != NULL);
2070 	if (!(MUTEX_HELD(&ssl->kssl_lock))) {
2071 		/* we're coming from an external API entry point */
2072 		mutex_enter(&ssl->kssl_lock);
2073 	}
2074 
2075 	if (ssl->job.kjob != NULL) {
2076 		crypto_cancel_req(ssl->job.kjob);
2077 		kmem_free(ssl->job.buf, ssl->job.buflen);
2078 
2079 		ssl->job.kjob = 0;
2080 		ssl->job.buf = NULL;
2081 		ssl->job.buflen = 0;
2082 	}
2083 
2084 	kssl_mblksfree(ssl);
2085 	kssl_specsfree(ssl);
2086 
2087 	KSSL_ENTRY_REFRELE(ssl->kssl_entry);
2088 	ssl->kssl_entry = NULL;
2089 
2090 	mutex_exit(&ssl->kssl_lock);
2091 
2092 	kmem_cache_free(kssl_cache, ssl);
2093 	kssl_cache_count--;
2094 }
2095