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