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