Merge commit '7e934d3acc051b7ee3ef0d11571fd1225800a607'
[unleashed.git] / kernel / net / ip / ipsecesp.c
blobb0a3e2b0632d375cbc7d78b04d0214629bf344f5
1 /*
2 * CDDL HEADER START
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.
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.
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]
19 * CDDL HEADER END
22 * Copyright 2010 Sun Microsystems, Inc. All rights reserved.
23 * Use is subject to license terms.
24 * Copyright (c) 2012 Nexenta Systems, Inc. All rights reserved.
25 * Copyright (c) 2017 Joyent, Inc.
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/stropts.h>
31 #include <sys/errno.h>
32 #include <sys/strlog.h>
33 #include <sys/tihdr.h>
34 #include <sys/socket.h>
35 #include <sys/ddi.h>
36 #include <sys/sunddi.h>
37 #include <sys/kmem.h>
38 #include <sys/zone.h>
39 #include <sys/sysmacros.h>
40 #include <sys/cmn_err.h>
41 #include <sys/vtrace.h>
42 #include <sys/debug.h>
43 #include <sys/atomic.h>
44 #include <sys/strsun.h>
45 #include <sys/random.h>
46 #include <netinet/in.h>
47 #include <net/if.h>
48 #include <netinet/ip6.h>
49 #include <net/pfkeyv2.h>
50 #include <net/pfpolicy.h>
52 #include <inet/common.h>
53 #include <inet/mi.h>
54 #include <inet/nd.h>
55 #include <inet/ip.h>
56 #include <inet/ip_impl.h>
57 #include <inet/ip6.h>
58 #include <inet/ip_if.h>
59 #include <inet/ip_ndp.h>
60 #include <inet/sadb.h>
61 #include <inet/ipsec_info.h>
62 #include <inet/ipsec_impl.h>
63 #include <inet/ipsecesp.h>
64 #include <inet/ipdrop.h>
65 #include <inet/tcp.h>
66 #include <sys/kstat.h>
67 #include <sys/policy.h>
68 #include <sys/strsun.h>
69 #include <sys/strsubr.h>
70 #include <inet/udp_impl.h>
71 #include <sys/taskq.h>
72 #include <sys/note.h>
75 * Table of ND variables supported by ipsecesp. These are loaded into
76 * ipsecesp_g_nd in ipsecesp_init_nd.
77 * All of these are alterable, within the min/max values given, at run time.
79 static ipsecespparam_t lcl_param_arr[] = {
80 /* min max value name */
81 { 0, 3, 0, "ipsecesp_debug"},
82 { 125, 32000, SADB_AGE_INTERVAL_DEFAULT, "ipsecesp_age_interval"},
83 { 1, 10, 1, "ipsecesp_reap_delay"},
84 { 1, SADB_MAX_REPLAY, 64, "ipsecesp_replay_size"},
85 { 1, 300, 15, "ipsecesp_acquire_timeout"},
86 { 1, 1800, 90, "ipsecesp_larval_timeout"},
87 /* Default lifetime values for ACQUIRE messages. */
88 { 0, 0xffffffffU, 0, "ipsecesp_default_soft_bytes"},
89 { 0, 0xffffffffU, 0, "ipsecesp_default_hard_bytes"},
90 { 0, 0xffffffffU, 24000, "ipsecesp_default_soft_addtime"},
91 { 0, 0xffffffffU, 28800, "ipsecesp_default_hard_addtime"},
92 { 0, 0xffffffffU, 0, "ipsecesp_default_soft_usetime"},
93 { 0, 0xffffffffU, 0, "ipsecesp_default_hard_usetime"},
94 { 0, 1, 0, "ipsecesp_log_unknown_spi"},
95 { 0, 2, 1, "ipsecesp_padding_check"},
96 { 0, 600, 20, "ipsecesp_nat_keepalive_interval"},
98 /* For ipsecesp_nat_keepalive_interval, see ipsecesp.h. */
100 #define esp0dbg(a) printf a
101 /* NOTE: != 0 instead of > 0 so lint doesn't complain. */
102 #define esp1dbg(espstack, a) if (espstack->ipsecesp_debug != 0) printf a
103 #define esp2dbg(espstack, a) if (espstack->ipsecesp_debug > 1) printf a
104 #define esp3dbg(espstack, a) if (espstack->ipsecesp_debug > 2) printf a
106 static int ipsecesp_open(queue_t *, dev_t *, int, int, cred_t *);
107 static int ipsecesp_close(queue_t *);
108 static void ipsecesp_wput(queue_t *, mblk_t *);
109 static void *ipsecesp_stack_init(netstackid_t stackid, netstack_t *ns);
110 static void ipsecesp_stack_fini(netstackid_t stackid, void *arg);
112 static void esp_prepare_udp(netstack_t *, mblk_t *, ipha_t *);
113 static void esp_outbound_finish(mblk_t *, ip_xmit_attr_t *);
114 static void esp_inbound_restart(mblk_t *, ip_recv_attr_t *);
116 static boolean_t esp_register_out(uint32_t, uint32_t, uint_t,
117 ipsecesp_stack_t *, cred_t *);
118 static boolean_t esp_strip_header(mblk_t *, boolean_t, uint32_t,
119 kstat_named_t **, ipsecesp_stack_t *);
120 static mblk_t *esp_submit_req_inbound(mblk_t *, ip_recv_attr_t *,
121 ipsa_t *, uint_t);
122 static mblk_t *esp_submit_req_outbound(mblk_t *, ip_xmit_attr_t *,
123 ipsa_t *, uchar_t *, uint_t);
125 /* Setable in /etc/system */
126 uint32_t esp_hash_size = IPSEC_DEFAULT_HASH_SIZE;
128 static struct module_info info = {
129 5137, "ipsecesp", 0, INFPSZ, 65536, 1024
132 static struct qinit rinit = {
133 (pfi_t)putnext, NULL, ipsecesp_open, ipsecesp_close, NULL, &info,
134 NULL
137 static struct qinit winit = {
138 (pfi_t)ipsecesp_wput, NULL, ipsecesp_open, ipsecesp_close, NULL, &info,
139 NULL
142 struct streamtab ipsecespinfo = {
143 &rinit, &winit, NULL, NULL
146 static taskq_t *esp_taskq;
149 * OTOH, this one is set at open/close, and I'm D_MTQPAIR for now.
151 * Question: Do I need this, given that all instance's esps->esps_wq point
152 * to IP?
154 * Answer: Yes, because I need to know which queue is BOUND to
155 * IPPROTO_ESP
158 static int esp_kstat_update(kstat_t *, int);
160 static boolean_t
161 esp_kstat_init(ipsecesp_stack_t *espstack, netstackid_t stackid)
163 espstack->esp_ksp = kstat_create_netstack("ipsecesp", 0, "esp_stat",
164 "net", KSTAT_TYPE_NAMED,
165 sizeof (esp_kstats_t) / sizeof (kstat_named_t), 0, stackid);
167 if (espstack->esp_ksp == NULL || espstack->esp_ksp->ks_data == NULL)
168 return (B_FALSE);
170 espstack->esp_kstats = espstack->esp_ksp->ks_data;
172 espstack->esp_ksp->ks_update = esp_kstat_update;
173 espstack->esp_ksp->ks_private = (void *)(uintptr_t)stackid;
175 #define K64 KSTAT_DATA_UINT64
176 #define KI(x) kstat_named_init(&(espstack->esp_kstats->esp_stat_##x), #x, K64)
178 KI(num_aalgs);
179 KI(num_ealgs);
180 KI(good_auth);
181 KI(bad_auth);
182 KI(bad_padding);
183 KI(replay_failures);
184 KI(replay_early_failures);
185 KI(keysock_in);
186 KI(out_requests);
187 KI(acquire_requests);
188 KI(bytes_expired);
189 KI(out_discards);
190 KI(crypto_sync);
191 KI(crypto_async);
192 KI(crypto_failures);
193 KI(bad_decrypt);
194 KI(sa_port_renumbers);
196 #undef KI
197 #undef K64
199 kstat_install(espstack->esp_ksp);
201 return (B_TRUE);
204 static int
205 esp_kstat_update(kstat_t *kp, int rw)
207 esp_kstats_t *ekp;
208 netstackid_t stackid = (zoneid_t)(uintptr_t)kp->ks_private;
209 netstack_t *ns;
210 ipsec_stack_t *ipss;
212 if ((kp == NULL) || (kp->ks_data == NULL))
213 return (EIO);
215 if (rw == KSTAT_WRITE)
216 return (EACCES);
218 ns = netstack_find_by_stackid(stackid);
219 if (ns == NULL)
220 return (-1);
221 ipss = ns->netstack_ipsec;
222 if (ipss == NULL) {
223 netstack_rele(ns);
224 return (-1);
226 ekp = (esp_kstats_t *)kp->ks_data;
228 rw_enter(&ipss->ipsec_alg_lock, RW_READER);
229 ekp->esp_stat_num_aalgs.value.ui64 =
230 ipss->ipsec_nalgs[IPSEC_ALG_AUTH];
231 ekp->esp_stat_num_ealgs.value.ui64 =
232 ipss->ipsec_nalgs[IPSEC_ALG_ENCR];
233 rw_exit(&ipss->ipsec_alg_lock);
235 netstack_rele(ns);
236 return (0);
239 #ifdef DEBUG
241 * Debug routine, useful to see pre-encryption data.
243 static char *
244 dump_msg(mblk_t *mp)
246 char tmp_str[3], tmp_line[256];
248 while (mp != NULL) {
249 unsigned char *ptr;
251 printf("mblk address 0x%p, length %ld, db_ref %d "
252 "type %d, base 0x%p, lim 0x%p\n",
253 (void *) mp, (long)(mp->b_wptr - mp->b_rptr),
254 mp->b_datap->db_ref, mp->b_datap->db_type,
255 (void *)mp->b_datap->db_base, (void *)mp->b_datap->db_lim);
256 ptr = mp->b_rptr;
258 tmp_line[0] = '\0';
259 while (ptr < mp->b_wptr) {
260 uint_t diff;
262 diff = (ptr - mp->b_rptr);
263 if (!(diff & 0x1f)) {
264 if (strlen(tmp_line) > 0) {
265 printf("bytes: %s\n", tmp_line);
266 tmp_line[0] = '\0';
269 if (!(diff & 0x3))
270 (void) strcat(tmp_line, " ");
271 (void) sprintf(tmp_str, "%02x", *ptr);
272 (void) strcat(tmp_line, tmp_str);
273 ptr++;
275 if (strlen(tmp_line) > 0)
276 printf("bytes: %s\n", tmp_line);
278 mp = mp->b_cont;
281 return ("\n");
284 #else /* DEBUG */
285 static char *
286 dump_msg(mblk_t *mp)
288 printf("Find value of mp %p.\n", mp);
289 return ("\n");
291 #endif /* DEBUG */
294 * Don't have to lock age_interval, as only one thread will access it at
295 * a time, because I control the one function that does with timeout().
297 static void
298 esp_ager(void *arg)
300 ipsecesp_stack_t *espstack = (ipsecesp_stack_t *)arg;
301 netstack_t *ns = espstack->ipsecesp_netstack;
302 hrtime_t begin = gethrtime();
304 sadb_ager(&espstack->esp_sadb.s_v4, espstack->esp_pfkey_q,
305 espstack->ipsecesp_reap_delay, ns);
306 sadb_ager(&espstack->esp_sadb.s_v6, espstack->esp_pfkey_q,
307 espstack->ipsecesp_reap_delay, ns);
309 espstack->esp_event = sadb_retimeout(begin, espstack->esp_pfkey_q,
310 esp_ager, espstack,
311 &espstack->ipsecesp_age_interval, espstack->ipsecesp_age_int_max,
312 info.mi_idnum);
316 * Get an ESP NDD parameter.
318 /* ARGSUSED */
319 static int
320 ipsecesp_param_get(
321 queue_t *q,
322 mblk_t *mp,
323 caddr_t cp,
324 cred_t *cr)
326 ipsecespparam_t *ipsecesppa = (ipsecespparam_t *)cp;
327 uint_t value;
328 ipsecesp_stack_t *espstack = (ipsecesp_stack_t *)q->q_ptr;
330 mutex_enter(&espstack->ipsecesp_param_lock);
331 value = ipsecesppa->ipsecesp_param_value;
332 mutex_exit(&espstack->ipsecesp_param_lock);
334 (void) mi_mpprintf(mp, "%u", value);
335 return (0);
339 * This routine sets an NDD variable in a ipsecespparam_t structure.
341 /* ARGSUSED */
342 static int
343 ipsecesp_param_set(
344 queue_t *q,
345 mblk_t *mp,
346 char *value,
347 caddr_t cp,
348 cred_t *cr)
350 ulong_t new_value;
351 ipsecespparam_t *ipsecesppa = (ipsecespparam_t *)cp;
352 ipsecesp_stack_t *espstack = (ipsecesp_stack_t *)q->q_ptr;
355 * Fail the request if the new value does not lie within the
356 * required bounds.
358 if (ddi_strtoul(value, NULL, 10, &new_value) != 0 ||
359 new_value < ipsecesppa->ipsecesp_param_min ||
360 new_value > ipsecesppa->ipsecesp_param_max) {
361 return (EINVAL);
364 /* Set the new value */
365 mutex_enter(&espstack->ipsecesp_param_lock);
366 ipsecesppa->ipsecesp_param_value = new_value;
367 mutex_exit(&espstack->ipsecesp_param_lock);
368 return (0);
372 * Using lifetime NDD variables, fill in an extended combination's
373 * lifetime information.
375 void
376 ipsecesp_fill_defs(sadb_x_ecomb_t *ecomb, netstack_t *ns)
378 ipsecesp_stack_t *espstack = ns->netstack_ipsecesp;
380 ecomb->sadb_x_ecomb_soft_bytes = espstack->ipsecesp_default_soft_bytes;
381 ecomb->sadb_x_ecomb_hard_bytes = espstack->ipsecesp_default_hard_bytes;
382 ecomb->sadb_x_ecomb_soft_addtime =
383 espstack->ipsecesp_default_soft_addtime;
384 ecomb->sadb_x_ecomb_hard_addtime =
385 espstack->ipsecesp_default_hard_addtime;
386 ecomb->sadb_x_ecomb_soft_usetime =
387 espstack->ipsecesp_default_soft_usetime;
388 ecomb->sadb_x_ecomb_hard_usetime =
389 espstack->ipsecesp_default_hard_usetime;
393 * Initialize things for ESP at module load time.
395 boolean_t
396 ipsecesp_ddi_init(void)
398 esp_taskq = taskq_create("esp_taskq", 1, minclsyspri,
399 IPSEC_TASKQ_MIN, IPSEC_TASKQ_MAX, 0);
402 * We want to be informed each time a stack is created or
403 * destroyed in the kernel, so we can maintain the
404 * set of ipsecesp_stack_t's.
406 netstack_register(NS_IPSECESP, ipsecesp_stack_init, NULL,
407 ipsecesp_stack_fini);
409 return (B_TRUE);
413 * Walk through the param array specified registering each element with the
414 * named dispatch handler.
416 static boolean_t
417 ipsecesp_param_register(IDP *ndp, ipsecespparam_t *espp, int cnt)
419 for (; cnt-- > 0; espp++) {
420 if (espp->ipsecesp_param_name != NULL &&
421 espp->ipsecesp_param_name[0]) {
422 if (!nd_load(ndp,
423 espp->ipsecesp_param_name,
424 ipsecesp_param_get, ipsecesp_param_set,
425 (caddr_t)espp)) {
426 nd_free(ndp);
427 return (B_FALSE);
431 return (B_TRUE);
435 * Initialize things for ESP for each stack instance
437 static void *
438 ipsecesp_stack_init(netstackid_t stackid, netstack_t *ns)
440 ipsecesp_stack_t *espstack;
441 ipsecespparam_t *espp;
443 espstack = (ipsecesp_stack_t *)kmem_zalloc(sizeof (*espstack),
444 KM_SLEEP);
445 espstack->ipsecesp_netstack = ns;
447 espp = (ipsecespparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
448 espstack->ipsecesp_params = espp;
449 bcopy(lcl_param_arr, espp, sizeof (lcl_param_arr));
451 (void) ipsecesp_param_register(&espstack->ipsecesp_g_nd, espp,
452 A_CNT(lcl_param_arr));
454 (void) esp_kstat_init(espstack, stackid);
456 espstack->esp_sadb.s_acquire_timeout =
457 &espstack->ipsecesp_acquire_timeout;
458 sadbp_init("ESP", &espstack->esp_sadb, SADB_SATYPE_ESP, esp_hash_size,
459 espstack->ipsecesp_netstack);
461 mutex_init(&espstack->ipsecesp_param_lock, NULL, MUTEX_DEFAULT, 0);
463 ip_drop_register(&espstack->esp_dropper, "IPsec ESP");
464 return (espstack);
468 * Destroy things for ESP at module unload time.
470 void
471 ipsecesp_ddi_destroy(void)
473 netstack_unregister(NS_IPSECESP);
474 taskq_destroy(esp_taskq);
478 * Destroy things for ESP for one stack instance
480 static void
481 ipsecesp_stack_fini(netstackid_t stackid, void *arg)
483 ipsecesp_stack_t *espstack = (ipsecesp_stack_t *)arg;
485 if (espstack->esp_pfkey_q != NULL) {
486 (void) quntimeout(espstack->esp_pfkey_q, espstack->esp_event);
488 espstack->esp_sadb.s_acquire_timeout = NULL;
489 sadbp_destroy(&espstack->esp_sadb, espstack->ipsecesp_netstack);
490 ip_drop_unregister(&espstack->esp_dropper);
491 mutex_destroy(&espstack->ipsecesp_param_lock);
492 nd_free(&espstack->ipsecesp_g_nd);
494 kmem_free(espstack->ipsecesp_params, sizeof (lcl_param_arr));
495 espstack->ipsecesp_params = NULL;
496 kstat_delete_netstack(espstack->esp_ksp, stackid);
497 espstack->esp_ksp = NULL;
498 espstack->esp_kstats = NULL;
499 kmem_free(espstack, sizeof (*espstack));
503 * ESP module open routine, which is here for keysock plumbing.
504 * Keysock is pushed over {AH,ESP} which is an artifact from the Bad Old
505 * Days of export control, and fears that ESP would not be allowed
506 * to be shipped at all by default. Eventually, keysock should
507 * either access AH and ESP via modstubs or krtld dependencies, or
508 * perhaps be folded in with AH and ESP into a single IPsec/netsec
509 * module ("netsec" if PF_KEY provides more than AH/ESP keying tables).
511 /* ARGSUSED */
512 static int
513 ipsecesp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
515 netstack_t *ns;
516 ipsecesp_stack_t *espstack;
518 if (secpolicy_ip_config(credp, B_FALSE) != 0)
519 return (EPERM);
521 if (q->q_ptr != NULL)
522 return (0); /* Re-open of an already open instance. */
524 if (sflag != MODOPEN)
525 return (EINVAL);
527 ns = netstack_find_by_cred(credp);
528 ASSERT(ns != NULL);
529 espstack = ns->netstack_ipsecesp;
530 ASSERT(espstack != NULL);
532 q->q_ptr = espstack;
533 WR(q)->q_ptr = q->q_ptr;
535 qprocson(q);
536 return (0);
540 * ESP module close routine.
542 static int
543 ipsecesp_close(queue_t *q)
545 ipsecesp_stack_t *espstack = (ipsecesp_stack_t *)q->q_ptr;
548 * Clean up q_ptr, if needed.
550 qprocsoff(q);
552 /* Keysock queue check is safe, because of OCEXCL perimeter. */
554 if (q == espstack->esp_pfkey_q) {
555 esp1dbg(espstack,
556 ("ipsecesp_close: Ummm... keysock is closing ESP.\n"));
557 espstack->esp_pfkey_q = NULL;
558 /* Detach qtimeouts. */
559 (void) quntimeout(q, espstack->esp_event);
562 netstack_rele(espstack->ipsecesp_netstack);
563 return (0);
567 * Add a number of bytes to what the SA has protected so far. Return
568 * B_TRUE if the SA can still protect that many bytes.
570 * Caller must REFRELE the passed-in assoc. This function must REFRELE
571 * any obtained peer SA.
573 static boolean_t
574 esp_age_bytes(ipsa_t *assoc, uint64_t bytes, boolean_t inbound)
576 ipsa_t *inassoc, *outassoc;
577 isaf_t *bucket;
578 boolean_t inrc, outrc, isv6;
579 sadb_t *sp;
580 int outhash;
581 netstack_t *ns = assoc->ipsa_netstack;
582 ipsecesp_stack_t *espstack = ns->netstack_ipsecesp;
584 /* No peer? No problem! */
585 if (!assoc->ipsa_haspeer) {
586 return (sadb_age_bytes(espstack->esp_pfkey_q, assoc, bytes,
587 B_TRUE));
591 * Otherwise, we want to grab both the original assoc and its peer.
592 * There might be a race for this, but if it's a real race, two
593 * expire messages may occur. We limit this by only sending the
594 * expire message on one of the peers, we'll pick the inbound
595 * arbitrarily.
597 * If we need tight synchronization on the peer SA, then we need to
598 * reconsider.
601 /* Use address length to select IPv6/IPv4 */
602 isv6 = (assoc->ipsa_addrfam == AF_INET6);
603 sp = isv6 ? &espstack->esp_sadb.s_v6 : &espstack->esp_sadb.s_v4;
605 if (inbound) {
606 inassoc = assoc;
607 if (isv6) {
608 outhash = OUTBOUND_HASH_V6(sp, *((in6_addr_t *)
609 &inassoc->ipsa_dstaddr));
610 } else {
611 outhash = OUTBOUND_HASH_V4(sp, *((ipaddr_t *)
612 &inassoc->ipsa_dstaddr));
614 bucket = &sp->sdb_of[outhash];
615 mutex_enter(&bucket->isaf_lock);
616 outassoc = ipsec_getassocbyspi(bucket, inassoc->ipsa_spi,
617 inassoc->ipsa_srcaddr, inassoc->ipsa_dstaddr,
618 inassoc->ipsa_addrfam);
619 mutex_exit(&bucket->isaf_lock);
620 if (outassoc == NULL) {
621 /* Q: Do we wish to set haspeer == B_FALSE? */
622 esp0dbg(("esp_age_bytes: "
623 "can't find peer for inbound.\n"));
624 return (sadb_age_bytes(espstack->esp_pfkey_q, inassoc,
625 bytes, B_TRUE));
627 } else {
628 outassoc = assoc;
629 bucket = INBOUND_BUCKET(sp, outassoc->ipsa_spi);
630 mutex_enter(&bucket->isaf_lock);
631 inassoc = ipsec_getassocbyspi(bucket, outassoc->ipsa_spi,
632 outassoc->ipsa_srcaddr, outassoc->ipsa_dstaddr,
633 outassoc->ipsa_addrfam);
634 mutex_exit(&bucket->isaf_lock);
635 if (inassoc == NULL) {
636 /* Q: Do we wish to set haspeer == B_FALSE? */
637 esp0dbg(("esp_age_bytes: "
638 "can't find peer for outbound.\n"));
639 return (sadb_age_bytes(espstack->esp_pfkey_q, outassoc,
640 bytes, B_TRUE));
644 inrc = sadb_age_bytes(espstack->esp_pfkey_q, inassoc, bytes, B_TRUE);
645 outrc = sadb_age_bytes(espstack->esp_pfkey_q, outassoc, bytes, B_FALSE);
648 * REFRELE any peer SA.
650 * Because of the multi-line macro nature of IPSA_REFRELE, keep
651 * them in { }.
653 if (inbound) {
654 IPSA_REFRELE(outassoc);
655 } else {
656 IPSA_REFRELE(inassoc);
659 return (inrc && outrc);
663 * Do incoming NAT-T manipulations for packet.
664 * Returns NULL if the mblk chain is consumed.
666 static mblk_t *
667 esp_fix_natt_checksums(mblk_t *data_mp, ipsa_t *assoc)
669 ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
670 tcpha_t *tcpha;
671 udpha_t *udpha;
672 /* Initialize to our inbound cksum adjustment... */
673 uint32_t sum = assoc->ipsa_inbound_cksum;
675 switch (ipha->ipha_protocol) {
676 case IPPROTO_TCP:
677 tcpha = (tcpha_t *)(data_mp->b_rptr +
678 IPH_HDR_LENGTH(ipha));
680 #define DOWN_SUM(x) (x) = ((x) & 0xFFFF) + ((x) >> 16)
681 sum += ~ntohs(tcpha->tha_sum) & 0xFFFF;
682 DOWN_SUM(sum);
683 DOWN_SUM(sum);
684 tcpha->tha_sum = ~htons(sum);
685 break;
686 case IPPROTO_UDP:
687 udpha = (udpha_t *)(data_mp->b_rptr + IPH_HDR_LENGTH(ipha));
689 if (udpha->uha_checksum != 0) {
690 /* Adujst if the inbound one was not zero. */
691 sum += ~ntohs(udpha->uha_checksum) & 0xFFFF;
692 DOWN_SUM(sum);
693 DOWN_SUM(sum);
694 udpha->uha_checksum = ~htons(sum);
695 if (udpha->uha_checksum == 0)
696 udpha->uha_checksum = 0xFFFF;
698 #undef DOWN_SUM
699 break;
700 case IPPROTO_IP:
702 * This case is only an issue for self-encapsulated
703 * packets. So for now, fall through.
705 break;
707 return (data_mp);
712 * Strip ESP header, check padding, and fix IP header.
713 * Returns B_TRUE on success, B_FALSE if an error occured.
715 static boolean_t
716 esp_strip_header(mblk_t *data_mp, boolean_t isv4, uint32_t ivlen,
717 kstat_named_t **counter, ipsecesp_stack_t *espstack)
719 ipha_t *ipha;
720 ip6_t *ip6h;
721 uint_t divpoint;
722 mblk_t *scratch;
723 uint8_t nexthdr, padlen;
724 uint8_t lastpad;
725 ipsec_stack_t *ipss = espstack->ipsecesp_netstack->netstack_ipsec;
726 uint8_t *lastbyte;
729 * Strip ESP data and fix IP header.
731 * XXX In case the beginning of esp_inbound() changes to not do a
732 * pullup, this part of the code can remain unchanged.
734 if (isv4) {
735 ASSERT((data_mp->b_wptr - data_mp->b_rptr) >= sizeof (ipha_t));
736 ipha = (ipha_t *)data_mp->b_rptr;
737 ASSERT((data_mp->b_wptr - data_mp->b_rptr) >= sizeof (esph_t) +
738 IPH_HDR_LENGTH(ipha));
739 divpoint = IPH_HDR_LENGTH(ipha);
740 } else {
741 ASSERT((data_mp->b_wptr - data_mp->b_rptr) >= sizeof (ip6_t));
742 ip6h = (ip6_t *)data_mp->b_rptr;
743 divpoint = ip_hdr_length_v6(data_mp, ip6h);
746 scratch = data_mp;
747 while (scratch->b_cont != NULL)
748 scratch = scratch->b_cont;
750 ASSERT((scratch->b_wptr - scratch->b_rptr) >= 3);
753 * "Next header" and padding length are the last two bytes in the
754 * ESP-protected datagram, thus the explicit - 1 and - 2.
755 * lastpad is the last byte of the padding, which can be used for
756 * a quick check to see if the padding is correct.
758 lastbyte = scratch->b_wptr - 1;
759 nexthdr = *lastbyte--;
760 padlen = *lastbyte--;
762 if (isv4) {
763 /* Fix part of the IP header. */
764 ipha->ipha_protocol = nexthdr;
766 * Reality check the padlen. The explicit - 2 is for the
767 * padding length and the next-header bytes.
769 if (padlen >= ntohs(ipha->ipha_length) - sizeof (ipha_t) - 2 -
770 sizeof (esph_t) - ivlen) {
771 ESP_BUMP_STAT(espstack, bad_decrypt);
772 ipsec_rl_strlog(espstack->ipsecesp_netstack,
773 info.mi_idnum, 0, 0,
774 SL_ERROR | SL_WARN,
775 "Corrupt ESP packet (padlen too big).\n");
776 esp1dbg(espstack, ("padlen (%d) is greater than:\n",
777 padlen));
778 esp1dbg(espstack, ("pkt len(%d) - ip hdr - esp "
779 "hdr - ivlen(%d) = %d.\n",
780 ntohs(ipha->ipha_length), ivlen,
781 (int)(ntohs(ipha->ipha_length) - sizeof (ipha_t) -
782 2 - sizeof (esph_t) - ivlen)));
783 *counter = DROPPER(ipss, ipds_esp_bad_padlen);
784 return (B_FALSE);
788 * Fix the rest of the header. The explicit - 2 is for the
789 * padding length and the next-header bytes.
791 ipha->ipha_length = htons(ntohs(ipha->ipha_length) - padlen -
792 2 - sizeof (esph_t) - ivlen);
793 ipha->ipha_hdr_checksum = 0;
794 ipha->ipha_hdr_checksum = (uint16_t)ip_csum_hdr(ipha);
795 } else {
796 if (ip6h->ip6_nxt == IPPROTO_ESP) {
797 ip6h->ip6_nxt = nexthdr;
798 } else {
799 ip_pkt_t ipp;
801 bzero(&ipp, sizeof (ipp));
802 (void) ip_find_hdr_v6(data_mp, ip6h, &ipp, NULL);
803 if (ipp.ipp_dstopts != NULL) {
804 ipp.ipp_dstopts->ip6d_nxt = nexthdr;
805 } else if (ipp.ipp_rthdr != NULL) {
806 ipp.ipp_rthdr->ip6r_nxt = nexthdr;
807 } else if (ipp.ipp_hopopts != NULL) {
808 ipp.ipp_hopopts->ip6h_nxt = nexthdr;
809 } else {
810 /* Panic a DEBUG kernel. */
811 ASSERT(ipp.ipp_hopopts != NULL);
812 /* Otherwise, pretend it's IP + ESP. */
813 cmn_err(CE_WARN, "ESP IPv6 headers wrong.\n");
814 ip6h->ip6_nxt = nexthdr;
818 if (padlen >= ntohs(ip6h->ip6_plen) - 2 - sizeof (esph_t) -
819 ivlen) {
820 ESP_BUMP_STAT(espstack, bad_decrypt);
821 ipsec_rl_strlog(espstack->ipsecesp_netstack,
822 info.mi_idnum, 0, 0,
823 SL_ERROR | SL_WARN,
824 "Corrupt ESP packet (v6 padlen too big).\n");
825 esp1dbg(espstack, ("padlen (%d) is greater than:\n",
826 padlen));
827 esp1dbg(espstack,
828 ("pkt len(%u) - ip hdr - esp hdr - ivlen(%d) = "
829 "%u.\n", (unsigned)(ntohs(ip6h->ip6_plen)
830 + sizeof (ip6_t)), ivlen,
831 (unsigned)(ntohs(ip6h->ip6_plen) - 2 -
832 sizeof (esph_t) - ivlen)));
833 *counter = DROPPER(ipss, ipds_esp_bad_padlen);
834 return (B_FALSE);
839 * Fix the rest of the header. The explicit - 2 is for the
840 * padding length and the next-header bytes. IPv6 is nice,
841 * because there's no hdr checksum!
843 ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) - padlen -
844 2 - sizeof (esph_t) - ivlen);
847 if (espstack->ipsecesp_padding_check > 0 && padlen > 0) {
849 * Weak padding check: compare last-byte to length, they
850 * should be equal.
852 lastpad = *lastbyte--;
854 if (padlen != lastpad) {
855 ipsec_rl_strlog(espstack->ipsecesp_netstack,
856 info.mi_idnum, 0, 0, SL_ERROR | SL_WARN,
857 "Corrupt ESP packet (lastpad != padlen).\n");
858 esp1dbg(espstack,
859 ("lastpad (%d) not equal to padlen (%d):\n",
860 lastpad, padlen));
861 ESP_BUMP_STAT(espstack, bad_padding);
862 *counter = DROPPER(ipss, ipds_esp_bad_padding);
863 return (B_FALSE);
867 * Strong padding check: Check all pad bytes to see that
868 * they're ascending. Go backwards using a descending counter
869 * to verify. padlen == 1 is checked by previous block, so
870 * only bother if we've more than 1 byte of padding.
871 * Consequently, start the check one byte before the location
872 * of "lastpad".
874 if (espstack->ipsecesp_padding_check > 1) {
876 * This assert may have to become an if and a pullup
877 * if we start accepting multi-dblk mblks. For now,
878 * though, any packet here will have been pulled up in
879 * esp_inbound.
881 ASSERT(MBLKL(scratch) >= lastpad + 3);
884 * Use "--lastpad" because we already checked the very
885 * last pad byte previously.
887 while (--lastpad != 0) {
888 if (lastpad != *lastbyte) {
889 ipsec_rl_strlog(
890 espstack->ipsecesp_netstack,
891 info.mi_idnum, 0, 0,
892 SL_ERROR | SL_WARN, "Corrupt ESP "
893 "packet (bad padding).\n");
894 esp1dbg(espstack,
895 ("padding not in correct"
896 " format:\n"));
897 ESP_BUMP_STAT(espstack, bad_padding);
898 *counter = DROPPER(ipss,
899 ipds_esp_bad_padding);
900 return (B_FALSE);
902 lastbyte--;
907 /* Trim off the padding. */
908 ASSERT(data_mp->b_cont == NULL);
909 data_mp->b_wptr -= (padlen + 2);
912 * Remove the ESP header.
914 * The above assertions about data_mp's size will make this work.
916 * XXX Question: If I send up and get back a contiguous mblk,
917 * would it be quicker to bcopy over, or keep doing the dupb stuff?
918 * I go with copying for now.
921 if (IS_P2ALIGNED(data_mp->b_rptr, sizeof (uint32_t)) &&
922 IS_P2ALIGNED(ivlen, sizeof (uint32_t))) {
923 uint8_t *start = data_mp->b_rptr;
924 uint32_t *src, *dst;
926 src = (uint32_t *)(start + divpoint);
927 dst = (uint32_t *)(start + divpoint + sizeof (esph_t) + ivlen);
929 ASSERT(IS_P2ALIGNED(dst, sizeof (uint32_t)) &&
930 IS_P2ALIGNED(src, sizeof (uint32_t)));
932 do {
933 src--;
934 dst--;
935 *dst = *src;
936 } while (src != (uint32_t *)start);
938 data_mp->b_rptr = (uchar_t *)dst;
939 } else {
940 uint8_t *start = data_mp->b_rptr;
941 uint8_t *src, *dst;
943 src = start + divpoint;
944 dst = src + sizeof (esph_t) + ivlen;
946 do {
947 src--;
948 dst--;
949 *dst = *src;
950 } while (src != start);
952 data_mp->b_rptr = dst;
955 esp2dbg(espstack, ("data_mp after inbound ESP adjustment:\n"));
956 esp2dbg(espstack, (dump_msg(data_mp)));
958 return (B_TRUE);
962 * Updating use times can be tricky business if the ipsa_haspeer flag is
963 * set. This function is called once in an SA's lifetime.
965 * Caller has to REFRELE "assoc" which is passed in. This function has
966 * to REFRELE any peer SA that is obtained.
968 static void
969 esp_set_usetime(ipsa_t *assoc, boolean_t inbound)
971 ipsa_t *inassoc, *outassoc;
972 isaf_t *bucket;
973 sadb_t *sp;
974 int outhash;
975 boolean_t isv6;
976 netstack_t *ns = assoc->ipsa_netstack;
977 ipsecesp_stack_t *espstack = ns->netstack_ipsecesp;
979 /* No peer? No problem! */
980 if (!assoc->ipsa_haspeer) {
981 sadb_set_usetime(assoc);
982 return;
986 * Otherwise, we want to grab both the original assoc and its peer.
987 * There might be a race for this, but if it's a real race, the times
988 * will be out-of-synch by at most a second, and since our time
989 * granularity is a second, this won't be a problem.
991 * If we need tight synchronization on the peer SA, then we need to
992 * reconsider.
995 /* Use address length to select IPv6/IPv4 */
996 isv6 = (assoc->ipsa_addrfam == AF_INET6);
997 sp = isv6 ? &espstack->esp_sadb.s_v6 : &espstack->esp_sadb.s_v4;
999 if (inbound) {
1000 inassoc = assoc;
1001 if (isv6) {
1002 outhash = OUTBOUND_HASH_V6(sp, *((in6_addr_t *)
1003 &inassoc->ipsa_dstaddr));
1004 } else {
1005 outhash = OUTBOUND_HASH_V4(sp, *((ipaddr_t *)
1006 &inassoc->ipsa_dstaddr));
1008 bucket = &sp->sdb_of[outhash];
1009 mutex_enter(&bucket->isaf_lock);
1010 outassoc = ipsec_getassocbyspi(bucket, inassoc->ipsa_spi,
1011 inassoc->ipsa_srcaddr, inassoc->ipsa_dstaddr,
1012 inassoc->ipsa_addrfam);
1013 mutex_exit(&bucket->isaf_lock);
1014 if (outassoc == NULL) {
1015 /* Q: Do we wish to set haspeer == B_FALSE? */
1016 esp0dbg(("esp_set_usetime: "
1017 "can't find peer for inbound.\n"));
1018 sadb_set_usetime(inassoc);
1019 return;
1021 } else {
1022 outassoc = assoc;
1023 bucket = INBOUND_BUCKET(sp, outassoc->ipsa_spi);
1024 mutex_enter(&bucket->isaf_lock);
1025 inassoc = ipsec_getassocbyspi(bucket, outassoc->ipsa_spi,
1026 outassoc->ipsa_srcaddr, outassoc->ipsa_dstaddr,
1027 outassoc->ipsa_addrfam);
1028 mutex_exit(&bucket->isaf_lock);
1029 if (inassoc == NULL) {
1030 /* Q: Do we wish to set haspeer == B_FALSE? */
1031 esp0dbg(("esp_set_usetime: "
1032 "can't find peer for outbound.\n"));
1033 sadb_set_usetime(outassoc);
1034 return;
1038 /* Update usetime on both. */
1039 sadb_set_usetime(inassoc);
1040 sadb_set_usetime(outassoc);
1043 * REFRELE any peer SA.
1045 * Because of the multi-line macro nature of IPSA_REFRELE, keep
1046 * them in { }.
1048 if (inbound) {
1049 IPSA_REFRELE(outassoc);
1050 } else {
1051 IPSA_REFRELE(inassoc);
1056 * Handle ESP inbound data for IPv4 and IPv6.
1057 * On success returns B_TRUE, on failure returns B_FALSE and frees the
1058 * mblk chain data_mp.
1060 mblk_t *
1061 esp_inbound(mblk_t *data_mp, void *arg, ip_recv_attr_t *ira)
1063 esph_t *esph = (esph_t *)arg;
1064 ipsa_t *ipsa = ira->ira_ipsec_esp_sa;
1065 netstack_t *ns = ira->ira_ill->ill_ipst->ips_netstack;
1066 ipsecesp_stack_t *espstack = ns->netstack_ipsecesp;
1067 ipsec_stack_t *ipss = ns->netstack_ipsec;
1070 * We may wish to check replay in-range-only here as an optimization.
1071 * Include the reality check of ipsa->ipsa_replay >
1072 * ipsa->ipsa_replay_wsize for times when it's the first N packets,
1073 * where N == ipsa->ipsa_replay_wsize.
1075 * Another check that may come here later is the "collision" check.
1076 * If legitimate packets flow quickly enough, this won't be a problem,
1077 * but collisions may cause authentication algorithm crunching to
1078 * take place when it doesn't need to.
1080 if (!sadb_replay_peek(ipsa, esph->esph_replay)) {
1081 ESP_BUMP_STAT(espstack, replay_early_failures);
1082 IP_ESP_BUMP_STAT(ipss, in_discards);
1083 ip_drop_packet(data_mp, B_TRUE, ira->ira_ill,
1084 DROPPER(ipss, ipds_esp_early_replay),
1085 &espstack->esp_dropper);
1086 BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
1087 return (NULL);
1091 * Adjust the IP header's payload length to reflect the removal
1092 * of the ICV.
1094 if (!(ira->ira_flags & IRAF_IS_IPV4)) {
1095 ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
1096 ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
1097 ipsa->ipsa_mac_len);
1098 } else {
1099 ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
1100 ipha->ipha_length = htons(ntohs(ipha->ipha_length) -
1101 ipsa->ipsa_mac_len);
1104 /* submit the request to the crypto framework */
1105 return (esp_submit_req_inbound(data_mp, ira, ipsa,
1106 (uint8_t *)esph - data_mp->b_rptr));
1109 /* XXX refactor me */
1111 * Handle the SADB_GETSPI message. Create a larval SA.
1113 static void
1114 esp_getspi(mblk_t *mp, keysock_in_t *ksi, ipsecesp_stack_t *espstack)
1116 ipsa_t *newbie, *target;
1117 isaf_t *outbound, *inbound;
1118 int rc, diagnostic;
1119 sadb_sa_t *assoc;
1120 keysock_out_t *kso;
1121 uint32_t newspi;
1124 * Randomly generate a proposed SPI value
1126 (void) random_get_pseudo_bytes((uint8_t *)&newspi, sizeof (uint32_t));
1128 newbie = sadb_getspi(ksi, newspi, &diagnostic,
1129 espstack->ipsecesp_netstack);
1130 if (newbie == NULL) {
1131 sadb_pfkey_error(espstack->esp_pfkey_q, mp, ENOMEM, diagnostic,
1132 ksi->ks_in_serial);
1133 return;
1134 } else if (newbie == (ipsa_t *)-1) {
1135 sadb_pfkey_error(espstack->esp_pfkey_q, mp, EINVAL, diagnostic,
1136 ksi->ks_in_serial);
1137 return;
1141 * XXX - We may randomly collide. We really should recover from this.
1142 * Unfortunately, that could require spending way-too-much-time
1143 * in here. For now, let the user retry.
1146 if (newbie->ipsa_addrfam == AF_INET6) {
1147 outbound = OUTBOUND_BUCKET_V6(&espstack->esp_sadb.s_v6,
1148 *(uint32_t *)(newbie->ipsa_dstaddr));
1149 inbound = INBOUND_BUCKET(&espstack->esp_sadb.s_v6,
1150 newbie->ipsa_spi);
1151 } else {
1152 ASSERT(newbie->ipsa_addrfam == AF_INET);
1153 outbound = OUTBOUND_BUCKET_V4(&espstack->esp_sadb.s_v4,
1154 *(uint32_t *)(newbie->ipsa_dstaddr));
1155 inbound = INBOUND_BUCKET(&espstack->esp_sadb.s_v4,
1156 newbie->ipsa_spi);
1159 mutex_enter(&outbound->isaf_lock);
1160 mutex_enter(&inbound->isaf_lock);
1163 * Check for collisions (i.e. did sadb_getspi() return with something
1164 * that already exists?).
1166 * Try outbound first. Even though SADB_GETSPI is traditionally
1167 * for inbound SAs, you never know what a user might do.
1169 target = ipsec_getassocbyspi(outbound, newbie->ipsa_spi,
1170 newbie->ipsa_srcaddr, newbie->ipsa_dstaddr, newbie->ipsa_addrfam);
1171 if (target == NULL) {
1172 target = ipsec_getassocbyspi(inbound, newbie->ipsa_spi,
1173 newbie->ipsa_srcaddr, newbie->ipsa_dstaddr,
1174 newbie->ipsa_addrfam);
1178 * I don't have collisions elsewhere!
1179 * (Nor will I because I'm still holding inbound/outbound locks.)
1182 if (target != NULL) {
1183 rc = EEXIST;
1184 IPSA_REFRELE(target);
1185 } else {
1187 * sadb_insertassoc() also checks for collisions, so
1188 * if there's a colliding entry, rc will be set
1189 * to EEXIST.
1191 rc = sadb_insertassoc(newbie, inbound);
1192 newbie->ipsa_hardexpiretime = gethrestime_sec();
1193 newbie->ipsa_hardexpiretime +=
1194 espstack->ipsecesp_larval_timeout;
1198 * Can exit outbound mutex. Hold inbound until we're done
1199 * with newbie.
1201 mutex_exit(&outbound->isaf_lock);
1203 if (rc != 0) {
1204 mutex_exit(&inbound->isaf_lock);
1205 IPSA_REFRELE(newbie);
1206 sadb_pfkey_error(espstack->esp_pfkey_q, mp, rc,
1207 SADB_X_DIAGNOSTIC_NONE, ksi->ks_in_serial);
1208 return;
1212 /* Can write here because I'm still holding the bucket lock. */
1213 newbie->ipsa_type = SADB_SATYPE_ESP;
1216 * Construct successful return message. We have one thing going
1217 * for us in PF_KEY v2. That's the fact that
1218 * sizeof (sadb_spirange_t) == sizeof (sadb_sa_t)
1220 assoc = (sadb_sa_t *)ksi->ks_in_extv[SADB_EXT_SPIRANGE];
1221 assoc->sadb_sa_exttype = SADB_EXT_SA;
1222 assoc->sadb_sa_spi = newbie->ipsa_spi;
1223 *((uint64_t *)(&assoc->sadb_sa_replay)) = 0;
1224 mutex_exit(&inbound->isaf_lock);
1226 /* Convert KEYSOCK_IN to KEYSOCK_OUT. */
1227 kso = (keysock_out_t *)ksi;
1228 kso->ks_out_len = sizeof (*kso);
1229 kso->ks_out_serial = ksi->ks_in_serial;
1230 kso->ks_out_type = KEYSOCK_OUT;
1233 * Can safely putnext() to esp_pfkey_q, because this is a turnaround
1234 * from the esp_pfkey_q.
1236 putnext(espstack->esp_pfkey_q, mp);
1240 * Insert the ESP header into a packet. Duplicate an mblk, and insert a newly
1241 * allocated mblk with the ESP header in between the two.
1243 static boolean_t
1244 esp_insert_esp(mblk_t *mp, mblk_t *esp_mp, uint_t divpoint,
1245 ipsecesp_stack_t *espstack)
1247 mblk_t *split_mp = mp;
1248 uint_t wheretodiv = divpoint;
1250 while ((split_mp->b_wptr - split_mp->b_rptr) < wheretodiv) {
1251 wheretodiv -= (split_mp->b_wptr - split_mp->b_rptr);
1252 split_mp = split_mp->b_cont;
1253 ASSERT(split_mp != NULL);
1256 if (split_mp->b_wptr - split_mp->b_rptr != wheretodiv) {
1257 mblk_t *scratch;
1259 /* "scratch" is the 2nd half, split_mp is the first. */
1260 scratch = dupb(split_mp);
1261 if (scratch == NULL) {
1262 esp1dbg(espstack,
1263 ("esp_insert_esp: can't allocate scratch.\n"));
1264 return (B_FALSE);
1266 /* NOTE: dupb() doesn't set b_cont appropriately. */
1267 scratch->b_cont = split_mp->b_cont;
1268 scratch->b_rptr += wheretodiv;
1269 split_mp->b_wptr = split_mp->b_rptr + wheretodiv;
1270 split_mp->b_cont = scratch;
1273 * At this point, split_mp is exactly "wheretodiv" bytes long, and
1274 * holds the end of the pre-ESP part of the datagram.
1276 esp_mp->b_cont = split_mp->b_cont;
1277 split_mp->b_cont = esp_mp;
1279 return (B_TRUE);
1283 * Section 7 of RFC 3947 says:
1285 * 7. Recovering from the Expiring NAT Mappings
1287 * There are cases where NAT box decides to remove mappings that are still
1288 * alive (for example, when the keepalive interval is too long, or when the
1289 * NAT box is rebooted). To recover from this, ends that are NOT behind
1290 * NAT SHOULD use the last valid UDP encapsulated IKE or IPsec packet from
1291 * the other end to determine which IP and port addresses should be used.
1292 * The host behind dynamic NAT MUST NOT do this, as otherwise it opens a
1293 * DoS attack possibility because the IP address or port of the other host
1294 * will not change (it is not behind NAT).
1296 * Keepalives cannot be used for these purposes, as they are not
1297 * authenticated, but any IKE authenticated IKE packet or ESP packet can be
1298 * used to detect whether the IP address or the port has changed.
1300 * The following function will check an SA and its explicitly-set pair to see
1301 * if the NAT-T remote port matches the received packet (which must have
1302 * passed ESP authentication, see esp_in_done() for the caller context). If
1303 * there is a mismatch, the SAs are updated. It is not important if we race
1304 * with a transmitting thread, as if there is a transmitting thread, it will
1305 * merely emit a packet that will most-likely be dropped.
1307 * "ports" are ordered src,dst, and assoc is an inbound SA, where src should
1308 * match ipsa_remote_nat_port and dst should match ipsa_local_nat_port.
1310 #ifdef _LITTLE_ENDIAN
1311 #define FIRST_16(x) ((x) & 0xFFFF)
1312 #define NEXT_16(x) (((x) >> 16) & 0xFFFF)
1313 #else
1314 #define FIRST_16(x) (((x) >> 16) & 0xFFFF)
1315 #define NEXT_16(x) ((x) & 0xFFFF)
1316 #endif
1317 static void
1318 esp_port_freshness(uint32_t ports, ipsa_t *assoc)
1320 uint16_t remote = FIRST_16(ports);
1321 uint16_t local = NEXT_16(ports);
1322 ipsa_t *outbound_peer;
1323 isaf_t *bucket;
1324 ipsecesp_stack_t *espstack = assoc->ipsa_netstack->netstack_ipsecesp;
1326 /* We found a conn_t, therefore local != 0. */
1327 ASSERT(local != 0);
1328 /* Assume an IPv4 SA. */
1329 ASSERT(assoc->ipsa_addrfam == AF_INET);
1332 * On-the-wire rport == 0 means something's very wrong.
1333 * An unpaired SA is also useless to us.
1334 * If we are behind the NAT, don't bother.
1335 * A zero local NAT port defaults to 4500, so check that too.
1336 * And, of course, if the ports already match, we don't need to
1337 * bother.
1339 if (remote == 0 || assoc->ipsa_otherspi == 0 ||
1340 (assoc->ipsa_flags & IPSA_F_BEHIND_NAT) ||
1341 (assoc->ipsa_remote_nat_port == 0 &&
1342 remote == htons(IPPORT_IKE_NATT)) ||
1343 remote == assoc->ipsa_remote_nat_port)
1344 return;
1346 /* Try and snag the peer. NOTE: Assume IPv4 for now. */
1347 bucket = OUTBOUND_BUCKET_V4(&(espstack->esp_sadb.s_v4),
1348 assoc->ipsa_srcaddr[0]);
1349 mutex_enter(&bucket->isaf_lock);
1350 outbound_peer = ipsec_getassocbyspi(bucket, assoc->ipsa_otherspi,
1351 assoc->ipsa_dstaddr, assoc->ipsa_srcaddr, AF_INET);
1352 mutex_exit(&bucket->isaf_lock);
1354 /* We probably lost a race to a deleting or expiring thread. */
1355 if (outbound_peer == NULL)
1356 return;
1359 * Hold the mutexes for both SAs so we don't race another inbound
1360 * thread. A lock-entry order shouldn't matter, since all other
1361 * per-ipsa locks are individually held-then-released.
1363 * Luckily, this has nothing to do with the remote-NAT address,
1364 * so we don't have to re-scribble the cached-checksum differential.
1366 mutex_enter(&outbound_peer->ipsa_lock);
1367 mutex_enter(&assoc->ipsa_lock);
1368 outbound_peer->ipsa_remote_nat_port = assoc->ipsa_remote_nat_port =
1369 remote;
1370 mutex_exit(&assoc->ipsa_lock);
1371 mutex_exit(&outbound_peer->ipsa_lock);
1372 IPSA_REFRELE(outbound_peer);
1373 ESP_BUMP_STAT(espstack, sa_port_renumbers);
1376 * Finish processing of an inbound ESP packet after processing by the
1377 * crypto framework.
1378 * - Remove the ESP header.
1379 * - Send packet back to IP.
1380 * If authentication was performed on the packet, this function is called
1381 * only if the authentication succeeded.
1382 * On success returns B_TRUE, on failure returns B_FALSE and frees the
1383 * mblk chain data_mp.
1385 static mblk_t *
1386 esp_in_done(mblk_t *data_mp, ip_recv_attr_t *ira, ipsec_crypto_t *ic)
1388 ipsa_t *assoc;
1389 uint_t espstart;
1390 uint32_t ivlen = 0;
1391 uint_t processed_len;
1392 esph_t *esph;
1393 kstat_named_t *counter;
1394 boolean_t is_natt;
1395 netstack_t *ns = ira->ira_ill->ill_ipst->ips_netstack;
1396 ipsecesp_stack_t *espstack = ns->netstack_ipsecesp;
1397 ipsec_stack_t *ipss = ns->netstack_ipsec;
1399 assoc = ira->ira_ipsec_esp_sa;
1400 ASSERT(assoc != NULL);
1402 is_natt = ((assoc->ipsa_flags & IPSA_F_NATT) != 0);
1404 /* get the pointer to the ESP header */
1405 if (assoc->ipsa_encr_alg == SADB_EALG_NULL) {
1406 /* authentication-only ESP */
1407 espstart = ic->ic_crypto_data.cd_offset;
1408 processed_len = ic->ic_crypto_data.cd_length;
1409 } else {
1410 /* encryption present */
1411 ivlen = assoc->ipsa_iv_len;
1412 if (assoc->ipsa_auth_alg == SADB_AALG_NONE) {
1413 /* encryption-only ESP */
1414 espstart = ic->ic_crypto_data.cd_offset -
1415 sizeof (esph_t) - assoc->ipsa_iv_len;
1416 processed_len = ic->ic_crypto_data.cd_length +
1417 ivlen;
1418 } else {
1419 /* encryption with authentication */
1420 espstart = ic->ic_crypto_dual_data.dd_offset1;
1421 processed_len = ic->ic_crypto_dual_data.dd_len2 +
1422 ivlen;
1426 esph = (esph_t *)(data_mp->b_rptr + espstart);
1428 if (assoc->ipsa_auth_alg != IPSA_AALG_NONE ||
1429 (assoc->ipsa_flags & IPSA_F_COMBINED)) {
1431 * Authentication passed if we reach this point.
1432 * Packets with authentication will have the ICV
1433 * after the crypto data. Adjust b_wptr before
1434 * making padlen checks.
1436 ESP_BUMP_STAT(espstack, good_auth);
1437 data_mp->b_wptr -= assoc->ipsa_mac_len;
1440 * Check replay window here!
1441 * For right now, assume keysock will set the replay window
1442 * size to zero for SAs that have an unspecified sender.
1443 * This may change...
1446 if (!sadb_replay_check(assoc, esph->esph_replay)) {
1448 * Log the event. As of now we print out an event.
1449 * Do not print the replay failure number, or else
1450 * syslog cannot collate the error messages. Printing
1451 * the replay number that failed opens a denial-of-
1452 * service attack.
1454 ipsec_assocfailure(info.mi_idnum, 0, 0,
1455 SL_ERROR | SL_WARN,
1456 "Replay failed for ESP spi 0x%x, dst %s.\n",
1457 assoc->ipsa_spi, assoc->ipsa_dstaddr,
1458 assoc->ipsa_addrfam, espstack->ipsecesp_netstack);
1459 ESP_BUMP_STAT(espstack, replay_failures);
1460 counter = DROPPER(ipss, ipds_esp_replay);
1461 goto drop_and_bail;
1464 if (is_natt) {
1465 ASSERT(ira->ira_flags & IRAF_ESP_UDP_PORTS);
1466 ASSERT(ira->ira_esp_udp_ports != 0);
1467 esp_port_freshness(ira->ira_esp_udp_ports, assoc);
1471 esp_set_usetime(assoc, B_TRUE);
1473 if (!esp_age_bytes(assoc, processed_len, B_TRUE)) {
1474 /* The ipsa has hit hard expiration, LOG and AUDIT. */
1475 ipsec_assocfailure(info.mi_idnum, 0, 0,
1476 SL_ERROR | SL_WARN,
1477 "ESP association 0x%x, dst %s had bytes expire.\n",
1478 assoc->ipsa_spi, assoc->ipsa_dstaddr, assoc->ipsa_addrfam,
1479 espstack->ipsecesp_netstack);
1480 ESP_BUMP_STAT(espstack, bytes_expired);
1481 counter = DROPPER(ipss, ipds_esp_bytes_expire);
1482 goto drop_and_bail;
1486 * Remove ESP header and padding from packet. I hope the compiler
1487 * spews "branch, predict taken" code for this.
1490 if (esp_strip_header(data_mp, (ira->ira_flags & IRAF_IS_IPV4),
1491 ivlen, &counter, espstack)) {
1493 if (is_natt)
1494 return (esp_fix_natt_checksums(data_mp, assoc));
1496 if (assoc->ipsa_state == IPSA_STATE_IDLE) {
1498 * Cluster buffering case. Tell caller that we're
1499 * handling the packet.
1501 sadb_buf_pkt(assoc, data_mp, ira);
1502 return (NULL);
1505 return (data_mp);
1508 esp1dbg(espstack, ("esp_in_done: esp_strip_header() failed\n"));
1509 drop_and_bail:
1510 IP_ESP_BUMP_STAT(ipss, in_discards);
1511 ip_drop_packet(data_mp, B_TRUE, ira->ira_ill, counter,
1512 &espstack->esp_dropper);
1513 BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
1514 return (NULL);
1518 * Called upon failing the inbound ICV check. The message passed as
1519 * argument is freed.
1521 static void
1522 esp_log_bad_auth(mblk_t *mp, ip_recv_attr_t *ira)
1524 ipsa_t *assoc = ira->ira_ipsec_esp_sa;
1525 netstack_t *ns = ira->ira_ill->ill_ipst->ips_netstack;
1526 ipsecesp_stack_t *espstack = ns->netstack_ipsecesp;
1527 ipsec_stack_t *ipss = ns->netstack_ipsec;
1530 * Log the event. Don't print to the console, block
1531 * potential denial-of-service attack.
1533 ESP_BUMP_STAT(espstack, bad_auth);
1535 ipsec_assocfailure(info.mi_idnum, 0, 0, SL_ERROR | SL_WARN,
1536 "ESP Authentication failed for spi 0x%x, dst %s.\n",
1537 assoc->ipsa_spi, assoc->ipsa_dstaddr, assoc->ipsa_addrfam,
1538 espstack->ipsecesp_netstack);
1540 IP_ESP_BUMP_STAT(ipss, in_discards);
1541 ip_drop_packet(mp, B_TRUE, ira->ira_ill,
1542 DROPPER(ipss, ipds_esp_bad_auth),
1543 &espstack->esp_dropper);
1548 * Invoked for outbound packets after ESP processing. If the packet
1549 * also requires AH, performs the AH SA selection and AH processing.
1551 * Returns data_mp (possibly with AH added) unless data_mp was consumed
1552 * due to an error, or queued due to async. crypto or an ACQUIRE trigger.
1554 static mblk_t *
1555 esp_do_outbound_ah(mblk_t *data_mp, ip_xmit_attr_t *ixa)
1557 ipsec_action_t *ap;
1559 ap = ixa->ixa_ipsec_action;
1560 if (ap == NULL) {
1561 ipsec_policy_t *pp = ixa->ixa_ipsec_policy;
1562 ap = pp->ipsp_act;
1565 if (!ap->ipa_want_ah)
1566 return (data_mp);
1569 * Normally the AH SA would have already been put in place
1570 * but it could have been flushed so we need to look for it.
1572 if (ixa->ixa_ipsec_ah_sa == NULL) {
1573 if (!ipsec_outbound_sa(data_mp, ixa, IPPROTO_AH)) {
1574 sadb_acquire(data_mp, ixa, B_TRUE, B_FALSE);
1575 return (NULL);
1578 ASSERT(ixa->ixa_ipsec_ah_sa != NULL);
1580 data_mp = ixa->ixa_ipsec_ah_sa->ipsa_output_func(data_mp, ixa);
1581 return (data_mp);
1586 * Kernel crypto framework callback invoked after completion of async
1587 * crypto requests for outbound packets.
1589 static void
1590 esp_kcf_callback_outbound(void *arg, int status)
1592 mblk_t *mp = (mblk_t *)arg;
1593 mblk_t *async_mp;
1594 netstack_t *ns;
1595 ipsec_stack_t *ipss;
1596 ipsecesp_stack_t *espstack;
1597 mblk_t *data_mp;
1598 ip_xmit_attr_t ixas;
1599 ipsec_crypto_t *ic;
1600 ill_t *ill;
1603 * First remove the ipsec_crypto_t mblk
1604 * Note that we need to ipsec_free_crypto_data(mp) once done with ic.
1606 async_mp = ipsec_remove_crypto_data(mp, &ic);
1607 ASSERT(async_mp != NULL);
1610 * Extract the ip_xmit_attr_t from the first mblk.
1611 * Verifies that the netstack and ill is still around; could
1612 * have vanished while kEf was doing its work.
1613 * On succesful return we have a nce_t and the ill/ipst can't
1614 * disappear until we do the nce_refrele in ixa_cleanup.
1616 data_mp = async_mp->b_cont;
1617 async_mp->b_cont = NULL;
1618 if (!ip_xmit_attr_from_mblk(async_mp, &ixas)) {
1619 /* Disappeared on us - no ill/ipst for MIB */
1620 /* We have nowhere to do stats since ixa_ipst could be NULL */
1621 if (ixas.ixa_nce != NULL) {
1622 ill = ixas.ixa_nce->nce_ill;
1623 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
1624 ip_drop_output("ipIfStatsOutDiscards", data_mp, ill);
1626 freemsg(data_mp);
1627 goto done;
1629 ns = ixas.ixa_ipst->ips_netstack;
1630 espstack = ns->netstack_ipsecesp;
1631 ipss = ns->netstack_ipsec;
1632 ill = ixas.ixa_nce->nce_ill;
1634 if (status == CRYPTO_SUCCESS) {
1636 * If a ICV was computed, it was stored by the
1637 * crypto framework at the end of the packet.
1639 ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
1641 esp_set_usetime(ixas.ixa_ipsec_esp_sa, B_FALSE);
1642 /* NAT-T packet. */
1643 if (IPH_HDR_VERSION(ipha) == IP_VERSION &&
1644 ipha->ipha_protocol == IPPROTO_UDP)
1645 esp_prepare_udp(ns, data_mp, ipha);
1647 /* do AH processing if needed */
1648 data_mp = esp_do_outbound_ah(data_mp, &ixas);
1649 if (data_mp == NULL)
1650 goto done;
1652 (void) ip_output_post_ipsec(data_mp, &ixas);
1653 } else {
1654 /* Outbound shouldn't see invalid MAC */
1655 ASSERT(status != CRYPTO_INVALID_MAC);
1657 esp1dbg(espstack,
1658 ("esp_kcf_callback_outbound: crypto failed with 0x%x\n",
1659 status));
1660 ESP_BUMP_STAT(espstack, crypto_failures);
1661 ESP_BUMP_STAT(espstack, out_discards);
1662 ip_drop_packet(data_mp, B_FALSE, ill,
1663 DROPPER(ipss, ipds_esp_crypto_failed),
1664 &espstack->esp_dropper);
1665 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
1667 done:
1668 ixa_cleanup(&ixas);
1669 (void) ipsec_free_crypto_data(mp);
1673 * Kernel crypto framework callback invoked after completion of async
1674 * crypto requests for inbound packets.
1676 static void
1677 esp_kcf_callback_inbound(void *arg, int status)
1679 mblk_t *mp = (mblk_t *)arg;
1680 mblk_t *async_mp;
1681 netstack_t *ns;
1682 ipsecesp_stack_t *espstack;
1683 ipsec_stack_t *ipss;
1684 mblk_t *data_mp;
1685 ip_recv_attr_t iras;
1686 ipsec_crypto_t *ic;
1689 * First remove the ipsec_crypto_t mblk
1690 * Note that we need to ipsec_free_crypto_data(mp) once done with ic.
1692 async_mp = ipsec_remove_crypto_data(mp, &ic);
1693 ASSERT(async_mp != NULL);
1696 * Extract the ip_recv_attr_t from the first mblk.
1697 * Verifies that the netstack and ill is still around; could
1698 * have vanished while kEf was doing its work.
1700 data_mp = async_mp->b_cont;
1701 async_mp->b_cont = NULL;
1702 if (!ip_recv_attr_from_mblk(async_mp, &iras)) {
1703 /* The ill or ip_stack_t disappeared on us */
1704 ip_drop_input("ip_recv_attr_from_mblk", data_mp, NULL);
1705 freemsg(data_mp);
1706 goto done;
1709 ns = iras.ira_ill->ill_ipst->ips_netstack;
1710 espstack = ns->netstack_ipsecesp;
1711 ipss = ns->netstack_ipsec;
1713 if (status == CRYPTO_SUCCESS) {
1714 data_mp = esp_in_done(data_mp, &iras, ic);
1715 if (data_mp == NULL)
1716 goto done;
1718 /* finish IPsec processing */
1719 ip_input_post_ipsec(data_mp, &iras);
1720 } else if (status == CRYPTO_INVALID_MAC) {
1721 esp_log_bad_auth(data_mp, &iras);
1722 } else {
1723 esp1dbg(espstack,
1724 ("esp_kcf_callback: crypto failed with 0x%x\n",
1725 status));
1726 ESP_BUMP_STAT(espstack, crypto_failures);
1727 IP_ESP_BUMP_STAT(ipss, in_discards);
1728 ip_drop_packet(data_mp, B_TRUE, iras.ira_ill,
1729 DROPPER(ipss, ipds_esp_crypto_failed),
1730 &espstack->esp_dropper);
1731 BUMP_MIB(iras.ira_ill->ill_ip_mib, ipIfStatsInDiscards);
1733 done:
1734 ira_cleanup(&iras, B_TRUE);
1735 (void) ipsec_free_crypto_data(mp);
1739 * Invoked on crypto framework failure during inbound and outbound processing.
1741 static void
1742 esp_crypto_failed(mblk_t *data_mp, boolean_t is_inbound, int kef_rc,
1743 ill_t *ill, ipsecesp_stack_t *espstack)
1745 ipsec_stack_t *ipss = espstack->ipsecesp_netstack->netstack_ipsec;
1747 esp1dbg(espstack, ("crypto failed for %s ESP with 0x%x\n",
1748 is_inbound ? "inbound" : "outbound", kef_rc));
1749 ip_drop_packet(data_mp, is_inbound, ill,
1750 DROPPER(ipss, ipds_esp_crypto_failed),
1751 &espstack->esp_dropper);
1752 ESP_BUMP_STAT(espstack, crypto_failures);
1753 if (is_inbound)
1754 IP_ESP_BUMP_STAT(ipss, in_discards);
1755 else
1756 ESP_BUMP_STAT(espstack, out_discards);
1760 * A statement-equivalent macro, _cr MUST point to a modifiable
1761 * crypto_call_req_t.
1763 #define ESP_INIT_CALLREQ(_cr, _mp, _callback) \
1764 (_cr)->cr_flag = CRYPTO_SKIP_REQID|CRYPTO_ALWAYS_QUEUE; \
1765 (_cr)->cr_callback_arg = (_mp); \
1766 (_cr)->cr_callback_func = (_callback)
1768 #define ESP_INIT_CRYPTO_MAC(mac, icvlen, icvbuf) { \
1769 (mac)->cd_format = CRYPTO_DATA_RAW; \
1770 (mac)->cd_offset = 0; \
1771 (mac)->cd_length = icvlen; \
1772 (mac)->cd_raw.iov_base = (char *)icvbuf; \
1773 (mac)->cd_raw.iov_len = icvlen; \
1776 #define ESP_INIT_CRYPTO_DATA(data, mp, off, len) { \
1777 if (MBLKL(mp) >= (len) + (off)) { \
1778 (data)->cd_format = CRYPTO_DATA_RAW; \
1779 (data)->cd_raw.iov_base = (char *)(mp)->b_rptr; \
1780 (data)->cd_raw.iov_len = MBLKL(mp); \
1781 (data)->cd_offset = off; \
1782 } else { \
1783 (data)->cd_format = CRYPTO_DATA_MBLK; \
1784 (data)->cd_mp = mp; \
1785 (data)->cd_offset = off; \
1787 (data)->cd_length = len; \
1790 #define ESP_INIT_CRYPTO_DUAL_DATA(data, mp, off1, len1, off2, len2) { \
1791 (data)->dd_format = CRYPTO_DATA_MBLK; \
1792 (data)->dd_mp = mp; \
1793 (data)->dd_len1 = len1; \
1794 (data)->dd_offset1 = off1; \
1795 (data)->dd_len2 = len2; \
1796 (data)->dd_offset2 = off2; \
1800 * Returns data_mp if successfully completed the request. Returns
1801 * NULL if it failed (and increments InDiscards) or if it is pending.
1803 static mblk_t *
1804 esp_submit_req_inbound(mblk_t *esp_mp, ip_recv_attr_t *ira,
1805 ipsa_t *assoc, uint_t esph_offset)
1807 uint_t auth_offset, msg_len, auth_len;
1808 crypto_call_req_t call_req, *callrp;
1809 mblk_t *mp;
1810 esph_t *esph_ptr;
1811 int kef_rc;
1812 uint_t icv_len = assoc->ipsa_mac_len;
1813 crypto_ctx_template_t auth_ctx_tmpl;
1814 boolean_t do_auth, do_encr, force;
1815 uint_t encr_offset, encr_len;
1816 uint_t iv_len = assoc->ipsa_iv_len;
1817 crypto_ctx_template_t encr_ctx_tmpl;
1818 ipsec_crypto_t *ic, icstack;
1819 uchar_t *iv_ptr;
1820 netstack_t *ns = ira->ira_ill->ill_ipst->ips_netstack;
1821 ipsec_stack_t *ipss = ns->netstack_ipsec;
1822 ipsecesp_stack_t *espstack = ns->netstack_ipsecesp;
1824 do_auth = assoc->ipsa_auth_alg != SADB_AALG_NONE;
1825 do_encr = assoc->ipsa_encr_alg != SADB_EALG_NULL;
1826 force = (assoc->ipsa_flags & IPSA_F_ASYNC);
1828 #ifdef IPSEC_LATENCY_TEST
1829 kef_rc = CRYPTO_SUCCESS;
1830 #else
1831 kef_rc = CRYPTO_FAILED;
1832 #endif
1835 * An inbound packet is of the form:
1836 * [IP,options,ESP,IV,data,ICV,pad]
1838 esph_ptr = (esph_t *)(esp_mp->b_rptr + esph_offset);
1839 iv_ptr = (uchar_t *)(esph_ptr + 1);
1840 /* Packet length starting at IP header ending after ESP ICV. */
1841 msg_len = MBLKL(esp_mp);
1843 encr_offset = esph_offset + sizeof (esph_t) + iv_len;
1844 encr_len = msg_len - encr_offset;
1847 * Counter mode algs need a nonce. This is setup in sadb_common_add().
1848 * If for some reason we are using a SA which does not have a nonce
1849 * then we must fail here.
1851 if ((assoc->ipsa_flags & IPSA_F_COUNTERMODE) &&
1852 (assoc->ipsa_nonce == NULL)) {
1853 ip_drop_packet(esp_mp, B_TRUE, ira->ira_ill,
1854 DROPPER(ipss, ipds_esp_nomem), &espstack->esp_dropper);
1855 return (NULL);
1858 if (force) {
1859 /* We are doing asynch; allocate mblks to hold state */
1860 if ((mp = ip_recv_attr_to_mblk(ira)) == NULL ||
1861 (mp = ipsec_add_crypto_data(mp, &ic)) == NULL) {
1862 BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
1863 ip_drop_input("ipIfStatsInDiscards", esp_mp,
1864 ira->ira_ill);
1865 return (NULL);
1867 linkb(mp, esp_mp);
1868 callrp = &call_req;
1869 ESP_INIT_CALLREQ(callrp, mp, esp_kcf_callback_inbound);
1870 } else {
1872 * If we know we are going to do sync then ipsec_crypto_t
1873 * should be on the stack.
1875 ic = &icstack;
1876 bzero(ic, sizeof (*ic));
1877 callrp = NULL;
1880 if (do_auth) {
1881 /* authentication context template */
1882 IPSEC_CTX_TMPL(assoc, ipsa_authtmpl, IPSEC_ALG_AUTH,
1883 auth_ctx_tmpl);
1885 /* ICV to be verified */
1886 ESP_INIT_CRYPTO_MAC(&ic->ic_crypto_mac,
1887 icv_len, esp_mp->b_wptr - icv_len);
1889 /* authentication starts at the ESP header */
1890 auth_offset = esph_offset;
1891 auth_len = msg_len - auth_offset - icv_len;
1892 if (!do_encr) {
1893 /* authentication only */
1894 /* initialize input data argument */
1895 ESP_INIT_CRYPTO_DATA(&ic->ic_crypto_data,
1896 esp_mp, auth_offset, auth_len);
1898 /* call the crypto framework */
1899 kef_rc = crypto_mac_verify(&assoc->ipsa_amech,
1900 &ic->ic_crypto_data,
1901 &assoc->ipsa_kcfauthkey, auth_ctx_tmpl,
1902 &ic->ic_crypto_mac, callrp);
1906 if (do_encr) {
1907 /* encryption template */
1908 IPSEC_CTX_TMPL(assoc, ipsa_encrtmpl, IPSEC_ALG_ENCR,
1909 encr_ctx_tmpl);
1911 /* Call the nonce update function. Also passes in IV */
1912 (assoc->ipsa_noncefunc)(assoc, (uchar_t *)esph_ptr, encr_len,
1913 iv_ptr, &ic->ic_cmm, &ic->ic_crypto_data);
1915 if (!do_auth) {
1916 /* decryption only */
1917 /* initialize input data argument */
1918 ESP_INIT_CRYPTO_DATA(&ic->ic_crypto_data,
1919 esp_mp, encr_offset, encr_len);
1921 /* call the crypto framework */
1922 kef_rc = crypto_decrypt((crypto_mechanism_t *)
1923 &ic->ic_cmm, &ic->ic_crypto_data,
1924 &assoc->ipsa_kcfencrkey, encr_ctx_tmpl,
1925 NULL, callrp);
1929 if (do_auth && do_encr) {
1930 /* dual operation */
1931 /* initialize input data argument */
1932 ESP_INIT_CRYPTO_DUAL_DATA(&ic->ic_crypto_dual_data,
1933 esp_mp, auth_offset, auth_len,
1934 encr_offset, encr_len - icv_len);
1936 /* specify IV */
1937 ic->ic_crypto_dual_data.dd_miscdata = (char *)iv_ptr;
1939 /* call the framework */
1940 kef_rc = crypto_mac_verify_decrypt(&assoc->ipsa_amech,
1941 &assoc->ipsa_emech, &ic->ic_crypto_dual_data,
1942 &assoc->ipsa_kcfauthkey, &assoc->ipsa_kcfencrkey,
1943 auth_ctx_tmpl, encr_ctx_tmpl, &ic->ic_crypto_mac,
1944 NULL, callrp);
1947 switch (kef_rc) {
1948 case CRYPTO_SUCCESS:
1949 ESP_BUMP_STAT(espstack, crypto_sync);
1950 esp_mp = esp_in_done(esp_mp, ira, ic);
1951 if (force) {
1952 /* Free mp after we are done with ic */
1953 mp = ipsec_free_crypto_data(mp);
1954 (void) ip_recv_attr_free_mblk(mp);
1956 return (esp_mp);
1957 case CRYPTO_QUEUED:
1958 /* esp_kcf_callback_inbound() will be invoked on completion */
1959 ESP_BUMP_STAT(espstack, crypto_async);
1960 return (NULL);
1961 case CRYPTO_INVALID_MAC:
1962 if (force) {
1963 mp = ipsec_free_crypto_data(mp);
1964 esp_mp = ip_recv_attr_free_mblk(mp);
1966 ESP_BUMP_STAT(espstack, crypto_sync);
1967 BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
1968 esp_log_bad_auth(esp_mp, ira);
1969 /* esp_mp was passed to ip_drop_packet */
1970 return (NULL);
1973 if (force) {
1974 mp = ipsec_free_crypto_data(mp);
1975 esp_mp = ip_recv_attr_free_mblk(mp);
1977 BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
1978 esp_crypto_failed(esp_mp, B_TRUE, kef_rc, ira->ira_ill, espstack);
1979 /* esp_mp was passed to ip_drop_packet */
1980 return (NULL);
1984 * Compute the IP and UDP checksums -- common code for both keepalives and
1985 * actual ESP-in-UDP packets. Be flexible with multiple mblks because ESP
1986 * uses mblk-insertion to insert the UDP header.
1987 * TODO - If there is an easy way to prep a packet for HW checksums, make
1988 * it happen here.
1989 * Note that this is used before both before calling ip_output_simple and
1990 * in the esp datapath. The former could use IXAF_SET_ULP_CKSUM but not the
1991 * latter.
1993 static void
1994 esp_prepare_udp(netstack_t *ns, mblk_t *mp, ipha_t *ipha)
1996 int offset;
1997 uint32_t cksum;
1998 uint16_t *arr;
1999 mblk_t *udpmp = mp;
2000 uint_t hlen = IPH_HDR_LENGTH(ipha);
2002 ASSERT(MBLKL(mp) >= sizeof (ipha_t));
2004 ipha->ipha_hdr_checksum = 0;
2005 ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
2007 if (ns->netstack_udp->us_do_checksum) {
2008 ASSERT(MBLKL(udpmp) >= sizeof (udpha_t));
2009 /* arr points to the IP header. */
2010 arr = (uint16_t *)ipha;
2011 IP_STAT(ns->netstack_ip, ip_out_sw_cksum);
2012 IP_STAT_UPDATE(ns->netstack_ip, ip_out_sw_cksum_bytes,
2013 ntohs(htons(ipha->ipha_length) - hlen));
2014 /* arr[6-9] are the IP addresses. */
2015 cksum = IP_UDP_CSUM_COMP + arr[6] + arr[7] + arr[8] + arr[9] +
2016 ntohs(htons(ipha->ipha_length) - hlen);
2017 cksum = IP_CSUM(mp, hlen, cksum);
2018 offset = hlen + UDP_CHECKSUM_OFFSET;
2019 while (offset >= MBLKL(udpmp)) {
2020 offset -= MBLKL(udpmp);
2021 udpmp = udpmp->b_cont;
2023 /* arr points to the UDP header's checksum field. */
2024 arr = (uint16_t *)(udpmp->b_rptr + offset);
2025 *arr = cksum;
2030 * taskq handler so we can send the NAT-T keepalive on a separate thread.
2032 static void
2033 actually_send_keepalive(void *arg)
2035 mblk_t *mp = (mblk_t *)arg;
2036 ip_xmit_attr_t ixas;
2037 netstack_t *ns;
2038 netstackid_t stackid;
2040 stackid = (netstackid_t)(uintptr_t)mp->b_prev;
2041 mp->b_prev = NULL;
2042 ns = netstack_find_by_stackid(stackid);
2043 if (ns == NULL) {
2044 /* Disappeared */
2045 ip_drop_output("ipIfStatsOutDiscards", mp, NULL);
2046 freemsg(mp);
2047 return;
2050 bzero(&ixas, sizeof (ixas));
2051 ixas.ixa_zoneid = ALL_ZONES;
2052 ixas.ixa_cred = kcred;
2053 ixas.ixa_cpid = NOPID;
2054 ixas.ixa_ipst = ns->netstack_ip;
2055 /* No ULP checksum; done by esp_prepare_udp */
2056 ixas.ixa_flags = (IXAF_IS_IPV4 | IXAF_NO_IPSEC | IXAF_VERIFY_SOURCE);
2058 (void) ip_output_simple(mp, &ixas);
2059 ixa_cleanup(&ixas);
2060 netstack_rele(ns);
2064 * Send a one-byte UDP NAT-T keepalive.
2066 void
2067 ipsecesp_send_keepalive(ipsa_t *assoc)
2069 mblk_t *mp;
2070 ipha_t *ipha;
2071 udpha_t *udpha;
2072 netstack_t *ns = assoc->ipsa_netstack;
2074 ASSERT(MUTEX_NOT_HELD(&assoc->ipsa_lock));
2076 mp = allocb(sizeof (ipha_t) + sizeof (udpha_t) + 1, BPRI_HI);
2077 if (mp == NULL)
2078 return;
2079 ipha = (ipha_t *)mp->b_rptr;
2080 ipha->ipha_version_and_hdr_length = IP_SIMPLE_HDR_VERSION;
2081 ipha->ipha_type_of_service = 0;
2082 ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (udpha_t) + 1);
2083 /* Use the low-16 of the SPI so we have some clue where it came from. */
2084 ipha->ipha_ident = *(((uint16_t *)(&assoc->ipsa_spi)) + 1);
2085 ipha->ipha_fragment_offset_and_flags = 0; /* Too small to fragment! */
2086 ipha->ipha_ttl = 0xFF;
2087 ipha->ipha_protocol = IPPROTO_UDP;
2088 ipha->ipha_hdr_checksum = 0;
2089 ipha->ipha_src = assoc->ipsa_srcaddr[0];
2090 ipha->ipha_dst = assoc->ipsa_dstaddr[0];
2091 udpha = (udpha_t *)(ipha + 1);
2092 udpha->uha_src_port = (assoc->ipsa_local_nat_port != 0) ?
2093 assoc->ipsa_local_nat_port : htons(IPPORT_IKE_NATT);
2094 udpha->uha_dst_port = (assoc->ipsa_remote_nat_port != 0) ?
2095 assoc->ipsa_remote_nat_port : htons(IPPORT_IKE_NATT);
2096 udpha->uha_length = htons(sizeof (udpha_t) + 1);
2097 udpha->uha_checksum = 0;
2098 mp->b_wptr = (uint8_t *)(udpha + 1);
2099 *(mp->b_wptr++) = 0xFF;
2101 esp_prepare_udp(ns, mp, ipha);
2104 * We're holding an isaf_t bucket lock, so pawn off the actual
2105 * packet transmission to another thread. Just in case syncq
2106 * processing causes a same-bucket packet to be processed.
2108 mp->b_prev = (mblk_t *)(uintptr_t)ns->netstack_stackid;
2110 if (taskq_dispatch(esp_taskq, actually_send_keepalive, mp,
2111 TQ_NOSLEEP) == 0) {
2112 /* Assume no memory if taskq_dispatch() fails. */
2113 mp->b_prev = NULL;
2114 ip_drop_packet(mp, B_FALSE, NULL,
2115 DROPPER(ns->netstack_ipsec, ipds_esp_nomem),
2116 &ns->netstack_ipsecesp->esp_dropper);
2121 * Returns mp if successfully completed the request. Returns
2122 * NULL if it failed (and increments InDiscards) or if it is pending.
2124 static mblk_t *
2125 esp_submit_req_outbound(mblk_t *data_mp, ip_xmit_attr_t *ixa, ipsa_t *assoc,
2126 uchar_t *icv_buf, uint_t payload_len)
2128 uint_t auth_len;
2129 crypto_call_req_t call_req, *callrp;
2130 mblk_t *esp_mp;
2131 esph_t *esph_ptr;
2132 mblk_t *mp;
2133 int kef_rc = CRYPTO_FAILED;
2134 uint_t icv_len = assoc->ipsa_mac_len;
2135 crypto_ctx_template_t auth_ctx_tmpl;
2136 boolean_t do_auth, do_encr, force;
2137 uint_t iv_len = assoc->ipsa_iv_len;
2138 crypto_ctx_template_t encr_ctx_tmpl;
2139 boolean_t is_natt = ((assoc->ipsa_flags & IPSA_F_NATT) != 0);
2140 size_t esph_offset = (is_natt ? UDPH_SIZE : 0);
2141 netstack_t *ns = ixa->ixa_ipst->ips_netstack;
2142 ipsecesp_stack_t *espstack = ns->netstack_ipsecesp;
2143 ipsec_crypto_t *ic, icstack;
2144 uchar_t *iv_ptr;
2145 crypto_data_t *cd_ptr = NULL;
2146 ill_t *ill = ixa->ixa_nce->nce_ill;
2147 ipsec_stack_t *ipss = ns->netstack_ipsec;
2149 esp3dbg(espstack, ("esp_submit_req_outbound:%s",
2150 is_natt ? "natt" : "not natt"));
2152 do_encr = assoc->ipsa_encr_alg != SADB_EALG_NULL;
2153 do_auth = assoc->ipsa_auth_alg != SADB_AALG_NONE;
2154 force = (assoc->ipsa_flags & IPSA_F_ASYNC);
2156 #ifdef IPSEC_LATENCY_TEST
2157 kef_rc = CRYPTO_SUCCESS;
2158 #else
2159 kef_rc = CRYPTO_FAILED;
2160 #endif
2163 * Outbound IPsec packets are of the form:
2164 * [IP,options] -> [ESP,IV] -> [data] -> [pad,ICV]
2165 * unless it's NATT, then it's
2166 * [IP,options] -> [udp][ESP,IV] -> [data] -> [pad,ICV]
2167 * Get a pointer to the mblk containing the ESP header.
2169 ASSERT(data_mp->b_cont != NULL);
2170 esp_mp = data_mp->b_cont;
2171 esph_ptr = (esph_t *)(esp_mp->b_rptr + esph_offset);
2172 iv_ptr = (uchar_t *)(esph_ptr + 1);
2175 * Combined mode algs need a nonce. This is setup in sadb_common_add().
2176 * If for some reason we are using a SA which does not have a nonce
2177 * then we must fail here.
2179 if ((assoc->ipsa_flags & IPSA_F_COUNTERMODE) &&
2180 (assoc->ipsa_nonce == NULL)) {
2181 ip_drop_packet(data_mp, B_FALSE, NULL,
2182 DROPPER(ipss, ipds_esp_nomem), &espstack->esp_dropper);
2183 return (NULL);
2186 if (force) {
2187 /* We are doing asynch; allocate mblks to hold state */
2188 if ((mp = ip_xmit_attr_to_mblk(ixa)) == NULL ||
2189 (mp = ipsec_add_crypto_data(mp, &ic)) == NULL) {
2190 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
2191 ip_drop_output("ipIfStatsOutDiscards", data_mp, ill);
2192 freemsg(data_mp);
2193 return (NULL);
2196 linkb(mp, data_mp);
2197 callrp = &call_req;
2198 ESP_INIT_CALLREQ(callrp, mp, esp_kcf_callback_outbound);
2199 } else {
2201 * If we know we are going to do sync then ipsec_crypto_t
2202 * should be on the stack.
2204 ic = &icstack;
2205 bzero(ic, sizeof (*ic));
2206 callrp = NULL;
2210 if (do_auth) {
2211 /* authentication context template */
2212 IPSEC_CTX_TMPL(assoc, ipsa_authtmpl, IPSEC_ALG_AUTH,
2213 auth_ctx_tmpl);
2215 /* where to store the computed mac */
2216 ESP_INIT_CRYPTO_MAC(&ic->ic_crypto_mac,
2217 icv_len, icv_buf);
2219 /* authentication starts at the ESP header */
2220 auth_len = payload_len + iv_len + sizeof (esph_t);
2221 if (!do_encr) {
2222 /* authentication only */
2223 /* initialize input data argument */
2224 ESP_INIT_CRYPTO_DATA(&ic->ic_crypto_data,
2225 esp_mp, esph_offset, auth_len);
2227 /* call the crypto framework */
2228 kef_rc = crypto_mac(&assoc->ipsa_amech,
2229 &ic->ic_crypto_data,
2230 &assoc->ipsa_kcfauthkey, auth_ctx_tmpl,
2231 &ic->ic_crypto_mac, callrp);
2235 if (do_encr) {
2236 /* encryption context template */
2237 IPSEC_CTX_TMPL(assoc, ipsa_encrtmpl, IPSEC_ALG_ENCR,
2238 encr_ctx_tmpl);
2239 /* Call the nonce update function. */
2240 (assoc->ipsa_noncefunc)(assoc, (uchar_t *)esph_ptr, payload_len,
2241 iv_ptr, &ic->ic_cmm, &ic->ic_crypto_data);
2243 if (!do_auth) {
2244 /* encryption only, skip mblk that contains ESP hdr */
2245 /* initialize input data argument */
2246 ESP_INIT_CRYPTO_DATA(&ic->ic_crypto_data,
2247 esp_mp->b_cont, 0, payload_len);
2250 * For combined mode ciphers, the ciphertext is the same
2251 * size as the clear text, the ICV should follow the
2252 * ciphertext. To convince the kcf to allow in-line
2253 * encryption, with an ICV, use ipsec_out_crypto_mac
2254 * to point to the same buffer as the data. The calling
2255 * function need to ensure the buffer is large enough to
2256 * include the ICV.
2258 * The IV is already written to the packet buffer, the
2259 * nonce setup function copied it to the params struct
2260 * for the cipher to use.
2262 if (assoc->ipsa_flags & IPSA_F_COMBINED) {
2263 bcopy(&ic->ic_crypto_data,
2264 &ic->ic_crypto_mac,
2265 sizeof (crypto_data_t));
2266 ic->ic_crypto_mac.cd_length =
2267 payload_len + icv_len;
2268 cd_ptr = &ic->ic_crypto_mac;
2271 /* call the crypto framework */
2272 kef_rc = crypto_encrypt((crypto_mechanism_t *)
2273 &ic->ic_cmm, &ic->ic_crypto_data,
2274 &assoc->ipsa_kcfencrkey, encr_ctx_tmpl,
2275 cd_ptr, callrp);
2280 if (do_auth && do_encr) {
2282 * Encryption and authentication:
2283 * Pass the pointer to the mblk chain starting at the ESP
2284 * header to the framework. Skip the ESP header mblk
2285 * for encryption, which is reflected by an encryption
2286 * offset equal to the length of that mblk. Start
2287 * the authentication at the ESP header, i.e. use an
2288 * authentication offset of zero.
2290 ESP_INIT_CRYPTO_DUAL_DATA(&ic->ic_crypto_dual_data,
2291 esp_mp, MBLKL(esp_mp), payload_len, esph_offset, auth_len);
2293 /* specify IV */
2294 ic->ic_crypto_dual_data.dd_miscdata = (char *)iv_ptr;
2296 /* call the framework */
2297 kef_rc = crypto_encrypt_mac(&assoc->ipsa_emech,
2298 &assoc->ipsa_amech, NULL,
2299 &assoc->ipsa_kcfencrkey, &assoc->ipsa_kcfauthkey,
2300 encr_ctx_tmpl, auth_ctx_tmpl,
2301 &ic->ic_crypto_dual_data,
2302 &ic->ic_crypto_mac, callrp);
2305 switch (kef_rc) {
2306 case CRYPTO_SUCCESS:
2307 ESP_BUMP_STAT(espstack, crypto_sync);
2308 esp_set_usetime(assoc, B_FALSE);
2309 if (force) {
2310 mp = ipsec_free_crypto_data(mp);
2311 data_mp = ip_xmit_attr_free_mblk(mp);
2313 if (is_natt)
2314 esp_prepare_udp(ns, data_mp, (ipha_t *)data_mp->b_rptr);
2315 return (data_mp);
2316 case CRYPTO_QUEUED:
2317 /* esp_kcf_callback_outbound() will be invoked on completion */
2318 ESP_BUMP_STAT(espstack, crypto_async);
2319 return (NULL);
2322 if (force) {
2323 mp = ipsec_free_crypto_data(mp);
2324 data_mp = ip_xmit_attr_free_mblk(mp);
2326 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
2327 esp_crypto_failed(data_mp, B_FALSE, kef_rc, NULL, espstack);
2328 /* data_mp was passed to ip_drop_packet */
2329 return (NULL);
2333 * Handle outbound IPsec processing for IPv4 and IPv6
2335 * Returns data_mp if successfully completed the request. Returns
2336 * NULL if it failed (and increments InDiscards) or if it is pending.
2338 static mblk_t *
2339 esp_outbound(mblk_t *data_mp, ip_xmit_attr_t *ixa)
2341 mblk_t *espmp, *tailmp;
2342 ipha_t *ipha;
2343 ip6_t *ip6h;
2344 esph_t *esph_ptr, *iv_ptr;
2345 uint_t af;
2346 uint8_t *nhp;
2347 uintptr_t divpoint, datalen, adj, padlen, i, alloclen;
2348 uintptr_t esplen = sizeof (esph_t);
2349 uint8_t protocol;
2350 ipsa_t *assoc;
2351 uint_t iv_len, block_size, mac_len = 0;
2352 uchar_t *icv_buf;
2353 udpha_t *udpha;
2354 boolean_t is_natt = B_FALSE;
2355 netstack_t *ns = ixa->ixa_ipst->ips_netstack;
2356 ipsecesp_stack_t *espstack = ns->netstack_ipsecesp;
2357 ipsec_stack_t *ipss = ns->netstack_ipsec;
2358 ill_t *ill = ixa->ixa_nce->nce_ill;
2359 boolean_t need_refrele = B_FALSE;
2361 ESP_BUMP_STAT(espstack, out_requests);
2364 * <sigh> We have to copy the message here, because TCP (for example)
2365 * keeps a dupb() of the message lying around for retransmission.
2366 * Since ESP changes the whole of the datagram, we have to create our
2367 * own copy lest we clobber TCP's data. Since we have to copy anyway,
2368 * we might as well make use of msgpullup() and get the mblk into one
2369 * contiguous piece!
2371 tailmp = msgpullup(data_mp, -1);
2372 if (tailmp == NULL) {
2373 esp0dbg(("esp_outbound: msgpullup() failed, "
2374 "dropping packet.\n"));
2375 ip_drop_packet(data_mp, B_FALSE, ill,
2376 DROPPER(ipss, ipds_esp_nomem),
2377 &espstack->esp_dropper);
2378 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
2379 return (NULL);
2381 freemsg(data_mp);
2382 data_mp = tailmp;
2384 assoc = ixa->ixa_ipsec_esp_sa;
2385 ASSERT(assoc != NULL);
2388 * Reality check....
2390 ipha = (ipha_t *)data_mp->b_rptr; /* So we can call esp_acquire(). */
2392 if (ixa->ixa_flags & IXAF_IS_IPV4) {
2393 ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
2395 af = AF_INET;
2396 divpoint = IPH_HDR_LENGTH(ipha);
2397 datalen = ntohs(ipha->ipha_length) - divpoint;
2398 nhp = (uint8_t *)&ipha->ipha_protocol;
2399 } else {
2400 ip_pkt_t ipp;
2402 ASSERT(IPH_HDR_VERSION(ipha) == IPV6_VERSION);
2404 af = AF_INET6;
2405 ip6h = (ip6_t *)ipha;
2406 bzero(&ipp, sizeof (ipp));
2407 divpoint = ip_find_hdr_v6(data_mp, ip6h, &ipp, NULL);
2408 if (ipp.ipp_dstopts != NULL &&
2409 ipp.ipp_dstopts->ip6d_nxt != IPPROTO_ROUTING) {
2411 * Destination options are tricky. If we get in here,
2412 * then we have a terminal header following the
2413 * destination options. We need to adjust backwards
2414 * so we insert ESP BEFORE the destination options
2415 * bag. (So that the dstopts get encrypted!)
2417 * Since this is for outbound packets only, we know
2418 * that non-terminal destination options only precede
2419 * routing headers.
2421 divpoint -= ipp.ipp_dstoptslen;
2423 datalen = ntohs(ip6h->ip6_plen) + sizeof (ip6_t) - divpoint;
2425 if (ipp.ipp_rthdr != NULL) {
2426 nhp = &ipp.ipp_rthdr->ip6r_nxt;
2427 } else if (ipp.ipp_hopopts != NULL) {
2428 nhp = &ipp.ipp_hopopts->ip6h_nxt;
2429 } else {
2430 ASSERT(divpoint == sizeof (ip6_t));
2431 /* It's probably IP + ESP. */
2432 nhp = &ip6h->ip6_nxt;
2436 mac_len = assoc->ipsa_mac_len;
2438 if (assoc->ipsa_flags & IPSA_F_NATT) {
2439 /* wedge in UDP header */
2440 is_natt = B_TRUE;
2441 esplen += UDPH_SIZE;
2445 * Set up ESP header and encryption padding for ENCR PI request.
2448 /* Determine the padding length. Pad to 4-bytes for no-encryption. */
2449 if (assoc->ipsa_encr_alg != SADB_EALG_NULL) {
2450 iv_len = assoc->ipsa_iv_len;
2451 block_size = assoc->ipsa_datalen;
2454 * Pad the data to the length of the cipher block size.
2455 * Include the two additional bytes (hence the - 2) for the
2456 * padding length and the next header. Take this into account
2457 * when calculating the actual length of the padding.
2459 ASSERT(ISP2(iv_len));
2460 padlen = ((unsigned)(block_size - datalen - 2)) &
2461 (block_size - 1);
2462 } else {
2463 iv_len = 0;
2464 padlen = ((unsigned)(sizeof (uint32_t) - datalen - 2)) &
2465 (sizeof (uint32_t) - 1);
2468 /* Allocate ESP header and IV. */
2469 esplen += iv_len;
2472 * Update association byte-count lifetimes. Don't forget to take
2473 * into account the padding length and next-header (hence the + 2).
2475 * Use the amount of data fed into the "encryption algorithm". This
2476 * is the IV, the data length, the padding length, and the final two
2477 * bytes (padlen, and next-header).
2481 if (!esp_age_bytes(assoc, datalen + padlen + iv_len + 2, B_FALSE)) {
2482 ip_drop_packet(data_mp, B_FALSE, ill,
2483 DROPPER(ipss, ipds_esp_bytes_expire),
2484 &espstack->esp_dropper);
2485 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
2486 if (need_refrele)
2487 ixa_refrele(ixa);
2488 return (NULL);
2491 espmp = allocb(esplen, BPRI_HI);
2492 if (espmp == NULL) {
2493 ESP_BUMP_STAT(espstack, out_discards);
2494 esp1dbg(espstack, ("esp_outbound: can't allocate espmp.\n"));
2495 ip_drop_packet(data_mp, B_FALSE, ill,
2496 DROPPER(ipss, ipds_esp_nomem),
2497 &espstack->esp_dropper);
2498 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
2499 if (need_refrele)
2500 ixa_refrele(ixa);
2501 return (NULL);
2503 espmp->b_wptr += esplen;
2504 esph_ptr = (esph_t *)espmp->b_rptr;
2506 if (is_natt) {
2507 esp3dbg(espstack, ("esp_outbound: NATT"));
2509 udpha = (udpha_t *)espmp->b_rptr;
2510 udpha->uha_src_port = (assoc->ipsa_local_nat_port != 0) ?
2511 assoc->ipsa_local_nat_port : htons(IPPORT_IKE_NATT);
2512 udpha->uha_dst_port = (assoc->ipsa_remote_nat_port != 0) ?
2513 assoc->ipsa_remote_nat_port : htons(IPPORT_IKE_NATT);
2515 * Set the checksum to 0, so that the esp_prepare_udp() call
2516 * can do the right thing.
2518 udpha->uha_checksum = 0;
2519 esph_ptr = (esph_t *)(udpha + 1);
2522 esph_ptr->esph_spi = assoc->ipsa_spi;
2524 esph_ptr->esph_replay = htonl(atomic_inc_32_nv(&assoc->ipsa_replay));
2525 if (esph_ptr->esph_replay == 0 && assoc->ipsa_replay_wsize != 0) {
2527 * XXX We have replay counter wrapping.
2528 * We probably want to nuke this SA (and its peer).
2530 ipsec_assocfailure(info.mi_idnum, 0, 0,
2531 SL_ERROR | SL_CONSOLE | SL_WARN,
2532 "Outbound ESP SA (0x%x, %s) has wrapped sequence.\n",
2533 esph_ptr->esph_spi, assoc->ipsa_dstaddr, af,
2534 espstack->ipsecesp_netstack);
2536 ESP_BUMP_STAT(espstack, out_discards);
2537 sadb_replay_delete(assoc);
2538 ip_drop_packet(data_mp, B_FALSE, ill,
2539 DROPPER(ipss, ipds_esp_replay),
2540 &espstack->esp_dropper);
2541 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
2542 if (need_refrele)
2543 ixa_refrele(ixa);
2544 return (NULL);
2547 iv_ptr = (esph_ptr + 1);
2549 * iv_ptr points to the mblk which will contain the IV once we have
2550 * written it there. This mblk will be part of a mblk chain that
2551 * will make up the packet.
2553 * For counter mode algorithms, the IV is a 64 bit quantity, it
2554 * must NEVER repeat in the lifetime of the SA, otherwise an
2555 * attacker who had recorded enough packets might be able to
2556 * determine some clear text.
2558 * To ensure this does not happen, the IV is stored in the SA and
2559 * incremented for each packet, the IV is then copied into the
2560 * "packet" for transmission to the receiving system. The IV will
2561 * also be copied into the nonce, when the packet is encrypted.
2563 * CBC mode algorithms use a random IV for each packet. We do not
2564 * require the highest quality random bits, but for best security
2565 * with CBC mode ciphers, the value must be unlikely to repeat and
2566 * must not be known in advance to an adversary capable of influencing
2567 * the clear text.
2569 if (!update_iv((uint8_t *)iv_ptr, espstack->esp_pfkey_q, assoc,
2570 espstack)) {
2571 ip_drop_packet(data_mp, B_FALSE, ill,
2572 DROPPER(ipss, ipds_esp_iv_wrap), &espstack->esp_dropper);
2573 if (need_refrele)
2574 ixa_refrele(ixa);
2575 return (NULL);
2578 /* Fix the IP header. */
2579 alloclen = padlen + 2 + mac_len;
2580 adj = alloclen + (espmp->b_wptr - espmp->b_rptr);
2582 protocol = *nhp;
2584 if (ixa->ixa_flags & IXAF_IS_IPV4) {
2585 ipha->ipha_length = htons(ntohs(ipha->ipha_length) + adj);
2586 if (is_natt) {
2587 *nhp = IPPROTO_UDP;
2588 udpha->uha_length = htons(ntohs(ipha->ipha_length) -
2589 IPH_HDR_LENGTH(ipha));
2590 } else {
2591 *nhp = IPPROTO_ESP;
2593 ipha->ipha_hdr_checksum = 0;
2594 ipha->ipha_hdr_checksum = (uint16_t)ip_csum_hdr(ipha);
2595 } else {
2596 ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) + adj);
2597 *nhp = IPPROTO_ESP;
2600 /* I've got the two ESP mblks, now insert them. */
2602 esp2dbg(espstack, ("data_mp before outbound ESP adjustment:\n"));
2603 esp2dbg(espstack, (dump_msg(data_mp)));
2605 if (!esp_insert_esp(data_mp, espmp, divpoint, espstack)) {
2606 ESP_BUMP_STAT(espstack, out_discards);
2607 /* NOTE: esp_insert_esp() only fails if there's no memory. */
2608 ip_drop_packet(data_mp, B_FALSE, ill,
2609 DROPPER(ipss, ipds_esp_nomem),
2610 &espstack->esp_dropper);
2611 freeb(espmp);
2612 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
2613 if (need_refrele)
2614 ixa_refrele(ixa);
2615 return (NULL);
2618 /* Append padding (and leave room for ICV). */
2619 for (tailmp = data_mp; tailmp->b_cont != NULL; tailmp = tailmp->b_cont)
2621 if (tailmp->b_wptr + alloclen > tailmp->b_datap->db_lim) {
2622 tailmp->b_cont = allocb(alloclen, BPRI_HI);
2623 if (tailmp->b_cont == NULL) {
2624 ESP_BUMP_STAT(espstack, out_discards);
2625 esp0dbg(("esp_outbound: Can't allocate tailmp.\n"));
2626 ip_drop_packet(data_mp, B_FALSE, ill,
2627 DROPPER(ipss, ipds_esp_nomem),
2628 &espstack->esp_dropper);
2629 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
2630 if (need_refrele)
2631 ixa_refrele(ixa);
2632 return (NULL);
2634 tailmp = tailmp->b_cont;
2638 * If there's padding, N bytes of padding must be of the form 0x1,
2639 * 0x2, 0x3... 0xN.
2641 for (i = 0; i < padlen; ) {
2642 i++;
2643 *tailmp->b_wptr++ = i;
2645 *tailmp->b_wptr++ = i;
2646 *tailmp->b_wptr++ = protocol;
2648 esp2dbg(espstack, ("data_Mp before encryption:\n"));
2649 esp2dbg(espstack, (dump_msg(data_mp)));
2652 * Okay. I've set up the pre-encryption ESP. Let's do it!
2655 if (mac_len > 0) {
2656 ASSERT(tailmp->b_wptr + mac_len <= tailmp->b_datap->db_lim);
2657 icv_buf = tailmp->b_wptr;
2658 tailmp->b_wptr += mac_len;
2659 } else {
2660 icv_buf = NULL;
2663 data_mp = esp_submit_req_outbound(data_mp, ixa, assoc, icv_buf,
2664 datalen + padlen + 2);
2665 if (need_refrele)
2666 ixa_refrele(ixa);
2667 return (data_mp);
2671 * IP calls this to validate the ICMP errors that
2672 * we got from the network.
2674 mblk_t *
2675 ipsecesp_icmp_error(mblk_t *data_mp, ip_recv_attr_t *ira)
2677 netstack_t *ns = ira->ira_ill->ill_ipst->ips_netstack;
2678 ipsecesp_stack_t *espstack = ns->netstack_ipsecesp;
2679 ipsec_stack_t *ipss = ns->netstack_ipsec;
2682 * Unless we get an entire packet back, this function is useless.
2683 * Why?
2685 * 1.) Partial packets are useless, because the "next header"
2686 * is at the end of the decrypted ESP packet. Without the
2687 * whole packet, this is useless.
2689 * 2.) If we every use a stateful cipher, such as a stream or a
2690 * one-time pad, we can't do anything.
2692 * Since the chances of us getting an entire packet back are very
2693 * very small, we discard here.
2695 IP_ESP_BUMP_STAT(ipss, in_discards);
2696 ip_drop_packet(data_mp, B_TRUE, ira->ira_ill,
2697 DROPPER(ipss, ipds_esp_icmp),
2698 &espstack->esp_dropper);
2699 return (NULL);
2703 * Construct an SADB_REGISTER message with the current algorithms.
2704 * This function gets called when 'ipsecalgs -s' is run or when
2705 * in.iked (or other KMD) starts.
2707 static boolean_t
2708 esp_register_out(uint32_t sequence, uint32_t pid, uint_t serial,
2709 ipsecesp_stack_t *espstack, cred_t *cr)
2711 mblk_t *pfkey_msg_mp, *keysock_out_mp;
2712 sadb_msg_t *samsg;
2713 sadb_supported_t *sasupp_auth = NULL;
2714 sadb_supported_t *sasupp_encr = NULL;
2715 sadb_alg_t *saalg;
2716 uint_t allocsize = sizeof (*samsg);
2717 uint_t i, numalgs_snap;
2718 int current_aalgs;
2719 ipsec_alginfo_t **authalgs;
2720 uint_t num_aalgs;
2721 int current_ealgs;
2722 ipsec_alginfo_t **encralgs;
2723 uint_t num_ealgs;
2724 ipsec_stack_t *ipss = espstack->ipsecesp_netstack->netstack_ipsec;
2725 sadb_ext_t *nextext;
2727 /* Allocate the KEYSOCK_OUT. */
2728 keysock_out_mp = sadb_keysock_out(serial);
2729 if (keysock_out_mp == NULL) {
2730 esp0dbg(("esp_register_out: couldn't allocate mblk.\n"));
2731 return (B_FALSE);
2735 * Allocate the PF_KEY message that follows KEYSOCK_OUT.
2738 rw_enter(&ipss->ipsec_alg_lock, RW_READER);
2740 * Fill SADB_REGISTER message's algorithm descriptors. Hold
2741 * down the lock while filling it.
2743 * Return only valid algorithms, so the number of algorithms
2744 * to send up may be less than the number of algorithm entries
2745 * in the table.
2747 authalgs = ipss->ipsec_alglists[IPSEC_ALG_AUTH];
2748 for (num_aalgs = 0, i = 0; i < IPSEC_MAX_ALGS; i++)
2749 if (authalgs[i] != NULL && ALG_VALID(authalgs[i]))
2750 num_aalgs++;
2752 if (num_aalgs != 0) {
2753 allocsize += (num_aalgs * sizeof (*saalg));
2754 allocsize += sizeof (*sasupp_auth);
2756 encralgs = ipss->ipsec_alglists[IPSEC_ALG_ENCR];
2757 for (num_ealgs = 0, i = 0; i < IPSEC_MAX_ALGS; i++)
2758 if (encralgs[i] != NULL && ALG_VALID(encralgs[i]))
2759 num_ealgs++;
2761 if (num_ealgs != 0) {
2762 allocsize += (num_ealgs * sizeof (*saalg));
2763 allocsize += sizeof (*sasupp_encr);
2765 keysock_out_mp->b_cont = allocb(allocsize, BPRI_HI);
2766 if (keysock_out_mp->b_cont == NULL) {
2767 rw_exit(&ipss->ipsec_alg_lock);
2768 freemsg(keysock_out_mp);
2769 return (B_FALSE);
2771 pfkey_msg_mp = keysock_out_mp->b_cont;
2772 pfkey_msg_mp->b_wptr += allocsize;
2774 nextext = (sadb_ext_t *)(pfkey_msg_mp->b_rptr + sizeof (*samsg));
2776 if (num_aalgs != 0) {
2777 sasupp_auth = (sadb_supported_t *)nextext;
2778 saalg = (sadb_alg_t *)(sasupp_auth + 1);
2780 ASSERT(((ulong_t)saalg & 0x7) == 0);
2782 numalgs_snap = 0;
2783 for (i = 0;
2784 ((i < IPSEC_MAX_ALGS) && (numalgs_snap < num_aalgs));
2785 i++) {
2786 if (authalgs[i] == NULL || !ALG_VALID(authalgs[i]))
2787 continue;
2789 saalg->sadb_alg_id = authalgs[i]->alg_id;
2790 saalg->sadb_alg_ivlen = 0;
2791 saalg->sadb_alg_minbits = authalgs[i]->alg_ef_minbits;
2792 saalg->sadb_alg_maxbits = authalgs[i]->alg_ef_maxbits;
2793 saalg->sadb_x_alg_increment =
2794 authalgs[i]->alg_increment;
2795 saalg->sadb_x_alg_saltbits = SADB_8TO1(
2796 authalgs[i]->alg_saltlen);
2797 numalgs_snap++;
2798 saalg++;
2800 ASSERT(numalgs_snap == num_aalgs);
2801 #ifdef DEBUG
2803 * Reality check to make sure I snagged all of the
2804 * algorithms.
2806 for (; i < IPSEC_MAX_ALGS; i++) {
2807 if (authalgs[i] != NULL && ALG_VALID(authalgs[i])) {
2808 cmn_err(CE_PANIC, "esp_register_out()! "
2809 "Missed aalg #%d.\n", i);
2812 #endif /* DEBUG */
2813 nextext = (sadb_ext_t *)saalg;
2816 if (num_ealgs != 0) {
2817 sasupp_encr = (sadb_supported_t *)nextext;
2818 saalg = (sadb_alg_t *)(sasupp_encr + 1);
2820 numalgs_snap = 0;
2821 for (i = 0;
2822 ((i < IPSEC_MAX_ALGS) && (numalgs_snap < num_ealgs)); i++) {
2823 if (encralgs[i] == NULL || !ALG_VALID(encralgs[i]))
2824 continue;
2825 saalg->sadb_alg_id = encralgs[i]->alg_id;
2826 saalg->sadb_alg_ivlen = encralgs[i]->alg_ivlen;
2827 saalg->sadb_alg_minbits = encralgs[i]->alg_ef_minbits;
2828 saalg->sadb_alg_maxbits = encralgs[i]->alg_ef_maxbits;
2830 * We could advertise the ICV length, except there
2831 * is not a value in sadb_x_algb to do this.
2832 * saalg->sadb_alg_maclen = encralgs[i]->alg_maclen;
2834 saalg->sadb_x_alg_increment =
2835 encralgs[i]->alg_increment;
2836 saalg->sadb_x_alg_saltbits =
2837 SADB_8TO1(encralgs[i]->alg_saltlen);
2839 numalgs_snap++;
2840 saalg++;
2842 ASSERT(numalgs_snap == num_ealgs);
2843 #ifdef DEBUG
2845 * Reality check to make sure I snagged all of the
2846 * algorithms.
2848 for (; i < IPSEC_MAX_ALGS; i++) {
2849 if (encralgs[i] != NULL && ALG_VALID(encralgs[i])) {
2850 cmn_err(CE_PANIC, "esp_register_out()! "
2851 "Missed ealg #%d.\n", i);
2854 #endif /* DEBUG */
2855 nextext = (sadb_ext_t *)saalg;
2858 current_aalgs = num_aalgs;
2859 current_ealgs = num_ealgs;
2861 rw_exit(&ipss->ipsec_alg_lock);
2863 /* Now fill the rest of the SADB_REGISTER message. */
2865 samsg = (sadb_msg_t *)pfkey_msg_mp->b_rptr;
2866 samsg->sadb_msg_version = PF_KEY_V2;
2867 samsg->sadb_msg_type = SADB_REGISTER;
2868 samsg->sadb_msg_errno = 0;
2869 samsg->sadb_msg_satype = SADB_SATYPE_ESP;
2870 samsg->sadb_msg_len = SADB_8TO64(allocsize);
2871 samsg->sadb_msg_reserved = 0;
2873 * Assume caller has sufficient sequence/pid number info. If it's one
2874 * from me over a new alg., I could give two hoots about sequence.
2876 samsg->sadb_msg_seq = sequence;
2877 samsg->sadb_msg_pid = pid;
2879 if (sasupp_auth != NULL) {
2880 sasupp_auth->sadb_supported_len = SADB_8TO64(
2881 sizeof (*sasupp_auth) + sizeof (*saalg) * current_aalgs);
2882 sasupp_auth->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
2883 sasupp_auth->sadb_supported_reserved = 0;
2886 if (sasupp_encr != NULL) {
2887 sasupp_encr->sadb_supported_len = SADB_8TO64(
2888 sizeof (*sasupp_encr) + sizeof (*saalg) * current_ealgs);
2889 sasupp_encr->sadb_supported_exttype =
2890 SADB_EXT_SUPPORTED_ENCRYPT;
2891 sasupp_encr->sadb_supported_reserved = 0;
2894 if (espstack->esp_pfkey_q != NULL)
2895 putnext(espstack->esp_pfkey_q, keysock_out_mp);
2896 else {
2897 freemsg(keysock_out_mp);
2898 return (B_FALSE);
2901 return (B_TRUE);
2905 * Invoked when the algorithm table changes. Causes SADB_REGISTER
2906 * messages continaining the current list of algorithms to be
2907 * sent up to the ESP listeners.
2909 void
2910 ipsecesp_algs_changed(netstack_t *ns)
2912 ipsecesp_stack_t *espstack = ns->netstack_ipsecesp;
2915 * Time to send a PF_KEY SADB_REGISTER message to ESP listeners
2916 * everywhere. (The function itself checks for NULL esp_pfkey_q.)
2918 (void) esp_register_out(0, 0, 0, espstack, NULL);
2922 * Stub function that taskq_dispatch() invokes to take the mblk (in arg)
2923 * and send() it into ESP and IP again.
2925 static void
2926 inbound_task(void *arg)
2928 mblk_t *mp = (mblk_t *)arg;
2929 mblk_t *async_mp;
2930 ip_recv_attr_t iras;
2932 async_mp = mp;
2933 mp = async_mp->b_cont;
2934 async_mp->b_cont = NULL;
2935 if (!ip_recv_attr_from_mblk(async_mp, &iras)) {
2936 /* The ill or ip_stack_t disappeared on us */
2937 ip_drop_input("ip_recv_attr_from_mblk", mp, NULL);
2938 freemsg(mp);
2939 goto done;
2942 esp_inbound_restart(mp, &iras);
2943 done:
2944 ira_cleanup(&iras, B_TRUE);
2948 * Restart ESP after the SA has been added.
2950 static void
2951 esp_inbound_restart(mblk_t *mp, ip_recv_attr_t *ira)
2953 esph_t *esph;
2954 netstack_t *ns = ira->ira_ill->ill_ipst->ips_netstack;
2955 ipsecesp_stack_t *espstack = ns->netstack_ipsecesp;
2957 esp2dbg(espstack, ("in ESP inbound_task"));
2958 ASSERT(espstack != NULL);
2960 mp = ipsec_inbound_esp_sa(mp, ira, &esph);
2961 if (mp == NULL)
2962 return;
2964 ASSERT(esph != NULL);
2965 ASSERT(ira->ira_flags & IRAF_IPSEC_SECURE);
2966 ASSERT(ira->ira_ipsec_esp_sa != NULL);
2968 mp = ira->ira_ipsec_esp_sa->ipsa_input_func(mp, esph, ira);
2969 if (mp == NULL) {
2971 * Either it failed or is pending. In the former case
2972 * ipIfStatsInDiscards was increased.
2974 return;
2977 ip_input_post_ipsec(mp, ira);
2981 * Now that weak-key passed, actually ADD the security association, and
2982 * send back a reply ADD message.
2984 static int
2985 esp_add_sa_finish(mblk_t *mp, sadb_msg_t *samsg, keysock_in_t *ksi,
2986 int *diagnostic, ipsecesp_stack_t *espstack)
2988 isaf_t *primary = NULL, *secondary;
2989 boolean_t clone = B_FALSE, is_inbound = B_FALSE;
2990 ipsa_t *larval = NULL;
2991 ipsacq_t *acqrec;
2992 iacqf_t *acq_bucket;
2993 mblk_t *acq_msgs = NULL;
2994 int rc;
2995 mblk_t *lpkt;
2996 int error;
2997 ipsa_query_t sq;
2998 ipsec_stack_t *ipss = espstack->ipsecesp_netstack->netstack_ipsec;
3001 * Locate the appropriate table(s).
3003 sq.spp = &espstack->esp_sadb; /* XXX */
3004 error = sadb_form_query(ksi, IPSA_Q_SA|IPSA_Q_DST,
3005 IPSA_Q_SA|IPSA_Q_DST|IPSA_Q_INBOUND|IPSA_Q_OUTBOUND,
3006 &sq, diagnostic);
3007 if (error)
3008 return (error);
3011 * Use the direction flags provided by the KMD to determine
3012 * if the inbound or outbound table should be the primary
3013 * for this SA. If these flags were absent then make this
3014 * decision based on the addresses.
3016 if (sq.assoc->sadb_sa_flags & IPSA_F_INBOUND) {
3017 primary = sq.inbound;
3018 secondary = sq.outbound;
3019 is_inbound = B_TRUE;
3020 if (sq.assoc->sadb_sa_flags & IPSA_F_OUTBOUND)
3021 clone = B_TRUE;
3022 } else if (sq.assoc->sadb_sa_flags & IPSA_F_OUTBOUND) {
3023 primary = sq.outbound;
3024 secondary = sq.inbound;
3027 if (primary == NULL) {
3029 * The KMD did not set a direction flag, determine which
3030 * table to insert the SA into based on addresses.
3032 switch (ksi->ks_in_dsttype) {
3033 case KS_IN_ADDR_MBCAST:
3034 clone = B_TRUE; /* All mcast SAs can be bidirectional */
3035 sq.assoc->sadb_sa_flags |= IPSA_F_OUTBOUND;
3036 /* FALLTHRU */
3038 * If the source address is either one of mine, or unspecified
3039 * (which is best summed up by saying "not 'not mine'"),
3040 * then the association is potentially bi-directional,
3041 * in that it can be used for inbound traffic and outbound
3042 * traffic. The best example of such an SA is a multicast
3043 * SA (which allows me to receive the outbound traffic).
3045 case KS_IN_ADDR_ME:
3046 sq.assoc->sadb_sa_flags |= IPSA_F_INBOUND;
3047 primary = sq.inbound;
3048 secondary = sq.outbound;
3049 if (ksi->ks_in_srctype != KS_IN_ADDR_NOTME)
3050 clone = B_TRUE;
3051 is_inbound = B_TRUE;
3052 break;
3054 * If the source address literally not mine (either
3055 * unspecified or not mine), then this SA may have an
3056 * address that WILL be mine after some configuration.
3057 * We pay the price for this by making it a bi-directional
3058 * SA.
3060 case KS_IN_ADDR_NOTME:
3061 sq.assoc->sadb_sa_flags |= IPSA_F_OUTBOUND;
3062 primary = sq.outbound;
3063 secondary = sq.inbound;
3064 if (ksi->ks_in_srctype != KS_IN_ADDR_ME) {
3065 sq.assoc->sadb_sa_flags |= IPSA_F_INBOUND;
3066 clone = B_TRUE;
3068 break;
3069 default:
3070 *diagnostic = SADB_X_DIAGNOSTIC_BAD_DST;
3071 return (EINVAL);
3076 * Find a ACQUIRE list entry if possible. If we've added an SA that
3077 * suits the needs of an ACQUIRE list entry, we can eliminate the
3078 * ACQUIRE list entry and transmit the enqueued packets. Use the
3079 * high-bit of the sequence number to queue it. Key off destination
3080 * addr, and change acqrec's state.
3083 if (samsg->sadb_msg_seq & IACQF_LOWEST_SEQ) {
3084 acq_bucket = &(sq.sp->sdb_acq[sq.outhash]);
3085 mutex_enter(&acq_bucket->iacqf_lock);
3086 for (acqrec = acq_bucket->iacqf_ipsacq; acqrec != NULL;
3087 acqrec = acqrec->ipsacq_next) {
3088 mutex_enter(&acqrec->ipsacq_lock);
3090 * Q: I only check sequence. Should I check dst?
3091 * A: Yes, check dest because those are the packets
3092 * that are queued up.
3094 if (acqrec->ipsacq_seq == samsg->sadb_msg_seq &&
3095 IPSA_ARE_ADDR_EQUAL(sq.dstaddr,
3096 acqrec->ipsacq_dstaddr, acqrec->ipsacq_addrfam))
3097 break;
3098 mutex_exit(&acqrec->ipsacq_lock);
3100 if (acqrec != NULL) {
3102 * AHA! I found an ACQUIRE record for this SA.
3103 * Grab the msg list, and free the acquire record.
3104 * I already am holding the lock for this record,
3105 * so all I have to do is free it.
3107 acq_msgs = acqrec->ipsacq_mp;
3108 acqrec->ipsacq_mp = NULL;
3109 mutex_exit(&acqrec->ipsacq_lock);
3110 sadb_destroy_acquire(acqrec,
3111 espstack->ipsecesp_netstack);
3113 mutex_exit(&acq_bucket->iacqf_lock);
3117 * Find PF_KEY message, and see if I'm an update. If so, find entry
3118 * in larval list (if there).
3120 if (samsg->sadb_msg_type == SADB_UPDATE) {
3121 mutex_enter(&sq.inbound->isaf_lock);
3122 larval = ipsec_getassocbyspi(sq.inbound, sq.assoc->sadb_sa_spi,
3123 ALL_ZEROES_PTR, sq.dstaddr, sq.dst->sin_family);
3124 mutex_exit(&sq.inbound->isaf_lock);
3126 if ((larval == NULL) ||
3127 (larval->ipsa_state != IPSA_STATE_LARVAL)) {
3128 *diagnostic = SADB_X_DIAGNOSTIC_SA_NOTFOUND;
3129 if (larval != NULL) {
3130 IPSA_REFRELE(larval);
3132 esp0dbg(("Larval update, but larval disappeared.\n"));
3133 return (ESRCH);
3134 } /* Else sadb_common_add unlinks it for me! */
3137 if (larval != NULL) {
3139 * Hold again, because sadb_common_add() consumes a reference,
3140 * and we don't want to clear_lpkt() without a reference.
3142 IPSA_REFHOLD(larval);
3145 rc = sadb_common_add(espstack->esp_pfkey_q,
3146 mp, samsg, ksi, primary, secondary, larval, clone, is_inbound,
3147 diagnostic, espstack->ipsecesp_netstack, &espstack->esp_sadb);
3149 if (larval != NULL) {
3150 if (rc == 0) {
3151 lpkt = sadb_clear_lpkt(larval);
3152 if (lpkt != NULL) {
3153 rc = !taskq_dispatch(esp_taskq, inbound_task,
3154 lpkt, TQ_NOSLEEP);
3157 IPSA_REFRELE(larval);
3161 * How much more stack will I create with all of these
3162 * esp_outbound() calls?
3165 /* Handle the packets queued waiting for the SA */
3166 while (acq_msgs != NULL) {
3167 mblk_t *asyncmp;
3168 mblk_t *data_mp;
3169 ip_xmit_attr_t ixas;
3170 ill_t *ill;
3172 asyncmp = acq_msgs;
3173 acq_msgs = acq_msgs->b_next;
3174 asyncmp->b_next = NULL;
3177 * Extract the ip_xmit_attr_t from the first mblk.
3178 * Verifies that the netstack and ill is still around; could
3179 * have vanished while iked was doing its work.
3180 * On succesful return we have a nce_t and the ill/ipst can't
3181 * disappear until we do the nce_refrele in ixa_cleanup.
3183 data_mp = asyncmp->b_cont;
3184 asyncmp->b_cont = NULL;
3185 if (!ip_xmit_attr_from_mblk(asyncmp, &ixas)) {
3186 ESP_BUMP_STAT(espstack, out_discards);
3187 ip_drop_packet(data_mp, B_FALSE, NULL,
3188 DROPPER(ipss, ipds_sadb_acquire_timeout),
3189 &espstack->esp_dropper);
3190 } else if (rc != 0) {
3191 ill = ixas.ixa_nce->nce_ill;
3192 ESP_BUMP_STAT(espstack, out_discards);
3193 ip_drop_packet(data_mp, B_FALSE, ill,
3194 DROPPER(ipss, ipds_sadb_acquire_timeout),
3195 &espstack->esp_dropper);
3196 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
3197 } else {
3198 esp_outbound_finish(data_mp, &ixas);
3200 ixa_cleanup(&ixas);
3203 return (rc);
3207 * Process one of the queued messages (from ipsacq_mp) once the SA
3208 * has been added.
3210 static void
3211 esp_outbound_finish(mblk_t *data_mp, ip_xmit_attr_t *ixa)
3213 netstack_t *ns = ixa->ixa_ipst->ips_netstack;
3214 ipsecesp_stack_t *espstack = ns->netstack_ipsecesp;
3215 ipsec_stack_t *ipss = ns->netstack_ipsec;
3216 ill_t *ill = ixa->ixa_nce->nce_ill;
3218 if (!ipsec_outbound_sa(data_mp, ixa, IPPROTO_ESP)) {
3219 ESP_BUMP_STAT(espstack, out_discards);
3220 ip_drop_packet(data_mp, B_FALSE, ill,
3221 DROPPER(ipss, ipds_sadb_acquire_timeout),
3222 &espstack->esp_dropper);
3223 BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
3224 return;
3227 data_mp = esp_outbound(data_mp, ixa);
3228 if (data_mp == NULL)
3229 return;
3231 /* do AH processing if needed */
3232 data_mp = esp_do_outbound_ah(data_mp, ixa);
3233 if (data_mp == NULL)
3234 return;
3236 (void) ip_output_post_ipsec(data_mp, ixa);
3240 * Add new ESP security association. This may become a generic AH/ESP
3241 * routine eventually.
3243 static int
3244 esp_add_sa(mblk_t *mp, keysock_in_t *ksi, int *diagnostic, netstack_t *ns)
3246 sadb_sa_t *assoc = (sadb_sa_t *)ksi->ks_in_extv[SADB_EXT_SA];
3247 sadb_address_t *srcext =
3248 (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_SRC];
3249 sadb_address_t *dstext =
3250 (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_DST];
3251 sadb_address_t *isrcext =
3252 (sadb_address_t *)ksi->ks_in_extv[SADB_X_EXT_ADDRESS_INNER_SRC];
3253 sadb_address_t *idstext =
3254 (sadb_address_t *)ksi->ks_in_extv[SADB_X_EXT_ADDRESS_INNER_DST];
3255 sadb_address_t *nttext_loc =
3256 (sadb_address_t *)ksi->ks_in_extv[SADB_X_EXT_ADDRESS_NATT_LOC];
3257 sadb_address_t *nttext_rem =
3258 (sadb_address_t *)ksi->ks_in_extv[SADB_X_EXT_ADDRESS_NATT_REM];
3259 sadb_key_t *akey = (sadb_key_t *)ksi->ks_in_extv[SADB_EXT_KEY_AUTH];
3260 sadb_key_t *ekey = (sadb_key_t *)ksi->ks_in_extv[SADB_EXT_KEY_ENCRYPT];
3261 struct sockaddr_in *src, *dst;
3262 struct sockaddr_in *natt_loc, *natt_rem;
3263 struct sockaddr_in6 *natt_loc6, *natt_rem6;
3264 sadb_lifetime_t *soft =
3265 (sadb_lifetime_t *)ksi->ks_in_extv[SADB_EXT_LIFETIME_SOFT];
3266 sadb_lifetime_t *hard =
3267 (sadb_lifetime_t *)ksi->ks_in_extv[SADB_EXT_LIFETIME_HARD];
3268 sadb_lifetime_t *idle =
3269 (sadb_lifetime_t *)ksi->ks_in_extv[SADB_X_EXT_LIFETIME_IDLE];
3270 ipsecesp_stack_t *espstack = ns->netstack_ipsecesp;
3271 ipsec_stack_t *ipss = ns->netstack_ipsec;
3275 /* I need certain extensions present for an ADD message. */
3276 if (srcext == NULL) {
3277 *diagnostic = SADB_X_DIAGNOSTIC_MISSING_SRC;
3278 return (EINVAL);
3280 if (dstext == NULL) {
3281 *diagnostic = SADB_X_DIAGNOSTIC_MISSING_DST;
3282 return (EINVAL);
3284 if (isrcext == NULL && idstext != NULL) {
3285 *diagnostic = SADB_X_DIAGNOSTIC_MISSING_INNER_SRC;
3286 return (EINVAL);
3288 if (isrcext != NULL && idstext == NULL) {
3289 *diagnostic = SADB_X_DIAGNOSTIC_MISSING_INNER_DST;
3290 return (EINVAL);
3292 if (assoc == NULL) {
3293 *diagnostic = SADB_X_DIAGNOSTIC_MISSING_SA;
3294 return (EINVAL);
3296 if (ekey == NULL && assoc->sadb_sa_encrypt != SADB_EALG_NULL) {
3297 *diagnostic = SADB_X_DIAGNOSTIC_MISSING_EKEY;
3298 return (EINVAL);
3301 src = (struct sockaddr_in *)(srcext + 1);
3302 dst = (struct sockaddr_in *)(dstext + 1);
3303 natt_loc = (struct sockaddr_in *)(nttext_loc + 1);
3304 natt_loc6 = (struct sockaddr_in6 *)(nttext_loc + 1);
3305 natt_rem = (struct sockaddr_in *)(nttext_rem + 1);
3306 natt_rem6 = (struct sockaddr_in6 *)(nttext_rem + 1);
3308 /* Sundry ADD-specific reality checks. */
3309 /* XXX STATS : Logging/stats here? */
3311 if ((assoc->sadb_sa_state != SADB_SASTATE_MATURE) &&
3312 (assoc->sadb_sa_state != SADB_X_SASTATE_ACTIVE_ELSEWHERE)) {
3313 *diagnostic = SADB_X_DIAGNOSTIC_BAD_SASTATE;
3314 return (EINVAL);
3316 if (assoc->sadb_sa_encrypt == SADB_EALG_NONE) {
3317 *diagnostic = SADB_X_DIAGNOSTIC_BAD_EALG;
3318 return (EINVAL);
3321 #ifndef IPSEC_LATENCY_TEST
3322 if (assoc->sadb_sa_encrypt == SADB_EALG_NULL &&
3323 assoc->sadb_sa_auth == SADB_AALG_NONE) {
3324 *diagnostic = SADB_X_DIAGNOSTIC_BAD_AALG;
3325 return (EINVAL);
3327 #endif
3329 if (assoc->sadb_sa_flags & ~espstack->esp_sadb.s_addflags) {
3330 *diagnostic = SADB_X_DIAGNOSTIC_BAD_SAFLAGS;
3331 return (EINVAL);
3334 if ((*diagnostic = sadb_hardsoftchk(hard, soft, idle)) != 0) {
3335 return (EINVAL);
3337 ASSERT(src->sin_family == dst->sin_family);
3339 if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_NATT_LOC) {
3340 if (nttext_loc == NULL) {
3341 *diagnostic = SADB_X_DIAGNOSTIC_MISSING_NATT_LOC;
3342 return (EINVAL);
3345 if (natt_loc->sin_family == AF_INET6 &&
3346 !IN6_IS_ADDR_V4MAPPED(&natt_loc6->sin6_addr)) {
3347 *diagnostic = SADB_X_DIAGNOSTIC_MALFORMED_NATT_LOC;
3348 return (EINVAL);
3352 if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_NATT_REM) {
3353 if (nttext_rem == NULL) {
3354 *diagnostic = SADB_X_DIAGNOSTIC_MISSING_NATT_REM;
3355 return (EINVAL);
3357 if (natt_rem->sin_family == AF_INET6 &&
3358 !IN6_IS_ADDR_V4MAPPED(&natt_rem6->sin6_addr)) {
3359 *diagnostic = SADB_X_DIAGNOSTIC_MALFORMED_NATT_REM;
3360 return (EINVAL);
3365 /* Stuff I don't support, for now. XXX Diagnostic? */
3366 if (ksi->ks_in_extv[SADB_EXT_LIFETIME_CURRENT] != NULL)
3367 return (EOPNOTSUPP);
3370 * XXX Policy : I'm not checking identities at this time,
3371 * but if I did, I'd do them here, before I sent
3372 * the weak key check up to the algorithm.
3375 rw_enter(&ipss->ipsec_alg_lock, RW_READER);
3378 * First locate the authentication algorithm.
3380 #ifdef IPSEC_LATENCY_TEST
3381 if (akey != NULL && assoc->sadb_sa_auth != SADB_AALG_NONE) {
3382 #else
3383 if (akey != NULL) {
3384 #endif
3385 ipsec_alginfo_t *aalg;
3387 aalg = ipss->ipsec_alglists[IPSEC_ALG_AUTH]
3388 [assoc->sadb_sa_auth];
3389 if (aalg == NULL || !ALG_VALID(aalg)) {
3390 rw_exit(&ipss->ipsec_alg_lock);
3391 esp1dbg(espstack, ("Couldn't find auth alg #%d.\n",
3392 assoc->sadb_sa_auth));
3393 *diagnostic = SADB_X_DIAGNOSTIC_BAD_AALG;
3394 return (EINVAL);
3398 * Sanity check key sizes.
3399 * Note: It's not possible to use SADB_AALG_NONE because
3400 * this auth_alg is not defined with ALG_FLAG_VALID. If this
3401 * ever changes, the same check for SADB_AALG_NONE and
3402 * a auth_key != NULL should be made here ( see below).
3404 if (!ipsec_valid_key_size(akey->sadb_key_bits, aalg)) {
3405 rw_exit(&ipss->ipsec_alg_lock);
3406 *diagnostic = SADB_X_DIAGNOSTIC_BAD_AKEYBITS;
3407 return (EINVAL);
3409 ASSERT(aalg->alg_mech_type != CRYPTO_MECHANISM_INVALID);
3411 /* check key and fix parity if needed */
3412 if (ipsec_check_key(aalg->alg_mech_type, akey, B_TRUE,
3413 diagnostic) != 0) {
3414 rw_exit(&ipss->ipsec_alg_lock);
3415 return (EINVAL);
3420 * Then locate the encryption algorithm.
3422 if (ekey != NULL) {
3423 uint_t keybits;
3424 ipsec_alginfo_t *ealg;
3426 ealg = ipss->ipsec_alglists[IPSEC_ALG_ENCR]
3427 [assoc->sadb_sa_encrypt];
3428 if (ealg == NULL || !ALG_VALID(ealg)) {
3429 rw_exit(&ipss->ipsec_alg_lock);
3430 esp1dbg(espstack, ("Couldn't find encr alg #%d.\n",
3431 assoc->sadb_sa_encrypt));
3432 *diagnostic = SADB_X_DIAGNOSTIC_BAD_EALG;
3433 return (EINVAL);
3437 * Sanity check key sizes. If the encryption algorithm is
3438 * SADB_EALG_NULL but the encryption key is NOT
3439 * NULL then complain.
3441 * The keying material includes salt bits if required by
3442 * algorithm and optionally the Initial IV, check the
3443 * length of whats left.
3445 keybits = ekey->sadb_key_bits;
3446 keybits -= ekey->sadb_key_reserved;
3447 keybits -= SADB_8TO1(ealg->alg_saltlen);
3448 if ((assoc->sadb_sa_encrypt == SADB_EALG_NULL) ||
3449 (!ipsec_valid_key_size(keybits, ealg))) {
3450 rw_exit(&ipss->ipsec_alg_lock);
3451 *diagnostic = SADB_X_DIAGNOSTIC_BAD_EKEYBITS;
3452 return (EINVAL);
3454 ASSERT(ealg->alg_mech_type != CRYPTO_MECHANISM_INVALID);
3456 /* check key */
3457 if (ipsec_check_key(ealg->alg_mech_type, ekey, B_FALSE,
3458 diagnostic) != 0) {
3459 rw_exit(&ipss->ipsec_alg_lock);
3460 return (EINVAL);
3463 rw_exit(&ipss->ipsec_alg_lock);
3465 return (esp_add_sa_finish(mp, (sadb_msg_t *)mp->b_cont->b_rptr, ksi,
3466 diagnostic, espstack));
3470 * Update a security association. Updates come in two varieties. The first
3471 * is an update of lifetimes on a non-larval SA. The second is an update of
3472 * a larval SA, which ends up looking a lot more like an add.
3474 static int
3475 esp_update_sa(mblk_t *mp, keysock_in_t *ksi, int *diagnostic,
3476 ipsecesp_stack_t *espstack, uint8_t sadb_msg_type)
3478 sadb_sa_t *assoc = (sadb_sa_t *)ksi->ks_in_extv[SADB_EXT_SA];
3479 mblk_t *buf_pkt;
3480 int rcode;
3482 sadb_address_t *dstext =
3483 (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_DST];
3485 if (dstext == NULL) {
3486 *diagnostic = SADB_X_DIAGNOSTIC_MISSING_DST;
3487 return (EINVAL);
3490 rcode = sadb_update_sa(mp, ksi, &buf_pkt, &espstack->esp_sadb,
3491 diagnostic, espstack->esp_pfkey_q, esp_add_sa,
3492 espstack->ipsecesp_netstack, sadb_msg_type);
3494 if ((assoc->sadb_sa_state != SADB_X_SASTATE_ACTIVE) ||
3495 (rcode != 0)) {
3496 return (rcode);
3499 HANDLE_BUF_PKT(esp_taskq, espstack->ipsecesp_netstack->netstack_ipsec,
3500 espstack->esp_dropper, buf_pkt);
3502 return (rcode);
3505 /* XXX refactor me */
3507 * Delete a security association. This is REALLY likely to be code common to
3508 * both AH and ESP. Find the association, then unlink it.
3510 static int
3511 esp_del_sa(mblk_t *mp, keysock_in_t *ksi, int *diagnostic,
3512 ipsecesp_stack_t *espstack, uint8_t sadb_msg_type)
3514 sadb_sa_t *assoc = (sadb_sa_t *)ksi->ks_in_extv[SADB_EXT_SA];
3515 sadb_address_t *dstext =
3516 (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_DST];
3517 sadb_address_t *srcext =
3518 (sadb_address_t *)ksi->ks_in_extv[SADB_EXT_ADDRESS_SRC];
3519 struct sockaddr_in *sin;
3521 if (assoc == NULL) {
3522 if (dstext != NULL) {
3523 sin = (struct sockaddr_in *)(dstext + 1);
3524 } else if (srcext != NULL) {
3525 sin = (struct sockaddr_in *)(srcext + 1);
3526 } else {
3527 *diagnostic = SADB_X_DIAGNOSTIC_MISSING_SA;
3528 return (EINVAL);
3530 return (sadb_purge_sa(mp, ksi,
3531 (sin->sin_family == AF_INET6) ? &espstack->esp_sadb.s_v6 :
3532 &espstack->esp_sadb.s_v4, diagnostic,
3533 espstack->esp_pfkey_q));
3536 return (sadb_delget_sa(mp, ksi, &espstack->esp_sadb, diagnostic,
3537 espstack->esp_pfkey_q, sadb_msg_type));
3540 /* XXX refactor me */
3542 * Convert the entire contents of all of ESP's SA tables into PF_KEY SADB_DUMP
3543 * messages.
3545 static void
3546 esp_dump(mblk_t *mp, keysock_in_t *ksi, ipsecesp_stack_t *espstack)
3548 int error;
3549 sadb_msg_t *samsg;
3552 * Dump each fanout, bailing if error is non-zero.
3555 error = sadb_dump(espstack->esp_pfkey_q, mp, ksi,
3556 &espstack->esp_sadb.s_v4);
3557 if (error != 0)
3558 goto bail;
3560 error = sadb_dump(espstack->esp_pfkey_q, mp, ksi,
3561 &espstack->esp_sadb.s_v6);
3562 bail:
3563 ASSERT(mp->b_cont != NULL);
3564 samsg = (sadb_msg_t *)mp->b_cont->b_rptr;
3565 samsg->sadb_msg_errno = (uint8_t)error;
3566 sadb_pfkey_echo(espstack->esp_pfkey_q, mp,
3567 (sadb_msg_t *)mp->b_cont->b_rptr, ksi, NULL);
3571 * First-cut reality check for an inbound PF_KEY message.
3573 static boolean_t
3574 esp_pfkey_reality_failures(mblk_t *mp, keysock_in_t *ksi,
3575 ipsecesp_stack_t *espstack)
3577 int diagnostic;
3579 if (ksi->ks_in_extv[SADB_EXT_PROPOSAL] != NULL) {
3580 diagnostic = SADB_X_DIAGNOSTIC_PROP_PRESENT;
3581 goto badmsg;
3583 if (ksi->ks_in_extv[SADB_EXT_SUPPORTED_AUTH] != NULL ||
3584 ksi->ks_in_extv[SADB_EXT_SUPPORTED_ENCRYPT] != NULL) {
3585 diagnostic = SADB_X_DIAGNOSTIC_SUPP_PRESENT;
3586 goto badmsg;
3588 return (B_FALSE); /* False ==> no failures */
3590 badmsg:
3591 sadb_pfkey_error(espstack->esp_pfkey_q, mp, EINVAL, diagnostic,
3592 ksi->ks_in_serial);
3593 return (B_TRUE); /* True ==> failures */
3597 * ESP parsing of PF_KEY messages. Keysock did most of the really silly
3598 * error cases. What I receive is a fully-formed, syntactically legal
3599 * PF_KEY message. I then need to check semantics...
3601 * This code may become common to AH and ESP. Stay tuned.
3603 * I also make the assumption that db_ref's are cool. If this assumption
3604 * is wrong, this means that someone other than keysock or me has been
3605 * mucking with PF_KEY messages.
3607 static void
3608 esp_parse_pfkey(mblk_t *mp, ipsecesp_stack_t *espstack)
3610 mblk_t *msg = mp->b_cont;
3611 sadb_msg_t *samsg;
3612 keysock_in_t *ksi;
3613 int error;
3614 int diagnostic = SADB_X_DIAGNOSTIC_NONE;
3616 ASSERT(msg != NULL);
3618 samsg = (sadb_msg_t *)msg->b_rptr;
3619 ksi = (keysock_in_t *)mp->b_rptr;
3622 * If applicable, convert unspecified AF_INET6 to unspecified
3623 * AF_INET. And do other address reality checks.
3625 if (!sadb_addrfix(ksi, espstack->esp_pfkey_q, mp,
3626 espstack->ipsecesp_netstack) ||
3627 esp_pfkey_reality_failures(mp, ksi, espstack)) {
3628 return;
3631 switch (samsg->sadb_msg_type) {
3632 case SADB_ADD:
3633 error = esp_add_sa(mp, ksi, &diagnostic,
3634 espstack->ipsecesp_netstack);
3635 if (error != 0) {
3636 sadb_pfkey_error(espstack->esp_pfkey_q, mp, error,
3637 diagnostic, ksi->ks_in_serial);
3639 /* else esp_add_sa() took care of things. */
3640 break;
3641 case SADB_DELETE:
3642 case SADB_X_DELPAIR:
3643 case SADB_X_DELPAIR_STATE:
3644 error = esp_del_sa(mp, ksi, &diagnostic, espstack,
3645 samsg->sadb_msg_type);
3646 if (error != 0) {
3647 sadb_pfkey_error(espstack->esp_pfkey_q, mp, error,
3648 diagnostic, ksi->ks_in_serial);
3650 /* Else esp_del_sa() took care of things. */
3651 break;
3652 case SADB_GET:
3653 error = sadb_delget_sa(mp, ksi, &espstack->esp_sadb,
3654 &diagnostic, espstack->esp_pfkey_q, samsg->sadb_msg_type);
3655 if (error != 0) {
3656 sadb_pfkey_error(espstack->esp_pfkey_q, mp, error,
3657 diagnostic, ksi->ks_in_serial);
3659 /* Else sadb_get_sa() took care of things. */
3660 break;
3661 case SADB_FLUSH:
3662 sadbp_flush(&espstack->esp_sadb, espstack->ipsecesp_netstack);
3663 sadb_pfkey_echo(espstack->esp_pfkey_q, mp, samsg, ksi, NULL);
3664 break;
3665 case SADB_REGISTER:
3667 * Hmmm, let's do it! Check for extensions (there should
3668 * be none), extract the fields, call esp_register_out(),
3669 * then either free or report an error.
3671 * Keysock takes care of the PF_KEY bookkeeping for this.
3673 if (esp_register_out(samsg->sadb_msg_seq, samsg->sadb_msg_pid,
3674 ksi->ks_in_serial, espstack, msg_getcred(mp, NULL))) {
3675 freemsg(mp);
3676 } else {
3678 * Only way this path hits is if there is a memory
3679 * failure. It will not return B_FALSE because of
3680 * lack of esp_pfkey_q if I am in wput().
3682 sadb_pfkey_error(espstack->esp_pfkey_q, mp, ENOMEM,
3683 diagnostic, ksi->ks_in_serial);
3685 break;
3686 case SADB_UPDATE:
3687 case SADB_X_UPDATEPAIR:
3689 * Find a larval, if not there, find a full one and get
3690 * strict.
3692 error = esp_update_sa(mp, ksi, &diagnostic, espstack,
3693 samsg->sadb_msg_type);
3694 if (error != 0) {
3695 sadb_pfkey_error(espstack->esp_pfkey_q, mp, error,
3696 diagnostic, ksi->ks_in_serial);
3698 /* else esp_update_sa() took care of things. */
3699 break;
3700 case SADB_GETSPI:
3702 * Reserve a new larval entry.
3704 esp_getspi(mp, ksi, espstack);
3705 break;
3706 case SADB_ACQUIRE:
3708 * Find larval and/or ACQUIRE record and kill it (them), I'm
3709 * most likely an error. Inbound ACQUIRE messages should only
3710 * have the base header.
3712 sadb_in_acquire(samsg, &espstack->esp_sadb,
3713 espstack->esp_pfkey_q, espstack->ipsecesp_netstack);
3714 freemsg(mp);
3715 break;
3716 case SADB_DUMP:
3718 * Dump all entries.
3720 esp_dump(mp, ksi, espstack);
3721 /* esp_dump will take care of the return message, etc. */
3722 break;
3723 case SADB_EXPIRE:
3724 /* Should never reach me. */
3725 sadb_pfkey_error(espstack->esp_pfkey_q, mp, EOPNOTSUPP,
3726 diagnostic, ksi->ks_in_serial);
3727 break;
3728 default:
3729 sadb_pfkey_error(espstack->esp_pfkey_q, mp, EINVAL,
3730 SADB_X_DIAGNOSTIC_UNKNOWN_MSG, ksi->ks_in_serial);
3731 break;
3736 * Handle case where PF_KEY says it can't find a keysock for one of my
3737 * ACQUIRE messages.
3739 static void
3740 esp_keysock_no_socket(mblk_t *mp, ipsecesp_stack_t *espstack)
3742 sadb_msg_t *samsg;
3743 keysock_out_err_t *kse = (keysock_out_err_t *)mp->b_rptr;
3745 if (mp->b_cont == NULL) {
3746 freemsg(mp);
3747 return;
3749 samsg = (sadb_msg_t *)mp->b_cont->b_rptr;
3752 * If keysock can't find any registered, delete the acquire record
3753 * immediately, and handle errors.
3755 if (samsg->sadb_msg_type == SADB_ACQUIRE) {
3756 samsg->sadb_msg_errno = kse->ks_err_errno;
3757 samsg->sadb_msg_len = SADB_8TO64(sizeof (*samsg));
3759 * Use the write-side of the esp_pfkey_q
3761 sadb_in_acquire(samsg, &espstack->esp_sadb,
3762 WR(espstack->esp_pfkey_q), espstack->ipsecesp_netstack);
3765 freemsg(mp);
3769 * ESP module write put routine.
3771 static void
3772 ipsecesp_wput(queue_t *q, mblk_t *mp)
3774 ipsec_info_t *ii;
3775 struct iocblk *iocp;
3776 ipsecesp_stack_t *espstack = (ipsecesp_stack_t *)q->q_ptr;
3778 esp3dbg(espstack, ("In esp_wput().\n"));
3780 /* NOTE: Each case must take care of freeing or passing mp. */
3781 switch (mp->b_datap->db_type) {
3782 case M_CTL:
3783 if ((mp->b_wptr - mp->b_rptr) < sizeof (ipsec_info_t)) {
3784 /* Not big enough message. */
3785 freemsg(mp);
3786 break;
3788 ii = (ipsec_info_t *)mp->b_rptr;
3790 switch (ii->ipsec_info_type) {
3791 case KEYSOCK_OUT_ERR:
3792 esp1dbg(espstack, ("Got KEYSOCK_OUT_ERR message.\n"));
3793 esp_keysock_no_socket(mp, espstack);
3794 break;
3795 case KEYSOCK_IN:
3796 ESP_BUMP_STAT(espstack, keysock_in);
3797 esp3dbg(espstack, ("Got KEYSOCK_IN message.\n"));
3799 /* Parse the message. */
3800 esp_parse_pfkey(mp, espstack);
3801 break;
3802 case KEYSOCK_HELLO:
3803 sadb_keysock_hello(&espstack->esp_pfkey_q, q, mp,
3804 esp_ager, (void *)espstack, &espstack->esp_event,
3805 SADB_SATYPE_ESP);
3806 break;
3807 default:
3808 esp2dbg(espstack, ("Got M_CTL from above of 0x%x.\n",
3809 ii->ipsec_info_type));
3810 freemsg(mp);
3811 break;
3813 break;
3814 case M_IOCTL:
3815 iocp = (struct iocblk *)mp->b_rptr;
3816 switch (iocp->ioc_cmd) {
3817 case ND_SET:
3818 case ND_GET:
3819 if (nd_getset(q, espstack->ipsecesp_g_nd, mp)) {
3820 qreply(q, mp);
3821 return;
3822 } else {
3823 iocp->ioc_error = ENOENT;
3825 /* FALLTHRU */
3826 default:
3827 /* We really don't support any other ioctls, do we? */
3829 /* Return EINVAL */
3830 if (iocp->ioc_error != ENOENT)
3831 iocp->ioc_error = EINVAL;
3832 iocp->ioc_count = 0;
3833 mp->b_datap->db_type = M_IOCACK;
3834 qreply(q, mp);
3835 return;
3837 default:
3838 esp3dbg(espstack,
3839 ("Got default message, type %d, passing to IP.\n",
3840 mp->b_datap->db_type));
3841 putnext(q, mp);
3846 * Wrapper to allow IP to trigger an ESP association failure message
3847 * during inbound SA selection.
3849 void
3850 ipsecesp_in_assocfailure(mblk_t *mp, char level, ushort_t sl, char *fmt,
3851 uint32_t spi, void *addr, int af, ip_recv_attr_t *ira)
3853 netstack_t *ns = ira->ira_ill->ill_ipst->ips_netstack;
3854 ipsecesp_stack_t *espstack = ns->netstack_ipsecesp;
3855 ipsec_stack_t *ipss = ns->netstack_ipsec;
3857 if (espstack->ipsecesp_log_unknown_spi) {
3858 ipsec_assocfailure(info.mi_idnum, 0, level, sl, fmt, spi,
3859 addr, af, espstack->ipsecesp_netstack);
3862 ip_drop_packet(mp, B_TRUE, ira->ira_ill,
3863 DROPPER(ipss, ipds_esp_no_sa),
3864 &espstack->esp_dropper);
3868 * Initialize the ESP input and output processing functions.
3870 void
3871 ipsecesp_init_funcs(ipsa_t *sa)
3873 if (sa->ipsa_output_func == NULL)
3874 sa->ipsa_output_func = esp_outbound;
3875 if (sa->ipsa_input_func == NULL)
3876 sa->ipsa_input_func = esp_inbound;