xref: /titanic_52/usr/src/uts/common/inet/kssl/ksslapi.c (revision c2580b931007758eab8cb5ae8726ebe1588e259b)
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 2005 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/strsun.h>
31 #include <sys/cmn_err.h>
32 #include <sys/kmem.h>
33 #include <sys/cpuvar.h>
34 #include <sys/atomic.h>
35 #include <sys/sysmacros.h>
36 
37 #include <inet/common.h>
38 #include <inet/ip.h>
39 #include <inet/ip6.h>
40 
41 #include <sys/systm.h>
42 #include <sys/param.h>
43 #include <sys/tihdr.h>
44 
45 #include "ksslimpl.h"
46 #include "ksslproto.h"
47 #include "ksslapi.h"
48 
49 static kssl_cmd_t kssl_handle_any_record(kssl_ctx_t ctx, mblk_t *mp,
50     mblk_t **decrmp, kssl_callback_t cbfn, void *arg);
51 static boolean_t kssl_enqueue(kssl_chain_t **head, void *item);
52 static void kssl_dequeue(kssl_chain_t **head, void *item);
53 static kssl_status_t kssl_build_single_record(ssl_t *ssl, mblk_t *mp);
54 
55 /*
56  * The socket T_bind_req message is intercepted and re-routed here
57  * to see is there is SSL relevant job to do, based on the kssl config
58  * in the kssl_entry_tab.
59  * Looks up the kernel SSL proxy table, to find an entry that matches the
60  * same serveraddr, and has one of the following two criteria:
61  * 1. in_port is an ssl_port. This endpoint can be used later as a fallback
62  *    to complete connections that cannot be handled by the SSL kernel proxy
63  *    (typically non supported ciphersuite). The cookie for the calling client
64  *    is saved with the kssl_entry to be retrieved for the fallback.
65  *    The function returns KSSL_HAS_PROXY.
66  *
67  * 2. in_port is a proxy port for another ssl port. The ssl port is then
68  *    substituted to the in_port in the bind_req TPI structure, so that
69  *    the bind falls through to the SSL port. At the end of this operation,
70  *    all the packets arriving to the SSL port will be delivered to an
71  *    accepted endpoint child of this bound socket.
72  *    The  kssl_entry_t is returned in *ksslent, for later use by the
73  *    lower modules' SSL hooks that handle the Handshake messages.
74  *    The function returns KSSL_IS_PROXY.
75  *
76  * The function returns KSSL_NO_PROXY otherwise. We do not suppport
77  * IPv6 addresses.
78  */
79 
80 kssl_endpt_type_t
81 kssl_check_proxy(mblk_t *bindmp, void *cookie, kssl_ent_t *ksslent)
82 {
83 	int i;
84 	kssl_endpt_type_t ret;
85 	kssl_entry_t *ep;
86 	sin_t *sin;
87 	struct T_bind_req *tbr;
88 	ipaddr_t v4addr;
89 	in_port_t in_port;
90 
91 	if (kssl_enabled == 0) {
92 		return (KSSL_NO_PROXY);
93 	}
94 
95 	tbr = (struct T_bind_req *)bindmp->b_rptr;
96 
97 	ret = KSSL_NO_PROXY;
98 
99 
100 	switch (tbr->ADDR_length) {
101 	case sizeof (sin_t):
102 		sin = (sin_t *)(bindmp->b_rptr + tbr->ADDR_length);
103 		in_port = ntohs(sin->sin_port);
104 		v4addr = sin->sin_addr.s_addr;
105 		break;
106 
107 	case sizeof (sin6_t):
108 		/* Future support of IPv6 goes here */
109 	default:
110 		/* Should ASSERT() here? */
111 		return (ret);
112 	}
113 
114 	mutex_enter(&kssl_tab_mutex);
115 
116 	for (i = 0; i < kssl_entry_tab_size; i++) {
117 		if ((ep = kssl_entry_tab[i]) == NULL)
118 			continue;
119 
120 		if ((ep->ke_laddr == v4addr) || (ep->ke_laddr == INADDR_ANY)) {
121 
122 			/* This is an SSL port to fallback to */
123 			if (ep->ke_ssl_port == in_port) {
124 
125 				/*
126 				 * Let's see first if there's at least
127 				 * an endpoint for a proxy server.
128 				 * If there's none, then we return as we have
129 				 * no proxy, so that the bind() to the
130 				 * transport layer goes through.
131 				 * The calling module will ask for this
132 				 * cookie if it wants to fall back to it,
133 				 * so add this one to the list of fallback
134 				 * clients.
135 				 */
136 				if (!kssl_enqueue((kssl_chain_t **)
137 				    &(ep->ke_fallback_head), cookie)) {
138 					break;
139 				}
140 
141 				/*
142 				 * Now transform the T_BIND_REQ into
143 				 * a T_BIND_ACK.
144 				 */
145 				tbr->PRIM_type = T_BIND_ACK;
146 				bindmp->b_datap->db_type = M_PCPROTO;
147 
148 				KSSL_ENTRY_REFHOLD(ep);
149 				*ksslent = (kssl_ent_t)ep;
150 
151 				ret = KSSL_HAS_PROXY;
152 				break;
153 			}
154 
155 			/* This is a proxy port. */
156 			if (ep->ke_proxy_port == in_port) {
157 				mblk_t *entmp;
158 
159 				/* Append this entry to the bind_req mblk */
160 
161 				entmp = allocb(sizeof (kssl_entry_t),
162 				    BPRI_MED);
163 				if (entmp == NULL)
164 					break;
165 				*((kssl_entry_t **)entmp->b_rptr) = ep;
166 
167 				entmp->b_wptr = entmp->b_rptr +
168 				    sizeof (kssl_entry_t);
169 
170 				bindmp->b_cont = entmp;
171 
172 				/* Add the caller's cookie to proxies list */
173 
174 				if (!kssl_enqueue((kssl_chain_t **)
175 				    &(ep->ke_proxy_head), cookie)) {
176 					freeb(bindmp->b_cont);
177 					bindmp->b_cont = NULL;
178 					break;
179 				}
180 
181 				/*
182 				 * Make this look  like the SSL port to the
183 				 * transport below
184 				 */
185 				sin->sin_port = htons(ep->ke_ssl_port);
186 
187 				tbr->PRIM_type = T_SSL_PROXY_BIND_REQ;
188 
189 				KSSL_ENTRY_REFHOLD(ep);
190 				*ksslent = (kssl_ent_t)ep;
191 
192 				ret = KSSL_IS_PROXY;
193 				break;
194 			}
195 		}
196 	}
197 
198 	mutex_exit(&kssl_tab_mutex);
199 	return (ret);
200 }
201 
202 /*
203  * Retrieved an endpoint "bound" to the SSL entry.
204  * Such endpoint has previously called kssl_check_proxy(), got itself
205  * linked to the kssl_entry's ke_fallback_head list.
206  * This routine returns the cookie from that SSL entry ke_fallback_head list.
207  */
208 void *
209 kssl_find_fallback(kssl_ent_t ksslent)
210 {
211 	kssl_entry_t *kssl_entry = (kssl_entry_t *)ksslent;
212 
213 	if (kssl_entry->ke_fallback_head != NULL)
214 		return (kssl_entry->ke_fallback_head->fallback_bound);
215 
216 	KSSL_COUNTER(proxy_fallback_failed, 1);
217 
218 	return (NULL);
219 }
220 
221 /*
222  * Re-usable code for adding and removing an element to/from a chain that
223  * matches "item"
224  * The chain is simple-linked and NULL ended.
225  */
226 
227 /*
228  * This routine returns TRUE if the item was either successfully added to
229  * the chain, or is already there. It returns FALSE otherwise.
230  */
231 static boolean_t
232 kssl_enqueue(kssl_chain_t **head, void *item)
233 {
234 	kssl_chain_t *newchain, *cur;
235 
236 	/* Lookup the existing entries to avoid duplicates */
237 	cur = *head;
238 	while (cur != NULL) {
239 		if (cur->item == item) {
240 			return (B_TRUE);
241 		}
242 		cur = cur->next;
243 	}
244 
245 	newchain = kmem_alloc(sizeof (kssl_chain_t), KM_NOSLEEP);
246 	if (newchain == NULL) {
247 		return (B_FALSE);
248 	}
249 
250 	newchain->item = item;
251 	newchain->next = *head;
252 	*head = newchain;
253 	return (B_TRUE);
254 }
255 
256 static void
257 kssl_dequeue(kssl_chain_t **head, void *item)
258 {
259 	kssl_chain_t *prev, *cur;
260 
261 	prev = cur = *head;
262 	while (cur != NULL) {
263 		if (cur->item == item) {
264 			if (cur == *head)
265 				*head = (*head)->next;
266 			else
267 				prev->next = cur->next;
268 			kmem_free(cur, sizeof (kssl_chain_t));
269 			return;
270 		}
271 		prev = cur;
272 		cur = cur->next;
273 	}
274 }
275 
276 /*
277  * Holds the kssl_entry
278  */
279 void
280 kssl_hold_ent(kssl_ent_t ksslent)
281 {
282 	KSSL_ENTRY_REFHOLD((kssl_entry_t *)ksslent);
283 }
284 
285 /*
286  * Releases the kssl_entry
287  * If the caller passes a cookie, then it should be removed from both
288  * proxies and fallbacks chains.
289  */
290 void
291 kssl_release_ent(kssl_ent_t ksslent, void *cookie, kssl_endpt_type_t endpt_type)
292 {
293 	kssl_entry_t *kssl_entry = (kssl_entry_t *)ksslent;
294 
295 	if (cookie != NULL) {
296 		if (endpt_type == KSSL_IS_PROXY)
297 			ASSERT(kssl_entry->ke_proxy_head != NULL);
298 			kssl_dequeue(
299 			    (kssl_chain_t **)&kssl_entry->ke_proxy_head,
300 			    cookie);
301 		if (endpt_type == KSSL_HAS_PROXY)
302 			ASSERT(kssl_entry->ke_fallback_head != NULL);
303 			kssl_dequeue(
304 			    (kssl_chain_t **)&kssl_entry->ke_fallback_head,
305 			    cookie);
306 	}
307 	KSSL_ENTRY_REFRELE(kssl_entry);
308 }
309 
310 /*
311  * Holds the kssl context
312  */
313 void
314 kssl_hold_ctx(kssl_ctx_t ksslctx)
315 {
316 	ssl_t *ssl = (ssl_t *)ksslctx;
317 
318 	KSSL_SSL_REFHOLD(ssl);
319 }
320 
321 /*
322  * Releases the kssl_context
323  */
324 void
325 kssl_release_ctx(kssl_ctx_t ksslctx)
326 {
327 	KSSL_SSL_REFRELE((ssl_t *)ksslctx);
328 }
329 
330 /*
331  * Packets are accumulated here, if there are packets already queued,
332  * or if the context is active.
333  * The context is active when an incoming record processing function
334  * is already executing on a different thread.
335  * Queued packets are handled either when an mblk arrived and completes
336  * a record, or, when the active context processor finishes the task at
337  * hand.
338  * The caller has to keep calling this routine in a loop until it returns
339  * B_FALSE in *more. The reason for this is SSL3: The protocol
340  * allows the client to send its first application_data message right
341  * after it had sent its Finished message, and not wait for the server
342  * ChangeCipherSpec and Finished. This overlap means we can't batch up
343  * a returned Handshake message to be sent on the wire
344  * with a decrypted application_data to be delivered to the application.
345  */
346 kssl_cmd_t
347 kssl_input(kssl_ctx_t ctx, mblk_t *mp, mblk_t **decrmp, boolean_t *more,
348     kssl_callback_t cbfn, void *arg)
349 {
350 	mblk_t *recmp, *outmp = NULL;
351 	kssl_cmd_t kssl_cmd;
352 	ssl_t *ssl;
353 	uint8_t *rec_sz_p;
354 	int mplen;
355 	SSL3ContentType content_type;
356 	uint16_t rec_sz;
357 
358 	ASSERT(ctx != NULL);
359 
360 	if (mp != NULL) {
361 		ASSERT(mp->b_prev == NULL && mp->b_next == NULL);
362 	}
363 
364 	ssl = (ssl_t *)(ctx);
365 
366 	*decrmp = NULL;
367 	*more = B_FALSE;
368 
369 	mutex_enter(&ssl->kssl_lock);
370 
371 	if (ssl->close_notify == B_TRUE) {
372 		goto sendnewalert;
373 	}
374 
375 	/* Whomever is currently processing this connection will get to this */
376 	if (ssl->activeinput) {
377 		if (mp != NULL) {
378 			KSSL_ENQUEUE_MP(ssl, mp);
379 		}
380 		mutex_exit(&ssl->kssl_lock);
381 		return (KSSL_CMD_NONE);
382 	}
383 
384 	/*
385 	 * Fast path for complete incoming application_data records on an empty
386 	 * queue.
387 	 * This is by far the most frequently encountered case
388 	 */
389 
390 	if ((!ssl->activeinput) && (ssl->rec_ass_head == NULL) &&
391 	    ((mp != NULL) && (mplen = MBLKL(mp)) > SSL3_HDR_LEN)) {
392 
393 		content_type = (SSL3ContentType)mp->b_rptr[0];
394 
395 		if ((content_type == content_application_data) &&
396 		    (ssl->hs_waitstate == idle_handshake)) {
397 			rec_sz_p = SSL3_REC_SIZE(mp);
398 			rec_sz = BE16_TO_U16(rec_sz_p);
399 
400 			if ((mp->b_cont == NULL) && (mplen == rec_sz)) {
401 
402 				mp->b_flag &= ~DBLK_COOKED;
403 				*decrmp = mp;
404 				mutex_exit(&ssl->kssl_lock);
405 				return (KSSL_CMD_DELIVER_PROXY);
406 			}
407 		}
408 	}
409 
410 	ssl->activeinput = B_TRUE;
411 	/* Accumulate at least one record */
412 	if (mp != NULL) {
413 		KSSL_ENQUEUE_MP(ssl, mp);
414 		mp = NULL;
415 	}
416 	recmp = kssl_get_next_record(ssl);
417 
418 	if (recmp == NULL) {
419 		ssl->activeinput = B_FALSE;
420 		if (ssl->alert_sendbuf != NULL) {
421 			goto sendalert;
422 		}
423 		/* Not even a complete header yet. wait for the rest */
424 		mutex_exit(&ssl->kssl_lock);
425 		return (KSSL_CMD_NONE);
426 	}
427 
428 	do {
429 		if ((SSL3ContentType)recmp->b_rptr[0] ==
430 		    content_application_data) {
431 			/*
432 			 * application_data records are decrypted and
433 			 * MAC-verified by the stream head, and in the context
434 			 * a read()'ing thread. This avoids unfairly charging
435 			 * the cost of handling this record on the whole system,
436 			 * and prevents doing it while in the shared IP
437 			 * perimeter.
438 			 */
439 			ssl->activeinput = B_FALSE;
440 			if (ssl->hs_waitstate != idle_handshake) {
441 				goto sendnewalert;
442 			}
443 			outmp = recmp;
444 			kssl_cmd = KSSL_CMD_DELIVER_PROXY;
445 		} else {
446 			/*
447 			 * If we're past the initial handshake, start letting
448 			 * the stream head process all records, in particular
449 			 * the close_notify.
450 			 * This is needed to avoid processing them out of
451 			 * sequence when previous application data packets are
452 			 * waiting to be decrypted/MAC'ed and delivered.
453 			 */
454 			if (ssl->hs_waitstate == idle_handshake) {
455 				ssl->activeinput = B_FALSE;
456 				outmp = recmp;
457 				kssl_cmd = KSSL_CMD_DELIVER_PROXY;
458 			} else {
459 				kssl_cmd = kssl_handle_any_record(ssl, recmp,
460 				    &outmp, cbfn, arg);
461 			}
462 		}
463 
464 		/* Priority to Alert messages */
465 		if (ssl->alert_sendbuf != NULL) {
466 			goto sendalert;
467 		}
468 
469 		/* Then handshake messages */
470 		if (ssl->handshake_sendbuf) {
471 			if (*decrmp != NULL) {
472 				linkb(*decrmp, ssl->handshake_sendbuf);
473 			} else {
474 				*decrmp = ssl->handshake_sendbuf;
475 			}
476 			ssl->handshake_sendbuf = NULL;
477 
478 			*more = ((ssl->rec_ass_head != NULL) &&
479 			    (!ssl->activeinput));
480 			mutex_exit(&ssl->kssl_lock);
481 			return (kssl_cmd);
482 		}
483 
484 		if (ssl->hs_waitstate == idle_handshake) {
485 			*more = ((ssl->rec_ass_head != NULL) &&
486 			    (!ssl->activeinput));
487 		}
488 
489 		if (outmp != NULL) {
490 			*decrmp = outmp;
491 			/*
492 			 * Don't process any packet after an application_data.
493 			 * We could well receive the close_notify which should
494 			 * be handled separately.
495 			 */
496 			mutex_exit(&ssl->kssl_lock);
497 			return (kssl_cmd);
498 		}
499 		/*
500 		 * The current record isn't done yet. Don't start the next one
501 		 */
502 		if (ssl->activeinput) {
503 			mutex_exit(&ssl->kssl_lock);
504 			return (kssl_cmd);
505 		}
506 	} while ((recmp = kssl_get_next_record(ssl)) != NULL);
507 
508 	mutex_exit(&ssl->kssl_lock);
509 	return (kssl_cmd);
510 
511 sendnewalert:
512 	kssl_send_alert(ssl, alert_fatal, unexpected_message);
513 	if (mp != NULL) {
514 		freeb(mp);
515 	}
516 
517 sendalert:
518 	*decrmp = ssl->alert_sendbuf;
519 	ssl->alert_sendbuf = NULL;
520 	mutex_exit(&ssl->kssl_lock);
521 	return (KSSL_CMD_SEND);
522 }
523 
524 /*
525  * Decrypt and verify the MAC of an incoming chain of application_data record.
526  * Each block has exactly one SSL record.
527  * This routine recycles its incoming mblk, and flags it as DBLK_COOKED
528  */
529 kssl_cmd_t
530 kssl_handle_record(kssl_ctx_t ctx, mblk_t **mpp, mblk_t **outmp)
531 {
532 	uchar_t *recend, *rec_sz_p;
533 	uchar_t *real_recend;
534 	mblk_t *prevmp = NULL, *nextmp, *firstmp, *mp, *copybp;
535 	int mac_sz;
536 	uchar_t version[2];
537 	uint16_t rec_sz;
538 	SSL3AlertDescription desc;
539 	SSL3ContentType content_type;
540 	ssl_t *ssl;
541 	KSSLCipherSpec *spec;
542 	int error = 0, ret;
543 	kssl_cmd_t kssl_cmd = KSSL_CMD_DELIVER_PROXY;
544 	boolean_t deliverit = B_FALSE;
545 	crypto_data_t cipher_data;
546 
547 	ASSERT(ctx != NULL);
548 
549 	ssl = (ssl_t *)(ctx);
550 
551 	mp = firstmp = *mpp;
552 	*outmp = NULL;
553 
554 more:
555 
556 	while (mp != NULL) {
557 
558 		if (DB_REF(mp) > 1) {
559 			/*
560 			 * Fortunately copyb() preserves the offset,
561 			 * tail space and alignement so the copy is
562 			 * ready to be made an SSL record.
563 			 */
564 			if ((copybp = copyb(mp)) == NULL)
565 				return (NULL);
566 
567 			copybp->b_cont = mp->b_cont;
568 			if (mp == firstmp) {
569 				*mpp = copybp;
570 			} else {
571 				prevmp->b_cont = copybp;
572 			}
573 			freeb(mp);
574 			mp = copybp;
575 		}
576 
577 		content_type = (SSL3ContentType)mp->b_rptr[0];
578 
579 		if (content_type != content_application_data) {
580 			nextmp = mp->b_cont;
581 
582 			/* Remove this message */
583 			if (prevmp != NULL) {
584 				prevmp->b_cont = nextmp;
585 
586 				/*
587 				 * If we had processed blocks that need to
588 				 * be delivered, then remember that error code
589 				 */
590 				if (kssl_cmd == KSSL_CMD_DELIVER_PROXY)
591 					deliverit = B_TRUE;
592 			}
593 
594 			mutex_enter(&ssl->kssl_lock);
595 			kssl_cmd = kssl_handle_any_record(ssl, mp, outmp,
596 			    NULL, NULL);
597 
598 			if (ssl->alert_sendbuf != NULL) {
599 				goto sendalert;
600 			}
601 			mutex_exit(&ssl->kssl_lock);
602 
603 			if (deliverit) {
604 				kssl_cmd = KSSL_CMD_DELIVER_PROXY;
605 			}
606 
607 			mp = nextmp;
608 			continue;
609 		}
610 
611 		version[0] = mp->b_rptr[1];
612 		version[1] = mp->b_rptr[2];
613 		rec_sz_p = SSL3_REC_SIZE(mp);
614 		rec_sz = BE16_TO_U16(rec_sz_p);
615 
616 		mp->b_rptr += SSL3_HDR_LEN;
617 		recend = mp->b_rptr + rec_sz;
618 		real_recend = recend;
619 
620 		spec = &ssl->spec[KSSL_READ];
621 		mac_sz = spec->mac_hashsz;
622 		if (spec->cipher_ctx != 0) {
623 
624 			/*
625 			 * The record length must be a multiple of the
626 			 * block size for block ciphers.
627 			 * The cipher_bsize is always a power of 2.
628 			 */
629 			if ((spec->cipher_type == type_block) &&
630 			    ((rec_sz & (spec->cipher_bsize - 1)) != 0)) {
631 #ifdef	DEBUG
632 				cmn_err(CE_WARN, "kssl_handle_record: "
633 				    "bad record size");
634 #endif	/* DEBUG */
635 				KSSL_COUNTER(record_decrypt_failure, 1);
636 				mp->b_rptr = recend;
637 				desc = decrypt_error;
638 				goto makealert;
639 			}
640 
641 			cipher_data.cd_format = CRYPTO_DATA_RAW;
642 			cipher_data.cd_offset = 0;
643 			cipher_data.cd_length = rec_sz;
644 			cipher_data.cd_miscdata = NULL;
645 			cipher_data.cd_raw.iov_base = (char *)mp->b_rptr;
646 			cipher_data.cd_raw.iov_len = rec_sz;
647 			error = crypto_decrypt_update(spec->cipher_ctx,
648 			    &cipher_data, NULL, NULL);
649 			if (CRYPTO_ERR(error)) {
650 #ifdef	DEBUG
651 				cmn_err(CE_WARN, "kssl_handle_record: "
652 				    "crypto_decrypt_update failed: 0x%02X",
653 				    error);
654 #endif	/* DEBUG */
655 				KSSL_COUNTER(record_decrypt_failure, 1);
656 				mp->b_rptr = recend;
657 				desc = decrypt_error;
658 				goto makealert;
659 			}
660 		}
661 		if (spec->cipher_type == type_block) {
662 			uint_t pad_sz = recend[-1];
663 			pad_sz++;
664 			if (pad_sz + mac_sz > rec_sz) {
665 				mp->b_rptr = recend;
666 				desc = bad_record_mac;
667 				goto makealert;
668 			}
669 			rec_sz -= pad_sz;
670 			recend -= pad_sz;
671 		}
672 		if (mac_sz != 0) {
673 			uchar_t hash[MAX_HASH_LEN];
674 			if (rec_sz < mac_sz) {
675 				mp->b_rptr = real_recend;
676 				desc = bad_record_mac;
677 				goto makealert;
678 			}
679 			rec_sz -= mac_sz;
680 			recend -= mac_sz;
681 			ret = kssl_compute_record_mac(ssl, KSSL_READ,
682 				ssl->seq_num[KSSL_READ], content_type,
683 				version, mp->b_rptr, rec_sz, hash);
684 			if (ret != CRYPTO_SUCCESS ||
685 			    bcmp(hash, recend, mac_sz)) {
686 				mp->b_rptr = real_recend;
687 				desc = bad_record_mac;
688 #ifdef	DEBUG
689 				cmn_err(CE_WARN, "kssl_handle_record: "
690 					"msg MAC mismatch");
691 #endif	/* DEBUG */
692 				KSSL_COUNTER(verify_mac_failure, 1);
693 				goto makealert;
694 			}
695 			ssl->seq_num[KSSL_READ]++;
696 		}
697 
698 		if (ssl->hs_waitstate != idle_handshake) {
699 			mp->b_rptr = real_recend;
700 			desc = unexpected_message;
701 			goto makealert;
702 		}
703 		mp->b_wptr = recend;
704 
705 		prevmp = mp;
706 		mp = mp->b_cont;
707 	}
708 
709 	KSSL_COUNTER(appdata_record_ins, 1);
710 	return (kssl_cmd);
711 
712 makealert:
713 	nextmp = mp->b_cont;
714 	freeb(mp);
715 	mp = nextmp;
716 	mutex_enter(&ssl->kssl_lock);
717 	kssl_send_alert(ssl, alert_fatal, desc);
718 
719 	if (ssl->alert_sendbuf == NULL) {
720 		/* internal memory allocation failure. just return. */
721 #ifdef	DEBUG
722 		cmn_err(CE_WARN, "kssl_handle_record: "
723 		    "alert message allocation failed");
724 #endif	/* DEBUG */
725 		mutex_exit(&ssl->kssl_lock);
726 
727 		if (mp) {
728 			prevmp = NULL;
729 			goto more;
730 		}
731 
732 		return (KSSL_CMD_NONE);
733 	}
734 	kssl_cmd = KSSL_CMD_SEND;
735 sendalert:
736 	if (*outmp == NULL) {
737 		*outmp = ssl->alert_sendbuf;
738 	} else {
739 		linkb(*outmp, ssl->alert_sendbuf);
740 	}
741 	ssl->alert_sendbuf = NULL;
742 	mutex_exit(&ssl->kssl_lock);
743 
744 	if (mp) {
745 		prevmp = NULL;
746 		goto more;
747 	}
748 
749 	return (kssl_cmd);
750 }
751 /*
752  * This is the routine that handles incoming SSL records.
753  * When called the first time, with a NULL context, this routine expects
754  * a ClientHello SSL Handshake packet and shall allocate a context
755  * of a new SSL connection.
756  * During the rest of the handshake packets, the routine adjusts the
757  * state of the context according to the record received.
758  * After the ChangeCipherSpec message is received, the routine first
759  * decrypts/authenticated the packet using the key materials in the
760  * connection's context.
761  * The return code tells the caller what to do with the returned packet.
762  */
763 static kssl_cmd_t
764 kssl_handle_any_record(kssl_ctx_t ctx, mblk_t *mp, mblk_t **decrmp,
765     kssl_callback_t cbfn, void *arg)
766 {
767 	uchar_t *recend, *rec_sz_p;
768 	uchar_t version[2];
769 	uchar_t *real_recend, *save_rptr, *save_wptr;
770 	int rhsz = SSL3_HDR_LEN;
771 	uint16_t rec_sz;
772 	int sz;
773 	int mac_sz;
774 	SSL3AlertDescription desc;
775 	SSL3AlertLevel level;
776 	SSL3ContentType content_type;
777 	ssl_t *ssl;
778 	KSSLCipherSpec *spec;
779 	int error = 0, ret;
780 
781 	ASSERT(ctx != NULL);
782 
783 	ssl = (ssl_t *)(ctx);
784 
785 	*decrmp = NULL;
786 
787 	save_rptr = mp->b_rptr;
788 	save_wptr = mp->b_wptr;
789 
790 	ASSERT(MUTEX_HELD(&ssl->kssl_lock));
791 
792 	content_type = (SSL3ContentType)mp->b_rptr[0];
793 	if (content_type == content_handshake_v2) {
794 		if (ssl->hs_waitstate == wait_client_hello) {
795 			/* V2 compatible ClientHello */
796 			if (mp->b_rptr[3] == 0x03 &&
797 			    (mp->b_rptr[4] == 0x01 ||
798 				mp->b_rptr[4] == 0x00)) {
799 				ssl->major_version = version[0] = mp->b_rptr[3];
800 				ssl->minor_version = version[1] = mp->b_rptr[4];
801 			} else {
802 			/* We don't support "pure" SSLv2 */
803 				desc = protocol_version;
804 				goto sendalert;
805 			}
806 		}
807 		rec_sz = (uint16_t)mp->b_rptr[1];
808 		rhsz = 2;
809 	} else {
810 		ssl->major_version = version[0] = mp->b_rptr[1];
811 		ssl->minor_version = version[1] = mp->b_rptr[2];
812 		rec_sz_p = SSL3_REC_SIZE(mp);
813 		rec_sz = BE16_TO_U16(rec_sz_p);
814 	}
815 
816 	mp->b_rptr += rhsz;
817 	recend = mp->b_rptr + rec_sz;
818 	real_recend = recend;
819 
820 	spec = &ssl->spec[KSSL_READ];
821 	mac_sz = spec->mac_hashsz;
822 	if (spec->cipher_ctx != 0) {
823 		/*
824 		 * The record length must be a multiple of the
825 		 * block size for block ciphers.
826 		 */
827 		if ((spec->cipher_type == type_block) &&
828 		    ((rec_sz & (spec->cipher_bsize - 1)) != 0)) {
829 #ifdef	DEBUG
830 			cmn_err(CE_WARN, "kssl_handle_any_record: "
831 			    "bad record size");
832 #endif	/* DEBUG */
833 			KSSL_COUNTER(record_decrypt_failure, 1);
834 			mp->b_rptr = recend;
835 			desc = decrypt_error;
836 			goto sendalert;
837 		}
838 
839 		spec->cipher_data.cd_length = rec_sz;
840 		spec->cipher_data.cd_raw.iov_base = (char *)mp->b_rptr;
841 		spec->cipher_data.cd_raw.iov_len = rec_sz;
842 		error = crypto_decrypt_update(spec->cipher_ctx,
843 		    &spec->cipher_data, NULL, NULL);
844 		if (CRYPTO_ERR(error)) {
845 #ifdef	DEBUG
846 			cmn_err(CE_WARN,
847 				"kssl_handle_any_record: crypto_decrypt_update "
848 				"failed: 0x%02X", error);
849 #endif	/* DEBUG */
850 			KSSL_COUNTER(record_decrypt_failure, 1);
851 			mp->b_rptr = recend;
852 			desc = decrypt_error;
853 			goto sendalert;
854 		}
855 	}
856 	if (spec->cipher_type == type_block) {
857 		uint_t pad_sz = recend[-1];
858 		pad_sz++;
859 		if (pad_sz + mac_sz > rec_sz) {
860 			mp->b_rptr = recend;
861 			desc = bad_record_mac;
862 			goto sendalert;
863 		}
864 		rec_sz -= pad_sz;
865 		recend -= pad_sz;
866 	}
867 	if (mac_sz != 0) {
868 		uchar_t hash[MAX_HASH_LEN];
869 		if (rec_sz < mac_sz) {
870 			mp->b_rptr = real_recend;
871 			desc = bad_record_mac;
872 			goto sendalert;
873 		}
874 		rec_sz -= mac_sz;
875 		recend -= mac_sz;
876 		ret = kssl_compute_record_mac(ssl, KSSL_READ,
877 			ssl->seq_num[KSSL_READ], content_type,
878 			version, mp->b_rptr, rec_sz, hash);
879 		if (ret != CRYPTO_SUCCESS ||
880 		    bcmp(hash, recend, mac_sz)) {
881 			mp->b_rptr = real_recend;
882 			desc = bad_record_mac;
883 #ifdef	DEBUG
884 			cmn_err(CE_WARN, "kssl_handle_any_record: "
885 				"msg MAC mismatch");
886 #endif	/* DEBUG */
887 			KSSL_COUNTER(verify_mac_failure, 1);
888 			goto sendalert;
889 		}
890 		ssl->seq_num[KSSL_READ]++;
891 	}
892 
893 	switch (content_type) {
894 	case content_handshake:
895 		do {
896 			if (error != 0 ||
897 			    /* ignore client renegotiation for now */
898 			    ssl->hs_waitstate == idle_handshake) {
899 				mp->b_rptr = recend;
900 			}
901 			if (mp->b_rptr == recend) {
902 				mp->b_rptr = real_recend;
903 				if (error != 0) {
904 					goto error;
905 				}
906 				freeb(mp);
907 
908 				if (ssl->hs_waitstate == wait_client_key_done)
909 					return (KSSL_CMD_QUEUED);
910 
911 				return ((ssl->handshake_sendbuf != NULL) ?
912 				    KSSL_CMD_SEND : KSSL_CMD_NONE);
913 			}
914 			if (ssl->msg.state < MSG_BODY) {
915 				if (ssl->msg.state == MSG_INIT) {
916 					ssl->msg.type =
917 					    (SSL3HandshakeType)*mp->b_rptr++;
918 					ssl->msg.state = MSG_INIT_LEN;
919 				}
920 				if (ssl->msg.state == MSG_INIT_LEN) {
921 					int msglenb =
922 					    ssl->msg.msglen_bytes;
923 					int msglen = ssl->msg.msglen;
924 					while (mp->b_rptr < recend &&
925 					    msglenb < 3) {
926 						msglen = (msglen << 8) +
927 						    (uint_t)(*mp->b_rptr++);
928 						msglenb++;
929 					}
930 					ssl->msg.msglen_bytes = msglenb;
931 					ssl->msg.msglen = msglen;
932 					if (msglenb == 3) {
933 						ssl->msg.state = MSG_BODY;
934 					}
935 				}
936 				if (mp->b_rptr == recend) {
937 					mp->b_rptr = real_recend;
938 					freeb(mp);
939 					return (KSSL_CMD_NONE);
940 				}
941 			}
942 			ASSERT(ssl->msg.state == MSG_BODY);
943 
944 			sz = recend - mp->b_rptr;
945 
946 			if (ssl->msg.head == NULL &&
947 			    ssl->msg.msglen <= sz) {
948 				continue;
949 			}
950 			if (ssl->msg.head != NULL) {
951 				sz += msgdsize(ssl->msg.head);
952 				if (ssl->msg.msglen <= sz) {
953 					ssl->msg.tail->b_cont = mp;
954 					mp = ssl->msg.head;
955 					ssl->sslcnt = 100;
956 					ssl->msg.head = NULL;
957 					ssl->msg.tail = NULL;
958 					if (pullupmsg(mp, -1)) {
959 						recend = mp->b_rptr + sz;
960 						ASSERT(recend <= mp->b_wptr);
961 						continue;
962 					}
963 					mp->b_rptr = real_recend;
964 					error = ENOMEM;
965 					KSSL_COUNTER(alloc_fails, 1);
966 					goto error;
967 				}
968 			}
969 
970 			mp->b_wptr = recend;
971 
972 			if (ssl->msg.head == NULL) {
973 				ssl->msg.head = mp;
974 				ssl->msg.tail = mp;
975 				return (KSSL_CMD_NONE);
976 			} else {
977 				ssl->msg.tail->b_cont = mp;
978 				ssl->msg.tail = mp;
979 				return (KSSL_CMD_NONE);
980 			}
981 		} while (kssl_handle_handshake_message(ssl, mp, &error, cbfn,
982 		    arg));
983 		if (error == SSL_MISS) {
984 			mp->b_rptr = save_rptr;
985 			mp->b_wptr = save_wptr;
986 			KSSL_COUNTER(fallback_connections, 1);
987 			return (KSSL_CMD_NOT_SUPPORTED);
988 		}
989 		if (ssl->hs_waitstate == wait_client_key_done) {
990 			return (KSSL_CMD_QUEUED);
991 		} else {
992 			return (KSSL_CMD_NONE);
993 		}
994 	case content_alert:
995 		if (rec_sz != 2) {
996 			mp->b_rptr = real_recend;
997 			desc = illegal_parameter;
998 			goto sendalert;
999 		} else {
1000 			level = *mp->b_rptr++;
1001 			desc = *mp->b_rptr++;
1002 			mp->b_rptr = real_recend;
1003 			if (level != alert_warning || desc != close_notify) {
1004 				if (ssl->sid.cached == B_TRUE) {
1005 					kssl_uncache_sid(&ssl->sid,
1006 					    ssl->kssl_entry);
1007 					ssl->sid.cached = B_FALSE;
1008 				}
1009 				ssl->fatal_alert = B_TRUE;
1010 				error = EBADMSG;
1011 				goto error;
1012 			} else {
1013 				ssl->close_notify = B_TRUE;
1014 				ssl->activeinput = B_FALSE;
1015 				freeb(mp);
1016 				return (KSSL_CMD_NONE);
1017 			}
1018 		}
1019 	case content_change_cipher_spec:
1020 		if (ssl->hs_waitstate != wait_change_cipher) {
1021 			desc = unexpected_message;
1022 		} else if (rec_sz != 1 || *mp->b_rptr != 1) {
1023 			desc = illegal_parameter;
1024 		} else {
1025 			mp->b_rptr = real_recend;
1026 			ssl->hs_waitstate = wait_finished;
1027 			ssl->seq_num[KSSL_READ] = 0;
1028 			if ((error = kssl_spec_init(ssl, KSSL_READ)) != 0) {
1029 #ifdef	DEBUG
1030 				cmn_err(CE_WARN,
1031 					"kssl_spec_init returned error "
1032 					"0x%02X", error);
1033 #endif	/* DEBUG */
1034 				goto error;
1035 			}
1036 			ssl->activeinput = B_FALSE;
1037 			freeb(mp);
1038 			return (KSSL_CMD_NONE);
1039 		}
1040 		mp->b_rptr = real_recend;
1041 		goto sendalert;
1042 
1043 	case content_application_data:
1044 		if (ssl->hs_waitstate != idle_handshake) {
1045 			mp->b_rptr = real_recend;
1046 			desc = unexpected_message;
1047 			goto sendalert;
1048 		}
1049 		mp->b_wptr = recend;
1050 		*decrmp = mp;
1051 		ssl->activeinput = B_FALSE;
1052 		return (KSSL_CMD_DELIVER_PROXY);
1053 
1054 	case content_handshake_v2:
1055 		error = kssl_handle_v2client_hello(ssl, mp, rec_sz);
1056 		if (error == SSL_MISS) {
1057 			mp->b_rptr = save_rptr;
1058 			mp->b_wptr = save_wptr;
1059 			KSSL_COUNTER(fallback_connections, 1);
1060 			return (KSSL_CMD_NOT_SUPPORTED);
1061 		} else if (error != 0) {
1062 			goto error;
1063 		}
1064 		freeb(mp);
1065 		return (KSSL_CMD_SEND);
1066 	default:
1067 		mp->b_rptr = real_recend;
1068 		desc = unexpected_message;
1069 		break;
1070 	}
1071 
1072 sendalert:
1073 	kssl_send_alert(ssl, alert_fatal, desc);
1074 	*decrmp = ssl->alert_sendbuf;
1075 	ssl->alert_sendbuf = NULL;
1076 	freeb(mp);
1077 	return ((*decrmp != NULL) ? KSSL_CMD_SEND : KSSL_CMD_NONE);
1078 error:
1079 	freeb(mp);
1080 	return (KSSL_CMD_NONE);
1081 }
1082 
1083 /*
1084  * Initialize the context of an SSL connection, coming to the specified
1085  * address.
1086  * the ssl structure returned is held.
1087  */
1088 kssl_status_t
1089 kssl_init_context(kssl_ent_t kssl_ent, ipaddr_t faddr, int mss,
1090     kssl_ctx_t *kssl_ctxp)
1091 {
1092 	ssl_t *ssl = kmem_cache_alloc(kssl_cache, KM_NOSLEEP);
1093 
1094 	if (ssl == NULL) {
1095 		return (KSSL_STS_ERR);
1096 	}
1097 
1098 	kssl_cache_count++;
1099 
1100 	bzero(ssl, sizeof (ssl_t));
1101 
1102 	ssl->kssl_entry = (kssl_entry_t *)kssl_ent;
1103 	KSSL_ENTRY_REFHOLD(ssl->kssl_entry);
1104 
1105 	ssl->faddr = faddr;
1106 	ssl->tcp_mss = mss;
1107 	ssl->sendalert_level = alert_warning;
1108 	ssl->sendalert_desc = close_notify;
1109 	ssl->sid.cached = B_FALSE;
1110 
1111 	*kssl_ctxp = (kssl_ctx_t)ssl;
1112 	KSSL_SSL_REFHOLD(ssl);
1113 	return (KSSL_STS_OK);
1114 }
1115 
1116 /*
1117  * Builds SSL records out of the chain of mblks, and returns it.
1118  * Taked a copy of the message before encypting it if it has another
1119  * reference.
1120  * In case of failure, NULL is returned, and the message will be
1121  * freed by the caller.
1122  * A NULL mp means a close_notify is requested.
1123  */
1124 mblk_t *
1125 kssl_build_record(kssl_ctx_t ctx, mblk_t *mp)
1126 {
1127 	ssl_t *ssl = (ssl_t *)ctx;
1128 	mblk_t *retmp = mp, *bp = mp, *prevbp = mp, *copybp;
1129 
1130 	ASSERT(ssl != NULL);
1131 	ASSERT(mp != NULL);
1132 
1133 	do {
1134 		if (DB_REF(bp) > 1) {
1135 			/*
1136 			 * Fortunately copyb() preserves the offset,
1137 			 * tail space and alignement so the copy is
1138 			 * ready to be made an SSL record.
1139 			 */
1140 			if ((copybp = copyb(bp)) == NULL)
1141 				return (NULL);
1142 
1143 			copybp->b_cont = bp->b_cont;
1144 			if (bp == mp) {
1145 				retmp = copybp;
1146 			} else {
1147 				prevbp->b_cont = copybp;
1148 			}
1149 			freeb(bp);
1150 			bp = copybp;
1151 		}
1152 
1153 		if (kssl_build_single_record(ssl, bp) != KSSL_STS_OK)
1154 			return (NULL);
1155 
1156 		prevbp = bp;
1157 		bp = bp->b_cont;
1158 	} while (bp != NULL);
1159 
1160 	return (retmp);
1161 }
1162 
1163 /*
1164  * Builds a single SSL record
1165  * In-line encryption of the record.
1166  */
1167 static kssl_status_t
1168 kssl_build_single_record(ssl_t *ssl, mblk_t *mp)
1169 {
1170 	int len;
1171 	int reclen = 0;
1172 	uchar_t *recstart, *versionp;
1173 	KSSLCipherSpec *spec;
1174 	int mac_sz;
1175 	int pad_sz = 0;
1176 
1177 
1178 	spec = &ssl->spec[KSSL_WRITE];
1179 	mac_sz = spec->mac_hashsz;
1180 
1181 
1182 	ASSERT(DB_REF(mp) == 1);
1183 	ASSERT((mp->b_rptr - mp->b_datap->db_base >= SSL3_HDR_LEN) &&
1184 	    (mp->b_datap->db_lim - mp->b_wptr >= mac_sz + spec->cipher_bsize));
1185 
1186 	len = MBLKL(mp);
1187 
1188 	ASSERT(len > 0);
1189 
1190 	mutex_enter(&ssl->kssl_lock);
1191 
1192 	recstart = mp->b_rptr = mp->b_rptr - SSL3_HDR_LEN;
1193 	recstart[0] = content_application_data;
1194 	recstart[1] = ssl->major_version;
1195 	recstart[2] = ssl->minor_version;
1196 	versionp = &recstart[1];
1197 
1198 	reclen = len + mac_sz;
1199 	if (spec->cipher_type == type_block) {
1200 		pad_sz = spec->cipher_bsize -
1201 		    (reclen & (spec->cipher_bsize - 1));
1202 		ASSERT(reclen + pad_sz <=
1203 		    SSL3_MAX_RECORD_LENGTH);
1204 		reclen += pad_sz;
1205 	}
1206 	recstart[3] = (reclen >> 8) & 0xff;
1207 	recstart[4] = reclen & 0xff;
1208 
1209 	if (kssl_mac_encrypt_record(ssl, content_application_data, versionp,
1210 	    recstart, mp) != 0) {
1211 		/* Do we need an internal_error Alert here? */
1212 		mutex_exit(&ssl->kssl_lock);
1213 		return (KSSL_STS_ERR);
1214 	}
1215 
1216 	KSSL_COUNTER(appdata_record_outs, 1);
1217 	mutex_exit(&ssl->kssl_lock);
1218 	return (KSSL_STS_OK);
1219 }
1220