]> git.saurik.com Git - apple/xnu.git/blob - bsd/netkey/key.c
d1d59cd6fb56a6d00cd3e0b00b62fae42cb50969
[apple/xnu.git] / bsd / netkey / key.c
1 /*
2 * Copyright (c) 2008-2011 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28
29 /* $FreeBSD: src/sys/netkey/key.c,v 1.16.2.13 2002/07/24 18:17:40 ume Exp $ */
30 /* $KAME: key.c,v 1.191 2001/06/27 10:46:49 sakane Exp $ */
31
32 /*
33 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
34 * All rights reserved.
35 *
36 * Redistribution and use in source and binary forms, with or without
37 * modification, are permitted provided that the following conditions
38 * are met:
39 * 1. Redistributions of source code must retain the above copyright
40 * notice, this list of conditions and the following disclaimer.
41 * 2. Redistributions in binary form must reproduce the above copyright
42 * notice, this list of conditions and the following disclaimer in the
43 * documentation and/or other materials provided with the distribution.
44 * 3. Neither the name of the project nor the names of its contributors
45 * may be used to endorse or promote products derived from this software
46 * without specific prior written permission.
47 *
48 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
49 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
52 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58 * SUCH DAMAGE.
59 */
60
61 /*
62 * This code is referd to RFC 2367
63 */
64
65 #include <machine/endian.h>
66 #include <sys/types.h>
67 #include <sys/param.h>
68 #include <sys/systm.h>
69 #include <sys/kernel.h>
70 #include <sys/mbuf.h>
71 #include <sys/domain.h>
72 #include <sys/protosw.h>
73 #include <sys/malloc.h>
74 #include <sys/socket.h>
75 #include <sys/socketvar.h>
76 #include <sys/sysctl.h>
77 #include <sys/errno.h>
78 #include <sys/proc.h>
79 #include <sys/queue.h>
80 #include <sys/syslog.h>
81 #include <sys/mcache.h>
82
83 #include <kern/locks.h>
84
85 #include <net/if.h>
86 #include <net/route.h>
87 #include <net/raw_cb.h>
88
89 #include <netinet/in.h>
90 #include <netinet/in_systm.h>
91 #include <netinet/ip.h>
92 #include <netinet/in_var.h>
93
94 #if INET6
95 #include <netinet/ip6.h>
96 #include <netinet6/in6_var.h>
97 #include <netinet6/ip6_var.h>
98 #endif /* INET6 */
99
100 #if INET
101 #include <netinet/in_pcb.h>
102 #endif
103 #if INET6
104 #include <netinet6/in6_pcb.h>
105 #endif /* INET6 */
106
107 #include <net/pfkeyv2.h>
108 #include <netkey/keydb.h>
109 #include <netkey/key.h>
110 #include <netkey/keysock.h>
111 #include <netkey/key_debug.h>
112 #include <stdarg.h>
113
114
115 #include <netinet6/ipsec.h>
116 #if INET6
117 #include <netinet6/ipsec6.h>
118 #endif
119 #include <netinet6/ah.h>
120 #if INET6
121 #include <netinet6/ah6.h>
122 #endif
123 #if IPSEC_ESP
124 #include <netinet6/esp.h>
125 #if INET6
126 #include <netinet6/esp6.h>
127 #endif
128 #endif
129 #include <netinet6/ipcomp.h>
130 #if INET6
131 #include <netinet6/ipcomp6.h>
132 #endif
133
134
135 /* randomness */
136 #include <sys/random.h>
137
138 #include <net/net_osdep.h>
139
140 #define FULLMASK 0xff
141
142 lck_grp_t *sadb_mutex_grp;
143 lck_grp_attr_t *sadb_mutex_grp_attr;
144 lck_attr_t *sadb_mutex_attr;
145 decl_lck_mtx_data(, sadb_mutex_data);
146 lck_mtx_t *sadb_mutex = &sadb_mutex_data;
147
148 lck_grp_t *pfkey_stat_mutex_grp;
149 lck_grp_attr_t *pfkey_stat_mutex_grp_attr;
150 lck_attr_t *pfkey_stat_mutex_attr;
151 decl_lck_mtx_data(, pfkey_stat_mutex_data);
152 lck_mtx_t *pfkey_stat_mutex = &pfkey_stat_mutex_data;
153
154 /*
155 * Note on SA reference counting:
156 * - SAs that are not in DEAD state will have (total external reference + 1)
157 * following value in reference count field. they cannot be freed and are
158 * referenced from SA header.
159 * - SAs that are in DEAD state will have (total external reference)
160 * in reference count field. they are ready to be freed. reference from
161 * SA header will be removed in key_delsav(), when the reference count
162 * field hits 0 (= no external reference other than from SA header.
163 */
164
165 u_int32_t key_debug_level = 0; //### our sysctl is not dynamic
166 static u_int key_spi_trycnt = 1000;
167 static u_int32_t key_spi_minval = 0x100;
168 static u_int32_t key_spi_maxval = 0x0fffffff; /* XXX */
169 static u_int32_t policy_id = 0;
170 static u_int key_int_random = 60; /*interval to initialize randseed,1(m)*/
171 static u_int key_larval_lifetime = 30; /* interval to expire acquiring, 30(s)*/
172 static int key_blockacq_count = 10; /* counter for blocking SADB_ACQUIRE.*/
173 static int key_blockacq_lifetime = 20; /* lifetime for blocking SADB_ACQUIRE.*/
174 static int key_preferred_oldsa = 0; /* preferred old sa rather than new sa.*/
175 __private_extern__ int natt_keepalive_interval = 20; /* interval between natt keepalives.*/
176 __private_extern__ int ipsec_policy_count = 0;
177 static int ipsec_sav_count = 0;
178
179 static u_int32_t acq_seq = 0;
180 static int key_tick_init_random = 0;
181 __private_extern__ u_int32_t natt_now = 0;
182
183 static LIST_HEAD(_sptree, secpolicy) sptree[IPSEC_DIR_MAX]; /* SPD */
184 static LIST_HEAD(_sahtree, secashead) sahtree; /* SAD */
185 static LIST_HEAD(_regtree, secreg) regtree[SADB_SATYPE_MAX + 1];
186 /* registed list */
187
188 #define SPIHASHSIZE 128
189 #define SPIHASH(x) (((x) ^ ((x) >> 16)) % SPIHASHSIZE)
190 static LIST_HEAD(_spihash, secasvar) spihash[SPIHASHSIZE];
191
192 #ifndef IPSEC_NONBLOCK_ACQUIRE
193 static LIST_HEAD(_acqtree, secacq) acqtree; /* acquiring list */
194 #endif
195 static LIST_HEAD(_spacqtree, secspacq) spacqtree; /* SP acquiring list */
196
197 struct key_cb key_cb;
198
199 /* search order for SAs */
200 static const u_int saorder_state_valid_prefer_old[] = {
201 SADB_SASTATE_DYING, SADB_SASTATE_MATURE,
202 };
203 static const u_int saorder_state_valid_prefer_new[] = {
204 SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
205 };
206 static const u_int saorder_state_alive[] = {
207 /* except DEAD */
208 SADB_SASTATE_MATURE, SADB_SASTATE_DYING, SADB_SASTATE_LARVAL
209 };
210 static const u_int saorder_state_any[] = {
211 SADB_SASTATE_MATURE, SADB_SASTATE_DYING,
212 SADB_SASTATE_LARVAL, SADB_SASTATE_DEAD
213 };
214
215 static const int minsize[] = {
216 sizeof(struct sadb_msg), /* SADB_EXT_RESERVED */
217 sizeof(struct sadb_sa), /* SADB_EXT_SA */
218 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_CURRENT */
219 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_HARD */
220 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_SOFT */
221 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_SRC */
222 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_DST */
223 sizeof(struct sadb_address), /* SADB_EXT_ADDRESS_PROXY */
224 sizeof(struct sadb_key), /* SADB_EXT_KEY_AUTH */
225 sizeof(struct sadb_key), /* SADB_EXT_KEY_ENCRYPT */
226 sizeof(struct sadb_ident), /* SADB_EXT_IDENTITY_SRC */
227 sizeof(struct sadb_ident), /* SADB_EXT_IDENTITY_DST */
228 sizeof(struct sadb_sens), /* SADB_EXT_SENSITIVITY */
229 sizeof(struct sadb_prop), /* SADB_EXT_PROPOSAL */
230 sizeof(struct sadb_supported), /* SADB_EXT_SUPPORTED_AUTH */
231 sizeof(struct sadb_supported), /* SADB_EXT_SUPPORTED_ENCRYPT */
232 sizeof(struct sadb_spirange), /* SADB_EXT_SPIRANGE */
233 0, /* SADB_X_EXT_KMPRIVATE */
234 sizeof(struct sadb_x_policy), /* SADB_X_EXT_POLICY */
235 sizeof(struct sadb_x_sa2), /* SADB_X_SA2 */
236 sizeof(struct sadb_session_id), /* SADB_EXT_SESSION_ID */
237 sizeof(struct sadb_sastat), /* SADB_EXT_SASTAT */
238 };
239 static const int maxsize[] = {
240 sizeof(struct sadb_msg), /* SADB_EXT_RESERVED */
241 sizeof(struct sadb_sa_2), /* SADB_EXT_SA */
242 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_CURRENT */
243 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_HARD */
244 sizeof(struct sadb_lifetime), /* SADB_EXT_LIFETIME_SOFT */
245 0, /* SADB_EXT_ADDRESS_SRC */
246 0, /* SADB_EXT_ADDRESS_DST */
247 0, /* SADB_EXT_ADDRESS_PROXY */
248 0, /* SADB_EXT_KEY_AUTH */
249 0, /* SADB_EXT_KEY_ENCRYPT */
250 0, /* SADB_EXT_IDENTITY_SRC */
251 0, /* SADB_EXT_IDENTITY_DST */
252 0, /* SADB_EXT_SENSITIVITY */
253 0, /* SADB_EXT_PROPOSAL */
254 0, /* SADB_EXT_SUPPORTED_AUTH */
255 0, /* SADB_EXT_SUPPORTED_ENCRYPT */
256 sizeof(struct sadb_spirange), /* SADB_EXT_SPIRANGE */
257 0, /* SADB_X_EXT_KMPRIVATE */
258 0, /* SADB_X_EXT_POLICY */
259 sizeof(struct sadb_x_sa2), /* SADB_X_SA2 */
260 0, /* SADB_EXT_SESSION_ID */
261 0, /* SADB_EXT_SASTAT */
262 };
263
264 static int ipsec_esp_keymin = 256;
265 static int ipsec_esp_auth = 0;
266 static int ipsec_ah_keymin = 128;
267
268 SYSCTL_DECL(_net_key);
269 /* Thread safe: no accumulated state */
270 SYSCTL_INT(_net_key, KEYCTL_DEBUG_LEVEL, debug, CTLFLAG_RW | CTLFLAG_LOCKED, \
271 &key_debug_level, 0, "");
272
273
274 /* max count of trial for the decision of spi value */
275 SYSCTL_INT(_net_key, KEYCTL_SPI_TRY, spi_trycnt, CTLFLAG_RW | CTLFLAG_LOCKED, \
276 &key_spi_trycnt, 0, "");
277
278 /* minimum spi value to allocate automatically. */
279 SYSCTL_INT(_net_key, KEYCTL_SPI_MIN_VALUE, spi_minval, CTLFLAG_RW | CTLFLAG_LOCKED, \
280 &key_spi_minval, 0, "");
281
282 /* maximun spi value to allocate automatically. */
283 SYSCTL_INT(_net_key, KEYCTL_SPI_MAX_VALUE, spi_maxval, CTLFLAG_RW | CTLFLAG_LOCKED, \
284 &key_spi_maxval, 0, "");
285
286 /* interval to initialize randseed */
287 SYSCTL_INT(_net_key, KEYCTL_RANDOM_INT, int_random, CTLFLAG_RW | CTLFLAG_LOCKED, \
288 &key_int_random, 0, "");
289
290 /* lifetime for larval SA; thread safe due to > compare */
291 SYSCTL_INT(_net_key, KEYCTL_LARVAL_LIFETIME, larval_lifetime, CTLFLAG_RW | CTLFLAG_LOCKED, \
292 &key_larval_lifetime, 0, "");
293
294 /* counter for blocking to send SADB_ACQUIRE to IKEd */
295 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_COUNT, blockacq_count, CTLFLAG_RW | CTLFLAG_LOCKED, \
296 &key_blockacq_count, 0, "");
297
298 /* lifetime for blocking to send SADB_ACQUIRE to IKEd: Thread safe, > compare */
299 SYSCTL_INT(_net_key, KEYCTL_BLOCKACQ_LIFETIME, blockacq_lifetime, CTLFLAG_RW | CTLFLAG_LOCKED, \
300 &key_blockacq_lifetime, 0, "");
301
302 /* ESP auth */
303 SYSCTL_INT(_net_key, KEYCTL_ESP_AUTH, esp_auth, CTLFLAG_RW | CTLFLAG_LOCKED, \
304 &ipsec_esp_auth, 0, "");
305
306 /* minimum ESP key length */
307 SYSCTL_INT(_net_key, KEYCTL_ESP_KEYMIN, esp_keymin, CTLFLAG_RW | CTLFLAG_LOCKED, \
308 &ipsec_esp_keymin, 0, "");
309
310 /* minimum AH key length */
311 SYSCTL_INT(_net_key, KEYCTL_AH_KEYMIN, ah_keymin, CTLFLAG_RW | CTLFLAG_LOCKED, \
312 &ipsec_ah_keymin, 0, "");
313
314 /* perfered old SA rather than new SA */
315 SYSCTL_INT(_net_key, KEYCTL_PREFERED_OLDSA, prefered_oldsa, CTLFLAG_RW | CTLFLAG_LOCKED,\
316 &key_preferred_oldsa, 0, "");
317
318 /* time between NATT keepalives in seconds, 0 disabled */
319 SYSCTL_INT(_net_key, KEYCTL_NATT_KEEPALIVE_INTERVAL, natt_keepalive_interval, CTLFLAG_RW | CTLFLAG_LOCKED,\
320 &natt_keepalive_interval, 0, "");
321
322 /* PF_KEY statistics */
323 SYSCTL_STRUCT(_net_key, KEYCTL_PFKEYSTAT, pfkeystat, CTLFLAG_RD | CTLFLAG_LOCKED,\
324 &pfkeystat, pfkeystat, "");
325
326 #ifndef LIST_FOREACH
327 #define LIST_FOREACH(elm, head, field) \
328 for (elm = LIST_FIRST(head); elm; elm = LIST_NEXT(elm, field))
329 #endif
330 #define __LIST_CHAINED(elm) \
331 (!((elm)->chain.le_next == NULL && (elm)->chain.le_prev == NULL))
332 #define LIST_INSERT_TAIL(head, elm, type, field) \
333 do {\
334 struct type *curelm = LIST_FIRST(head); \
335 if (curelm == NULL) {\
336 LIST_INSERT_HEAD(head, elm, field); \
337 } else { \
338 while (LIST_NEXT(curelm, field)) \
339 curelm = LIST_NEXT(curelm, field);\
340 LIST_INSERT_AFTER(curelm, elm, field);\
341 }\
342 } while (0)
343
344 #define KEY_CHKSASTATE(head, sav, name) \
345 do { \
346 if ((head) != (sav)) { \
347 ipseclog((LOG_DEBUG, "%s: state mismatched (TREE=%d SA=%d)\n", \
348 (name), (head), (sav))); \
349 continue; \
350 } \
351 } while (0)
352
353 #define KEY_CHKSPDIR(head, sp, name) \
354 do { \
355 if ((head) != (sp)) { \
356 ipseclog((LOG_DEBUG, "%s: direction mismatched (TREE=%d SP=%d), " \
357 "anyway continue.\n", \
358 (name), (head), (sp))); \
359 } \
360 } while (0)
361
362 #if 1
363 #define KMALLOC_WAIT(p, t, n) \
364 ((p) = (t) _MALLOC((u_int32_t)(n), M_SECA, M_WAITOK))
365 #define KMALLOC_NOWAIT(p, t, n) \
366 ((p) = (t) _MALLOC((u_int32_t)(n), M_SECA, M_NOWAIT))
367 #define KFREE(p) \
368 _FREE((caddr_t)(p), M_SECA);
369 #else
370 #define KMALLOC_WAIT(p, t, n) \
371 do { \
372 ((p) = (t)_MALLOC((u_int32_t)(n), M_SECA, M_WAITOK)); \
373 printf("%s %d: %p <- KMALLOC_WAIT(%s, %d)\n", \
374 __FILE__, __LINE__, (p), #t, n); \
375 } while (0)
376 #define KMALLOC_NOWAIT(p, t, n) \
377 do { \
378 ((p) = (t)_MALLOC((u_int32_t)(n), M_SECA, M_NOWAIT)); \
379 printf("%s %d: %p <- KMALLOC_NOWAIT(%s, %d)\n", \
380 __FILE__, __LINE__, (p), #t, n); \
381 } while (0)
382
383 #define KFREE(p) \
384 do { \
385 printf("%s %d: %p -> KFREE()\n", __FILE__, __LINE__, (p)); \
386 _FREE((caddr_t)(p), M_SECA); \
387 } while (0)
388 #endif
389
390 /*
391 * set parameters into secpolicyindex buffer.
392 * Must allocate secpolicyindex buffer passed to this function.
393 */
394 #define KEY_SETSECSPIDX(_dir, s, d, ps, pd, ulp, idx) \
395 do { \
396 bzero((idx), sizeof(struct secpolicyindex)); \
397 (idx)->dir = (_dir); \
398 (idx)->prefs = (ps); \
399 (idx)->prefd = (pd); \
400 (idx)->ul_proto = (ulp); \
401 bcopy((s), &(idx)->src, ((struct sockaddr *)(s))->sa_len); \
402 bcopy((d), &(idx)->dst, ((struct sockaddr *)(d))->sa_len); \
403 } while (0)
404
405 /*
406 * set parameters into secasindex buffer.
407 * Must allocate secasindex buffer before calling this function.
408 */
409 #define KEY_SETSECASIDX(p, m, r, s, d, idx) \
410 do { \
411 bzero((idx), sizeof(struct secasindex)); \
412 (idx)->proto = (p); \
413 (idx)->mode = (m); \
414 (idx)->reqid = (r); \
415 bcopy((s), &(idx)->src, ((const struct sockaddr *)(s))->sa_len); \
416 bcopy((d), &(idx)->dst, ((const struct sockaddr *)(d))->sa_len); \
417 } while (0)
418
419 /* key statistics */
420 struct _keystat {
421 u_int32_t getspi_count; /* the avarage of count to try to get new SPI */
422 } keystat;
423
424 struct sadb_msghdr {
425 struct sadb_msg *msg;
426 struct sadb_ext *ext[SADB_EXT_MAX + 1];
427 int extoff[SADB_EXT_MAX + 1];
428 int extlen[SADB_EXT_MAX + 1];
429 };
430
431 static struct secasvar *key_do_allocsa_policy(struct secashead *, u_int, u_int16_t);
432 static int key_do_get_translated_port(struct secashead *, struct secasvar *, u_int);
433 static void key_delsp(struct secpolicy *);
434 static struct secpolicy *key_getsp(struct secpolicyindex *);
435 static struct secpolicy *key_getspbyid(u_int32_t);
436 static u_int32_t key_newreqid(void);
437 static struct mbuf *key_gather_mbuf(struct mbuf *,
438 const struct sadb_msghdr *, int, int, int *);
439 static int key_spdadd(struct socket *, struct mbuf *,
440 const struct sadb_msghdr *);
441 static u_int32_t key_getnewspid(void);
442 static int key_spddelete(struct socket *, struct mbuf *,
443 const struct sadb_msghdr *);
444 static int key_spddelete2(struct socket *, struct mbuf *,
445 const struct sadb_msghdr *);
446 static int key_spdget(struct socket *, struct mbuf *,
447 const struct sadb_msghdr *);
448 static int key_spdflush(struct socket *, struct mbuf *,
449 const struct sadb_msghdr *);
450 static int key_spddump(struct socket *, struct mbuf *,
451 const struct sadb_msghdr *);
452 static struct mbuf *key_setdumpsp(struct secpolicy *,
453 u_int8_t, u_int32_t, u_int32_t);
454 static u_int key_getspreqmsglen(struct secpolicy *);
455 static int key_spdexpire(struct secpolicy *);
456 static struct secashead *key_newsah(struct secasindex *, u_int8_t);
457 static struct secasvar *key_newsav(struct mbuf *,
458 const struct sadb_msghdr *, struct secashead *, int *);
459 static struct secashead *key_getsah(struct secasindex *);
460 static struct secasvar *key_checkspidup(struct secasindex *, u_int32_t);
461 static void key_setspi __P((struct secasvar *, u_int32_t));
462 static struct secasvar *key_getsavbyspi(struct secashead *, u_int32_t);
463 static int key_setsaval(struct secasvar *, struct mbuf *,
464 const struct sadb_msghdr *);
465 static int key_mature(struct secasvar *);
466 static struct mbuf *key_setdumpsa(struct secasvar *, u_int8_t,
467 u_int8_t, u_int32_t, u_int32_t);
468 static struct mbuf *key_setsadbmsg(u_int8_t, u_int16_t, u_int8_t,
469 u_int32_t, pid_t, u_int16_t);
470 static struct mbuf *key_setsadbsa(struct secasvar *);
471 static struct mbuf *key_setsadbaddr(u_int16_t,
472 struct sockaddr *, u_int8_t, u_int16_t);
473 #if 0
474 static struct mbuf *key_setsadbident(u_int16_t, u_int16_t, caddr_t,
475 int, u_int64_t);
476 #endif
477 static struct mbuf *key_setsadbxsa2(u_int8_t, u_int32_t, u_int32_t);
478 static struct mbuf *key_setsadbxpolicy(u_int16_t, u_int8_t,
479 u_int32_t);
480 static void *key_newbuf(const void *, u_int);
481 #if INET6
482 static int key_ismyaddr6(struct sockaddr_in6 *);
483 #endif
484 static void key_update_natt_keepalive_timestamp(struct secasvar *, struct secasvar *);
485
486 /* flags for key_cmpsaidx() */
487 #define CMP_HEAD 0x1 /* protocol, addresses. */
488 #define CMP_PORT 0x2 /* additionally HEAD, reqid, mode. */
489 #define CMP_REQID 0x4 /* additionally HEAD, reqid. */
490 #define CMP_MODE 0x8 /* additionally mode. */
491 #define CMP_EXACTLY 0xF /* all elements. */
492 static int key_cmpsaidx(struct secasindex *, struct secasindex *, int);
493
494 static int key_cmpspidx_exactly(struct secpolicyindex *,
495 struct secpolicyindex *);
496 static int key_cmpspidx_withmask(struct secpolicyindex *,
497 struct secpolicyindex *);
498 static int key_sockaddrcmp(struct sockaddr *, struct sockaddr *, int);
499 static int key_bbcmp(caddr_t, caddr_t, u_int);
500 static void key_srandom(void);
501 static u_int16_t key_satype2proto(u_int8_t);
502 static u_int8_t key_proto2satype(u_int16_t);
503
504 static int key_getspi(struct socket *, struct mbuf *,
505 const struct sadb_msghdr *);
506 static u_int32_t key_do_getnewspi(struct sadb_spirange *, struct secasindex *);
507 static int key_update(struct socket *, struct mbuf *,
508 const struct sadb_msghdr *);
509 #if IPSEC_DOSEQCHECK
510 static struct secasvar *key_getsavbyseq(struct secashead *, u_int32_t);
511 #endif
512 static int key_add(struct socket *, struct mbuf *, const struct sadb_msghdr *);
513 static int key_setident(struct secashead *, struct mbuf *,
514 const struct sadb_msghdr *);
515 static struct mbuf *key_getmsgbuf_x1(struct mbuf *, const struct sadb_msghdr *);
516 static int key_delete(struct socket *, struct mbuf *,
517 const struct sadb_msghdr *);
518 static int key_get(struct socket *, struct mbuf *, const struct sadb_msghdr *);
519
520 static void key_getcomb_setlifetime(struct sadb_comb *);
521 #if IPSEC_ESP
522 static struct mbuf *key_getcomb_esp(void);
523 #endif
524 static struct mbuf *key_getcomb_ah(void);
525 static struct mbuf *key_getcomb_ipcomp(void);
526 static struct mbuf *key_getprop(const struct secasindex *);
527
528 static int key_acquire(struct secasindex *, struct secpolicy *);
529 #ifndef IPSEC_NONBLOCK_ACQUIRE
530 static struct secacq *key_newacq(struct secasindex *);
531 static struct secacq *key_getacq(struct secasindex *);
532 static struct secacq *key_getacqbyseq(u_int32_t);
533 #endif
534 static struct secspacq *key_newspacq(struct secpolicyindex *);
535 static struct secspacq *key_getspacq(struct secpolicyindex *);
536 static int key_acquire2(struct socket *, struct mbuf *,
537 const struct sadb_msghdr *);
538 static int key_register(struct socket *, struct mbuf *,
539 const struct sadb_msghdr *);
540 static int key_expire(struct secasvar *);
541 static int key_flush(struct socket *, struct mbuf *,
542 const struct sadb_msghdr *);
543 static int key_dump(struct socket *, struct mbuf *, const struct sadb_msghdr *);
544 static int key_promisc(struct socket *, struct mbuf *,
545 const struct sadb_msghdr *);
546 static int key_senderror(struct socket *, struct mbuf *, int);
547 static int key_validate_ext(const struct sadb_ext *, int);
548 static int key_align(struct mbuf *, struct sadb_msghdr *);
549 static struct mbuf *key_alloc_mbuf(int);
550 static int key_getsastat (struct socket *, struct mbuf *, const struct sadb_msghdr *);
551 static int key_setsaval2(struct secasvar *sav,
552 u_int8_t satype,
553 u_int8_t alg_auth,
554 u_int8_t alg_enc,
555 u_int32_t flags,
556 u_int8_t replay,
557 struct sadb_key *key_auth,
558 u_int16_t key_auth_len,
559 struct sadb_key *key_enc,
560 u_int16_t key_enc_len,
561 u_int16_t natt_port,
562 u_int32_t seq,
563 u_int32_t spi,
564 u_int32_t pid,
565 struct sadb_lifetime *lifetime_hard,
566 struct sadb_lifetime *lifetime_soft);
567
568 extern int ipsec_bypass;
569 extern int esp_udp_encap_port;
570 int ipsec_send_natt_keepalive(struct secasvar *sav);
571
572 void key_init(void);
573
574
575
576 /*
577 * PF_KEY init
578 * setup locks, call raw_init(), and then init timer and associated data
579 *
580 */
581 void
582 key_init(void)
583 {
584
585 int i;
586
587 sadb_mutex_grp_attr = lck_grp_attr_alloc_init();
588 sadb_mutex_grp = lck_grp_alloc_init("sadb", sadb_mutex_grp_attr);
589 sadb_mutex_attr = lck_attr_alloc_init();
590
591 lck_mtx_init(sadb_mutex, sadb_mutex_grp, sadb_mutex_attr);
592
593 pfkey_stat_mutex_grp_attr = lck_grp_attr_alloc_init();
594 pfkey_stat_mutex_grp = lck_grp_alloc_init("pfkey_stat", pfkey_stat_mutex_grp_attr);
595 pfkey_stat_mutex_attr = lck_attr_alloc_init();
596
597 lck_mtx_init(pfkey_stat_mutex, pfkey_stat_mutex_grp, pfkey_stat_mutex_attr);
598
599 for (i = 0; i < SPIHASHSIZE; i++)
600 LIST_INIT(&spihash[i]);
601
602 raw_init();
603
604 bzero((caddr_t)&key_cb, sizeof(key_cb));
605
606 for (i = 0; i < IPSEC_DIR_MAX; i++) {
607 LIST_INIT(&sptree[i]);
608 }
609 ipsec_policy_count = 0;
610
611 LIST_INIT(&sahtree);
612
613 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
614 LIST_INIT(&regtree[i]);
615 }
616 ipsec_sav_count = 0;
617
618 #ifndef IPSEC_NONBLOCK_ACQUIRE
619 LIST_INIT(&acqtree);
620 #endif
621 LIST_INIT(&spacqtree);
622
623 /* system default */
624 #if INET
625 ip4_def_policy.policy = IPSEC_POLICY_NONE;
626 ip4_def_policy.refcnt++; /*never reclaim this*/
627 #endif
628 #if INET6
629 ip6_def_policy.policy = IPSEC_POLICY_NONE;
630 ip6_def_policy.refcnt++; /*never reclaim this*/
631 #endif
632
633 #ifndef IPSEC_DEBUG2
634 timeout((void *)key_timehandler, (void *)0, hz);
635 #endif /*IPSEC_DEBUG2*/
636
637 /* initialize key statistics */
638 keystat.getspi_count = 1;
639
640 #ifndef __APPLE__
641 printf("IPsec: Initialized Security Association Processing.\n");
642 #endif
643 }
644
645
646 /* %%% IPsec policy management */
647 /*
648 * allocating a SP for OUTBOUND or INBOUND packet.
649 * Must call key_freesp() later.
650 * OUT: NULL: not found
651 * others: found and return the pointer.
652 */
653 struct secpolicy *
654 key_allocsp(
655 struct secpolicyindex *spidx,
656 u_int dir)
657 {
658 struct secpolicy *sp;
659 struct timeval tv;
660
661 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
662 /* sanity check */
663 if (spidx == NULL)
664 panic("key_allocsp: NULL pointer is passed.\n");
665
666 /* check direction */
667 switch (dir) {
668 case IPSEC_DIR_INBOUND:
669 case IPSEC_DIR_OUTBOUND:
670 break;
671 default:
672 panic("key_allocsp: Invalid direction is passed.\n");
673 }
674
675 /* get a SP entry */
676 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
677 printf("*** objects\n");
678 kdebug_secpolicyindex(spidx));
679
680 lck_mtx_lock(sadb_mutex);
681 LIST_FOREACH(sp, &sptree[dir], chain) {
682 KEYDEBUG(KEYDEBUG_IPSEC_DATA,
683 printf("*** in SPD\n");
684 kdebug_secpolicyindex(&sp->spidx));
685
686 if (sp->state == IPSEC_SPSTATE_DEAD)
687 continue;
688 if (key_cmpspidx_withmask(&sp->spidx, spidx))
689 goto found;
690 }
691 lck_mtx_unlock(sadb_mutex);
692 return NULL;
693
694 found:
695
696 /* found a SPD entry */
697 microtime(&tv);
698 sp->lastused = tv.tv_sec;
699 sp->refcnt++;
700 lck_mtx_unlock(sadb_mutex);
701
702 /* sanity check */
703 KEY_CHKSPDIR(sp->spidx.dir, dir, "key_allocsp");
704 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
705 printf("DP key_allocsp cause refcnt++:%d SP:%p\n",
706 sp->refcnt, sp));
707 return sp;
708 }
709
710 /*
711 * return a policy that matches this particular inbound packet.
712 * XXX slow
713 */
714 struct secpolicy *
715 key_gettunnel(
716 struct sockaddr *osrc,
717 struct sockaddr *odst,
718 struct sockaddr *isrc,
719 struct sockaddr *idst)
720 {
721 struct secpolicy *sp;
722 const int dir = IPSEC_DIR_INBOUND;
723 struct timeval tv;
724 struct ipsecrequest *r1, *r2, *p;
725 struct sockaddr *os, *od, *is, *id;
726 struct secpolicyindex spidx;
727
728 if (isrc->sa_family != idst->sa_family) {
729 ipseclog((LOG_ERR, "protocol family mismatched %d != %d\n.",
730 isrc->sa_family, idst->sa_family));
731 return NULL;
732 }
733
734 lck_mtx_lock(sadb_mutex);
735 LIST_FOREACH(sp, &sptree[dir], chain) {
736 if (sp->state == IPSEC_SPSTATE_DEAD)
737 continue;
738
739 r1 = r2 = NULL;
740 for (p = sp->req; p; p = p->next) {
741 if (p->saidx.mode != IPSEC_MODE_TUNNEL)
742 continue;
743
744 r1 = r2;
745 r2 = p;
746
747 if (!r1) {
748 /* here we look at address matches only */
749 spidx = sp->spidx;
750 if (isrc->sa_len > sizeof(spidx.src) ||
751 idst->sa_len > sizeof(spidx.dst))
752 continue;
753 bcopy(isrc, &spidx.src, isrc->sa_len);
754 bcopy(idst, &spidx.dst, idst->sa_len);
755 if (!key_cmpspidx_withmask(&sp->spidx, &spidx))
756 continue;
757 } else {
758 is = (struct sockaddr *)&r1->saidx.src;
759 id = (struct sockaddr *)&r1->saidx.dst;
760 if (key_sockaddrcmp(is, isrc, 0) ||
761 key_sockaddrcmp(id, idst, 0))
762 continue;
763 }
764
765 os = (struct sockaddr *)&r2->saidx.src;
766 od = (struct sockaddr *)&r2->saidx.dst;
767 if (key_sockaddrcmp(os, osrc, 0) ||
768 key_sockaddrcmp(od, odst, 0))
769 continue;
770
771 goto found;
772 }
773 }
774 lck_mtx_unlock(sadb_mutex);
775 return NULL;
776
777 found:
778 microtime(&tv);
779 sp->lastused = tv.tv_sec;
780 sp->refcnt++;
781 lck_mtx_unlock(sadb_mutex);
782 return sp;
783 }
784
785 /*
786 * allocating an SA entry for an *OUTBOUND* packet.
787 * checking each request entries in SP, and acquire an SA if need.
788 * OUT: 0: there are valid requests.
789 * ENOENT: policy may be valid, but SA with REQUIRE is on acquiring.
790 */
791 int
792 key_checkrequest(
793 struct ipsecrequest *isr,
794 struct secasindex *saidx,
795 struct secasvar **sav)
796 {
797 u_int level;
798 int error;
799 struct sockaddr_in *sin;
800
801 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
802
803 *sav = NULL;
804
805 /* sanity check */
806 if (isr == NULL || saidx == NULL)
807 panic("key_checkrequest: NULL pointer is passed.\n");
808
809 /* check mode */
810 switch (saidx->mode) {
811 case IPSEC_MODE_TRANSPORT:
812 case IPSEC_MODE_TUNNEL:
813 break;
814 case IPSEC_MODE_ANY:
815 default:
816 panic("key_checkrequest: Invalid policy defined.\n");
817 }
818
819 /* get current level */
820 level = ipsec_get_reqlevel(isr);
821
822
823 /*
824 * key_allocsa_policy should allocate the oldest SA available.
825 * See key_do_allocsa_policy(), and draft-jenkins-ipsec-rekeying-03.txt.
826 */
827 if (*sav == NULL)
828 *sav = key_allocsa_policy(saidx);
829
830 /* When there is SA. */
831 if (*sav != NULL)
832 return 0;
833
834 /* There is no SA.
835 *
836 * Remove dst port - used for special natt support - don't call
837 * key_acquire with it.
838 */
839 if (saidx->mode == IPSEC_MODE_TRANSPORT) {
840 sin = (struct sockaddr_in *)&saidx->dst;
841 sin->sin_port = IPSEC_PORT_ANY;
842 }
843 if ((error = key_acquire(saidx, isr->sp)) != 0) {
844 /* XXX What should I do ? */
845 ipseclog((LOG_DEBUG, "key_checkrequest: error %d returned "
846 "from key_acquire.\n", error));
847 return error;
848 }
849
850 return level == IPSEC_LEVEL_REQUIRE ? ENOENT : 0;
851 }
852
853 /*
854 * allocating a SA for policy entry from SAD.
855 * NOTE: searching SAD of aliving state.
856 * OUT: NULL: not found.
857 * others: found and return the pointer.
858 */
859 u_int32_t sah_search_calls = 0;
860 u_int32_t sah_search_count = 0;
861 struct secasvar *
862 key_allocsa_policy(
863 struct secasindex *saidx)
864 {
865 struct secashead *sah;
866 struct secasvar *sav;
867 u_int stateidx, state;
868 const u_int *saorder_state_valid;
869 int arraysize;
870 struct sockaddr_in *sin;
871 u_int16_t dstport;
872
873 lck_mtx_lock(sadb_mutex);
874 sah_search_calls++;
875 LIST_FOREACH(sah, &sahtree, chain) {
876 sah_search_count++;
877 if (sah->state == SADB_SASTATE_DEAD)
878 continue;
879 if (key_cmpsaidx(&sah->saidx, saidx, CMP_MODE | CMP_REQID))
880 goto found;
881 }
882 lck_mtx_unlock(sadb_mutex);
883 return NULL;
884
885 found:
886
887 /*
888 * search a valid state list for outbound packet.
889 * This search order is important.
890 */
891 if (key_preferred_oldsa) {
892 saorder_state_valid = saorder_state_valid_prefer_old;
893 arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
894 } else {
895 saorder_state_valid = saorder_state_valid_prefer_new;
896 arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
897 }
898
899
900 sin = (struct sockaddr_in *)&saidx->dst;
901 dstport = sin->sin_port;
902 if (saidx->mode == IPSEC_MODE_TRANSPORT)
903 sin->sin_port = IPSEC_PORT_ANY;
904
905 for (stateidx = 0; stateidx < arraysize; stateidx++) {
906
907 state = saorder_state_valid[stateidx];
908
909 sav = key_do_allocsa_policy(sah, state, dstport);
910 if (sav != NULL) {
911 lck_mtx_unlock(sadb_mutex);
912 return sav;
913 }
914 }
915 lck_mtx_unlock(sadb_mutex);
916 return NULL;
917 }
918
919 /*
920 * searching SAD with direction, protocol, mode and state.
921 * called by key_allocsa_policy().
922 * OUT:
923 * NULL : not found
924 * others : found, pointer to a SA.
925 */
926 static struct secasvar *
927 key_do_allocsa_policy(
928 struct secashead *sah,
929 u_int state,
930 u_int16_t dstport)
931 {
932 struct secasvar *sav, *nextsav, *candidate, *natt_candidate, *no_natt_candidate, *d;
933
934 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
935
936 /* initialize */
937 candidate = NULL;
938 natt_candidate = NULL;
939 no_natt_candidate = NULL;
940
941 for (sav = LIST_FIRST(&sah->savtree[state]);
942 sav != NULL;
943 sav = nextsav) {
944
945 nextsav = LIST_NEXT(sav, chain);
946
947 /* sanity check */
948 KEY_CHKSASTATE(sav->state, state, "key_do_allocsa_policy");
949
950 if (sah->saidx.mode == IPSEC_MODE_TUNNEL && dstport &&
951 ((sav->flags & SADB_X_EXT_NATT) != 0) &&
952 ntohs(dstport) != sav->remote_ike_port)
953 continue;
954
955 if (sah->saidx.mode == IPSEC_MODE_TRANSPORT &&
956 ((sav->flags & SADB_X_EXT_NATT_MULTIPLEUSERS) != 0) &&
957 ntohs(dstport) != sav->remote_ike_port)
958 continue; /* skip this one - not a match - or not UDP */
959
960 if ((sah->saidx.mode == IPSEC_MODE_TUNNEL &&
961 ((sav->flags & SADB_X_EXT_NATT) != 0)) ||
962 (sah->saidx.mode == IPSEC_MODE_TRANSPORT &&
963 ((sav->flags & SADB_X_EXT_NATT_MULTIPLEUSERS) != 0))) {
964 if (natt_candidate == NULL) {
965 natt_candidate = sav;
966 continue;
967 } else
968 candidate = natt_candidate;
969 } else {
970 if (no_natt_candidate == NULL) {
971 no_natt_candidate = sav;
972 continue;
973 } else
974 candidate = no_natt_candidate;
975 }
976
977 /* Which SA is the better ? */
978
979 /* sanity check 2 */
980 if (candidate->lft_c == NULL || sav->lft_c == NULL)
981 panic("key_do_allocsa_policy: "
982 "lifetime_current is NULL.\n");
983
984 /* What the best method is to compare ? */
985 if (key_preferred_oldsa) {
986 if (candidate->lft_c->sadb_lifetime_addtime >
987 sav->lft_c->sadb_lifetime_addtime) {
988 if ((sav->flags & SADB_X_EXT_NATT_MULTIPLEUSERS) != 0)
989 natt_candidate = sav;
990 else
991 no_natt_candidate = sav;
992 }
993 continue;
994 /*NOTREACHED*/
995 }
996
997 /* prefered new sa rather than old sa */
998 if (candidate->lft_c->sadb_lifetime_addtime <
999 sav->lft_c->sadb_lifetime_addtime) {
1000 d = candidate;
1001 if ((sav->flags & SADB_X_EXT_NATT_MULTIPLEUSERS) != 0)
1002 natt_candidate = sav;
1003 else
1004 no_natt_candidate = sav;
1005 } else
1006 d = sav;
1007
1008 /*
1009 * prepared to delete the SA when there is more
1010 * suitable candidate and the lifetime of the SA is not
1011 * permanent.
1012 */
1013 if (d->lft_c->sadb_lifetime_addtime != 0) {
1014 struct mbuf *m, *result;
1015
1016 key_sa_chgstate(d, SADB_SASTATE_DEAD);
1017
1018 m = key_setsadbmsg(SADB_DELETE, 0,
1019 d->sah->saidx.proto, 0, 0, d->refcnt - 1);
1020 if (!m)
1021 goto msgfail;
1022 result = m;
1023
1024 /* set sadb_address for saidx's. */
1025 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
1026 (struct sockaddr *)&d->sah->saidx.src,
1027 d->sah->saidx.src.ss_len << 3,
1028 IPSEC_ULPROTO_ANY);
1029 if (!m)
1030 goto msgfail;
1031 m_cat(result, m);
1032
1033 /* set sadb_address for saidx's. */
1034 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
1035 (struct sockaddr *)&d->sah->saidx.src,
1036 d->sah->saidx.src.ss_len << 3,
1037 IPSEC_ULPROTO_ANY);
1038 if (!m)
1039 goto msgfail;
1040 m_cat(result, m);
1041
1042 /* create SA extension */
1043 m = key_setsadbsa(d);
1044 if (!m)
1045 goto msgfail;
1046 m_cat(result, m);
1047
1048 if (result->m_len < sizeof(struct sadb_msg)) {
1049 result = m_pullup(result,
1050 sizeof(struct sadb_msg));
1051 if (result == NULL)
1052 goto msgfail;
1053 }
1054
1055 result->m_pkthdr.len = 0;
1056 for (m = result; m; m = m->m_next)
1057 result->m_pkthdr.len += m->m_len;
1058 mtod(result, struct sadb_msg *)->sadb_msg_len =
1059 PFKEY_UNIT64(result->m_pkthdr.len);
1060
1061 if (key_sendup_mbuf(NULL, result,
1062 KEY_SENDUP_REGISTERED))
1063 goto msgfail;
1064 msgfail:
1065 key_freesav(d, KEY_SADB_LOCKED);
1066 }
1067 }
1068
1069 /* choose latest if both types present */
1070 if (natt_candidate == NULL)
1071 candidate = no_natt_candidate;
1072 else if (no_natt_candidate == NULL)
1073 candidate = natt_candidate;
1074 else if (sah->saidx.mode == IPSEC_MODE_TUNNEL && dstport)
1075 candidate = natt_candidate;
1076 else if (natt_candidate->lft_c->sadb_lifetime_addtime >
1077 no_natt_candidate->lft_c->sadb_lifetime_addtime)
1078 candidate = natt_candidate;
1079 else
1080 candidate = no_natt_candidate;
1081
1082 if (candidate) {
1083 candidate->refcnt++;
1084 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1085 printf("DP allocsa_policy cause "
1086 "refcnt++:%d SA:%p\n",
1087 candidate->refcnt, candidate));
1088 }
1089 return candidate;
1090 }
1091
1092 /*
1093 * allocating a SA entry for a *INBOUND* packet.
1094 * Must call key_freesav() later.
1095 * OUT: positive: pointer to a sav.
1096 * NULL: not found, or error occurred.
1097 *
1098 * In the comparison, source address will be ignored for RFC2401 conformance.
1099 * To quote, from section 4.1:
1100 * A security association is uniquely identified by a triple consisting
1101 * of a Security Parameter Index (SPI), an IP Destination Address, and a
1102 * security protocol (AH or ESP) identifier.
1103 * Note that, however, we do need to keep source address in IPsec SA.
1104 * IKE specification and PF_KEY specification do assume that we
1105 * keep source address in IPsec SA. We see a tricky situation here.
1106 */
1107 struct secasvar *
1108 key_allocsa(
1109 u_int family,
1110 caddr_t src,
1111 caddr_t dst,
1112 u_int proto,
1113 u_int32_t spi)
1114 {
1115 struct secasvar *sav, *match;
1116 u_int stateidx, state, tmpidx, matchidx;
1117 struct sockaddr_in sin;
1118 struct sockaddr_in6 sin6;
1119 const u_int *saorder_state_valid;
1120 int arraysize;
1121
1122 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
1123
1124 /* sanity check */
1125 if (src == NULL || dst == NULL)
1126 panic("key_allocsa: NULL pointer is passed.\n");
1127
1128 /*
1129 * when both systems employ similar strategy to use a SA.
1130 * the search order is important even in the inbound case.
1131 */
1132 if (key_preferred_oldsa) {
1133 saorder_state_valid = saorder_state_valid_prefer_old;
1134 arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
1135 } else {
1136 saorder_state_valid = saorder_state_valid_prefer_new;
1137 arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
1138 }
1139
1140 /*
1141 * searching SAD.
1142 * XXX: to be checked internal IP header somewhere. Also when
1143 * IPsec tunnel packet is received. But ESP tunnel mode is
1144 * encrypted so we can't check internal IP header.
1145 */
1146 /*
1147 * search a valid state list for inbound packet.
1148 * the search order is not important.
1149 */
1150 match = NULL;
1151 matchidx = arraysize;
1152 lck_mtx_lock(sadb_mutex);
1153 LIST_FOREACH(sav, &spihash[SPIHASH(spi)], spihash) {
1154 if (sav->spi != spi)
1155 continue;
1156 if (proto != sav->sah->saidx.proto)
1157 continue;
1158 if (family != sav->sah->saidx.src.ss_family ||
1159 family != sav->sah->saidx.dst.ss_family)
1160 continue;
1161 tmpidx = arraysize;
1162 for (stateidx = 0; stateidx < matchidx; stateidx++) {
1163 state = saorder_state_valid[stateidx];
1164 if (sav->state == state) {
1165 tmpidx = stateidx;
1166 break;
1167 }
1168 }
1169 if (tmpidx >= matchidx)
1170 continue;
1171
1172 #if 0 /* don't check src */
1173 /* check src address */
1174 switch (family) {
1175 case AF_INET:
1176 bzero(&sin, sizeof(sin));
1177 sin.sin_family = AF_INET;
1178 sin.sin_len = sizeof(sin);
1179 bcopy(src, &sin.sin_addr,
1180 sizeof(sin.sin_addr));
1181 if (key_sockaddrcmp((struct sockaddr*)&sin,
1182 (struct sockaddr *)&sav->sah->saidx.src, 0) != 0)
1183 continue;
1184 break;
1185 case AF_INET6:
1186 bzero(&sin6, sizeof(sin6));
1187 sin6.sin6_family = AF_INET6;
1188 sin6.sin6_len = sizeof(sin6);
1189 bcopy(src, &sin6.sin6_addr,
1190 sizeof(sin6.sin6_addr));
1191 if (IN6_IS_SCOPE_LINKLOCAL(&sin6.sin6_addr)) {
1192 /* kame fake scopeid */
1193 sin6.sin6_scope_id =
1194 ntohs(sin6.sin6_addr.s6_addr16[1]);
1195 sin6.sin6_addr.s6_addr16[1] = 0;
1196 }
1197 if (key_sockaddrcmp((struct sockaddr*)&sin6,
1198 (struct sockaddr *)&sav->sah->saidx.src, 0) != 0)
1199 continue;
1200 break;
1201 default:
1202 ipseclog((LOG_DEBUG, "key_allocsa: "
1203 "unknown address family=%d.\n",
1204 family));
1205 continue;
1206 }
1207
1208 #endif
1209 /* check dst address */
1210 switch (family) {
1211 case AF_INET:
1212 bzero(&sin, sizeof(sin));
1213 sin.sin_family = AF_INET;
1214 sin.sin_len = sizeof(sin);
1215 bcopy(dst, &sin.sin_addr,
1216 sizeof(sin.sin_addr));
1217 if (key_sockaddrcmp((struct sockaddr*)&sin,
1218 (struct sockaddr *)&sav->sah->saidx.dst, 0) != 0)
1219 continue;
1220
1221 break;
1222 case AF_INET6:
1223 bzero(&sin6, sizeof(sin6));
1224 sin6.sin6_family = AF_INET6;
1225 sin6.sin6_len = sizeof(sin6);
1226 bcopy(dst, &sin6.sin6_addr,
1227 sizeof(sin6.sin6_addr));
1228 if (IN6_IS_SCOPE_LINKLOCAL(&sin6.sin6_addr)) {
1229 /* kame fake scopeid */
1230 sin6.sin6_scope_id =
1231 ntohs(sin6.sin6_addr.s6_addr16[1]);
1232 sin6.sin6_addr.s6_addr16[1] = 0;
1233 }
1234 if (key_sockaddrcmp((struct sockaddr*)&sin6,
1235 (struct sockaddr *)&sav->sah->saidx.dst, 0) != 0)
1236 continue;
1237 break;
1238 default:
1239 ipseclog((LOG_DEBUG, "key_allocsa: "
1240 "unknown address family=%d.\n", family));
1241 continue;
1242 }
1243
1244 match = sav;
1245 matchidx = tmpidx;
1246 }
1247 if (match)
1248 goto found;
1249
1250 /* not found */
1251 lck_mtx_unlock(sadb_mutex);
1252 return NULL;
1253
1254 found:
1255 match->refcnt++;
1256 lck_mtx_unlock(sadb_mutex);
1257 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1258 printf("DP allocsa cause refcnt++:%d SA:%p\n",
1259 match->refcnt, match));
1260 return match;
1261 }
1262
1263 u_int16_t
1264 key_natt_get_translated_port(
1265 struct secasvar *outsav)
1266 {
1267
1268 struct secasindex saidx;
1269 struct secashead *sah;
1270 u_int stateidx, state;
1271 const u_int *saorder_state_valid;
1272 int arraysize;
1273
1274 /* get sa for incoming */
1275 saidx.mode = outsav->sah->saidx.mode;
1276 saidx.reqid = 0;
1277 saidx.proto = outsav->sah->saidx.proto;
1278 bcopy(&outsav->sah->saidx.src, &saidx.dst, sizeof(struct sockaddr_in));
1279 bcopy(&outsav->sah->saidx.dst, &saidx.src, sizeof(struct sockaddr_in));
1280
1281 lck_mtx_lock(sadb_mutex);
1282 LIST_FOREACH(sah, &sahtree, chain) {
1283 if (sah->state == SADB_SASTATE_DEAD)
1284 continue;
1285 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE))
1286 goto found;
1287 }
1288 lck_mtx_unlock(sadb_mutex);
1289 return 0;
1290
1291 found:
1292 /*
1293 * Found sah - now go thru list of SAs and find
1294 * matching remote ike port. If found - set
1295 * sav->natt_encapsulated_src_port and return the port.
1296 */
1297 /*
1298 * search a valid state list for outbound packet.
1299 * This search order is important.
1300 */
1301 if (key_preferred_oldsa) {
1302 saorder_state_valid = saorder_state_valid_prefer_old;
1303 arraysize = _ARRAYLEN(saorder_state_valid_prefer_old);
1304 } else {
1305 saorder_state_valid = saorder_state_valid_prefer_new;
1306 arraysize = _ARRAYLEN(saorder_state_valid_prefer_new);
1307 }
1308
1309 for (stateidx = 0; stateidx < arraysize; stateidx++) {
1310 state = saorder_state_valid[stateidx];
1311 if (key_do_get_translated_port(sah, outsav, state)) {
1312 lck_mtx_unlock(sadb_mutex);
1313 return outsav->natt_encapsulated_src_port;
1314 }
1315 }
1316 lck_mtx_unlock(sadb_mutex);
1317 return 0;
1318 }
1319
1320 static int
1321 key_do_get_translated_port(
1322 struct secashead *sah,
1323 struct secasvar *outsav,
1324 u_int state)
1325 {
1326 struct secasvar *currsav, *nextsav, *candidate;
1327
1328
1329 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
1330
1331 /* initilize */
1332 candidate = NULL;
1333
1334 for (currsav = LIST_FIRST(&sah->savtree[state]);
1335 currsav != NULL;
1336 currsav = nextsav) {
1337
1338 nextsav = LIST_NEXT(currsav, chain);
1339
1340 /* sanity check */
1341 KEY_CHKSASTATE(currsav->state, state, "key_do_get_translated_port");
1342
1343 if ((currsav->flags & SADB_X_EXT_NATT_MULTIPLEUSERS) == 0 ||
1344 currsav->remote_ike_port != outsav->remote_ike_port)
1345 continue;
1346
1347 if (candidate == NULL) {
1348 candidate = currsav;
1349 continue;
1350 }
1351
1352 /* Which SA is the better ? */
1353
1354 /* sanity check 2 */
1355 if (candidate->lft_c == NULL || currsav->lft_c == NULL)
1356 panic("key_do_get_translated_port: "
1357 "lifetime_current is NULL.\n");
1358
1359 /* What the best method is to compare ? */
1360 if (key_preferred_oldsa) {
1361 if (candidate->lft_c->sadb_lifetime_addtime >
1362 currsav->lft_c->sadb_lifetime_addtime) {
1363 candidate = currsav;
1364 }
1365 continue;
1366 /*NOTREACHED*/
1367 }
1368
1369 /* prefered new sa rather than old sa */
1370 if (candidate->lft_c->sadb_lifetime_addtime <
1371 currsav->lft_c->sadb_lifetime_addtime)
1372 candidate = currsav;
1373 }
1374
1375 if (candidate) {
1376 outsav->natt_encapsulated_src_port = candidate->natt_encapsulated_src_port;
1377 return 1;
1378 }
1379
1380 return 0;
1381 }
1382
1383 /*
1384 * Must be called after calling key_allocsp().
1385 * For both the packet without socket and key_freeso().
1386 */
1387 void
1388 key_freesp(
1389 struct secpolicy *sp,
1390 int locked)
1391 {
1392
1393 /* sanity check */
1394 if (sp == NULL)
1395 panic("key_freesp: NULL pointer is passed.\n");
1396
1397 if (!locked)
1398 lck_mtx_lock(sadb_mutex);
1399 else
1400 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
1401 sp->refcnt--;
1402 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1403 printf("DP freesp cause refcnt--:%d SP:%p\n",
1404 sp->refcnt, sp));
1405
1406 if (sp->refcnt == 0)
1407 key_delsp(sp);
1408 if (!locked)
1409 lck_mtx_unlock(sadb_mutex);
1410 return;
1411 }
1412
1413 #if 0
1414 static void key_freesp_so(struct secpolicy **);
1415
1416 /*
1417 * Must be called after calling key_allocsp().
1418 * For the packet with socket.
1419 */
1420 void
1421 key_freeso(
1422 struct socket *so)
1423 {
1424
1425 /* sanity check */
1426 if (so == NULL)
1427 panic("key_freeso: NULL pointer is passed.\n");
1428
1429 lck_mtx_lock(sadb_mutex);
1430 switch (so->so_proto->pr_domain->dom_family) {
1431 #if INET
1432 case PF_INET:
1433 {
1434 struct inpcb *pcb = sotoinpcb(so);
1435
1436 /* Does it have a PCB ? */
1437 if (pcb == NULL || pcb->inp_sp == NULL)
1438 goto done;
1439 key_freesp_so(&pcb->inp_sp->sp_in);
1440 key_freesp_so(&pcb->inp_sp->sp_out);
1441 }
1442 break;
1443 #endif
1444 #if INET6
1445 case PF_INET6:
1446 {
1447 #if HAVE_NRL_INPCB
1448 struct inpcb *pcb = sotoinpcb(so);
1449
1450 /* Does it have a PCB ? */
1451 if (pcb == NULL || pcb->inp_sp == NULL)
1452 goto done;
1453 key_freesp_so(&pcb->inp_sp->sp_in);
1454 key_freesp_so(&pcb->inp_sp->sp_out);
1455 #else
1456 struct in6pcb *pcb = sotoin6pcb(so);
1457
1458 /* Does it have a PCB ? */
1459 if (pcb == NULL || pcb->in6p_sp == NULL)
1460 goto done;
1461 key_freesp_so(&pcb->in6p_sp->sp_in);
1462 key_freesp_so(&pcb->in6p_sp->sp_out);
1463 #endif
1464 }
1465 break;
1466 #endif /* INET6 */
1467 default:
1468 ipseclog((LOG_DEBUG, "key_freeso: unknown address family=%d.\n",
1469 so->so_proto->pr_domain->dom_family));
1470 break;
1471 }
1472 done:
1473 lck_mtx_unlock(sadb_mutex);
1474
1475 return;
1476 }
1477
1478 static void
1479 key_freesp_so(
1480 struct secpolicy **sp)
1481 {
1482
1483 /* sanity check */
1484 if (sp == NULL || *sp == NULL)
1485 panic("key_freesp_so: sp == NULL\n");
1486
1487 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
1488
1489 switch ((*sp)->policy) {
1490 case IPSEC_POLICY_IPSEC:
1491 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1492 printf("DP freeso calls free SP:%p\n", *sp));
1493 key_freesp(*sp, KEY_SADB_LOCKED);
1494 *sp = NULL;
1495 break;
1496 case IPSEC_POLICY_ENTRUST:
1497 case IPSEC_POLICY_BYPASS:
1498 return;
1499 default:
1500 panic("key_freesp_so: Invalid policy found %d", (*sp)->policy);
1501 }
1502
1503 return;
1504 }
1505
1506 #endif
1507
1508 /*
1509 * Must be called after calling key_allocsa().
1510 * This function is called by key_freesp() to free some SA allocated
1511 * for a policy.
1512 */
1513 void
1514 key_freesav(
1515 struct secasvar *sav,
1516 int locked)
1517 {
1518
1519 /* sanity check */
1520 if (sav == NULL)
1521 panic("key_freesav: NULL pointer is passed.\n");
1522
1523 if (!locked)
1524 lck_mtx_lock(sadb_mutex);
1525 else
1526 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
1527 sav->refcnt--;
1528 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1529 printf("DP freesav cause refcnt--:%d SA:%p SPI %u\n",
1530 sav->refcnt, sav, (u_int32_t)ntohl(sav->spi)));
1531
1532 if (sav->refcnt == 0)
1533 key_delsav(sav);
1534 if (!locked)
1535 lck_mtx_unlock(sadb_mutex);
1536 return;
1537 }
1538
1539 /* %%% SPD management */
1540 /*
1541 * free security policy entry.
1542 */
1543 static void
1544 key_delsp(
1545 struct secpolicy *sp)
1546 {
1547
1548 /* sanity check */
1549 if (sp == NULL)
1550 panic("key_delsp: NULL pointer is passed.\n");
1551
1552 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
1553 sp->state = IPSEC_SPSTATE_DEAD;
1554
1555 if (sp->refcnt > 0)
1556 return; /* can't free */
1557
1558 /* remove from SP index */
1559 if (__LIST_CHAINED(sp)) {
1560 LIST_REMOVE(sp, chain);
1561 ipsec_policy_count--;
1562 }
1563
1564 {
1565 struct ipsecrequest *isr = sp->req, *nextisr;
1566
1567 while (isr != NULL) {
1568 nextisr = isr->next;
1569 KFREE(isr);
1570 isr = nextisr;
1571 }
1572 }
1573 keydb_delsecpolicy(sp);
1574
1575 return;
1576 }
1577
1578 /*
1579 * search SPD
1580 * OUT: NULL : not found
1581 * others : found, pointer to a SP.
1582 */
1583 static struct secpolicy *
1584 key_getsp(
1585 struct secpolicyindex *spidx)
1586 {
1587 struct secpolicy *sp;
1588
1589 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
1590
1591 /* sanity check */
1592 if (spidx == NULL)
1593 panic("key_getsp: NULL pointer is passed.\n");
1594
1595 LIST_FOREACH(sp, &sptree[spidx->dir], chain) {
1596 if (sp->state == IPSEC_SPSTATE_DEAD)
1597 continue;
1598 if (key_cmpspidx_exactly(spidx, &sp->spidx)) {
1599 sp->refcnt++;
1600 return sp;
1601 }
1602 }
1603
1604 return NULL;
1605 }
1606
1607 /*
1608 * get SP by index.
1609 * OUT: NULL : not found
1610 * others : found, pointer to a SP.
1611 */
1612 static struct secpolicy *
1613 key_getspbyid(
1614 u_int32_t id)
1615 {
1616 struct secpolicy *sp;
1617
1618 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
1619
1620 LIST_FOREACH(sp, &sptree[IPSEC_DIR_INBOUND], chain) {
1621 if (sp->state == IPSEC_SPSTATE_DEAD)
1622 continue;
1623 if (sp->id == id) {
1624 sp->refcnt++;
1625 return sp;
1626 }
1627 }
1628
1629 LIST_FOREACH(sp, &sptree[IPSEC_DIR_OUTBOUND], chain) {
1630 if (sp->state == IPSEC_SPSTATE_DEAD)
1631 continue;
1632 if (sp->id == id) {
1633 sp->refcnt++;
1634 return sp;
1635 }
1636 }
1637
1638 return NULL;
1639 }
1640
1641 struct secpolicy *
1642 key_newsp(void)
1643 {
1644 struct secpolicy *newsp = NULL;
1645
1646 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
1647 newsp = keydb_newsecpolicy();
1648 if (!newsp)
1649 return newsp;
1650
1651 newsp->refcnt = 1;
1652 newsp->req = NULL;
1653
1654 return newsp;
1655 }
1656
1657 /*
1658 * create secpolicy structure from sadb_x_policy structure.
1659 * NOTE: `state', `secpolicyindex' in secpolicy structure are not set,
1660 * so must be set properly later.
1661 */
1662 struct secpolicy *
1663 key_msg2sp(
1664 struct sadb_x_policy *xpl0,
1665 size_t len,
1666 int *error)
1667 {
1668 struct secpolicy *newsp;
1669
1670 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
1671
1672 /* sanity check */
1673 if (xpl0 == NULL)
1674 panic("key_msg2sp: NULL pointer was passed.\n");
1675 if (len < sizeof(*xpl0))
1676 panic("key_msg2sp: invalid length.\n");
1677 if (len != PFKEY_EXTLEN(xpl0)) {
1678 ipseclog((LOG_DEBUG, "key_msg2sp: Invalid msg length.\n"));
1679 *error = EINVAL;
1680 return NULL;
1681 }
1682
1683 if ((newsp = key_newsp()) == NULL) {
1684 *error = ENOBUFS;
1685 return NULL;
1686 }
1687
1688 newsp->spidx.dir = xpl0->sadb_x_policy_dir;
1689 newsp->policy = xpl0->sadb_x_policy_type;
1690
1691 /* check policy */
1692 switch (xpl0->sadb_x_policy_type) {
1693 case IPSEC_POLICY_DISCARD:
1694 case IPSEC_POLICY_GENERATE:
1695 case IPSEC_POLICY_NONE:
1696 case IPSEC_POLICY_ENTRUST:
1697 case IPSEC_POLICY_BYPASS:
1698 newsp->req = NULL;
1699 break;
1700
1701 case IPSEC_POLICY_IPSEC:
1702 {
1703 int tlen;
1704 struct sadb_x_ipsecrequest *xisr;
1705 struct ipsecrequest **p_isr = &newsp->req;
1706
1707 /* validity check */
1708 if (PFKEY_EXTLEN(xpl0) < sizeof(*xpl0)) {
1709 ipseclog((LOG_DEBUG,
1710 "key_msg2sp: Invalid msg length.\n"));
1711 key_freesp(newsp, KEY_SADB_UNLOCKED);
1712 *error = EINVAL;
1713 return NULL;
1714 }
1715
1716 tlen = PFKEY_EXTLEN(xpl0) - sizeof(*xpl0);
1717 xisr = (struct sadb_x_ipsecrequest *)(xpl0 + 1);
1718
1719 while (tlen > 0) {
1720
1721 /* length check */
1722 if (xisr->sadb_x_ipsecrequest_len < sizeof(*xisr)) {
1723 ipseclog((LOG_DEBUG, "key_msg2sp: "
1724 "invalid ipsecrequest length.\n"));
1725 key_freesp(newsp, KEY_SADB_UNLOCKED);
1726 *error = EINVAL;
1727 return NULL;
1728 }
1729
1730 /* allocate request buffer */
1731 KMALLOC_WAIT(*p_isr, struct ipsecrequest *, sizeof(**p_isr));
1732 if ((*p_isr) == NULL) {
1733 ipseclog((LOG_DEBUG,
1734 "key_msg2sp: No more memory.\n"));
1735 key_freesp(newsp, KEY_SADB_UNLOCKED);
1736 *error = ENOBUFS;
1737 return NULL;
1738 }
1739 bzero(*p_isr, sizeof(**p_isr));
1740
1741 /* set values */
1742 (*p_isr)->next = NULL;
1743
1744 switch (xisr->sadb_x_ipsecrequest_proto) {
1745 case IPPROTO_ESP:
1746 case IPPROTO_AH:
1747 case IPPROTO_IPCOMP:
1748 break;
1749 default:
1750 ipseclog((LOG_DEBUG,
1751 "key_msg2sp: invalid proto type=%u\n",
1752 xisr->sadb_x_ipsecrequest_proto));
1753 key_freesp(newsp, KEY_SADB_UNLOCKED);
1754 *error = EPROTONOSUPPORT;
1755 return NULL;
1756 }
1757 (*p_isr)->saidx.proto = xisr->sadb_x_ipsecrequest_proto;
1758
1759 switch (xisr->sadb_x_ipsecrequest_mode) {
1760 case IPSEC_MODE_TRANSPORT:
1761 case IPSEC_MODE_TUNNEL:
1762 break;
1763 case IPSEC_MODE_ANY:
1764 default:
1765 ipseclog((LOG_DEBUG,
1766 "key_msg2sp: invalid mode=%u\n",
1767 xisr->sadb_x_ipsecrequest_mode));
1768 key_freesp(newsp, KEY_SADB_UNLOCKED);
1769 *error = EINVAL;
1770 return NULL;
1771 }
1772 (*p_isr)->saidx.mode = xisr->sadb_x_ipsecrequest_mode;
1773
1774 switch (xisr->sadb_x_ipsecrequest_level) {
1775 case IPSEC_LEVEL_DEFAULT:
1776 case IPSEC_LEVEL_USE:
1777 case IPSEC_LEVEL_REQUIRE:
1778 break;
1779 case IPSEC_LEVEL_UNIQUE:
1780 /* validity check */
1781 /*
1782 * If range violation of reqid, kernel will
1783 * update it, don't refuse it.
1784 */
1785 if (xisr->sadb_x_ipsecrequest_reqid
1786 > IPSEC_MANUAL_REQID_MAX) {
1787 ipseclog((LOG_DEBUG,
1788 "key_msg2sp: reqid=%d range "
1789 "violation, updated by kernel.\n",
1790 xisr->sadb_x_ipsecrequest_reqid));
1791 xisr->sadb_x_ipsecrequest_reqid = 0;
1792 }
1793
1794 /* allocate new reqid id if reqid is zero. */
1795 if (xisr->sadb_x_ipsecrequest_reqid == 0) {
1796 u_int32_t reqid;
1797 if ((reqid = key_newreqid()) == 0) {
1798 key_freesp(newsp, KEY_SADB_UNLOCKED);
1799 *error = ENOBUFS;
1800 return NULL;
1801 }
1802 (*p_isr)->saidx.reqid = reqid;
1803 xisr->sadb_x_ipsecrequest_reqid = reqid;
1804 } else {
1805 /* set it for manual keying. */
1806 (*p_isr)->saidx.reqid =
1807 xisr->sadb_x_ipsecrequest_reqid;
1808 }
1809 break;
1810
1811 default:
1812 ipseclog((LOG_DEBUG, "key_msg2sp: invalid level=%u\n",
1813 xisr->sadb_x_ipsecrequest_level));
1814 key_freesp(newsp, KEY_SADB_UNLOCKED);
1815 *error = EINVAL;
1816 return NULL;
1817 }
1818 (*p_isr)->level = xisr->sadb_x_ipsecrequest_level;
1819
1820 /* set IP addresses if there */
1821 if (xisr->sadb_x_ipsecrequest_len > sizeof(*xisr)) {
1822 struct sockaddr *paddr;
1823
1824 paddr = (struct sockaddr *)(xisr + 1);
1825
1826 /* validity check */
1827 if (paddr->sa_len
1828 > sizeof((*p_isr)->saidx.src)) {
1829 ipseclog((LOG_DEBUG, "key_msg2sp: invalid request "
1830 "address length.\n"));
1831 key_freesp(newsp, KEY_SADB_UNLOCKED);
1832 *error = EINVAL;
1833 return NULL;
1834 }
1835 bcopy(paddr, &(*p_isr)->saidx.src,
1836 paddr->sa_len);
1837
1838 paddr = (struct sockaddr *)((caddr_t)paddr
1839 + paddr->sa_len);
1840
1841 /* validity check */
1842 if (paddr->sa_len
1843 > sizeof((*p_isr)->saidx.dst)) {
1844 ipseclog((LOG_DEBUG, "key_msg2sp: invalid request "
1845 "address length.\n"));
1846 key_freesp(newsp, KEY_SADB_UNLOCKED);
1847 *error = EINVAL;
1848 return NULL;
1849 }
1850 bcopy(paddr, &(*p_isr)->saidx.dst,
1851 paddr->sa_len);
1852 }
1853
1854 (*p_isr)->sp = newsp;
1855
1856 /* initialization for the next. */
1857 p_isr = &(*p_isr)->next;
1858 tlen -= xisr->sadb_x_ipsecrequest_len;
1859
1860 /* validity check */
1861 if (tlen < 0) {
1862 ipseclog((LOG_DEBUG, "key_msg2sp: becoming tlen < 0.\n"));
1863 key_freesp(newsp, KEY_SADB_UNLOCKED);
1864 *error = EINVAL;
1865 return NULL;
1866 }
1867
1868 xisr = (struct sadb_x_ipsecrequest *)(void *)
1869 ((caddr_t)xisr + xisr->sadb_x_ipsecrequest_len);
1870 }
1871 }
1872 break;
1873 default:
1874 ipseclog((LOG_DEBUG, "key_msg2sp: invalid policy type.\n"));
1875 key_freesp(newsp, KEY_SADB_UNLOCKED);
1876 *error = EINVAL;
1877 return NULL;
1878 }
1879
1880 *error = 0;
1881 return newsp;
1882 }
1883
1884 static u_int32_t
1885 key_newreqid(void)
1886 {
1887 lck_mtx_lock(sadb_mutex);
1888 static u_int32_t auto_reqid = IPSEC_MANUAL_REQID_MAX + 1;
1889 int done = 0;
1890
1891 /* The reqid must be limited to 16 bits because the PF_KEY message format only uses
1892 16 bits for this field. Once it becomes larger than 16 bits - ipsec fails to
1893 work anymore. Changing the PF_KEY message format would introduce compatibility
1894 issues. This code now tests to see if the tentative reqid is in use */
1895
1896 while (!done) {
1897 struct secpolicy *sp;
1898 struct ipsecrequest *isr;
1899 int dir;
1900
1901 auto_reqid = (auto_reqid == 0xFFFF
1902 ? IPSEC_MANUAL_REQID_MAX + 1 : auto_reqid + 1);
1903
1904 /* check for uniqueness */
1905 done = 1;
1906 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
1907 LIST_FOREACH(sp, &sptree[dir], chain) {
1908 for (isr = sp->req; isr != NULL; isr = isr->next) {
1909 if (isr->saidx.reqid == auto_reqid) {
1910 done = 0;
1911 break;
1912 }
1913 }
1914 if (done == 0)
1915 break;
1916 }
1917 if (done == 0)
1918 break;
1919 }
1920 }
1921
1922 lck_mtx_unlock(sadb_mutex);
1923 return auto_reqid;
1924 }
1925
1926 /*
1927 * copy secpolicy struct to sadb_x_policy structure indicated.
1928 */
1929 struct mbuf *
1930 key_sp2msg(
1931 struct secpolicy *sp)
1932 {
1933 struct sadb_x_policy *xpl;
1934 int tlen;
1935 caddr_t p;
1936 struct mbuf *m;
1937
1938 /* sanity check. */
1939 if (sp == NULL)
1940 panic("key_sp2msg: NULL pointer was passed.\n");
1941
1942 tlen = key_getspreqmsglen(sp);
1943
1944 m = key_alloc_mbuf(tlen);
1945 if (!m || m->m_next) { /*XXX*/
1946 if (m)
1947 m_freem(m);
1948 return NULL;
1949 }
1950
1951 m->m_len = tlen;
1952 m->m_next = NULL;
1953 xpl = mtod(m, struct sadb_x_policy *);
1954 bzero(xpl, tlen);
1955
1956 xpl->sadb_x_policy_len = PFKEY_UNIT64(tlen);
1957 xpl->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
1958 xpl->sadb_x_policy_type = sp->policy;
1959 xpl->sadb_x_policy_dir = sp->spidx.dir;
1960 xpl->sadb_x_policy_id = sp->id;
1961 p = (caddr_t)xpl + sizeof(*xpl);
1962
1963 /* if is the policy for ipsec ? */
1964 if (sp->policy == IPSEC_POLICY_IPSEC) {
1965 struct sadb_x_ipsecrequest *xisr;
1966 struct ipsecrequest *isr;
1967
1968 for (isr = sp->req; isr != NULL; isr = isr->next) {
1969
1970 xisr = (struct sadb_x_ipsecrequest *)(void *)p;
1971
1972 xisr->sadb_x_ipsecrequest_proto = isr->saidx.proto;
1973 xisr->sadb_x_ipsecrequest_mode = isr->saidx.mode;
1974 xisr->sadb_x_ipsecrequest_level = isr->level;
1975 xisr->sadb_x_ipsecrequest_reqid = isr->saidx.reqid;
1976
1977 p += sizeof(*xisr);
1978 bcopy(&isr->saidx.src, p, isr->saidx.src.ss_len);
1979 p += isr->saidx.src.ss_len;
1980 bcopy(&isr->saidx.dst, p, isr->saidx.dst.ss_len);
1981 p += isr->saidx.src.ss_len;
1982
1983 xisr->sadb_x_ipsecrequest_len =
1984 PFKEY_ALIGN8(sizeof(*xisr)
1985 + isr->saidx.src.ss_len
1986 + isr->saidx.dst.ss_len);
1987 }
1988 }
1989
1990 return m;
1991 }
1992
1993 /* m will not be freed nor modified */
1994 static struct mbuf *
1995 key_gather_mbuf(struct mbuf *m, const struct sadb_msghdr *mhp,
1996 int ndeep, int nitem, int *items)
1997 {
1998 int idx;
1999 int i;
2000 struct mbuf *result = NULL, *n;
2001 int len;
2002
2003 if (m == NULL || mhp == NULL)
2004 panic("null pointer passed to key_gather");
2005
2006 for (i = 0; i < nitem; i++) {
2007 idx = items[i];
2008 if (idx < 0 || idx > SADB_EXT_MAX)
2009 goto fail;
2010 /* don't attempt to pull empty extension */
2011 if (idx == SADB_EXT_RESERVED && mhp->msg == NULL)
2012 continue;
2013 if (idx != SADB_EXT_RESERVED &&
2014 (mhp->ext[idx] == NULL || mhp->extlen[idx] == 0))
2015 continue;
2016
2017 if (idx == SADB_EXT_RESERVED) {
2018 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2019 #if DIAGNOSTIC
2020 if (len > MHLEN)
2021 panic("assumption failed");
2022 #endif
2023 MGETHDR(n, M_WAITOK, MT_DATA);
2024 if (!n)
2025 goto fail;
2026 n->m_len = len;
2027 n->m_next = NULL;
2028 m_copydata(m, 0, sizeof(struct sadb_msg),
2029 mtod(n, caddr_t));
2030 } else if (i < ndeep) {
2031 len = mhp->extlen[idx];
2032 n = key_alloc_mbuf(len);
2033 if (!n || n->m_next) { /*XXX*/
2034 if (n)
2035 m_freem(n);
2036 goto fail;
2037 }
2038 m_copydata(m, mhp->extoff[idx], mhp->extlen[idx],
2039 mtod(n, caddr_t));
2040 } else {
2041 n = m_copym(m, mhp->extoff[idx], mhp->extlen[idx],
2042 M_WAITOK);
2043 }
2044 if (n == NULL)
2045 goto fail;
2046
2047 if (result)
2048 m_cat(result, n);
2049 else
2050 result = n;
2051 }
2052
2053 if ((result->m_flags & M_PKTHDR) != 0) {
2054 result->m_pkthdr.len = 0;
2055 for (n = result; n; n = n->m_next)
2056 result->m_pkthdr.len += n->m_len;
2057 }
2058
2059 return result;
2060
2061 fail:
2062 m_freem(result);
2063 return NULL;
2064 }
2065
2066 /*
2067 * SADB_X_SPDADD, SADB_X_SPDSETIDX or SADB_X_SPDUPDATE processing
2068 * add a entry to SP database, when received
2069 * <base, address(SD), (lifetime(H),) policy>
2070 * from the user(?).
2071 * Adding to SP database,
2072 * and send
2073 * <base, address(SD), (lifetime(H),) policy>
2074 * to the socket which was send.
2075 *
2076 * SPDADD set a unique policy entry.
2077 * SPDSETIDX like SPDADD without a part of policy requests.
2078 * SPDUPDATE replace a unique policy entry.
2079 *
2080 * m will always be freed.
2081 */
2082 static int
2083 key_spdadd(
2084 struct socket *so,
2085 struct mbuf *m,
2086 const struct sadb_msghdr *mhp)
2087 {
2088 struct sadb_address *src0, *dst0;
2089 struct sadb_x_policy *xpl0, *xpl;
2090 struct sadb_lifetime *lft = NULL;
2091 struct secpolicyindex spidx;
2092 struct secpolicy *newsp;
2093 struct timeval tv;
2094 int error;
2095
2096 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
2097
2098 /* sanity check */
2099 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
2100 panic("key_spdadd: NULL pointer is passed.\n");
2101
2102 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
2103 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
2104 mhp->ext[SADB_X_EXT_POLICY] == NULL) {
2105 ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
2106 return key_senderror(so, m, EINVAL);
2107 }
2108 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
2109 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
2110 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2111 ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
2112 return key_senderror(so, m, EINVAL);
2113 }
2114 if (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL) {
2115 if (mhp->extlen[SADB_EXT_LIFETIME_HARD]
2116 < sizeof(struct sadb_lifetime)) {
2117 ipseclog((LOG_DEBUG, "key_spdadd: invalid message is passed.\n"));
2118 return key_senderror(so, m, EINVAL);
2119 }
2120 lft = (struct sadb_lifetime *)
2121 (void *)mhp->ext[SADB_EXT_LIFETIME_HARD];
2122 }
2123
2124 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2125 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2126 xpl0 = (struct sadb_x_policy *)(void *)mhp->ext[SADB_X_EXT_POLICY];
2127
2128 /* make secindex */
2129 /* XXX boundary check against sa_len */
2130 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2131 src0 + 1,
2132 dst0 + 1,
2133 src0->sadb_address_prefixlen,
2134 dst0->sadb_address_prefixlen,
2135 src0->sadb_address_proto,
2136 &spidx);
2137
2138 /* checking the direciton. */
2139 switch (xpl0->sadb_x_policy_dir) {
2140 case IPSEC_DIR_INBOUND:
2141 case IPSEC_DIR_OUTBOUND:
2142 break;
2143 default:
2144 ipseclog((LOG_DEBUG, "key_spdadd: Invalid SP direction.\n"));
2145 mhp->msg->sadb_msg_errno = EINVAL;
2146 return 0;
2147 }
2148
2149 /* check policy */
2150 /* key_spdadd() accepts DISCARD, NONE and IPSEC. */
2151 if (xpl0->sadb_x_policy_type == IPSEC_POLICY_ENTRUST
2152 || xpl0->sadb_x_policy_type == IPSEC_POLICY_BYPASS) {
2153 ipseclog((LOG_DEBUG, "key_spdadd: Invalid policy type.\n"));
2154 return key_senderror(so, m, EINVAL);
2155 }
2156
2157 /* policy requests are mandatory when action is ipsec. */
2158 if (mhp->msg->sadb_msg_type != SADB_X_SPDSETIDX
2159 && xpl0->sadb_x_policy_type == IPSEC_POLICY_IPSEC
2160 && mhp->extlen[SADB_X_EXT_POLICY] <= sizeof(*xpl0)) {
2161 ipseclog((LOG_DEBUG, "key_spdadd: some policy requests part required.\n"));
2162 return key_senderror(so, m, EINVAL);
2163 }
2164
2165 /*
2166 * checking there is SP already or not.
2167 * SPDUPDATE doesn't depend on whether there is a SP or not.
2168 * If the type is either SPDADD or SPDSETIDX AND a SP is found,
2169 * then error.
2170 */
2171 lck_mtx_lock(sadb_mutex);
2172 newsp = key_getsp(&spidx);
2173 if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
2174 if (newsp) {
2175 newsp->state = IPSEC_SPSTATE_DEAD;
2176 key_freesp(newsp, KEY_SADB_LOCKED);
2177 }
2178 } else {
2179 if (newsp != NULL) {
2180 key_freesp(newsp, KEY_SADB_LOCKED);
2181 ipseclog((LOG_DEBUG, "key_spdadd: a SP entry exists already.\n"));
2182 lck_mtx_unlock(sadb_mutex);
2183 return key_senderror(so, m, EEXIST);
2184 }
2185 }
2186 lck_mtx_unlock(sadb_mutex);
2187 /* allocation new SP entry */
2188 if ((newsp = key_msg2sp(xpl0, PFKEY_EXTLEN(xpl0), &error)) == NULL) {
2189 return key_senderror(so, m, error);
2190 }
2191
2192 if ((newsp->id = key_getnewspid()) == 0) {
2193 keydb_delsecpolicy(newsp);
2194 return key_senderror(so, m, ENOBUFS);
2195 }
2196
2197 /* XXX boundary check against sa_len */
2198 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2199 src0 + 1,
2200 dst0 + 1,
2201 src0->sadb_address_prefixlen,
2202 dst0->sadb_address_prefixlen,
2203 src0->sadb_address_proto,
2204 &newsp->spidx);
2205
2206 /* sanity check on addr pair */
2207 if (((struct sockaddr *)(src0 + 1))->sa_family !=
2208 ((struct sockaddr *)(dst0+ 1))->sa_family) {
2209 keydb_delsecpolicy(newsp);
2210 return key_senderror(so, m, EINVAL);
2211 }
2212 if (((struct sockaddr *)(src0 + 1))->sa_len !=
2213 ((struct sockaddr *)(dst0+ 1))->sa_len) {
2214 keydb_delsecpolicy(newsp);
2215 return key_senderror(so, m, EINVAL);
2216 }
2217 #if 1
2218 /*
2219 * allow IPv6 over IPv4 tunnels using ESP -
2220 * otherwise reject if inner and outer address families not equal
2221 */
2222 if (newsp->req && newsp->req->saidx.src.ss_family) {
2223 struct sockaddr *sa;
2224 sa = (struct sockaddr *)(src0 + 1);
2225 if (sa->sa_family != newsp->req->saidx.src.ss_family) {
2226 if (newsp->req->saidx.mode != IPSEC_MODE_TUNNEL || newsp->req->saidx.proto != IPPROTO_ESP
2227 || sa->sa_family != AF_INET6 || newsp->req->saidx.src.ss_family != AF_INET) {
2228 keydb_delsecpolicy(newsp);
2229 return key_senderror(so, m, EINVAL);
2230 }
2231 }
2232 }
2233 if (newsp->req && newsp->req->saidx.dst.ss_family) {
2234 struct sockaddr *sa;
2235 sa = (struct sockaddr *)(dst0 + 1);
2236 if (sa->sa_family != newsp->req->saidx.dst.ss_family) {
2237 if (newsp->req->saidx.mode != IPSEC_MODE_TUNNEL || newsp->req->saidx.proto != IPPROTO_ESP
2238 || sa->sa_family != AF_INET6 || newsp->req->saidx.dst.ss_family != AF_INET) {
2239 keydb_delsecpolicy(newsp);
2240 return key_senderror(so, m, EINVAL);
2241 }
2242 }
2243 }
2244 #endif
2245
2246 microtime(&tv);
2247 newsp->created = tv.tv_sec;
2248 newsp->lastused = tv.tv_sec;
2249 newsp->lifetime = lft ? lft->sadb_lifetime_addtime : 0;
2250 newsp->validtime = lft ? lft->sadb_lifetime_usetime : 0;
2251
2252 newsp->refcnt = 1; /* do not reclaim until I say I do */
2253 newsp->state = IPSEC_SPSTATE_ALIVE;
2254 lck_mtx_lock(sadb_mutex);
2255 /*
2256 * policies of type generate should be at the end of the SPD
2257 * because they function as default discard policies
2258 */
2259 if (newsp->policy == IPSEC_POLICY_GENERATE)
2260 LIST_INSERT_TAIL(&sptree[newsp->spidx.dir], newsp, secpolicy, chain);
2261 else { /* XXX until we have policy ordering in the kernel */
2262 struct secpolicy *tmpsp;
2263
2264 LIST_FOREACH(tmpsp, &sptree[newsp->spidx.dir], chain)
2265 if (tmpsp->policy == IPSEC_POLICY_GENERATE)
2266 break;
2267 if (tmpsp)
2268 LIST_INSERT_BEFORE(tmpsp, newsp, chain);
2269 else
2270 LIST_INSERT_TAIL(&sptree[newsp->spidx.dir], newsp, secpolicy, chain);
2271 }
2272
2273 ipsec_policy_count++;
2274 /* Turn off the ipsec bypass */
2275 if (ipsec_bypass != 0)
2276 ipsec_bypass = 0;
2277
2278 /* delete the entry in spacqtree */
2279 if (mhp->msg->sadb_msg_type == SADB_X_SPDUPDATE) {
2280 struct secspacq *spacq;
2281 if ((spacq = key_getspacq(&spidx)) != NULL) {
2282 /* reset counter in order to deletion by timehandler. */
2283 microtime(&tv);
2284 spacq->created = tv.tv_sec;
2285 spacq->count = 0;
2286 }
2287 }
2288 lck_mtx_unlock(sadb_mutex);
2289
2290 {
2291 struct mbuf *n, *mpolicy;
2292 struct sadb_msg *newmsg;
2293 int off;
2294
2295 /* create new sadb_msg to reply. */
2296 if (lft) {
2297 int mbufItems[] = {SADB_EXT_RESERVED, SADB_X_EXT_POLICY,
2298 SADB_EXT_LIFETIME_HARD, SADB_EXT_ADDRESS_SRC,
2299 SADB_EXT_ADDRESS_DST};
2300 n = key_gather_mbuf(m, mhp, 2, sizeof(mbufItems)/sizeof(int), mbufItems);
2301 } else {
2302 int mbufItems[] = {SADB_EXT_RESERVED, SADB_X_EXT_POLICY,
2303 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST};
2304 n = key_gather_mbuf(m, mhp, 2, sizeof(mbufItems)/sizeof(int), mbufItems);
2305 }
2306 if (!n)
2307 return key_senderror(so, m, ENOBUFS);
2308
2309 if (n->m_len < sizeof(*newmsg)) {
2310 n = m_pullup(n, sizeof(*newmsg));
2311 if (!n)
2312 return key_senderror(so, m, ENOBUFS);
2313 }
2314 newmsg = mtod(n, struct sadb_msg *);
2315 newmsg->sadb_msg_errno = 0;
2316 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2317
2318 off = 0;
2319 mpolicy = m_pulldown(n, PFKEY_ALIGN8(sizeof(struct sadb_msg)),
2320 sizeof(*xpl), &off);
2321 if (mpolicy == NULL) {
2322 /* n is already freed */
2323 return key_senderror(so, m, ENOBUFS);
2324 }
2325 xpl = (struct sadb_x_policy *)(void *)(mtod(mpolicy, caddr_t) + off);
2326 if (xpl->sadb_x_policy_exttype != SADB_X_EXT_POLICY) {
2327 m_freem(n);
2328 return key_senderror(so, m, EINVAL);
2329 }
2330 xpl->sadb_x_policy_id = newsp->id;
2331
2332 m_freem(m);
2333 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2334 }
2335 }
2336
2337 /*
2338 * get new policy id.
2339 * OUT:
2340 * 0: failure.
2341 * others: success.
2342 */
2343 static u_int32_t
2344 key_getnewspid(void)
2345 {
2346 u_int32_t newid = 0;
2347 int count = key_spi_trycnt; /* XXX */
2348 struct secpolicy *sp;
2349
2350 /* when requesting to allocate spi ranged */
2351 lck_mtx_lock(sadb_mutex);
2352 while (count--) {
2353 newid = (policy_id = (policy_id == ~0 ? 1 : policy_id + 1));
2354
2355 if ((sp = key_getspbyid(newid)) == NULL)
2356 break;
2357
2358 key_freesp(sp, KEY_SADB_LOCKED);
2359 }
2360 lck_mtx_unlock(sadb_mutex);
2361 if (count == 0 || newid == 0) {
2362 ipseclog((LOG_DEBUG, "key_getnewspid: to allocate policy id is failed.\n"));
2363 return 0;
2364 }
2365
2366 return newid;
2367 }
2368
2369 /*
2370 * SADB_SPDDELETE processing
2371 * receive
2372 * <base, address(SD), policy(*)>
2373 * from the user(?), and set SADB_SASTATE_DEAD,
2374 * and send,
2375 * <base, address(SD), policy(*)>
2376 * to the ikmpd.
2377 * policy(*) including direction of policy.
2378 *
2379 * m will always be freed.
2380 */
2381 static int
2382 key_spddelete(
2383 struct socket *so,
2384 struct mbuf *m,
2385 const struct sadb_msghdr *mhp)
2386 {
2387 struct sadb_address *src0, *dst0;
2388 struct sadb_x_policy *xpl0;
2389 struct secpolicyindex spidx;
2390 struct secpolicy *sp;
2391
2392 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
2393
2394 /* sanity check */
2395 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
2396 panic("key_spddelete: NULL pointer is passed.\n");
2397
2398 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
2399 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
2400 mhp->ext[SADB_X_EXT_POLICY] == NULL) {
2401 ipseclog((LOG_DEBUG, "key_spddelete: invalid message is passed.\n"));
2402 return key_senderror(so, m, EINVAL);
2403 }
2404 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
2405 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
2406 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2407 ipseclog((LOG_DEBUG, "key_spddelete: invalid message is passed.\n"));
2408 return key_senderror(so, m, EINVAL);
2409 }
2410
2411 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
2412 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
2413 xpl0 = (struct sadb_x_policy *)(void *)mhp->ext[SADB_X_EXT_POLICY];
2414
2415 /* make secindex */
2416 /* XXX boundary check against sa_len */
2417 KEY_SETSECSPIDX(xpl0->sadb_x_policy_dir,
2418 src0 + 1,
2419 dst0 + 1,
2420 src0->sadb_address_prefixlen,
2421 dst0->sadb_address_prefixlen,
2422 src0->sadb_address_proto,
2423 &spidx);
2424
2425 /* checking the direciton. */
2426 switch (xpl0->sadb_x_policy_dir) {
2427 case IPSEC_DIR_INBOUND:
2428 case IPSEC_DIR_OUTBOUND:
2429 break;
2430 default:
2431 ipseclog((LOG_DEBUG, "key_spddelete: Invalid SP direction.\n"));
2432 return key_senderror(so, m, EINVAL);
2433 }
2434
2435 /* Is there SP in SPD ? */
2436 lck_mtx_lock(sadb_mutex);
2437 if ((sp = key_getsp(&spidx)) == NULL) {
2438 ipseclog((LOG_DEBUG, "key_spddelete: no SP found.\n"));
2439 lck_mtx_unlock(sadb_mutex);
2440 return key_senderror(so, m, EINVAL);
2441 }
2442
2443 /* save policy id to buffer to be returned. */
2444 xpl0->sadb_x_policy_id = sp->id;
2445
2446 sp->state = IPSEC_SPSTATE_DEAD;
2447 key_freesp(sp, KEY_SADB_LOCKED);
2448 lck_mtx_unlock(sadb_mutex);
2449
2450
2451 {
2452 struct mbuf *n;
2453 struct sadb_msg *newmsg;
2454 int mbufItems[] = {SADB_EXT_RESERVED, SADB_X_EXT_POLICY,
2455 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST};
2456
2457 /* create new sadb_msg to reply. */
2458 n = key_gather_mbuf(m, mhp, 1, sizeof(mbufItems)/sizeof(int), mbufItems);
2459 if (!n)
2460 return key_senderror(so, m, ENOBUFS);
2461
2462 newmsg = mtod(n, struct sadb_msg *);
2463 newmsg->sadb_msg_errno = 0;
2464 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2465
2466 m_freem(m);
2467 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2468 }
2469 }
2470
2471 /*
2472 * SADB_SPDDELETE2 processing
2473 * receive
2474 * <base, policy(*)>
2475 * from the user(?), and set SADB_SASTATE_DEAD,
2476 * and send,
2477 * <base, policy(*)>
2478 * to the ikmpd.
2479 * policy(*) including direction of policy.
2480 *
2481 * m will always be freed.
2482 */
2483 static int
2484 key_spddelete2(
2485 struct socket *so,
2486 struct mbuf *m,
2487 const struct sadb_msghdr *mhp)
2488 {
2489 u_int32_t id;
2490 struct secpolicy *sp;
2491
2492 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
2493
2494 /* sanity check */
2495 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
2496 panic("key_spddelete2: NULL pointer is passed.\n");
2497
2498 if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2499 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2500 ipseclog((LOG_DEBUG, "key_spddelete2: invalid message is passed.\n"));
2501 key_senderror(so, m, EINVAL);
2502 return 0;
2503 }
2504
2505 id = ((struct sadb_x_policy *)
2506 (void *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2507
2508 /* Is there SP in SPD ? */
2509 lck_mtx_lock(sadb_mutex);
2510 if ((sp = key_getspbyid(id)) == NULL) {
2511 lck_mtx_unlock(sadb_mutex);
2512 ipseclog((LOG_DEBUG, "key_spddelete2: no SP found id:%u.\n", id));
2513 return key_senderror(so, m, EINVAL);
2514 }
2515
2516 sp->state = IPSEC_SPSTATE_DEAD;
2517 key_freesp(sp, KEY_SADB_LOCKED);
2518 lck_mtx_unlock(sadb_mutex);
2519
2520 {
2521 struct mbuf *n, *nn;
2522 struct sadb_msg *newmsg;
2523 int off, len;
2524
2525 /* create new sadb_msg to reply. */
2526 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2527
2528 if (len > MCLBYTES)
2529 return key_senderror(so, m, ENOBUFS);
2530 MGETHDR(n, M_WAITOK, MT_DATA);
2531 if (n && len > MHLEN) {
2532 MCLGET(n, M_WAITOK);
2533 if ((n->m_flags & M_EXT) == 0) {
2534 m_freem(n);
2535 n = NULL;
2536 }
2537 }
2538 if (!n)
2539 return key_senderror(so, m, ENOBUFS);
2540
2541 n->m_len = len;
2542 n->m_next = NULL;
2543 off = 0;
2544
2545 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
2546 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
2547
2548 #if DIAGNOSTIC
2549 if (off != len)
2550 panic("length inconsistency in key_spddelete2");
2551 #endif
2552
2553 n->m_next = m_copym(m, mhp->extoff[SADB_X_EXT_POLICY],
2554 mhp->extlen[SADB_X_EXT_POLICY], M_WAITOK);
2555 if (!n->m_next) {
2556 m_freem(n);
2557 return key_senderror(so, m, ENOBUFS);
2558 }
2559
2560 n->m_pkthdr.len = 0;
2561 for (nn = n; nn; nn = nn->m_next)
2562 n->m_pkthdr.len += nn->m_len;
2563
2564 newmsg = mtod(n, struct sadb_msg *);
2565 newmsg->sadb_msg_errno = 0;
2566 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
2567
2568 m_freem(m);
2569 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
2570 }
2571 }
2572
2573 /*
2574 * SADB_X_GET processing
2575 * receive
2576 * <base, policy(*)>
2577 * from the user(?),
2578 * and send,
2579 * <base, address(SD), policy>
2580 * to the ikmpd.
2581 * policy(*) including direction of policy.
2582 *
2583 * m will always be freed.
2584 */
2585 static int
2586 key_spdget(
2587 struct socket *so,
2588 struct mbuf *m,
2589 const struct sadb_msghdr *mhp)
2590 {
2591 u_int32_t id;
2592 struct secpolicy *sp;
2593 struct mbuf *n;
2594
2595 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
2596
2597 /* sanity check */
2598 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
2599 panic("key_spdget: NULL pointer is passed.\n");
2600
2601 if (mhp->ext[SADB_X_EXT_POLICY] == NULL ||
2602 mhp->extlen[SADB_X_EXT_POLICY] < sizeof(struct sadb_x_policy)) {
2603 ipseclog((LOG_DEBUG, "key_spdget: invalid message is passed.\n"));
2604 return key_senderror(so, m, EINVAL);
2605 }
2606
2607 id = ((struct sadb_x_policy *)
2608 (void *)mhp->ext[SADB_X_EXT_POLICY])->sadb_x_policy_id;
2609
2610 /* Is there SP in SPD ? */
2611 lck_mtx_lock(sadb_mutex);
2612 if ((sp = key_getspbyid(id)) == NULL) {
2613 ipseclog((LOG_DEBUG, "key_spdget: no SP found id:%u.\n", id));
2614 lck_mtx_unlock(sadb_mutex);
2615 return key_senderror(so, m, ENOENT);
2616 }
2617 lck_mtx_unlock(sadb_mutex);
2618 n = key_setdumpsp(sp, SADB_X_SPDGET, 0, mhp->msg->sadb_msg_pid);
2619 if (n != NULL) {
2620 m_freem(m);
2621 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2622 } else
2623 return key_senderror(so, m, ENOBUFS);
2624 }
2625
2626 /*
2627 * SADB_X_SPDACQUIRE processing.
2628 * Acquire policy and SA(s) for a *OUTBOUND* packet.
2629 * send
2630 * <base, policy(*)>
2631 * to KMD, and expect to receive
2632 * <base> with SADB_X_SPDACQUIRE if error occurred,
2633 * or
2634 * <base, policy>
2635 * with SADB_X_SPDUPDATE from KMD by PF_KEY.
2636 * policy(*) is without policy requests.
2637 *
2638 * 0 : succeed
2639 * others: error number
2640 */
2641 int
2642 key_spdacquire(
2643 struct secpolicy *sp)
2644 {
2645 struct mbuf *result = NULL, *m;
2646 struct secspacq *newspacq;
2647 int error;
2648
2649 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
2650
2651 /* sanity check */
2652 if (sp == NULL)
2653 panic("key_spdacquire: NULL pointer is passed.\n");
2654 if (sp->req != NULL)
2655 panic("key_spdacquire: called but there is request.\n");
2656 if (sp->policy != IPSEC_POLICY_IPSEC)
2657 panic("key_spdacquire: policy mismathed. IPsec is expected.\n");
2658
2659 /* get a entry to check whether sent message or not. */
2660 lck_mtx_lock(sadb_mutex);
2661 if ((newspacq = key_getspacq(&sp->spidx)) != NULL) {
2662 if (key_blockacq_count < newspacq->count) {
2663 /* reset counter and do send message. */
2664 newspacq->count = 0;
2665 } else {
2666 /* increment counter and do nothing. */
2667 newspacq->count++;
2668 lck_mtx_unlock(sadb_mutex);
2669 return 0;
2670 }
2671 } else {
2672 /* make new entry for blocking to send SADB_ACQUIRE. */
2673 if ((newspacq = key_newspacq(&sp->spidx)) == NULL) {
2674 lck_mtx_unlock(sadb_mutex);
2675 return ENOBUFS;
2676 }
2677 /* add to acqtree */
2678 LIST_INSERT_HEAD(&spacqtree, newspacq, chain);
2679 }
2680 lck_mtx_unlock(sadb_mutex);
2681 /* create new sadb_msg to reply. */
2682 m = key_setsadbmsg(SADB_X_SPDACQUIRE, 0, 0, 0, 0, 0);
2683 if (!m) {
2684 error = ENOBUFS;
2685 goto fail;
2686 }
2687 result = m;
2688
2689 result->m_pkthdr.len = 0;
2690 for (m = result; m; m = m->m_next)
2691 result->m_pkthdr.len += m->m_len;
2692
2693 mtod(result, struct sadb_msg *)->sadb_msg_len =
2694 PFKEY_UNIT64(result->m_pkthdr.len);
2695
2696 return key_sendup_mbuf(NULL, m, KEY_SENDUP_REGISTERED);
2697
2698 fail:
2699 if (result)
2700 m_freem(result);
2701 return error;
2702 }
2703
2704 /*
2705 * SADB_SPDFLUSH processing
2706 * receive
2707 * <base>
2708 * from the user, and free all entries in secpctree.
2709 * and send,
2710 * <base>
2711 * to the user.
2712 * NOTE: what to do is only marking SADB_SASTATE_DEAD.
2713 *
2714 * m will always be freed.
2715 */
2716 static int
2717 key_spdflush(
2718 struct socket *so,
2719 struct mbuf *m,
2720 const struct sadb_msghdr *mhp)
2721 {
2722 struct sadb_msg *newmsg;
2723 struct secpolicy *sp;
2724 u_int dir;
2725
2726 /* sanity check */
2727 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
2728 panic("key_spdflush: NULL pointer is passed.\n");
2729
2730 if (m->m_len != PFKEY_ALIGN8(sizeof(struct sadb_msg)))
2731 return key_senderror(so, m, EINVAL);
2732
2733 lck_mtx_lock(sadb_mutex);
2734 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2735 LIST_FOREACH(sp, &sptree[dir], chain) {
2736 sp->state = IPSEC_SPSTATE_DEAD;
2737 }
2738 }
2739 lck_mtx_unlock(sadb_mutex);
2740
2741 if (sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
2742 ipseclog((LOG_DEBUG, "key_spdflush: No more memory.\n"));
2743 return key_senderror(so, m, ENOBUFS);
2744 }
2745
2746 if (m->m_next)
2747 m_freem(m->m_next);
2748 m->m_next = NULL;
2749 m->m_pkthdr.len = m->m_len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
2750 newmsg = mtod(m, struct sadb_msg *);
2751 newmsg->sadb_msg_errno = 0;
2752 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
2753
2754 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
2755 }
2756
2757 /*
2758 * SADB_SPDDUMP processing
2759 * receive
2760 * <base>
2761 * from the user, and dump all SP leaves
2762 * and send,
2763 * <base> .....
2764 * to the ikmpd.
2765 *
2766 * m will always be freed.
2767 */
2768
2769 static int
2770 key_spddump(
2771 struct socket *so,
2772 struct mbuf *m,
2773 const struct sadb_msghdr *mhp)
2774 {
2775 struct secpolicy *sp, **spbuf = NULL, **sp_ptr;
2776 int cnt = 0, bufcount;
2777 u_int dir;
2778 struct mbuf *n;
2779 int error = 0;
2780
2781 /* sanity check */
2782 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
2783 panic("key_spddump: NULL pointer is passed.\n");
2784
2785 if ((bufcount = ipsec_policy_count) == 0) {
2786 error = ENOENT;
2787 goto end;
2788 }
2789 bufcount += 256; /* extra */
2790 KMALLOC_WAIT(spbuf, struct secpolicy**, bufcount * sizeof(struct secpolicy*));
2791 if (spbuf == NULL) {
2792 ipseclog((LOG_DEBUG, "key_spddump: No more memory.\n"));
2793 error = ENOMEM;
2794 goto end;
2795 }
2796 lck_mtx_lock(sadb_mutex);
2797 /* search SPD entry, make list. */
2798 sp_ptr = spbuf;
2799 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
2800 LIST_FOREACH(sp, &sptree[dir], chain) {
2801 if (cnt == bufcount)
2802 break; /* buffer full */
2803 *sp_ptr++ = sp;
2804 sp->refcnt++;
2805 cnt++;
2806 }
2807 }
2808 lck_mtx_unlock(sadb_mutex);
2809
2810 if (cnt == 0) {
2811 error = ENOENT;
2812 goto end;
2813 }
2814
2815 sp_ptr = spbuf;
2816 while (cnt) {
2817 --cnt;
2818 n = key_setdumpsp(*sp_ptr++, SADB_X_SPDDUMP, cnt,
2819 mhp->msg->sadb_msg_pid);
2820
2821 if (n)
2822 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
2823 }
2824
2825 lck_mtx_lock(sadb_mutex);
2826 while (sp_ptr > spbuf)
2827 key_freesp(*(--sp_ptr), KEY_SADB_LOCKED);
2828 lck_mtx_unlock(sadb_mutex);
2829
2830 end:
2831 if (spbuf)
2832 KFREE(spbuf);
2833 if (error)
2834 return key_senderror(so, m, error);
2835
2836 m_freem(m);
2837 return 0;
2838
2839 }
2840
2841 static struct mbuf *
2842 key_setdumpsp(
2843 struct secpolicy *sp,
2844 u_int8_t type,
2845 u_int32_t seq,
2846 u_int32_t pid)
2847 {
2848 struct mbuf *result = NULL, *m;
2849
2850 m = key_setsadbmsg(type, 0, SADB_SATYPE_UNSPEC, seq, pid, sp->refcnt);
2851 if (!m)
2852 goto fail;
2853 result = m;
2854
2855 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2856 (struct sockaddr *)&sp->spidx.src, sp->spidx.prefs,
2857 sp->spidx.ul_proto);
2858 if (!m)
2859 goto fail;
2860 m_cat(result, m);
2861
2862 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2863 (struct sockaddr *)&sp->spidx.dst, sp->spidx.prefd,
2864 sp->spidx.ul_proto);
2865 if (!m)
2866 goto fail;
2867 m_cat(result, m);
2868
2869 m = key_sp2msg(sp);
2870 if (!m)
2871 goto fail;
2872 m_cat(result, m);
2873
2874 if ((result->m_flags & M_PKTHDR) == 0)
2875 goto fail;
2876
2877 if (result->m_len < sizeof(struct sadb_msg)) {
2878 result = m_pullup(result, sizeof(struct sadb_msg));
2879 if (result == NULL)
2880 goto fail;
2881 }
2882
2883 result->m_pkthdr.len = 0;
2884 for (m = result; m; m = m->m_next)
2885 result->m_pkthdr.len += m->m_len;
2886
2887 mtod(result, struct sadb_msg *)->sadb_msg_len =
2888 PFKEY_UNIT64(result->m_pkthdr.len);
2889
2890 return result;
2891
2892 fail:
2893 m_freem(result);
2894 return NULL;
2895 }
2896
2897 /*
2898 * get PFKEY message length for security policy and request.
2899 */
2900 static u_int
2901 key_getspreqmsglen(
2902 struct secpolicy *sp)
2903 {
2904 u_int tlen;
2905
2906 tlen = sizeof(struct sadb_x_policy);
2907
2908 /* if is the policy for ipsec ? */
2909 if (sp->policy != IPSEC_POLICY_IPSEC)
2910 return tlen;
2911
2912 /* get length of ipsec requests */
2913 {
2914 struct ipsecrequest *isr;
2915 int len;
2916
2917 for (isr = sp->req; isr != NULL; isr = isr->next) {
2918 len = sizeof(struct sadb_x_ipsecrequest)
2919 + isr->saidx.src.ss_len
2920 + isr->saidx.dst.ss_len;
2921
2922 tlen += PFKEY_ALIGN8(len);
2923 }
2924 }
2925
2926 return tlen;
2927 }
2928
2929 /*
2930 * SADB_SPDEXPIRE processing
2931 * send
2932 * <base, address(SD), lifetime(CH), policy>
2933 * to KMD by PF_KEY.
2934 *
2935 * OUT: 0 : succeed
2936 * others : error number
2937 */
2938 static int
2939 key_spdexpire(
2940 struct secpolicy *sp)
2941 {
2942 struct mbuf *result = NULL, *m;
2943 int len;
2944 int error = EINVAL;
2945 struct sadb_lifetime *lt;
2946
2947 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
2948
2949 /* sanity check */
2950 if (sp == NULL)
2951 panic("key_spdexpire: NULL pointer is passed.\n");
2952
2953 /* set msg header */
2954 m = key_setsadbmsg(SADB_X_SPDEXPIRE, 0, 0, 0, 0, 0);
2955 if (!m) {
2956 error = ENOBUFS;
2957 goto fail;
2958 }
2959 result = m;
2960
2961 /* create lifetime extension (current and hard) */
2962 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
2963 m = key_alloc_mbuf(len);
2964 if (!m || m->m_next) { /*XXX*/
2965 if (m)
2966 m_freem(m);
2967 error = ENOBUFS;
2968 goto fail;
2969 }
2970 bzero(mtod(m, caddr_t), len);
2971 lt = mtod(m, struct sadb_lifetime *);
2972 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2973 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2974 lt->sadb_lifetime_allocations = 0;
2975 lt->sadb_lifetime_bytes = 0;
2976 lt->sadb_lifetime_addtime = sp->created;
2977 lt->sadb_lifetime_usetime = sp->lastused;
2978 lt = (struct sadb_lifetime *)(void *)(mtod(m, caddr_t) + len / 2);
2979 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
2980 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2981 lt->sadb_lifetime_allocations = 0;
2982 lt->sadb_lifetime_bytes = 0;
2983 lt->sadb_lifetime_addtime = sp->lifetime;
2984 lt->sadb_lifetime_usetime = sp->validtime;
2985 m_cat(result, m);
2986
2987 /* set sadb_address for source */
2988 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
2989 (struct sockaddr *)&sp->spidx.src,
2990 sp->spidx.prefs, sp->spidx.ul_proto);
2991 if (!m) {
2992 error = ENOBUFS;
2993 goto fail;
2994 }
2995 m_cat(result, m);
2996
2997 /* set sadb_address for destination */
2998 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
2999 (struct sockaddr *)&sp->spidx.dst,
3000 sp->spidx.prefd, sp->spidx.ul_proto);
3001 if (!m) {
3002 error = ENOBUFS;
3003 goto fail;
3004 }
3005 m_cat(result, m);
3006
3007 /* set secpolicy */
3008 m = key_sp2msg(sp);
3009 if (!m) {
3010 error = ENOBUFS;
3011 goto fail;
3012 }
3013 m_cat(result, m);
3014
3015 if ((result->m_flags & M_PKTHDR) == 0) {
3016 error = EINVAL;
3017 goto fail;
3018 }
3019
3020 if (result->m_len < sizeof(struct sadb_msg)) {
3021 result = m_pullup(result, sizeof(struct sadb_msg));
3022 if (result == NULL) {
3023 error = ENOBUFS;
3024 goto fail;
3025 }
3026 }
3027
3028 result->m_pkthdr.len = 0;
3029 for (m = result; m; m = m->m_next)
3030 result->m_pkthdr.len += m->m_len;
3031
3032 mtod(result, struct sadb_msg *)->sadb_msg_len =
3033 PFKEY_UNIT64(result->m_pkthdr.len);
3034
3035 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
3036
3037 fail:
3038 if (result)
3039 m_freem(result);
3040 return error;
3041 }
3042
3043 /* %%% SAD management */
3044 /*
3045 * allocating a memory for new SA head, and copy from the values of mhp.
3046 * OUT: NULL : failure due to the lack of memory.
3047 * others : pointer to new SA head.
3048 */
3049 static struct secashead *
3050 key_newsah(
3051 struct secasindex *saidx,
3052 u_int8_t dir)
3053 {
3054 struct secashead *newsah;
3055
3056 /* sanity check */
3057 if (saidx == NULL)
3058 panic("key_newsaidx: NULL pointer is passed.\n");
3059
3060 newsah = keydb_newsecashead();
3061 if (newsah == NULL)
3062 return NULL;
3063
3064 bcopy(saidx, &newsah->saidx, sizeof(newsah->saidx));
3065
3066 /* remove the ports */
3067 switch (saidx->src.ss_family) {
3068 case AF_INET:
3069 ((struct sockaddr_in *)(&newsah->saidx.src))->sin_port = IPSEC_PORT_ANY;
3070 break;
3071 case AF_INET6:
3072 ((struct sockaddr_in6 *)(&newsah->saidx.src))->sin6_port = IPSEC_PORT_ANY;
3073 break;
3074 default:
3075 break;
3076 }
3077 switch (saidx->dst.ss_family) {
3078 case AF_INET:
3079 ((struct sockaddr_in *)(&newsah->saidx.dst))->sin_port = IPSEC_PORT_ANY;
3080 break;
3081 case AF_INET6:
3082 ((struct sockaddr_in6 *)(&newsah->saidx.dst))->sin6_port = IPSEC_PORT_ANY;
3083 break;
3084 default:
3085 break;
3086 }
3087
3088 newsah->dir = dir;
3089 /* add to saidxtree */
3090 newsah->state = SADB_SASTATE_MATURE;
3091 LIST_INSERT_HEAD(&sahtree, newsah, chain);
3092
3093 return(newsah);
3094 }
3095
3096 /*
3097 * delete SA index and all SA registerd.
3098 */
3099 void
3100 key_delsah(
3101 struct secashead *sah)
3102 {
3103 struct secasvar *sav, *nextsav;
3104 u_int stateidx, state;
3105 int zombie = 0;
3106
3107 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
3108
3109 /* sanity check */
3110 if (sah == NULL)
3111 panic("key_delsah: NULL pointer is passed.\n");
3112
3113 /* searching all SA registerd in the secindex. */
3114 for (stateidx = 0;
3115 stateidx < _ARRAYLEN(saorder_state_any);
3116 stateidx++) {
3117
3118 state = saorder_state_any[stateidx];
3119 for (sav = (struct secasvar *)LIST_FIRST(&sah->savtree[state]);
3120 sav != NULL;
3121 sav = nextsav) {
3122
3123 nextsav = LIST_NEXT(sav, chain);
3124
3125 if (sav->refcnt > 0) {
3126 /* give up to delete this sa */
3127 zombie++;
3128 continue;
3129 }
3130
3131 /* sanity check */
3132 KEY_CHKSASTATE(state, sav->state, "key_delsah");
3133
3134 key_freesav(sav, KEY_SADB_LOCKED);
3135
3136 /* remove back pointer */
3137 sav->sah = NULL;
3138 sav = NULL;
3139 }
3140 }
3141
3142 /* don't delete sah only if there are savs. */
3143 if (zombie)
3144 return;
3145
3146 if (sah->sa_route.ro_rt) {
3147 rtfree(sah->sa_route.ro_rt);
3148 sah->sa_route.ro_rt = (struct rtentry *)NULL;
3149 }
3150
3151 /* remove from tree of SA index */
3152 if (__LIST_CHAINED(sah))
3153 LIST_REMOVE(sah, chain);
3154
3155 KFREE(sah);
3156
3157 return;
3158 }
3159
3160 /*
3161 * allocating a new SA with LARVAL state. key_add() and key_getspi() call,
3162 * and copy the values of mhp into new buffer.
3163 * When SAD message type is GETSPI:
3164 * to set sequence number from acq_seq++,
3165 * to set zero to SPI.
3166 * not to call key_setsava().
3167 * OUT: NULL : fail
3168 * others : pointer to new secasvar.
3169 *
3170 * does not modify mbuf. does not free mbuf on error.
3171 */
3172 static struct secasvar *
3173 key_newsav(
3174 struct mbuf *m,
3175 const struct sadb_msghdr *mhp,
3176 struct secashead *sah,
3177 int *errp)
3178 {
3179 struct secasvar *newsav;
3180 const struct sadb_sa *xsa;
3181
3182 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
3183
3184 /* sanity check */
3185 if (m == NULL || mhp == NULL || mhp->msg == NULL || sah == NULL)
3186 panic("key_newsa: NULL pointer is passed.\n");
3187
3188 KMALLOC_NOWAIT(newsav, struct secasvar *, sizeof(struct secasvar));
3189 if (newsav == NULL) {
3190 lck_mtx_unlock(sadb_mutex);
3191 KMALLOC_WAIT(newsav, struct secasvar *, sizeof(struct secasvar));
3192 lck_mtx_lock(sadb_mutex);
3193 if (newsav == NULL) {
3194 ipseclog((LOG_DEBUG, "key_newsa: No more memory.\n"));
3195 *errp = ENOBUFS;
3196 return NULL;
3197 }
3198 }
3199 bzero((caddr_t)newsav, sizeof(struct secasvar));
3200
3201 switch (mhp->msg->sadb_msg_type) {
3202 case SADB_GETSPI:
3203 key_setspi(newsav, 0);
3204
3205 #if IPSEC_DOSEQCHECK
3206 /* sync sequence number */
3207 if (mhp->msg->sadb_msg_seq == 0)
3208 newsav->seq =
3209 (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
3210 else
3211 #endif
3212 newsav->seq = mhp->msg->sadb_msg_seq;
3213 break;
3214
3215 case SADB_ADD:
3216 /* sanity check */
3217 if (mhp->ext[SADB_EXT_SA] == NULL) {
3218 KFREE(newsav);
3219 ipseclog((LOG_DEBUG, "key_newsa: invalid message is passed.\n"));
3220 *errp = EINVAL;
3221 return NULL;
3222 }
3223 xsa = (struct sadb_sa *)(void *)mhp->ext[SADB_EXT_SA];
3224 key_setspi(newsav, xsa->sadb_sa_spi);
3225 newsav->seq = mhp->msg->sadb_msg_seq;
3226 break;
3227 default:
3228 KFREE(newsav);
3229 *errp = EINVAL;
3230 return NULL;
3231 }
3232
3233 /* copy sav values */
3234 if (mhp->msg->sadb_msg_type != SADB_GETSPI) {
3235 *errp = key_setsaval(newsav, m, mhp);
3236 if (*errp) {
3237 if (newsav->spihash.le_prev || newsav->spihash.le_next)
3238 LIST_REMOVE(newsav, spihash);
3239 KFREE(newsav);
3240 return NULL;
3241 }
3242 }
3243
3244 /* reset created */
3245 {
3246 struct timeval tv;
3247 microtime(&tv);
3248 newsav->created = tv.tv_sec;
3249 }
3250
3251 newsav->pid = mhp->msg->sadb_msg_pid;
3252
3253 /* add to satree */
3254 newsav->sah = sah;
3255 newsav->refcnt = 1;
3256 newsav->state = SADB_SASTATE_LARVAL;
3257 LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
3258 secasvar, chain);
3259 ipsec_sav_count++;
3260
3261 return newsav;
3262 }
3263
3264 /*
3265 * allocating a new SA with LARVAL state. key_add() and key_getspi() call,
3266 * and copy the values passed into new buffer.
3267 * When SAD message type is GETSPI:
3268 * to set sequence number from acq_seq++,
3269 * to set zero to SPI.
3270 * not to call key_setsava().
3271 * OUT: NULL : fail
3272 * others : pointer to new secasvar.
3273 */
3274 struct secasvar *
3275 key_newsav2(struct secashead *sah,
3276 u_int8_t satype,
3277 u_int8_t alg_auth,
3278 u_int8_t alg_enc,
3279 u_int32_t flags,
3280 u_int8_t replay,
3281 struct sadb_key *key_auth,
3282 u_int16_t key_auth_len,
3283 struct sadb_key *key_enc,
3284 u_int16_t key_enc_len,
3285 u_int16_t natt_port,
3286 u_int32_t seq,
3287 u_int32_t spi,
3288 u_int32_t pid,
3289 struct sadb_lifetime *lifetime_hard,
3290 struct sadb_lifetime *lifetime_soft)
3291 {
3292 struct secasvar *newsav;
3293
3294 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
3295
3296 /* sanity check */
3297 if (sah == NULL)
3298 panic("key_newsa: NULL pointer is passed.\n");
3299
3300 KMALLOC_NOWAIT(newsav, struct secasvar *, sizeof(struct secasvar));
3301 if (newsav == NULL) {
3302 lck_mtx_unlock(sadb_mutex);
3303 KMALLOC_WAIT(newsav, struct secasvar *, sizeof(struct secasvar));
3304 lck_mtx_lock(sadb_mutex);
3305 if (newsav == NULL) {
3306 ipseclog((LOG_DEBUG, "key_newsa: No more memory.\n"));
3307 return NULL;
3308 }
3309 }
3310 bzero((caddr_t)newsav, sizeof(struct secasvar));
3311
3312 #if IPSEC_DOSEQCHECK
3313 /* sync sequence number */
3314 if (seq == 0)
3315 newsav->seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
3316 else
3317 #endif
3318 newsav->seq = seq;
3319 key_setspi(newsav, spi);
3320
3321 if (key_setsaval2(newsav,
3322 satype,
3323 alg_auth,
3324 alg_enc,
3325 flags,
3326 replay,
3327 key_auth,
3328 key_auth_len,
3329 key_enc,
3330 key_enc_len,
3331 natt_port,
3332 seq,
3333 spi,
3334 pid,
3335 lifetime_hard,
3336 lifetime_soft)) {
3337 if (newsav->spihash.le_prev || newsav->spihash.le_next)
3338 LIST_REMOVE(newsav, spihash);
3339 KFREE(newsav);
3340 return NULL;
3341 }
3342
3343 /* reset created */
3344 {
3345 struct timeval tv;
3346 microtime(&tv);
3347 newsav->created = tv.tv_sec;
3348 }
3349
3350 newsav->pid = pid;
3351
3352 /* add to satree */
3353 newsav->sah = sah;
3354 newsav->refcnt = 1;
3355 if (spi && key_auth && key_auth_len && key_enc && key_enc_len) {
3356 newsav->state = SADB_SASTATE_MATURE;
3357 LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_MATURE], newsav,
3358 secasvar, chain);
3359 } else {
3360 newsav->state = SADB_SASTATE_LARVAL;
3361 LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
3362 secasvar, chain);
3363 }
3364 ipsec_sav_count++;
3365
3366 return newsav;
3367 }
3368
3369 /*
3370 * free() SA variable entry.
3371 */
3372 void
3373 key_delsav(
3374 struct secasvar *sav)
3375 {
3376
3377 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
3378
3379 /* sanity check */
3380 if (sav == NULL)
3381 panic("key_delsav: NULL pointer is passed.\n");
3382
3383 if (sav->refcnt > 0)
3384 return; /* can't free */
3385
3386 /* remove from SA header */
3387 if (__LIST_CHAINED(sav))
3388 LIST_REMOVE(sav, chain);
3389 ipsec_sav_count--;
3390
3391 if (sav->spihash.le_prev || sav->spihash.le_next)
3392 LIST_REMOVE(sav, spihash);
3393
3394 if (sav->key_auth != NULL) {
3395 bzero(_KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
3396 KFREE(sav->key_auth);
3397 sav->key_auth = NULL;
3398 }
3399 if (sav->key_enc != NULL) {
3400 bzero(_KEYBUF(sav->key_enc), _KEYLEN(sav->key_enc));
3401 KFREE(sav->key_enc);
3402 sav->key_enc = NULL;
3403 }
3404 if (sav->sched) {
3405 bzero(sav->sched, sav->schedlen);
3406 KFREE(sav->sched);
3407 sav->sched = NULL;
3408 }
3409 if (sav->replay != NULL) {
3410 keydb_delsecreplay(sav->replay);
3411 sav->replay = NULL;
3412 }
3413 if (sav->lft_c != NULL) {
3414 KFREE(sav->lft_c);
3415 sav->lft_c = NULL;
3416 }
3417 if (sav->lft_h != NULL) {
3418 KFREE(sav->lft_h);
3419 sav->lft_h = NULL;
3420 }
3421 if (sav->lft_s != NULL) {
3422 KFREE(sav->lft_s);
3423 sav->lft_s = NULL;
3424 }
3425 if (sav->iv != NULL) {
3426 KFREE(sav->iv);
3427 sav->iv = NULL;
3428 }
3429
3430 KFREE(sav);
3431
3432 return;
3433 }
3434
3435 /*
3436 * search SAD.
3437 * OUT:
3438 * NULL : not found
3439 * others : found, pointer to a SA.
3440 */
3441 static struct secashead *
3442 key_getsah(
3443 struct secasindex *saidx)
3444 {
3445 struct secashead *sah;
3446
3447 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
3448
3449 LIST_FOREACH(sah, &sahtree, chain) {
3450 if (sah->state == SADB_SASTATE_DEAD)
3451 continue;
3452 if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
3453 return sah;
3454 }
3455
3456 return NULL;
3457 }
3458
3459 struct secashead *
3460 key_newsah2 (struct secasindex *saidx,
3461 u_int8_t dir)
3462 {
3463 struct secashead *sah;
3464
3465 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
3466
3467 sah = key_getsah(saidx);
3468 if (!sah) {
3469 return(key_newsah(saidx, dir));
3470 }
3471 return sah;
3472 }
3473
3474 /*
3475 * check not to be duplicated SPI.
3476 * NOTE: this function is too slow due to searching all SAD.
3477 * OUT:
3478 * NULL : not found
3479 * others : found, pointer to a SA.
3480 */
3481 static struct secasvar *
3482 key_checkspidup(
3483 struct secasindex *saidx,
3484 u_int32_t spi)
3485 {
3486 struct secasvar *sav;
3487 u_int stateidx, state;
3488
3489 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
3490
3491 /* check address family */
3492 if (saidx->src.ss_family != saidx->dst.ss_family) {
3493 ipseclog((LOG_DEBUG, "key_checkspidup: address family mismatched.\n"));
3494 return NULL;
3495 }
3496
3497 /* check all SAD */
3498 LIST_FOREACH(sav, &spihash[SPIHASH(spi)], spihash) {
3499 if (sav->spi != spi)
3500 continue;
3501 for (stateidx = 0;
3502 stateidx < _ARRAYLEN(saorder_state_alive);
3503 stateidx++) {
3504 state = saorder_state_alive[stateidx];
3505 if (sav->state == state &&
3506 key_ismyaddr((struct sockaddr *)&sav->sah->saidx.dst))
3507 return sav;
3508 }
3509 }
3510
3511 return NULL;
3512 }
3513
3514 static void
3515 key_setspi(
3516 struct secasvar *sav,
3517 u_int32_t spi)
3518 {
3519 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
3520 sav->spi = spi;
3521 if (sav->spihash.le_prev || sav->spihash.le_next)
3522 LIST_REMOVE(sav, spihash);
3523 LIST_INSERT_HEAD(&spihash[SPIHASH(spi)], sav, spihash);
3524 }
3525
3526
3527 /*
3528 * search SAD litmited alive SA, protocol, SPI.
3529 * OUT:
3530 * NULL : not found
3531 * others : found, pointer to a SA.
3532 */
3533 static struct secasvar *
3534 key_getsavbyspi(
3535 struct secashead *sah,
3536 u_int32_t spi)
3537 {
3538 struct secasvar *sav, *match;
3539 u_int stateidx, state, matchidx;
3540
3541 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
3542 match = NULL;
3543 matchidx = _ARRAYLEN(saorder_state_alive);
3544 LIST_FOREACH(sav, &spihash[SPIHASH(spi)], spihash) {
3545 if (sav->spi != spi)
3546 continue;
3547 if (sav->sah != sah)
3548 continue;
3549 for (stateidx = 0; stateidx < matchidx; stateidx++) {
3550 state = saorder_state_alive[stateidx];
3551 if (sav->state == state) {
3552 match = sav;
3553 matchidx = stateidx;
3554 break;
3555 }
3556 }
3557 }
3558
3559 return match;
3560 }
3561
3562 /*
3563 * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
3564 * You must update these if need.
3565 * OUT: 0: success.
3566 * !0: failure.
3567 *
3568 * does not modify mbuf. does not free mbuf on error.
3569 */
3570 static int
3571 key_setsaval(
3572 struct secasvar *sav,
3573 struct mbuf *m,
3574 const struct sadb_msghdr *mhp)
3575 {
3576 #if IPSEC_ESP
3577 const struct esp_algorithm *algo;
3578 #endif
3579 int error = 0;
3580 struct timeval tv;
3581
3582 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
3583
3584 /* sanity check */
3585 if (m == NULL || mhp == NULL || mhp->msg == NULL)
3586 panic("key_setsaval: NULL pointer is passed.\n");
3587
3588 /* initialization */
3589 sav->replay = NULL;
3590 sav->key_auth = NULL;
3591 sav->key_enc = NULL;
3592 sav->sched = NULL;
3593 sav->schedlen = 0;
3594 sav->iv = NULL;
3595 sav->lft_c = NULL;
3596 sav->lft_h = NULL;
3597 sav->lft_s = NULL;
3598 sav->remote_ike_port = 0;
3599 sav->natt_last_activity = natt_now;
3600 sav->natt_encapsulated_src_port = 0;
3601
3602 /* SA */
3603 if (mhp->ext[SADB_EXT_SA] != NULL) {
3604 const struct sadb_sa *sa0;
3605
3606 sa0 = (struct sadb_sa *)(void *)mhp->ext[SADB_EXT_SA];
3607 if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
3608 ipseclog((LOG_DEBUG, "key_setsaval: invalid message size.\n"));
3609 error = EINVAL;
3610 goto fail;
3611 }
3612
3613 sav->alg_auth = sa0->sadb_sa_auth;
3614 sav->alg_enc = sa0->sadb_sa_encrypt;
3615 sav->flags = sa0->sadb_sa_flags;
3616
3617 /*
3618 * Verify that a nat-traversal port was specified if
3619 * the nat-traversal flag is set.
3620 */
3621 if ((sav->flags & SADB_X_EXT_NATT) != 0) {
3622 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa_2) ||
3623 ((const struct sadb_sa_2*)(sa0))->sadb_sa_natt_port == 0) {
3624 ipseclog((LOG_DEBUG, "key_setsaval: natt port not set.\n"));
3625 error = EINVAL;
3626 goto fail;
3627 }
3628 sav->remote_ike_port = ((const struct sadb_sa_2*)(sa0))->sadb_sa_natt_port;
3629 }
3630
3631 /*
3632 * Verify if SADB_X_EXT_NATT_MULTIPLEUSERS flag is set that
3633 * SADB_X_EXT_NATT is set and SADB_X_EXT_NATT_KEEPALIVE is not
3634 * set (we're not behind nat) - otherwise clear it.
3635 */
3636 if ((sav->flags & SADB_X_EXT_NATT_MULTIPLEUSERS) != 0)
3637 if ((sav->flags & SADB_X_EXT_NATT) == 0 ||
3638 (sav->flags & SADB_X_EXT_NATT_KEEPALIVE) != 0)
3639 sav->flags &= ~SADB_X_EXT_NATT_MULTIPLEUSERS;
3640
3641 /* replay window */
3642 if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
3643 sav->replay = keydb_newsecreplay(sa0->sadb_sa_replay);
3644 if (sav->replay == NULL) {
3645 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3646 error = ENOBUFS;
3647 goto fail;
3648 }
3649 }
3650 }
3651
3652 /* Authentication keys */
3653 if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
3654 const struct sadb_key *key0;
3655 int len;
3656
3657 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3658 len = mhp->extlen[SADB_EXT_KEY_AUTH];
3659
3660 error = 0;
3661 if (len < sizeof(*key0)) {
3662 ipseclog((LOG_DEBUG, "key_setsaval: invalid auth key ext len. len = %d\n", len));
3663 error = EINVAL;
3664 goto fail;
3665 }
3666 switch (mhp->msg->sadb_msg_satype) {
3667 case SADB_SATYPE_AH:
3668 case SADB_SATYPE_ESP:
3669 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3670 sav->alg_auth != SADB_X_AALG_NULL)
3671 error = EINVAL;
3672 break;
3673 case SADB_X_SATYPE_IPCOMP:
3674 default:
3675 error = EINVAL;
3676 break;
3677 }
3678 if (error) {
3679 ipseclog((LOG_DEBUG, "key_setsaval: invalid key_auth values.\n"));
3680 goto fail;
3681 }
3682
3683 sav->key_auth = (struct sadb_key *)key_newbuf(key0, len);
3684 if (sav->key_auth == NULL) {
3685 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3686 error = ENOBUFS;
3687 goto fail;
3688 }
3689 }
3690
3691 /* Encryption key */
3692 if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
3693 const struct sadb_key *key0;
3694 int len;
3695
3696 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3697 len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3698
3699 error = 0;
3700 if (len < sizeof(*key0)) {
3701 ipseclog((LOG_DEBUG, "key_setsaval: invalid encryption key ext len. len = %d\n", len));
3702 error = EINVAL;
3703 goto fail;
3704 }
3705 switch (mhp->msg->sadb_msg_satype) {
3706 case SADB_SATYPE_ESP:
3707 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3708 sav->alg_enc != SADB_EALG_NULL) {
3709 ipseclog((LOG_DEBUG, "key_setsaval: invalid ESP algorithm.\n"));
3710 error = EINVAL;
3711 break;
3712 }
3713 sav->key_enc = (struct sadb_key *)key_newbuf(key0, len);
3714 if (sav->key_enc == NULL) {
3715 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3716 error = ENOBUFS;
3717 goto fail;
3718 }
3719 break;
3720 case SADB_X_SATYPE_IPCOMP:
3721 if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3722 error = EINVAL;
3723 sav->key_enc = NULL; /*just in case*/
3724 break;
3725 case SADB_SATYPE_AH:
3726 default:
3727 error = EINVAL;
3728 break;
3729 }
3730 if (error) {
3731 ipseclog((LOG_DEBUG, "key_setsaval: invalid key_enc value.\n"));
3732 goto fail;
3733 }
3734 }
3735
3736 /* set iv */
3737 sav->ivlen = 0;
3738
3739 switch (mhp->msg->sadb_msg_satype) {
3740 case SADB_SATYPE_ESP:
3741 #if IPSEC_ESP
3742 algo = esp_algorithm_lookup(sav->alg_enc);
3743 if (algo && algo->ivlen)
3744 sav->ivlen = (*algo->ivlen)(algo, sav);
3745 if (sav->ivlen == 0)
3746 break;
3747 KMALLOC_NOWAIT(sav->iv, caddr_t, sav->ivlen);
3748 if (sav->iv == 0) {
3749 lck_mtx_unlock(sadb_mutex);
3750 KMALLOC_WAIT(sav->iv, caddr_t, sav->ivlen);
3751 lck_mtx_lock(sadb_mutex);
3752 if (sav->iv == 0) {
3753 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3754 error = ENOBUFS;
3755 goto fail;
3756 }
3757 }
3758
3759 /* initialize */
3760 key_randomfill(sav->iv, sav->ivlen);
3761 #endif
3762 break;
3763 case SADB_SATYPE_AH:
3764 case SADB_X_SATYPE_IPCOMP:
3765 break;
3766 default:
3767 ipseclog((LOG_DEBUG, "key_setsaval: invalid SA type.\n"));
3768 error = EINVAL;
3769 goto fail;
3770 }
3771
3772 /* reset created */
3773 microtime(&tv);
3774 sav->created = tv.tv_sec;
3775
3776 /* make lifetime for CURRENT */
3777 KMALLOC_NOWAIT(sav->lft_c, struct sadb_lifetime *,
3778 sizeof(struct sadb_lifetime));
3779 if (sav->lft_c == NULL) {
3780 lck_mtx_unlock(sadb_mutex);
3781 KMALLOC_WAIT(sav->lft_c, struct sadb_lifetime *,
3782 sizeof(struct sadb_lifetime));
3783 lck_mtx_lock(sadb_mutex);
3784 if (sav->lft_c == NULL) {
3785 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3786 error = ENOBUFS;
3787 goto fail;
3788 }
3789 }
3790
3791 microtime(&tv);
3792
3793 sav->lft_c->sadb_lifetime_len =
3794 PFKEY_UNIT64(sizeof(struct sadb_lifetime));
3795 sav->lft_c->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
3796 sav->lft_c->sadb_lifetime_allocations = 0;
3797 sav->lft_c->sadb_lifetime_bytes = 0;
3798 sav->lft_c->sadb_lifetime_addtime = tv.tv_sec;
3799 sav->lft_c->sadb_lifetime_usetime = 0;
3800
3801 /* lifetimes for HARD and SOFT */
3802 {
3803 const struct sadb_lifetime *lft0;
3804
3805 lft0 = (struct sadb_lifetime *)
3806 (void *)mhp->ext[SADB_EXT_LIFETIME_HARD];
3807 if (lft0 != NULL) {
3808 if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
3809 ipseclog((LOG_DEBUG, "key_setsaval: invalid hard lifetime ext len.\n"));
3810 error = EINVAL;
3811 goto fail;
3812 }
3813 sav->lft_h = (struct sadb_lifetime *)key_newbuf(lft0,
3814 sizeof(*lft0));
3815 if (sav->lft_h == NULL) {
3816 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3817 error = ENOBUFS;
3818 goto fail;
3819 }
3820 /* to be initialize ? */
3821 }
3822
3823 lft0 = (struct sadb_lifetime *)
3824 (void *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
3825 if (lft0 != NULL) {
3826 if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
3827 ipseclog((LOG_DEBUG, "key_setsaval: invalid soft lifetime ext len.\n"));
3828 error = EINVAL;
3829 goto fail;
3830 }
3831 sav->lft_s = (struct sadb_lifetime *)key_newbuf(lft0,
3832 sizeof(*lft0));
3833 if (sav->lft_s == NULL) {
3834 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3835 error = ENOBUFS;
3836 goto fail;
3837 }
3838 /* to be initialize ? */
3839 }
3840 }
3841
3842 return 0;
3843
3844 fail:
3845 /* initialization */
3846 if (sav->replay != NULL) {
3847 keydb_delsecreplay(sav->replay);
3848 sav->replay = NULL;
3849 }
3850 if (sav->key_auth != NULL) {
3851 bzero(_KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
3852 KFREE(sav->key_auth);
3853 sav->key_auth = NULL;
3854 }
3855 if (sav->key_enc != NULL) {
3856 bzero(_KEYBUF(sav->key_enc), _KEYLEN(sav->key_enc));
3857 KFREE(sav->key_enc);
3858 sav->key_enc = NULL;
3859 }
3860 if (sav->sched) {
3861 bzero(sav->sched, sav->schedlen);
3862 KFREE(sav->sched);
3863 sav->sched = NULL;
3864 }
3865 if (sav->iv != NULL) {
3866 KFREE(sav->iv);
3867 sav->iv = NULL;
3868 }
3869 if (sav->lft_c != NULL) {
3870 KFREE(sav->lft_c);
3871 sav->lft_c = NULL;
3872 }
3873 if (sav->lft_h != NULL) {
3874 KFREE(sav->lft_h);
3875 sav->lft_h = NULL;
3876 }
3877 if (sav->lft_s != NULL) {
3878 KFREE(sav->lft_s);
3879 sav->lft_s = NULL;
3880 }
3881
3882 return error;
3883 }
3884
3885 /*
3886 * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
3887 * You must update these if need.
3888 * OUT: 0: success.
3889 * !0: failure.
3890 *
3891 * does not modify mbuf. does not free mbuf on error.
3892 */
3893 int
3894 key_setsaval2(struct secasvar *sav,
3895 u_int8_t satype,
3896 u_int8_t alg_auth,
3897 u_int8_t alg_enc,
3898 u_int32_t flags,
3899 u_int8_t replay,
3900 struct sadb_key *key_auth,
3901 u_int16_t key_auth_len,
3902 struct sadb_key *key_enc,
3903 u_int16_t key_enc_len,
3904 u_int16_t natt_port,
3905 u_int32_t seq,
3906 u_int32_t spi,
3907 u_int32_t pid,
3908 struct sadb_lifetime *lifetime_hard,
3909 struct sadb_lifetime *lifetime_soft)
3910 {
3911 #if IPSEC_ESP
3912 const struct esp_algorithm *algo;
3913 #endif
3914 int error = 0;
3915 struct timeval tv;
3916
3917 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
3918
3919 /* initialization */
3920 sav->replay = NULL;
3921 sav->key_auth = NULL;
3922 sav->key_enc = NULL;
3923 sav->sched = NULL;
3924 sav->schedlen = 0;
3925 sav->iv = NULL;
3926 sav->lft_c = NULL;
3927 sav->lft_h = NULL;
3928 sav->lft_s = NULL;
3929 sav->remote_ike_port = 0;
3930 sav->natt_last_activity = natt_now;
3931 sav->natt_encapsulated_src_port = 0;
3932
3933 sav->alg_auth = alg_auth;
3934 sav->alg_enc = alg_enc;
3935 sav->flags = flags;
3936 sav->pid = pid;
3937 sav->seq = seq;
3938 key_setspi(sav, htonl(spi));
3939
3940 /*
3941 * Verify that a nat-traversal port was specified if
3942 * the nat-traversal flag is set.
3943 */
3944 if ((sav->flags & SADB_X_EXT_NATT) != 0) {
3945 if (natt_port == 0) {
3946 ipseclog((LOG_DEBUG, "key_setsaval2: natt port not set.\n"));
3947 error = EINVAL;
3948 goto fail;
3949 }
3950 sav->remote_ike_port = natt_port;
3951 }
3952
3953 /*
3954 * Verify if SADB_X_EXT_NATT_MULTIPLEUSERS flag is set that
3955 * SADB_X_EXT_NATT is set and SADB_X_EXT_NATT_KEEPALIVE is not
3956 * set (we're not behind nat) - otherwise clear it.
3957 */
3958 if ((sav->flags & SADB_X_EXT_NATT_MULTIPLEUSERS) != 0)
3959 if ((sav->flags & SADB_X_EXT_NATT) == 0 ||
3960 (sav->flags & SADB_X_EXT_NATT_KEEPALIVE) != 0)
3961 sav->flags &= ~SADB_X_EXT_NATT_MULTIPLEUSERS;
3962
3963 /* replay window */
3964 if ((flags & SADB_X_EXT_OLD) == 0) {
3965 sav->replay = keydb_newsecreplay(replay);
3966 if (sav->replay == NULL) {
3967 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3968 error = ENOBUFS;
3969 goto fail;
3970 }
3971 }
3972
3973 /* Authentication keys */
3974 sav->key_auth = (__typeof__(sav->key_auth))key_newbuf(key_auth, key_auth_len);
3975 if (sav->key_auth == NULL) {
3976 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3977 error = ENOBUFS;
3978 goto fail;
3979 }
3980
3981 /* Encryption key */
3982 sav->key_enc = (__typeof__(sav->key_enc))key_newbuf(key_enc, key_enc_len);
3983 if (sav->key_enc == NULL) {
3984 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3985 error = ENOBUFS;
3986 goto fail;
3987 }
3988
3989 /* set iv */
3990 sav->ivlen = 0;
3991
3992 if (satype == SADB_SATYPE_ESP) {
3993 #if IPSEC_ESP
3994 algo = esp_algorithm_lookup(sav->alg_enc);
3995 if (algo && algo->ivlen)
3996 sav->ivlen = (*algo->ivlen)(algo, sav);
3997 if (sav->ivlen != 0) {
3998 KMALLOC_NOWAIT(sav->iv, caddr_t, sav->ivlen);
3999 if (sav->iv == 0) {
4000 lck_mtx_unlock(sadb_mutex);
4001 KMALLOC_WAIT(sav->iv, caddr_t, sav->ivlen);
4002 lck_mtx_lock(sadb_mutex);
4003 if (sav->iv == 0) {
4004 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
4005 error = ENOBUFS;
4006 goto fail;
4007 }
4008 }
4009 /* initialize */
4010 key_randomfill(sav->iv, sav->ivlen);
4011 }
4012 #endif
4013 }
4014
4015 /* reset created */
4016 microtime(&tv);
4017 sav->created = tv.tv_sec;
4018
4019 /* make lifetime for CURRENT */
4020 KMALLOC_NOWAIT(sav->lft_c, struct sadb_lifetime *,
4021 sizeof(struct sadb_lifetime));
4022 if (sav->lft_c == NULL) {
4023 lck_mtx_unlock(sadb_mutex);
4024 KMALLOC_WAIT(sav->lft_c, struct sadb_lifetime *,
4025 sizeof(struct sadb_lifetime));
4026 lck_mtx_lock(sadb_mutex);
4027 if (sav->lft_c == NULL) {
4028 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
4029 error = ENOBUFS;
4030 goto fail;
4031 }
4032 }
4033
4034 microtime(&tv);
4035
4036 sav->lft_c->sadb_lifetime_len =
4037 PFKEY_UNIT64(sizeof(struct sadb_lifetime));
4038 sav->lft_c->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
4039 sav->lft_c->sadb_lifetime_allocations = 0;
4040 sav->lft_c->sadb_lifetime_bytes = 0;
4041 sav->lft_c->sadb_lifetime_addtime = tv.tv_sec;
4042 sav->lft_c->sadb_lifetime_usetime = 0;
4043
4044 /* lifetimes for HARD and SOFT */
4045 sav->lft_h = (__typeof__(sav->lft_h))key_newbuf(lifetime_hard,
4046 sizeof(*lifetime_hard));
4047 if (sav->lft_h == NULL) {
4048 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
4049 error = ENOBUFS;
4050 goto fail;
4051 }
4052 sav->lft_s = (__typeof__(sav->lft_s))key_newbuf(lifetime_soft,
4053 sizeof(*lifetime_soft));
4054 if (sav->lft_s == NULL) {
4055 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
4056 error = ENOBUFS;
4057 goto fail;
4058 }
4059
4060 return 0;
4061
4062 fail:
4063 /* initialization */
4064 if (sav->replay != NULL) {
4065 keydb_delsecreplay(sav->replay);
4066 sav->replay = NULL;
4067 }
4068 if (sav->key_auth != NULL) {
4069 bzero(_KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
4070 KFREE(sav->key_auth);
4071 sav->key_auth = NULL;
4072 }
4073 if (sav->key_enc != NULL) {
4074 bzero(_KEYBUF(sav->key_enc), _KEYLEN(sav->key_enc));
4075 KFREE(sav->key_enc);
4076 sav->key_enc = NULL;
4077 }
4078 if (sav->sched) {
4079 bzero(sav->sched, sav->schedlen);
4080 KFREE(sav->sched);
4081 sav->sched = NULL;
4082 }
4083 if (sav->iv != NULL) {
4084 KFREE(sav->iv);
4085 sav->iv = NULL;
4086 }
4087 if (sav->lft_c != NULL) {
4088 KFREE(sav->lft_c);
4089 sav->lft_c = NULL;
4090 }
4091 if (sav->lft_h != NULL) {
4092 KFREE(sav->lft_h);
4093 sav->lft_h = NULL;
4094 }
4095 if (sav->lft_s != NULL) {
4096 KFREE(sav->lft_s);
4097 sav->lft_s = NULL;
4098 }
4099
4100 return error;
4101 }
4102
4103 /*
4104 * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
4105 * OUT: 0: valid
4106 * other: errno
4107 */
4108 static int
4109 key_mature(
4110 struct secasvar *sav)
4111 {
4112 int mature;
4113 int checkmask = 0; /* 2^0: ealg 2^1: aalg 2^2: calg */
4114 int mustmask = 0; /* 2^0: ealg 2^1: aalg 2^2: calg */
4115
4116 mature = 0;
4117
4118 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
4119
4120 /* check SPI value */
4121 switch (sav->sah->saidx.proto) {
4122 case IPPROTO_ESP:
4123 case IPPROTO_AH:
4124
4125 /* No reason to test if this is >= 0, because ntohl(sav->spi) is unsigned. */
4126 if (ntohl(sav->spi) <= 255) {
4127 ipseclog((LOG_DEBUG,
4128 "key_mature: illegal range of SPI %u.\n",
4129 (u_int32_t)ntohl(sav->spi)));
4130 return EINVAL;
4131 }
4132 break;
4133 }
4134
4135 /* check satype */
4136 switch (sav->sah->saidx.proto) {
4137 case IPPROTO_ESP:
4138 /* check flags */
4139 if ((sav->flags & SADB_X_EXT_OLD)
4140 && (sav->flags & SADB_X_EXT_DERIV)) {
4141 ipseclog((LOG_DEBUG, "key_mature: "
4142 "invalid flag (derived) given to old-esp.\n"));
4143 return EINVAL;
4144 }
4145 if (sav->alg_auth == SADB_AALG_NONE)
4146 checkmask = 1;
4147 else
4148 checkmask = 3;
4149 mustmask = 1;
4150 break;
4151 case IPPROTO_AH:
4152 /* check flags */
4153 if (sav->flags & SADB_X_EXT_DERIV) {
4154 ipseclog((LOG_DEBUG, "key_mature: "
4155 "invalid flag (derived) given to AH SA.\n"));
4156 return EINVAL;
4157 }
4158 if (sav->alg_enc != SADB_EALG_NONE) {
4159 ipseclog((LOG_DEBUG, "key_mature: "
4160 "protocol and algorithm mismated.\n"));
4161 return(EINVAL);
4162 }
4163 checkmask = 2;
4164 mustmask = 2;
4165 break;
4166 case IPPROTO_IPCOMP:
4167 if (sav->alg_auth != SADB_AALG_NONE) {
4168 ipseclog((LOG_DEBUG, "key_mature: "
4169 "protocol and algorithm mismated.\n"));
4170 return(EINVAL);
4171 }
4172 if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
4173 && ntohl(sav->spi) >= 0x10000) {
4174 ipseclog((LOG_DEBUG, "key_mature: invalid cpi for IPComp.\n"));
4175 return(EINVAL);
4176 }
4177 checkmask = 4;
4178 mustmask = 4;
4179 break;
4180 default:
4181 ipseclog((LOG_DEBUG, "key_mature: Invalid satype.\n"));
4182 return EPROTONOSUPPORT;
4183 }
4184
4185 /* check authentication algorithm */
4186 if ((checkmask & 2) != 0) {
4187 const struct ah_algorithm *algo;
4188 int keylen;
4189
4190 algo = ah_algorithm_lookup(sav->alg_auth);
4191 if (!algo) {
4192 ipseclog((LOG_DEBUG,"key_mature: "
4193 "unknown authentication algorithm.\n"));
4194 return EINVAL;
4195 }
4196
4197 /* algorithm-dependent check */
4198 if (sav->key_auth)
4199 keylen = sav->key_auth->sadb_key_bits;
4200 else
4201 keylen = 0;
4202 if (keylen < algo->keymin || algo->keymax < keylen) {
4203 ipseclog((LOG_DEBUG,
4204 "key_mature: invalid AH key length %d "
4205 "(%d-%d allowed)\n",
4206 keylen, algo->keymin, algo->keymax));
4207 return EINVAL;
4208 }
4209
4210 if (algo->mature) {
4211 if ((*algo->mature)(sav)) {
4212 /* message generated in per-algorithm function*/
4213 return EINVAL;
4214 } else
4215 mature = SADB_SATYPE_AH;
4216 }
4217
4218 if ((mustmask & 2) != 0 && mature != SADB_SATYPE_AH) {
4219 ipseclog((LOG_DEBUG, "key_mature: no satisfy algorithm for AH\n"));
4220 return EINVAL;
4221 }
4222 }
4223
4224 /* check encryption algorithm */
4225 if ((checkmask & 1) != 0) {
4226 #if IPSEC_ESP
4227 const struct esp_algorithm *algo;
4228 int keylen;
4229
4230 algo = esp_algorithm_lookup(sav->alg_enc);
4231 if (!algo) {
4232 ipseclog((LOG_DEBUG, "key_mature: unknown encryption algorithm.\n"));
4233 return EINVAL;
4234 }
4235
4236 /* algorithm-dependent check */
4237 if (sav->key_enc)
4238 keylen = sav->key_enc->sadb_key_bits;
4239 else
4240 keylen = 0;
4241 if (keylen < algo->keymin || algo->keymax < keylen) {
4242 ipseclog((LOG_DEBUG,
4243 "key_mature: invalid ESP key length %d "
4244 "(%d-%d allowed)\n",
4245 keylen, algo->keymin, algo->keymax));
4246 return EINVAL;
4247 }
4248
4249 if (algo->mature) {
4250 if ((*algo->mature)(sav)) {
4251 /* message generated in per-algorithm function*/
4252 return EINVAL;
4253 } else
4254 mature = SADB_SATYPE_ESP;
4255 }
4256
4257 if ((mustmask & 1) != 0 && mature != SADB_SATYPE_ESP) {
4258 ipseclog((LOG_DEBUG, "key_mature: no satisfy algorithm for ESP\n"));
4259 return EINVAL;
4260 }
4261 #else /*IPSEC_ESP*/
4262 ipseclog((LOG_DEBUG, "key_mature: ESP not supported in this configuration\n"));
4263 return EINVAL;
4264 #endif
4265 }
4266
4267 /* check compression algorithm */
4268 if ((checkmask & 4) != 0) {
4269 const struct ipcomp_algorithm *algo;
4270
4271 /* algorithm-dependent check */
4272 algo = ipcomp_algorithm_lookup(sav->alg_enc);
4273 if (!algo) {
4274 ipseclog((LOG_DEBUG, "key_mature: unknown compression algorithm.\n"));
4275 return EINVAL;
4276 }
4277 }
4278
4279 key_sa_chgstate(sav, SADB_SASTATE_MATURE);
4280
4281 return 0;
4282 }
4283
4284 /*
4285 * subroutine for SADB_GET and SADB_DUMP.
4286 */
4287 static struct mbuf *
4288 key_setdumpsa(
4289 struct secasvar *sav,
4290 u_int8_t type,
4291 u_int8_t satype,
4292 u_int32_t seq,
4293 u_int32_t pid)
4294 {
4295 struct mbuf *result = NULL, *tres = NULL, *m;
4296 int l = 0;
4297 int i;
4298 void *p;
4299 int dumporder[] = {
4300 SADB_EXT_SA, SADB_X_EXT_SA2,
4301 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
4302 SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
4303 SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
4304 SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
4305 SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
4306 };
4307
4308 m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
4309 if (m == NULL)
4310 goto fail;
4311 result = m;
4312
4313 for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
4314 m = NULL;
4315 p = NULL;
4316 switch (dumporder[i]) {
4317 case SADB_EXT_SA:
4318 m = key_setsadbsa(sav);
4319 if (!m)
4320 goto fail;
4321 break;
4322
4323 case SADB_X_EXT_SA2:
4324 m = key_setsadbxsa2(sav->sah->saidx.mode,
4325 sav->replay ? sav->replay->count : 0,
4326 sav->sah->saidx.reqid);
4327 if (!m)
4328 goto fail;
4329 break;
4330
4331 case SADB_EXT_ADDRESS_SRC:
4332 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
4333 (struct sockaddr *)&sav->sah->saidx.src,
4334 FULLMASK, IPSEC_ULPROTO_ANY);
4335 if (!m)
4336 goto fail;
4337 break;
4338
4339 case SADB_EXT_ADDRESS_DST:
4340 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
4341 (struct sockaddr *)&sav->sah->saidx.dst,
4342 FULLMASK, IPSEC_ULPROTO_ANY);
4343 if (!m)
4344 goto fail;
4345 break;
4346
4347 case SADB_EXT_KEY_AUTH:
4348 if (!sav->key_auth)
4349 continue;
4350 l = PFKEY_UNUNIT64(sav->key_auth->sadb_key_len);
4351 p = sav->key_auth;
4352 break;
4353
4354 case SADB_EXT_KEY_ENCRYPT:
4355 if (!sav->key_enc)
4356 continue;
4357 l = PFKEY_UNUNIT64(sav->key_enc->sadb_key_len);
4358 p = sav->key_enc;
4359 break;
4360
4361 case SADB_EXT_LIFETIME_CURRENT:
4362 if (!sav->lft_c)
4363 continue;
4364 l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_c)->sadb_ext_len);
4365 p = sav->lft_c;
4366 break;
4367
4368 case SADB_EXT_LIFETIME_HARD:
4369 if (!sav->lft_h)
4370 continue;
4371 l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_h)->sadb_ext_len);
4372 p = sav->lft_h;
4373 break;
4374
4375 case SADB_EXT_LIFETIME_SOFT:
4376 if (!sav->lft_s)
4377 continue;
4378 l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_s)->sadb_ext_len);
4379 p = sav->lft_s;
4380 break;
4381
4382 case SADB_EXT_ADDRESS_PROXY:
4383 case SADB_EXT_IDENTITY_SRC:
4384 case SADB_EXT_IDENTITY_DST:
4385 /* XXX: should we brought from SPD ? */
4386 case SADB_EXT_SENSITIVITY:
4387 default:
4388 continue;
4389 }
4390
4391 if ((!m && !p) || (m && p))
4392 goto fail;
4393 if (p && tres) {
4394 M_PREPEND(tres, l, M_WAITOK);
4395 if (!tres)
4396 goto fail;
4397 bcopy(p, mtod(tres, caddr_t), l);
4398 continue;
4399 }
4400 if (p) {
4401 m = key_alloc_mbuf(l);
4402 if (!m)
4403 goto fail;
4404 m_copyback(m, 0, l, p);
4405 }
4406
4407 if (tres)
4408 m_cat(m, tres);
4409 tres = m;
4410 }
4411
4412 m_cat(result, tres);
4413
4414 if (result->m_len < sizeof(struct sadb_msg)) {
4415 result = m_pullup(result, sizeof(struct sadb_msg));
4416 if (result == NULL)
4417 goto fail;
4418 }
4419
4420 result->m_pkthdr.len = 0;
4421 for (m = result; m; m = m->m_next)
4422 result->m_pkthdr.len += m->m_len;
4423
4424 mtod(result, struct sadb_msg *)->sadb_msg_len =
4425 PFKEY_UNIT64(result->m_pkthdr.len);
4426
4427 return result;
4428
4429 fail:
4430 m_freem(result);
4431 m_freem(tres);
4432 return NULL;
4433 }
4434
4435 /*
4436 * set data into sadb_msg.
4437 */
4438 static struct mbuf *
4439 key_setsadbmsg(
4440 u_int8_t type,
4441 u_int16_t tlen,
4442 u_int8_t satype,
4443 u_int32_t seq,
4444 pid_t pid,
4445 u_int16_t reserved)
4446 {
4447 struct mbuf *m;
4448 struct sadb_msg *p;
4449 int len;
4450
4451 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
4452 if (len > MCLBYTES)
4453 return NULL;
4454 MGETHDR(m, M_DONTWAIT, MT_DATA);
4455 if (m && len > MHLEN) {
4456 MCLGET(m, M_DONTWAIT);
4457 if ((m->m_flags & M_EXT) == 0) {
4458 m_freem(m);
4459 m = NULL;
4460 }
4461 }
4462 if (!m)
4463 return NULL;
4464 m->m_pkthdr.len = m->m_len = len;
4465 m->m_next = NULL;
4466
4467 p = mtod(m, struct sadb_msg *);
4468
4469 bzero(p, len);
4470 p->sadb_msg_version = PF_KEY_V2;
4471 p->sadb_msg_type = type;
4472 p->sadb_msg_errno = 0;
4473 p->sadb_msg_satype = satype;
4474 p->sadb_msg_len = PFKEY_UNIT64(tlen);
4475 p->sadb_msg_reserved = reserved;
4476 p->sadb_msg_seq = seq;
4477 p->sadb_msg_pid = (u_int32_t)pid;
4478
4479 return m;
4480 }
4481
4482 /*
4483 * copy secasvar data into sadb_address.
4484 */
4485 static struct mbuf *
4486 key_setsadbsa(
4487 struct secasvar *sav)
4488 {
4489 struct mbuf *m;
4490 struct sadb_sa *p;
4491 int len;
4492
4493 len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
4494 m = key_alloc_mbuf(len);
4495 if (!m || m->m_next) { /*XXX*/
4496 if (m)
4497 m_freem(m);
4498 return NULL;
4499 }
4500
4501 p = mtod(m, struct sadb_sa *);
4502
4503 bzero(p, len);
4504 p->sadb_sa_len = PFKEY_UNIT64(len);
4505 p->sadb_sa_exttype = SADB_EXT_SA;
4506 p->sadb_sa_spi = sav->spi;
4507 p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
4508 p->sadb_sa_state = sav->state;
4509 p->sadb_sa_auth = sav->alg_auth;
4510 p->sadb_sa_encrypt = sav->alg_enc;
4511 p->sadb_sa_flags = sav->flags;
4512
4513 return m;
4514 }
4515
4516 /*
4517 * set data into sadb_address.
4518 */
4519 static struct mbuf *
4520 key_setsadbaddr(
4521 u_int16_t exttype,
4522 struct sockaddr *saddr,
4523 u_int8_t prefixlen,
4524 u_int16_t ul_proto)
4525 {
4526 struct mbuf *m;
4527 struct sadb_address *p;
4528 size_t len;
4529
4530 len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
4531 PFKEY_ALIGN8(saddr->sa_len);
4532 m = key_alloc_mbuf(len);
4533 if (!m || m->m_next) { /*XXX*/
4534 if (m)
4535 m_freem(m);
4536 return NULL;
4537 }
4538
4539 p = mtod(m, struct sadb_address *);
4540
4541 bzero(p, len);
4542 p->sadb_address_len = PFKEY_UNIT64(len);
4543 p->sadb_address_exttype = exttype;
4544 p->sadb_address_proto = ul_proto;
4545 if (prefixlen == FULLMASK) {
4546 switch (saddr->sa_family) {
4547 case AF_INET:
4548 prefixlen = sizeof(struct in_addr) << 3;
4549 break;
4550 case AF_INET6:
4551 prefixlen = sizeof(struct in6_addr) << 3;
4552 break;
4553 default:
4554 ; /*XXX*/
4555 }
4556 }
4557 p->sadb_address_prefixlen = prefixlen;
4558 p->sadb_address_reserved = 0;
4559
4560 bcopy(saddr,
4561 mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
4562 saddr->sa_len);
4563
4564 return m;
4565 }
4566
4567 /*
4568 * set data into sadb_session_id
4569 */
4570 static struct mbuf *
4571 key_setsadbsession_id (u_int64_t session_ids[])
4572 {
4573 struct mbuf *m;
4574 struct sadb_session_id *p;
4575 size_t len;
4576
4577 len = PFKEY_ALIGN8(sizeof(*p));
4578 m = key_alloc_mbuf(len);
4579 if (!m || m->m_next) { /*XXX*/
4580 if (m)
4581 m_freem(m);
4582 return NULL;
4583 }
4584
4585 p = mtod(m, __typeof__(p));
4586
4587 bzero(p, len);
4588 p->sadb_session_id_len = PFKEY_UNIT64(len);
4589 p->sadb_session_id_exttype = SADB_EXT_SESSION_ID;
4590 p->sadb_session_id_v[0] = session_ids[0];
4591 p->sadb_session_id_v[1] = session_ids[1];
4592
4593 return m;
4594 }
4595
4596 /*
4597 * copy stats data into sadb_sastat type.
4598 */
4599 static struct mbuf *
4600 key_setsadbsastat (u_int32_t dir,
4601 struct sastat *stats,
4602 u_int32_t max_stats)
4603 {
4604 struct mbuf *m;
4605 struct sadb_sastat *p;
4606 int list_len, len;
4607
4608 if (!stats) {
4609 return NULL;
4610 }
4611
4612 list_len = sizeof(*stats) * max_stats;
4613 len = PFKEY_ALIGN8(sizeof(*p)) + PFKEY_ALIGN8(list_len);
4614 m = key_alloc_mbuf(len);
4615 if (!m || m->m_next) { /*XXX*/
4616 if (m)
4617 m_freem(m);
4618 return NULL;
4619 }
4620
4621 p = mtod(m, __typeof__(p));
4622
4623 bzero(p, len);
4624 p->sadb_sastat_len = PFKEY_UNIT64(len);
4625 p->sadb_sastat_exttype = SADB_EXT_SASTAT;
4626 p->sadb_sastat_dir = dir;
4627 p->sadb_sastat_list_len = max_stats;
4628 if (list_len) {
4629 bcopy(stats,
4630 mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(*p)),
4631 list_len);
4632 }
4633
4634 return m;
4635 }
4636
4637 #if 0
4638 /*
4639 * set data into sadb_ident.
4640 */
4641 static struct mbuf *
4642 key_setsadbident(
4643 u_int16_t exttype,
4644 u_int16_t idtype,
4645 caddr_t string,
4646 int stringlen,
4647 u_int64_t id)
4648 {
4649 struct mbuf *m;
4650 struct sadb_ident *p;
4651 size_t len;
4652
4653 len = PFKEY_ALIGN8(sizeof(struct sadb_ident)) + PFKEY_ALIGN8(stringlen);
4654 m = key_alloc_mbuf(len);
4655 if (!m || m->m_next) { /*XXX*/
4656 if (m)
4657 m_freem(m);
4658 return NULL;
4659 }
4660
4661 p = mtod(m, struct sadb_ident *);
4662
4663 bzero(p, len);
4664 p->sadb_ident_len = PFKEY_UNIT64(len);
4665 p->sadb_ident_exttype = exttype;
4666 p->sadb_ident_type = idtype;
4667 p->sadb_ident_reserved = 0;
4668 p->sadb_ident_id = id;
4669
4670 bcopy(string,
4671 mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_ident)),
4672 stringlen);
4673
4674 return m;
4675 }
4676 #endif
4677
4678 /*
4679 * set data into sadb_x_sa2.
4680 */
4681 static struct mbuf *
4682 key_setsadbxsa2(
4683 u_int8_t mode,
4684 u_int32_t seq,
4685 u_int32_t reqid)
4686 {
4687 struct mbuf *m;
4688 struct sadb_x_sa2 *p;
4689 size_t len;
4690
4691 len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
4692 m = key_alloc_mbuf(len);
4693 if (!m || m->m_next) { /*XXX*/
4694 if (m)
4695 m_freem(m);
4696 return NULL;
4697 }
4698
4699 p = mtod(m, struct sadb_x_sa2 *);
4700
4701 bzero(p, len);
4702 p->sadb_x_sa2_len = PFKEY_UNIT64(len);
4703 p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
4704 p->sadb_x_sa2_mode = mode;
4705 p->sadb_x_sa2_reserved1 = 0;
4706 p->sadb_x_sa2_reserved2 = 0;
4707 p->sadb_x_sa2_sequence = seq;
4708 p->sadb_x_sa2_reqid = reqid;
4709
4710 return m;
4711 }
4712
4713 /*
4714 * set data into sadb_x_policy
4715 */
4716 static struct mbuf *
4717 key_setsadbxpolicy(
4718 u_int16_t type,
4719 u_int8_t dir,
4720 u_int32_t id)
4721 {
4722 struct mbuf *m;
4723 struct sadb_x_policy *p;
4724 size_t len;
4725
4726 len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
4727 m = key_alloc_mbuf(len);
4728 if (!m || m->m_next) { /*XXX*/
4729 if (m)
4730 m_freem(m);
4731 return NULL;
4732 }
4733
4734 p = mtod(m, struct sadb_x_policy *);
4735
4736 bzero(p, len);
4737 p->sadb_x_policy_len = PFKEY_UNIT64(len);
4738 p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
4739 p->sadb_x_policy_type = type;
4740 p->sadb_x_policy_dir = dir;
4741 p->sadb_x_policy_id = id;
4742
4743 return m;
4744 }
4745
4746 /* %%% utilities */
4747 /*
4748 * copy a buffer into the new buffer allocated.
4749 */
4750 static void *
4751 key_newbuf(
4752 const void *src,
4753 u_int len)
4754 {
4755 caddr_t new;
4756
4757 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
4758 KMALLOC_NOWAIT(new, caddr_t, len);
4759 if (new == NULL) {
4760 lck_mtx_unlock(sadb_mutex);
4761 KMALLOC_WAIT(new, caddr_t, len);
4762 lck_mtx_lock(sadb_mutex);
4763 if (new == NULL) {
4764 ipseclog((LOG_DEBUG, "key_newbuf: No more memory.\n"));
4765 return NULL;
4766 }
4767 }
4768 bcopy(src, new, len);
4769
4770 return new;
4771 }
4772
4773 /* compare my own address
4774 * OUT: 1: true, i.e. my address.
4775 * 0: false
4776 */
4777 int
4778 key_ismyaddr(
4779 struct sockaddr *sa)
4780 {
4781 #if INET
4782 struct sockaddr_in *sin;
4783 struct in_ifaddr *ia;
4784 #endif
4785
4786 /* sanity check */
4787 if (sa == NULL)
4788 panic("key_ismyaddr: NULL pointer is passed.\n");
4789
4790 switch (sa->sa_family) {
4791 #if INET
4792 case AF_INET:
4793 lck_rw_lock_shared(in_ifaddr_rwlock);
4794 sin = (struct sockaddr_in *)(void *)sa;
4795 for (ia = in_ifaddrhead.tqh_first; ia;
4796 ia = ia->ia_link.tqe_next) {
4797 IFA_LOCK_SPIN(&ia->ia_ifa);
4798 if (sin->sin_family == ia->ia_addr.sin_family &&
4799 sin->sin_len == ia->ia_addr.sin_len &&
4800 sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
4801 {
4802 IFA_UNLOCK(&ia->ia_ifa);
4803 lck_rw_done(in_ifaddr_rwlock);
4804 return 1;
4805 }
4806 IFA_UNLOCK(&ia->ia_ifa);
4807 }
4808 lck_rw_done(in_ifaddr_rwlock);
4809 break;
4810 #endif
4811 #if INET6
4812 case AF_INET6:
4813 return key_ismyaddr6((struct sockaddr_in6 *)(void *)sa);
4814 #endif
4815 }
4816
4817 return 0;
4818 }
4819
4820 #if INET6
4821 /*
4822 * compare my own address for IPv6.
4823 * 1: ours
4824 * 0: other
4825 * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
4826 */
4827 #include <netinet6/in6_var.h>
4828
4829 static int
4830 key_ismyaddr6(
4831 struct sockaddr_in6 *sin6)
4832 {
4833 struct in6_ifaddr *ia;
4834 struct in6_multi *in6m;
4835
4836 lck_rw_lock_shared(&in6_ifaddr_rwlock);
4837 for (ia = in6_ifaddrs; ia; ia = ia->ia_next) {
4838 IFA_LOCK(&ia->ia_ifa);
4839 if (key_sockaddrcmp((struct sockaddr *)&sin6,
4840 (struct sockaddr *)&ia->ia_addr, 0) == 0) {
4841 IFA_UNLOCK(&ia->ia_ifa);
4842 lck_rw_done(&in6_ifaddr_rwlock);
4843 return 1;
4844 }
4845 IFA_UNLOCK(&ia->ia_ifa);
4846
4847 /*
4848 * XXX Multicast
4849 * XXX why do we care about multlicast here while we don't care
4850 * about IPv4 multicast??
4851 * XXX scope
4852 */
4853 in6m = NULL;
4854 in6_multihead_lock_shared();
4855 IN6_LOOKUP_MULTI(&sin6->sin6_addr, ia->ia_ifp, in6m);
4856 in6_multihead_lock_done();
4857 if (in6m != NULL) {
4858 lck_rw_done(&in6_ifaddr_rwlock);
4859 IN6M_REMREF(in6m);
4860 return 1;
4861 }
4862 }
4863 lck_rw_done(&in6_ifaddr_rwlock);
4864
4865 /* loopback, just for safety */
4866 if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
4867 return 1;
4868
4869 return 0;
4870 }
4871 #endif /*INET6*/
4872
4873 /*
4874 * compare two secasindex structure.
4875 * flag can specify to compare 2 saidxes.
4876 * compare two secasindex structure without both mode and reqid.
4877 * don't compare port.
4878 * IN:
4879 * saidx0: source, it can be in SAD.
4880 * saidx1: object.
4881 * OUT:
4882 * 1 : equal
4883 * 0 : not equal
4884 */
4885 static int
4886 key_cmpsaidx(
4887 struct secasindex *saidx0,
4888 struct secasindex *saidx1,
4889 int flag)
4890 {
4891 /* sanity */
4892 if (saidx0 == NULL && saidx1 == NULL)
4893 return 1;
4894
4895 if (saidx0 == NULL || saidx1 == NULL)
4896 return 0;
4897
4898 if (saidx0->proto != saidx1->proto)
4899 return 0;
4900
4901 if (flag == CMP_EXACTLY) {
4902 if (saidx0->mode != saidx1->mode)
4903 return 0;
4904 if (saidx0->reqid != saidx1->reqid)
4905 return 0;
4906 if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.ss_len) != 0 ||
4907 bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.ss_len) != 0)
4908 return 0;
4909 } else {
4910
4911 /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
4912 if (flag & CMP_REQID) {
4913 /*
4914 * If reqid of SPD is non-zero, unique SA is required.
4915 * The result must be of same reqid in this case.
4916 */
4917 if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
4918 return 0;
4919 }
4920
4921 if (flag & CMP_MODE) {
4922 if (saidx0->mode != IPSEC_MODE_ANY
4923 && saidx0->mode != saidx1->mode)
4924 return 0;
4925 }
4926
4927 if (key_sockaddrcmp((struct sockaddr *)&saidx0->src,
4928 (struct sockaddr *)&saidx1->src, flag & CMP_PORT ? 1 : 0) != 0) {
4929 return 0;
4930 }
4931 if (key_sockaddrcmp((struct sockaddr *)&saidx0->dst,
4932 (struct sockaddr *)&saidx1->dst, flag & CMP_PORT ? 1 : 0) != 0) {
4933 return 0;
4934 }
4935 }
4936
4937 return 1;
4938 }
4939
4940 /*
4941 * compare two secindex structure exactly.
4942 * IN:
4943 * spidx0: source, it is often in SPD.
4944 * spidx1: object, it is often from PFKEY message.
4945 * OUT:
4946 * 1 : equal
4947 * 0 : not equal
4948 */
4949 static int
4950 key_cmpspidx_exactly(
4951 struct secpolicyindex *spidx0,
4952 struct secpolicyindex *spidx1)
4953 {
4954 /* sanity */
4955 if (spidx0 == NULL && spidx1 == NULL)
4956 return 1;
4957
4958 if (spidx0 == NULL || spidx1 == NULL)
4959 return 0;
4960
4961 if (spidx0->prefs != spidx1->prefs
4962 || spidx0->prefd != spidx1->prefd
4963 || spidx0->ul_proto != spidx1->ul_proto)
4964 return 0;
4965
4966 if (key_sockaddrcmp((struct sockaddr *)&spidx0->src,
4967 (struct sockaddr *)&spidx1->src, 1) != 0) {
4968 return 0;
4969 }
4970 if (key_sockaddrcmp((struct sockaddr *)&spidx0->dst,
4971 (struct sockaddr *)&spidx1->dst, 1) != 0) {
4972 return 0;
4973 }
4974
4975 return 1;
4976 }
4977
4978 /*
4979 * compare two secindex structure with mask.
4980 * IN:
4981 * spidx0: source, it is often in SPD.
4982 * spidx1: object, it is often from IP header.
4983 * OUT:
4984 * 1 : equal
4985 * 0 : not equal
4986 */
4987 static int
4988 key_cmpspidx_withmask(
4989 struct secpolicyindex *spidx0,
4990 struct secpolicyindex *spidx1)
4991 {
4992 /* sanity */
4993 if (spidx0 == NULL && spidx1 == NULL)
4994 return 1;
4995
4996 if (spidx0 == NULL || spidx1 == NULL)
4997 return 0;
4998
4999 if (spidx0->src.ss_family != spidx1->src.ss_family ||
5000 spidx0->dst.ss_family != spidx1->dst.ss_family ||
5001 spidx0->src.ss_len != spidx1->src.ss_len ||
5002 spidx0->dst.ss_len != spidx1->dst.ss_len)
5003 return 0;
5004
5005 /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
5006 if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
5007 && spidx0->ul_proto != spidx1->ul_proto)
5008 return 0;
5009
5010 switch (spidx0->src.ss_family) {
5011 case AF_INET:
5012 if (satosin(&spidx0->src)->sin_port != IPSEC_PORT_ANY
5013 && satosin(&spidx0->src)->sin_port !=
5014 satosin(&spidx1->src)->sin_port)
5015 return 0;
5016 if (!key_bbcmp((caddr_t)&satosin(&spidx0->src)->sin_addr,
5017 (caddr_t)&satosin(&spidx1->src)->sin_addr, spidx0->prefs))
5018 return 0;
5019 break;
5020 case AF_INET6:
5021 if (satosin6(&spidx0->src)->sin6_port != IPSEC_PORT_ANY
5022 && satosin6(&spidx0->src)->sin6_port !=
5023 satosin6(&spidx1->src)->sin6_port)
5024 return 0;
5025 /*
5026 * scope_id check. if sin6_scope_id is 0, we regard it
5027 * as a wildcard scope, which matches any scope zone ID.
5028 */
5029 if (satosin6(&spidx0->src)->sin6_scope_id &&
5030 satosin6(&spidx1->src)->sin6_scope_id &&
5031 satosin6(&spidx0->src)->sin6_scope_id !=
5032 satosin6(&spidx1->src)->sin6_scope_id)
5033 return 0;
5034 if (!key_bbcmp((caddr_t)&satosin6(&spidx0->src)->sin6_addr,
5035 (caddr_t)&satosin6(&spidx1->src)->sin6_addr, spidx0->prefs))
5036 return 0;
5037 break;
5038 default:
5039 /* XXX */
5040 if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.ss_len) != 0)
5041 return 0;
5042 break;
5043 }
5044
5045 switch (spidx0->dst.ss_family) {
5046 case AF_INET:
5047 if (satosin(&spidx0->dst)->sin_port != IPSEC_PORT_ANY
5048 && satosin(&spidx0->dst)->sin_port !=
5049 satosin(&spidx1->dst)->sin_port)
5050 return 0;
5051 if (!key_bbcmp((caddr_t)&satosin(&spidx0->dst)->sin_addr,
5052 (caddr_t)&satosin(&spidx1->dst)->sin_addr, spidx0->prefd))
5053 return 0;
5054 break;
5055 case AF_INET6:
5056 if (satosin6(&spidx0->dst)->sin6_port != IPSEC_PORT_ANY
5057 && satosin6(&spidx0->dst)->sin6_port !=
5058 satosin6(&spidx1->dst)->sin6_port)
5059 return 0;
5060 /*
5061 * scope_id check. if sin6_scope_id is 0, we regard it
5062 * as a wildcard scope, which matches any scope zone ID.
5063 */
5064 if (satosin6(&spidx0->src)->sin6_scope_id &&
5065 satosin6(&spidx1->src)->sin6_scope_id &&
5066 satosin6(&spidx0->dst)->sin6_scope_id !=
5067 satosin6(&spidx1->dst)->sin6_scope_id)
5068 return 0;
5069 if (!key_bbcmp((caddr_t)&satosin6(&spidx0->dst)->sin6_addr,
5070 (caddr_t)&satosin6(&spidx1->dst)->sin6_addr, spidx0->prefd))
5071 return 0;
5072 break;
5073 default:
5074 /* XXX */
5075 if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.ss_len) != 0)
5076 return 0;
5077 break;
5078 }
5079
5080 /* XXX Do we check other field ? e.g. flowinfo */
5081
5082 return 1;
5083 }
5084
5085 /* returns 0 on match */
5086 static int
5087 key_sockaddrcmp(
5088 struct sockaddr *sa1,
5089 struct sockaddr *sa2,
5090 int port)
5091 {
5092 if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
5093 return 1;
5094
5095 switch (sa1->sa_family) {
5096 case AF_INET:
5097 if (sa1->sa_len != sizeof(struct sockaddr_in))
5098 return 1;
5099 if (satosin(sa1)->sin_addr.s_addr !=
5100 satosin(sa2)->sin_addr.s_addr) {
5101 return 1;
5102 }
5103 if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
5104 return 1;
5105 break;
5106 case AF_INET6:
5107 if (sa1->sa_len != sizeof(struct sockaddr_in6))
5108 return 1; /*EINVAL*/
5109 if (satosin6(sa1)->sin6_scope_id !=
5110 satosin6(sa2)->sin6_scope_id) {
5111 return 1;
5112 }
5113 if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
5114 &satosin6(sa2)->sin6_addr)) {
5115 return 1;
5116 }
5117 if (port &&
5118 satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
5119 return 1;
5120 }
5121 break;
5122 default:
5123 if (bcmp(sa1, sa2, sa1->sa_len) != 0)
5124 return 1;
5125 break;
5126 }
5127
5128 return 0;
5129 }
5130
5131 /*
5132 * compare two buffers with mask.
5133 * IN:
5134 * addr1: source
5135 * addr2: object
5136 * bits: Number of bits to compare
5137 * OUT:
5138 * 1 : equal
5139 * 0 : not equal
5140 */
5141 static int
5142 key_bbcmp(
5143 caddr_t p1,
5144 caddr_t p2,
5145 u_int bits)
5146 {
5147 u_int8_t mask;
5148
5149 /* XXX: This could be considerably faster if we compare a word
5150 * at a time, but it is complicated on LSB Endian machines */
5151
5152 /* Handle null pointers */
5153 if (p1 == NULL || p2 == NULL)
5154 return (p1 == p2);
5155
5156 while (bits >= 8) {
5157 if (*p1++ != *p2++)
5158 return 0;
5159 bits -= 8;
5160 }
5161
5162 if (bits > 0) {
5163 mask = ~((1<<(8-bits))-1);
5164 if ((*p1 & mask) != (*p2 & mask))
5165 return 0;
5166 }
5167 return 1; /* Match! */
5168 }
5169
5170 /*
5171 * time handler.
5172 * scanning SPD and SAD to check status for each entries,
5173 * and do to remove or to expire.
5174 * XXX: year 2038 problem may remain.
5175 */
5176 int key_timehandler_debug = 0;
5177 u_int32_t spd_count = 0, sah_count = 0, dead_sah_count = 0, empty_sah_count = 0, larval_sav_count = 0, mature_sav_count = 0, dying_sav_count = 0, dead_sav_count = 0;
5178 u_int64_t total_sav_count = 0;
5179 void
5180 key_timehandler(void)
5181 {
5182 u_int dir;
5183 struct timeval tv;
5184 struct secpolicy **spbuf = NULL, **spptr = NULL;
5185 struct secasvar **savexbuf = NULL, **savexptr = NULL;
5186 struct secasvar **savkabuf = NULL, **savkaptr = NULL;
5187 int spbufcount = 0, savbufcount = 0, spcount = 0, savexcount = 0, savkacount = 0, cnt;
5188
5189 microtime(&tv);
5190
5191 /* pre-allocate buffers before taking the lock */
5192 /* if allocation failures occur - portions of the processing will be skipped */
5193 if ((spbufcount = ipsec_policy_count) != 0) {
5194 spbufcount += 256;
5195 KMALLOC_WAIT(spbuf, struct secpolicy **, spbufcount * sizeof(struct secpolicy *));
5196 if (spbuf)
5197 spptr = spbuf;
5198 }
5199 if ((savbufcount = ipsec_sav_count) != 0) {
5200 savbufcount += 512;
5201 KMALLOC_WAIT(savexbuf, struct secasvar **, savbufcount * sizeof(struct secasvar *));
5202 if (savexbuf)
5203 savexptr = savexbuf;
5204 KMALLOC_WAIT(savkabuf, struct secasvar **, savbufcount * sizeof(struct secasvar *));
5205 if (savkabuf)
5206 savkaptr = savkabuf;
5207 }
5208 lck_mtx_lock(sadb_mutex);
5209 /* SPD */
5210 if (spbuf) {
5211
5212 struct secpolicy *sp, *nextsp;
5213
5214 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
5215 for (sp = LIST_FIRST(&sptree[dir]);
5216 sp != NULL;
5217 sp = nextsp) {
5218
5219 spd_count++;
5220 nextsp = LIST_NEXT(sp, chain);
5221
5222 if (sp->state == IPSEC_SPSTATE_DEAD) {
5223 key_freesp(sp, KEY_SADB_LOCKED);
5224 continue;
5225 }
5226
5227 if (sp->lifetime == 0 && sp->validtime == 0)
5228 continue;
5229 if (spbuf && spcount < spbufcount) {
5230 /* the deletion will occur next time */
5231 if ((sp->lifetime
5232 && tv.tv_sec - sp->created > sp->lifetime)
5233 || (sp->validtime
5234 && tv.tv_sec - sp->lastused > sp->validtime)) {
5235 //key_spdexpire(sp);
5236 sp->state = IPSEC_SPSTATE_DEAD;
5237 sp->refcnt++;
5238 *spptr++ = sp;
5239 spcount++;
5240 }
5241 }
5242 }
5243 }
5244 }
5245
5246 /* SAD */
5247 if (savbufcount != 0) {
5248 struct secashead *sah, *nextsah;
5249 struct secasvar *sav, *nextsav;
5250
5251 for (sah = LIST_FIRST(&sahtree);
5252 sah != NULL;
5253 sah = nextsah) {
5254
5255 sah_count++;
5256 nextsah = LIST_NEXT(sah, chain);
5257
5258 /* if sah has been dead, then delete it and process next sah. */
5259 if (sah->state == SADB_SASTATE_DEAD) {
5260 key_delsah(sah);
5261 dead_sah_count++;
5262 continue;
5263 }
5264
5265 if (LIST_FIRST(&sah->savtree[SADB_SASTATE_LARVAL]) == NULL &&
5266 LIST_FIRST(&sah->savtree[SADB_SASTATE_MATURE]) == NULL &&
5267 LIST_FIRST(&sah->savtree[SADB_SASTATE_DYING]) == NULL &&
5268 LIST_FIRST(&sah->savtree[SADB_SASTATE_DEAD]) == NULL) {
5269 key_delsah(sah);
5270 empty_sah_count++;
5271 continue;
5272 }
5273
5274 /* if LARVAL entry doesn't become MATURE, delete it. */
5275 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_LARVAL]);
5276 sav != NULL;
5277 sav = nextsav) {
5278
5279 larval_sav_count++;
5280 total_sav_count++;
5281 nextsav = LIST_NEXT(sav, chain);
5282
5283 if (tv.tv_sec - sav->created > key_larval_lifetime) {
5284 key_freesav(sav, KEY_SADB_LOCKED);
5285 }
5286 }
5287
5288 /*
5289 * If this is a NAT traversal SA with no activity,
5290 * we need to send a keep alive.
5291 *
5292 * Performed outside of the loop before so we will
5293 * only ever send one keepalive. The first SA on
5294 * the list is the one that will be used for sending
5295 * traffic, so this is the one we use for determining
5296 * when to send the keepalive.
5297 */
5298 if (savkabuf && savkacount < savbufcount) {
5299 sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_MATURE]); //%%% should we check dying list if this is empty???
5300 if (natt_keepalive_interval && sav &&
5301 (sav->flags & (SADB_X_EXT_NATT_KEEPALIVE | SADB_X_EXT_ESP_KEEPALIVE)) != 0) {
5302 sav->refcnt++;
5303 *savkaptr++ = sav;
5304 savkacount++;
5305 }
5306 }
5307
5308 /*
5309 * check MATURE entry to start to send expire message
5310 * whether or not.
5311 */
5312 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_MATURE]);
5313 sav != NULL;
5314 sav = nextsav) {
5315
5316 mature_sav_count++;
5317 total_sav_count++;
5318 nextsav = LIST_NEXT(sav, chain);
5319
5320 /* we don't need to check. */
5321 if (sav->lft_s == NULL)
5322 continue;
5323
5324 /* sanity check */
5325 if (sav->lft_c == NULL) {
5326 ipseclog((LOG_DEBUG,"key_timehandler: "
5327 "There is no CURRENT time, why?\n"));
5328 continue;
5329 }
5330
5331 /* check SOFT lifetime */
5332 if (sav->lft_s->sadb_lifetime_addtime != 0
5333 && tv.tv_sec - sav->created > sav->lft_s->sadb_lifetime_addtime) {
5334 /*
5335 * check the SA if it has been used.
5336 * when it hasn't been used, delete it.
5337 * i don't think such SA will be used.
5338 */
5339 if (sav->lft_c->sadb_lifetime_usetime == 0) {
5340 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5341 key_freesav(sav, KEY_SADB_LOCKED);
5342 sav = NULL;
5343 } else if (savexbuf && savexcount < savbufcount) {
5344 key_sa_chgstate(sav, SADB_SASTATE_DYING);
5345 sav->refcnt++;
5346 *savexptr++ = sav;
5347 savexcount++;
5348 }
5349 }
5350
5351 /* check SOFT lifetime by bytes */
5352 /*
5353 * XXX I don't know the way to delete this SA
5354 * when new SA is installed. Caution when it's
5355 * installed too big lifetime by time.
5356 */
5357 else if (savexbuf && savexcount < savbufcount
5358 && sav->lft_s->sadb_lifetime_bytes != 0
5359 && sav->lft_s->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
5360
5361 /*
5362 * XXX If we keep to send expire
5363 * message in the status of
5364 * DYING. Do remove below code.
5365 */
5366 //key_expire(sav);
5367 key_sa_chgstate(sav, SADB_SASTATE_DYING);
5368 sav->refcnt++;
5369 *savexptr++ = sav;
5370 savexcount++;
5371 }
5372 }
5373
5374 /* check DYING entry to change status to DEAD. */
5375 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DYING]);
5376 sav != NULL;
5377 sav = nextsav) {
5378
5379 dying_sav_count++;
5380 total_sav_count++;
5381 nextsav = LIST_NEXT(sav, chain);
5382
5383 /* we don't need to check. */
5384 if (sav->lft_h == NULL)
5385 continue;
5386
5387 /* sanity check */
5388 if (sav->lft_c == NULL) {
5389 ipseclog((LOG_DEBUG, "key_timehandler: "
5390 "There is no CURRENT time, why?\n"));
5391 continue;
5392 }
5393
5394 if (sav->lft_h->sadb_lifetime_addtime != 0
5395 && tv.tv_sec - sav->created > sav->lft_h->sadb_lifetime_addtime) {
5396 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5397 key_freesav(sav, KEY_SADB_LOCKED);
5398 sav = NULL;
5399 }
5400 #if 0 /* XXX Should we keep to send expire message until HARD lifetime ? */
5401 else if (savbuf && savexcount < savbufcount
5402 && sav->lft_s != NULL
5403 && sav->lft_s->sadb_lifetime_addtime != 0
5404 && tv.tv_sec - sav->created > sav->lft_s->sadb_lifetime_addtime) {
5405 /*
5406 * XXX: should be checked to be
5407 * installed the valid SA.
5408 */
5409
5410 /*
5411 * If there is no SA then sending
5412 * expire message.
5413 */
5414 //key_expire(sav);
5415 sav->refcnt++;
5416 *savexptr++ = sav;
5417 savexcount++;
5418 }
5419 #endif
5420 /* check HARD lifetime by bytes */
5421 else if (sav->lft_h->sadb_lifetime_bytes != 0
5422 && sav->lft_h->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
5423 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5424 key_freesav(sav, KEY_SADB_LOCKED);
5425 sav = NULL;
5426 }
5427 }
5428
5429 /* delete entry in DEAD */
5430 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DEAD]);
5431 sav != NULL;
5432 sav = nextsav) {
5433
5434 dead_sav_count++;
5435 total_sav_count++;
5436 nextsav = LIST_NEXT(sav, chain);
5437
5438 /* sanity check */
5439 if (sav->state != SADB_SASTATE_DEAD) {
5440 ipseclog((LOG_DEBUG, "key_timehandler: "
5441 "invalid sav->state "
5442 "(queue: %d SA: %d): "
5443 "kill it anyway\n",
5444 SADB_SASTATE_DEAD, sav->state));
5445 }
5446
5447 /*
5448 * do not call key_freesav() here.
5449 * sav should already be freed, and sav->refcnt
5450 * shows other references to sav
5451 * (such as from SPD).
5452 */
5453 }
5454 }
5455 }
5456
5457 if (++key_timehandler_debug >= 300) {
5458 if (key_debug_level) {
5459 printf("%s: total stats for %u calls\n", __FUNCTION__, key_timehandler_debug);
5460 printf("%s: walked %u SPDs\n", __FUNCTION__, spd_count);
5461 printf("%s: walked %llu SAs: LARVAL SAs %u, MATURE SAs %u, DYING SAs %u, DEAD SAs %u\n", __FUNCTION__,
5462 total_sav_count, larval_sav_count, mature_sav_count, dying_sav_count, dead_sav_count);
5463 printf("%s: walked %u SAHs: DEAD SAHs %u, EMPTY SAHs %u\n", __FUNCTION__,
5464 sah_count, dead_sah_count, empty_sah_count);
5465 if (sah_search_calls) {
5466 printf("%s: SAH search cost %d iters per call\n", __FUNCTION__,
5467 (sah_search_count/sah_search_calls));
5468 }
5469 }
5470 spd_count = 0;
5471 sah_count = 0;
5472 dead_sah_count = 0;
5473 empty_sah_count = 0;
5474 larval_sav_count = 0;
5475 mature_sav_count = 0;
5476 dying_sav_count = 0;
5477 dead_sav_count = 0;
5478 total_sav_count = 0;
5479 sah_search_count = 0;
5480 sah_search_calls = 0;
5481 key_timehandler_debug = 0;
5482 }
5483 #ifndef IPSEC_NONBLOCK_ACQUIRE
5484 /* ACQ tree */
5485 {
5486 struct secacq *acq, *nextacq;
5487
5488 for (acq = LIST_FIRST(&acqtree);
5489 acq != NULL;
5490 acq = nextacq) {
5491
5492 nextacq = LIST_NEXT(acq, chain);
5493
5494 if (tv.tv_sec - acq->created > key_blockacq_lifetime
5495 && __LIST_CHAINED(acq)) {
5496 LIST_REMOVE(acq, chain);
5497 KFREE(acq);
5498 }
5499 }
5500 }
5501 #endif
5502
5503 /* SP ACQ tree */
5504 {
5505 struct secspacq *acq, *nextacq;
5506
5507 for (acq = LIST_FIRST(&spacqtree);
5508 acq != NULL;
5509 acq = nextacq) {
5510
5511 nextacq = LIST_NEXT(acq, chain);
5512
5513 if (tv.tv_sec - acq->created > key_blockacq_lifetime
5514 && __LIST_CHAINED(acq)) {
5515 LIST_REMOVE(acq, chain);
5516 KFREE(acq);
5517 }
5518 }
5519 }
5520
5521 /* initialize random seed */
5522 if (key_tick_init_random++ > key_int_random) {
5523 key_tick_init_random = 0;
5524 key_srandom();
5525 }
5526
5527 natt_now++;
5528
5529 lck_mtx_unlock(sadb_mutex);
5530
5531 /* send messages outside of sadb_mutex */
5532 if (spbuf && spcount > 0) {
5533 cnt = spcount;
5534 while (cnt--)
5535 key_spdexpire(*(--spptr));
5536 }
5537 if (savkabuf && savkacount > 0) {
5538 struct secasvar **savkaptr_sav = savkaptr;
5539 int cnt_send = savkacount;
5540
5541 while (cnt_send--) {
5542 if (ipsec_send_natt_keepalive(*(--savkaptr))) {
5543 // <rdar://6768487> iterate (all over again) and update timestamps
5544 struct secasvar **savkaptr_update = savkaptr_sav;
5545 int cnt_update = savkacount;
5546 while (cnt_update--) {
5547 key_update_natt_keepalive_timestamp(*savkaptr,
5548 *(--savkaptr_update));
5549 }
5550 }
5551 }
5552 }
5553 if (savexbuf && savexcount > 0) {
5554 cnt = savexcount;
5555 while (cnt--)
5556 key_expire(*(--savexptr));
5557 }
5558
5559 /* decrement ref counts and free buffers */
5560 lck_mtx_lock(sadb_mutex);
5561 if (spbuf) {
5562 while (spcount--)
5563 key_freesp(*spptr++, KEY_SADB_LOCKED);
5564 KFREE(spbuf);
5565 }
5566 if (savkabuf) {
5567 while (savkacount--)
5568 key_freesav(*savkaptr++, KEY_SADB_LOCKED);
5569 KFREE(savkabuf);
5570 }
5571 if (savexbuf) {
5572 while (savexcount--)
5573 key_freesav(*savexptr++, KEY_SADB_LOCKED);
5574 KFREE(savexbuf);
5575 }
5576 lck_mtx_unlock(sadb_mutex);
5577
5578
5579 #ifndef IPSEC_DEBUG2
5580 /* do exchange to tick time !! */
5581 (void)timeout((void *)key_timehandler, (void *)0, hz);
5582 #endif /* IPSEC_DEBUG2 */
5583
5584 return;
5585 }
5586
5587 /*
5588 * to initialize a seed for random()
5589 */
5590 static void
5591 key_srandom(void)
5592 {
5593 #ifdef __APPLE__
5594 /* Our PRNG is based on Yarrow and doesn't need to be seeded */
5595 random();
5596 #else
5597 struct timeval tv;
5598
5599 microtime(&tv);
5600
5601 srandom(tv.tv_usec);
5602 #endif
5603
5604 return;
5605 }
5606
5607 u_int32_t
5608 key_random(void)
5609 {
5610 u_int32_t value;
5611
5612 key_randomfill(&value, sizeof(value));
5613 return value;
5614 }
5615
5616 void
5617 key_randomfill(
5618 void *p,
5619 size_t l)
5620 {
5621 #ifdef __APPLE__
5622
5623 read_random(p, (u_int)l);
5624 #else
5625 size_t n;
5626 u_int32_t v;
5627 static int warn = 1;
5628
5629 n = 0;
5630 n = (size_t)read_random(p, (u_int)l);
5631 /* last resort */
5632 while (n < l) {
5633 v = random();
5634 bcopy(&v, (u_int8_t *)p + n,
5635 l - n < sizeof(v) ? l - n : sizeof(v));
5636 n += sizeof(v);
5637
5638 if (warn) {
5639 printf("WARNING: pseudo-random number generator "
5640 "used for IPsec processing\n");
5641 warn = 0;
5642 }
5643 }
5644 #endif
5645 }
5646
5647 /*
5648 * map SADB_SATYPE_* to IPPROTO_*.
5649 * if satype == SADB_SATYPE then satype is mapped to ~0.
5650 * OUT:
5651 * 0: invalid satype.
5652 */
5653 static u_int16_t
5654 key_satype2proto(
5655 u_int8_t satype)
5656 {
5657 switch (satype) {
5658 case SADB_SATYPE_UNSPEC:
5659 return IPSEC_PROTO_ANY;
5660 case SADB_SATYPE_AH:
5661 return IPPROTO_AH;
5662 case SADB_SATYPE_ESP:
5663 return IPPROTO_ESP;
5664 case SADB_X_SATYPE_IPCOMP:
5665 return IPPROTO_IPCOMP;
5666 break;
5667 default:
5668 return 0;
5669 }
5670 /* NOTREACHED */
5671 }
5672
5673 /*
5674 * map IPPROTO_* to SADB_SATYPE_*
5675 * OUT:
5676 * 0: invalid protocol type.
5677 */
5678 static u_int8_t
5679 key_proto2satype(
5680 u_int16_t proto)
5681 {
5682 switch (proto) {
5683 case IPPROTO_AH:
5684 return SADB_SATYPE_AH;
5685 case IPPROTO_ESP:
5686 return SADB_SATYPE_ESP;
5687 case IPPROTO_IPCOMP:
5688 return SADB_X_SATYPE_IPCOMP;
5689 break;
5690 default:
5691 return 0;
5692 }
5693 /* NOTREACHED */
5694 }
5695
5696 /* %%% PF_KEY */
5697 /*
5698 * SADB_GETSPI processing is to receive
5699 * <base, (SA2), src address, dst address, (SPI range)>
5700 * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
5701 * tree with the status of LARVAL, and send
5702 * <base, SA(*), address(SD)>
5703 * to the IKMPd.
5704 *
5705 * IN: mhp: pointer to the pointer to each header.
5706 * OUT: NULL if fail.
5707 * other if success, return pointer to the message to send.
5708 */
5709 static int
5710 key_getspi(
5711 struct socket *so,
5712 struct mbuf *m,
5713 const struct sadb_msghdr *mhp)
5714 {
5715 struct sadb_address *src0, *dst0;
5716 struct secasindex saidx;
5717 struct secashead *newsah;
5718 struct secasvar *newsav;
5719 u_int8_t proto;
5720 u_int32_t spi;
5721 u_int8_t mode;
5722 u_int32_t reqid;
5723 int error;
5724
5725 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
5726
5727 /* sanity check */
5728 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5729 panic("key_getspi: NULL pointer is passed.\n");
5730
5731 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5732 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5733 ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
5734 return key_senderror(so, m, EINVAL);
5735 }
5736 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5737 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5738 ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
5739 return key_senderror(so, m, EINVAL);
5740 }
5741 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5742 mode = ((struct sadb_x_sa2 *)
5743 (void *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5744 reqid = ((struct sadb_x_sa2 *)
5745 (void *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5746 } else {
5747 mode = IPSEC_MODE_ANY;
5748 reqid = 0;
5749 }
5750
5751 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5752 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5753
5754 /* map satype to proto */
5755 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5756 ipseclog((LOG_DEBUG, "key_getspi: invalid satype is passed.\n"));
5757 return key_senderror(so, m, EINVAL);
5758 }
5759
5760 /* make sure if port number is zero. */
5761 switch (((struct sockaddr *)(src0 + 1))->sa_family) {
5762 case AF_INET:
5763 if (((struct sockaddr *)(src0 + 1))->sa_len !=
5764 sizeof(struct sockaddr_in))
5765 return key_senderror(so, m, EINVAL);
5766 ((struct sockaddr_in *)(void *)(src0 + 1))->sin_port = 0;
5767 break;
5768 case AF_INET6:
5769 if (((struct sockaddr *)(src0 + 1))->sa_len !=
5770 sizeof(struct sockaddr_in6))
5771 return key_senderror(so, m, EINVAL);
5772 ((struct sockaddr_in6 *)(void *)(src0 + 1))->sin6_port = 0;
5773 break;
5774 default:
5775 ; /*???*/
5776 }
5777 switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
5778 case AF_INET:
5779 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
5780 sizeof(struct sockaddr_in))
5781 return key_senderror(so, m, EINVAL);
5782 ((struct sockaddr_in *)(void *)(dst0 + 1))->sin_port = 0;
5783 break;
5784 case AF_INET6:
5785 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
5786 sizeof(struct sockaddr_in6))
5787 return key_senderror(so, m, EINVAL);
5788 ((struct sockaddr_in6 *)(void *)(dst0 + 1))->sin6_port = 0;
5789 break;
5790 default:
5791 ; /*???*/
5792 }
5793
5794 /* XXX boundary check against sa_len */
5795 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5796
5797 lck_mtx_lock(sadb_mutex);
5798
5799 /* SPI allocation */
5800 spi = key_do_getnewspi((struct sadb_spirange *)
5801 (void *)mhp->ext[SADB_EXT_SPIRANGE], &saidx);
5802 if (spi == 0) {
5803 lck_mtx_unlock(sadb_mutex);
5804 return key_senderror(so, m, EINVAL);
5805 }
5806
5807 /* get a SA index */
5808 if ((newsah = key_getsah(&saidx)) == NULL) {
5809 /* create a new SA index: key_addspi is always used for inbound spi */
5810 if ((newsah = key_newsah(&saidx, IPSEC_DIR_INBOUND)) == NULL) {
5811 lck_mtx_unlock(sadb_mutex);
5812 ipseclog((LOG_DEBUG, "key_getspi: No more memory.\n"));
5813 return key_senderror(so, m, ENOBUFS);
5814 }
5815 }
5816
5817 /* get a new SA */
5818 /* XXX rewrite */
5819 newsav = key_newsav(m, mhp, newsah, &error);
5820 if (newsav == NULL) {
5821 /* XXX don't free new SA index allocated in above. */
5822 lck_mtx_unlock(sadb_mutex);
5823 return key_senderror(so, m, error);
5824 }
5825
5826 /* set spi */
5827 key_setspi(newsav, htonl(spi));
5828
5829 #ifndef IPSEC_NONBLOCK_ACQUIRE
5830 /* delete the entry in acqtree */
5831 if (mhp->msg->sadb_msg_seq != 0) {
5832 struct secacq *acq;
5833 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
5834 /* reset counter in order to deletion by timehandler. */
5835 struct timeval tv;
5836 microtime(&tv);
5837 acq->created = tv.tv_sec;
5838 acq->count = 0;
5839 }
5840 }
5841 #endif
5842
5843 lck_mtx_unlock(sadb_mutex);
5844
5845 {
5846 struct mbuf *n, *nn;
5847 struct sadb_sa *m_sa;
5848 struct sadb_msg *newmsg;
5849 int off, len;
5850
5851 /* create new sadb_msg to reply. */
5852 len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
5853 PFKEY_ALIGN8(sizeof(struct sadb_sa));
5854 if (len > MCLBYTES)
5855 return key_senderror(so, m, ENOBUFS);
5856
5857 MGETHDR(n, M_WAITOK, MT_DATA);
5858 if (n && len > MHLEN) {
5859 MCLGET(n, M_WAITOK);
5860 if ((n->m_flags & M_EXT) == 0) {
5861 m_freem(n);
5862 n = NULL;
5863 }
5864 }
5865 if (!n)
5866 return key_senderror(so, m, ENOBUFS);
5867
5868 n->m_len = len;
5869 n->m_next = NULL;
5870 off = 0;
5871
5872 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
5873 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
5874
5875 m_sa = (struct sadb_sa *)(void *)(mtod(n, caddr_t) + off);
5876 m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
5877 m_sa->sadb_sa_exttype = SADB_EXT_SA;
5878 m_sa->sadb_sa_spi = htonl(spi);
5879 off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
5880
5881 #if DIAGNOSTIC
5882 if (off != len)
5883 panic("length inconsistency in key_getspi");
5884 #endif
5885 {
5886 int mbufItems[] = {SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST};
5887 n->m_next = key_gather_mbuf(m, mhp, 0, sizeof(mbufItems)/sizeof(int), mbufItems);
5888 if (!n->m_next) {
5889 m_freem(n);
5890 return key_senderror(so, m, ENOBUFS);
5891 }
5892 }
5893
5894 if (n->m_len < sizeof(struct sadb_msg)) {
5895 n = m_pullup(n, sizeof(struct sadb_msg));
5896 if (n == NULL)
5897 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
5898 }
5899
5900 n->m_pkthdr.len = 0;
5901 for (nn = n; nn; nn = nn->m_next)
5902 n->m_pkthdr.len += nn->m_len;
5903
5904 newmsg = mtod(n, struct sadb_msg *);
5905 newmsg->sadb_msg_seq = newsav->seq;
5906 newmsg->sadb_msg_errno = 0;
5907 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5908
5909 m_freem(m);
5910 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5911 }
5912 }
5913
5914 u_int32_t
5915 key_getspi2(struct sockaddr *src,
5916 struct sockaddr *dst,
5917 u_int8_t proto,
5918 u_int8_t mode,
5919 u_int32_t reqid,
5920 struct sadb_spirange *spirange)
5921 {
5922 u_int32_t spi;
5923 struct secasindex saidx;
5924
5925 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
5926
5927 /* XXX boundary check against sa_len */
5928 KEY_SETSECASIDX(proto, mode, reqid, src, dst, &saidx);
5929
5930 /* make sure if port number is zero. */
5931 switch (((struct sockaddr *)&saidx.src)->sa_family) {
5932 case AF_INET:
5933 if (((struct sockaddr *)&saidx.src)->sa_len != sizeof(struct sockaddr_in))
5934 return 0;
5935 ((struct sockaddr_in *)&saidx.src)->sin_port = 0;
5936 break;
5937 case AF_INET6:
5938 if (((struct sockaddr *)&saidx.src)->sa_len != sizeof(struct sockaddr_in6))
5939 return 0;
5940 ((struct sockaddr_in6 *)&saidx.src)->sin6_port = 0;
5941 break;
5942 default:
5943 ; /*???*/
5944 }
5945 switch (((struct sockaddr *)&saidx.dst)->sa_family) {
5946 case AF_INET:
5947 if (((struct sockaddr *)&saidx.dst)->sa_len != sizeof(struct sockaddr_in))
5948 return 0;
5949 ((struct sockaddr_in *)&saidx.dst)->sin_port = 0;
5950 break;
5951 case AF_INET6:
5952 if (((struct sockaddr *)&saidx.dst)->sa_len != sizeof(struct sockaddr_in6))
5953 return 0;
5954 ((struct sockaddr_in6 *)&saidx.dst)->sin6_port = 0;
5955 break;
5956 default:
5957 ; /*???*/
5958 }
5959
5960 lck_mtx_lock(sadb_mutex);
5961
5962 /* SPI allocation */
5963 spi = key_do_getnewspi(spirange, &saidx);
5964
5965 lck_mtx_unlock(sadb_mutex);
5966
5967 return spi;
5968 }
5969
5970 /*
5971 * allocating new SPI
5972 * called by key_getspi() and key_getspi2().
5973 * OUT:
5974 * 0: failure.
5975 * others: success.
5976 */
5977 static u_int32_t
5978 key_do_getnewspi(
5979 struct sadb_spirange *spirange,
5980 struct secasindex *saidx)
5981 {
5982 u_int32_t newspi;
5983 u_int32_t keymin, keymax;
5984 int count = key_spi_trycnt;
5985
5986 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
5987
5988 /* set spi range to allocate */
5989 if (spirange != NULL) {
5990 keymin = spirange->sadb_spirange_min;
5991 keymax = spirange->sadb_spirange_max;
5992 } else {
5993 keymin = key_spi_minval;
5994 keymax = key_spi_maxval;
5995 }
5996 /* IPCOMP needs 2-byte SPI */
5997 if (saidx->proto == IPPROTO_IPCOMP) {
5998 u_int32_t t;
5999 if (keymin >= 0x10000)
6000 keymin = 0xffff;
6001 if (keymax >= 0x10000)
6002 keymax = 0xffff;
6003 if (keymin > keymax) {
6004 t = keymin; keymin = keymax; keymax = t;
6005 }
6006 }
6007
6008 if (keymin == keymax) {
6009 if (key_checkspidup(saidx, keymin) != NULL) {
6010 ipseclog((LOG_DEBUG, "key_do_getnewspi: SPI %u exists already.\n", keymin));
6011 return 0;
6012 }
6013
6014 count--; /* taking one cost. */
6015 newspi = keymin;
6016
6017 } else {
6018
6019 u_int32_t range = keymax - keymin + 1; /* overflow value of zero means full range */
6020
6021 /* init SPI */
6022 newspi = 0;
6023
6024 /* when requesting to allocate spi ranged */
6025 while (count--) {
6026 u_int32_t rand_val = key_random();
6027
6028 /* generate pseudo-random SPI value ranged. */
6029 newspi = (range == 0 ? rand_val : keymin + (rand_val % range));
6030
6031 if (key_checkspidup(saidx, newspi) == NULL)
6032 break;
6033 }
6034
6035 if (count == 0 || newspi == 0) {
6036 ipseclog((LOG_DEBUG, "key_do_getnewspi: to allocate spi is failed.\n"));
6037 return 0;
6038 }
6039 }
6040
6041 /* statistics */
6042 keystat.getspi_count =
6043 (keystat.getspi_count + key_spi_trycnt - count) / 2;
6044
6045 return newspi;
6046 }
6047
6048 /*
6049 * SADB_UPDATE processing
6050 * receive
6051 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
6052 * key(AE), (identity(SD),) (sensitivity)>
6053 * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
6054 * and send
6055 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
6056 * (identity(SD),) (sensitivity)>
6057 * to the ikmpd.
6058 *
6059 * m will always be freed.
6060 */
6061 static int
6062 key_update(
6063 struct socket *so,
6064 struct mbuf *m,
6065 const struct sadb_msghdr *mhp)
6066 {
6067 struct sadb_sa *sa0;
6068 struct sadb_address *src0, *dst0;
6069 struct secasindex saidx;
6070 struct secashead *sah;
6071 struct secasvar *sav;
6072 u_int16_t proto;
6073 u_int8_t mode;
6074 u_int32_t reqid;
6075 int error;
6076
6077 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
6078
6079 /* sanity check */
6080 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6081 panic("key_update: NULL pointer is passed.\n");
6082
6083 /* map satype to proto */
6084 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6085 ipseclog((LOG_DEBUG, "key_update: invalid satype is passed.\n"));
6086 return key_senderror(so, m, EINVAL);
6087 }
6088
6089 if (mhp->ext[SADB_EXT_SA] == NULL ||
6090 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6091 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6092 (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
6093 mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
6094 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
6095 mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
6096 (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
6097 mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
6098 (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
6099 mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
6100 ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
6101 return key_senderror(so, m, EINVAL);
6102 }
6103 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
6104 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6105 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
6106 ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
6107 return key_senderror(so, m, EINVAL);
6108 }
6109 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
6110 mode = ((struct sadb_x_sa2 *)
6111 (void *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
6112 reqid = ((struct sadb_x_sa2 *)
6113 (void *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
6114 } else {
6115 mode = IPSEC_MODE_ANY;
6116 reqid = 0;
6117 }
6118 /* XXX boundary checking for other extensions */
6119
6120 sa0 = (struct sadb_sa *)(void *)mhp->ext[SADB_EXT_SA];
6121 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
6122 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
6123
6124 /* XXX boundary check against sa_len */
6125 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
6126
6127 lck_mtx_lock(sadb_mutex);
6128
6129 /* get a SA header */
6130 if ((sah = key_getsah(&saidx)) == NULL) {
6131 lck_mtx_unlock(sadb_mutex);
6132 ipseclog((LOG_DEBUG, "key_update: no SA index found.\n"));
6133 return key_senderror(so, m, ENOENT);
6134 }
6135
6136 /* set spidx if there */
6137 /* XXX rewrite */
6138 error = key_setident(sah, m, mhp);
6139 if (error) {
6140 lck_mtx_unlock(sadb_mutex);
6141 return key_senderror(so, m, error);
6142 }
6143
6144 /* find a SA with sequence number. */
6145 #if IPSEC_DOSEQCHECK
6146 if (mhp->msg->sadb_msg_seq != 0
6147 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
6148 lck_mtx_unlock(sadb_mutex);
6149 ipseclog((LOG_DEBUG,
6150 "key_update: no larval SA with sequence %u exists.\n",
6151 mhp->msg->sadb_msg_seq));
6152 return key_senderror(so, m, ENOENT);
6153 }
6154 #else
6155 if ((sav = key_getsavbyspi(sah, sa0->sadb_sa_spi)) == NULL) {
6156 lck_mtx_unlock(sadb_mutex);
6157 ipseclog((LOG_DEBUG,
6158 "key_update: no such a SA found (spi:%u)\n",
6159 (u_int32_t)ntohl(sa0->sadb_sa_spi)));
6160 return key_senderror(so, m, EINVAL);
6161 }
6162 #endif
6163
6164 /* validity check */
6165 if (sav->sah->saidx.proto != proto) {
6166 lck_mtx_unlock(sadb_mutex);
6167 ipseclog((LOG_DEBUG,
6168 "key_update: protocol mismatched (DB=%u param=%u)\n",
6169 sav->sah->saidx.proto, proto));
6170 return key_senderror(so, m, EINVAL);
6171 }
6172 #if IPSEC_DOSEQCHECK
6173 if (sav->spi != sa0->sadb_sa_spi) {
6174 lck_mtx_unlock(sadb_mutex);
6175 ipseclog((LOG_DEBUG,
6176 "key_update: SPI mismatched (DB:%u param:%u)\n",
6177 (u_int32_t)ntohl(sav->spi),
6178 (u_int32_t)ntohl(sa0->sadb_sa_spi)));
6179 return key_senderror(so, m, EINVAL);
6180 }
6181 #endif
6182 if (sav->pid != mhp->msg->sadb_msg_pid) {
6183 lck_mtx_unlock(sadb_mutex);
6184 ipseclog((LOG_DEBUG,
6185 "key_update: pid mismatched (DB:%u param:%u)\n",
6186 sav->pid, mhp->msg->sadb_msg_pid));
6187 return key_senderror(so, m, EINVAL);
6188 }
6189
6190 /* copy sav values */
6191 error = key_setsaval(sav, m, mhp);
6192 if (error) {
6193 key_freesav(sav, KEY_SADB_LOCKED);
6194 lck_mtx_unlock(sadb_mutex);
6195 return key_senderror(so, m, error);
6196 }
6197
6198 /*
6199 * Verify if SADB_X_EXT_NATT_MULTIPLEUSERS flag is set that
6200 * this SA is for transport mode - otherwise clear it.
6201 */
6202 if ((sav->flags & SADB_X_EXT_NATT_MULTIPLEUSERS) != 0 &&
6203 (sav->sah->saidx.mode != IPSEC_MODE_TRANSPORT ||
6204 sav->sah->saidx.src.ss_family != AF_INET))
6205 sav->flags &= ~SADB_X_EXT_NATT_MULTIPLEUSERS;
6206
6207 /* check SA values to be mature. */
6208 if ((error = key_mature(sav)) != 0) {
6209 key_freesav(sav, KEY_SADB_LOCKED);
6210 lck_mtx_unlock(sadb_mutex);
6211 return key_senderror(so, m, error);
6212 }
6213
6214 lck_mtx_unlock(sadb_mutex);
6215
6216 {
6217 struct mbuf *n;
6218
6219 /* set msg buf from mhp */
6220 n = key_getmsgbuf_x1(m, mhp);
6221 if (n == NULL) {
6222 ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
6223 return key_senderror(so, m, ENOBUFS);
6224 }
6225
6226 m_freem(m);
6227 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
6228 }
6229 }
6230
6231 /*
6232 * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
6233 * only called by key_update().
6234 * OUT:
6235 * NULL : not found
6236 * others : found, pointer to a SA.
6237 */
6238 #if IPSEC_DOSEQCHECK
6239 static struct secasvar *
6240 key_getsavbyseq(
6241 struct secashead *sah,
6242 u_int32_t seq)
6243 {
6244 struct secasvar *sav;
6245 u_int state;
6246
6247 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
6248
6249 state = SADB_SASTATE_LARVAL;
6250
6251 /* search SAD with sequence number ? */
6252 LIST_FOREACH(sav, &sah->savtree[state], chain) {
6253
6254 KEY_CHKSASTATE(state, sav->state, "key_getsabyseq");
6255
6256 if (sav->seq == seq) {
6257 sav->refcnt++;
6258 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
6259 printf("DP key_getsavbyseq cause "
6260 "refcnt++:%d SA:%p\n",
6261 sav->refcnt, sav));
6262 return sav;
6263 }
6264 }
6265
6266 return NULL;
6267 }
6268 #endif
6269
6270 /*
6271 * SADB_ADD processing
6272 * add a entry to SA database, when received
6273 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
6274 * key(AE), (identity(SD),) (sensitivity)>
6275 * from the ikmpd,
6276 * and send
6277 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
6278 * (identity(SD),) (sensitivity)>
6279 * to the ikmpd.
6280 *
6281 * IGNORE identity and sensitivity messages.
6282 *
6283 * m will always be freed.
6284 */
6285 static int
6286 key_add(
6287 struct socket *so,
6288 struct mbuf *m,
6289 const struct sadb_msghdr *mhp)
6290 {
6291 struct sadb_sa *sa0;
6292 struct sadb_address *src0, *dst0;
6293 struct secasindex saidx;
6294 struct secashead *newsah;
6295 struct secasvar *newsav;
6296 u_int16_t proto;
6297 u_int8_t mode;
6298 u_int32_t reqid;
6299 int error;
6300
6301 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
6302
6303 /* sanity check */
6304 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6305 panic("key_add: NULL pointer is passed.\n");
6306
6307 /* map satype to proto */
6308 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6309 ipseclog((LOG_DEBUG, "key_add: invalid satype is passed.\n"));
6310 return key_senderror(so, m, EINVAL);
6311 }
6312
6313 if (mhp->ext[SADB_EXT_SA] == NULL ||
6314 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6315 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6316 (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
6317 mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
6318 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
6319 mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
6320 (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
6321 mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
6322 (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
6323 mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
6324 ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
6325 return key_senderror(so, m, EINVAL);
6326 }
6327 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
6328 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6329 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
6330 /* XXX need more */
6331 ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
6332 return key_senderror(so, m, EINVAL);
6333 }
6334 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
6335 mode = ((struct sadb_x_sa2 *)
6336 (void *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
6337 reqid = ((struct sadb_x_sa2 *)
6338 (void *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
6339 } else {
6340 mode = IPSEC_MODE_ANY;
6341 reqid = 0;
6342 }
6343
6344 sa0 = (struct sadb_sa *)(void *)mhp->ext[SADB_EXT_SA];
6345 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6346 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6347
6348 /* XXX boundary check against sa_len */
6349 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
6350
6351 lck_mtx_lock(sadb_mutex);
6352
6353 /* get a SA header */
6354 if ((newsah = key_getsah(&saidx)) == NULL) {
6355 /* create a new SA header: key_addspi is always used for outbound spi */
6356 if ((newsah = key_newsah(&saidx, IPSEC_DIR_OUTBOUND)) == NULL) {
6357 lck_mtx_unlock(sadb_mutex);
6358 ipseclog((LOG_DEBUG, "key_add: No more memory.\n"));
6359 return key_senderror(so, m, ENOBUFS);
6360 }
6361 }
6362
6363 /* set spidx if there */
6364 /* XXX rewrite */
6365 error = key_setident(newsah, m, mhp);
6366 if (error) {
6367 lck_mtx_unlock(sadb_mutex);
6368 return key_senderror(so, m, error);
6369 }
6370
6371 /* create new SA entry. */
6372 /* We can create new SA only if SPI is different. */
6373 if (key_getsavbyspi(newsah, sa0->sadb_sa_spi)) {
6374 lck_mtx_unlock(sadb_mutex);
6375 ipseclog((LOG_DEBUG, "key_add: SA already exists.\n"));
6376 return key_senderror(so, m, EEXIST);
6377 }
6378 newsav = key_newsav(m, mhp, newsah, &error);
6379 if (newsav == NULL) {
6380 lck_mtx_unlock(sadb_mutex);
6381 return key_senderror(so, m, error);
6382 }
6383
6384 /*
6385 * Verify if SADB_X_EXT_NATT_MULTIPLEUSERS flag is set that
6386 * this SA is for transport mode - otherwise clear it.
6387 */
6388 if ((newsav->flags & SADB_X_EXT_NATT_MULTIPLEUSERS) != 0 &&
6389 (newsah->saidx.mode != IPSEC_MODE_TRANSPORT ||
6390 newsah->saidx.dst.ss_family != AF_INET))
6391 newsav->flags &= ~SADB_X_EXT_NATT_MULTIPLEUSERS;
6392
6393 /* check SA values to be mature. */
6394 if ((error = key_mature(newsav)) != 0) {
6395 key_freesav(newsav, KEY_SADB_LOCKED);
6396 lck_mtx_unlock(sadb_mutex);
6397 return key_senderror(so, m, error);
6398 }
6399
6400 lck_mtx_unlock(sadb_mutex);
6401
6402 /*
6403 * don't call key_freesav() here, as we would like to keep the SA
6404 * in the database on success.
6405 */
6406
6407 {
6408 struct mbuf *n;
6409
6410 /* set msg buf from mhp */
6411 n = key_getmsgbuf_x1(m, mhp);
6412 if (n == NULL) {
6413 ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
6414 return key_senderror(so, m, ENOBUFS);
6415 }
6416
6417 m_freem(m);
6418 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
6419 }
6420 }
6421
6422 /* m is retained */
6423 static int
6424 key_setident(
6425 struct secashead *sah,
6426 struct mbuf *m,
6427 const struct sadb_msghdr *mhp)
6428 {
6429 const struct sadb_ident *idsrc, *iddst;
6430 int idsrclen, iddstlen;
6431
6432 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
6433
6434 /* sanity check */
6435 if (sah == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6436 panic("key_setident: NULL pointer is passed.\n");
6437
6438 /* don't make buffer if not there */
6439 if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
6440 mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
6441 sah->idents = NULL;
6442 sah->identd = NULL;
6443 return 0;
6444 }
6445
6446 if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
6447 mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
6448 ipseclog((LOG_DEBUG, "key_setident: invalid identity.\n"));
6449 return EINVAL;
6450 }
6451
6452 idsrc = (const struct sadb_ident *)
6453 (void *)mhp->ext[SADB_EXT_IDENTITY_SRC];
6454 iddst = (const struct sadb_ident *)
6455 (void *)mhp->ext[SADB_EXT_IDENTITY_DST];
6456 idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
6457 iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
6458
6459 /* validity check */
6460 if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
6461 ipseclog((LOG_DEBUG, "key_setident: ident type mismatch.\n"));
6462 return EINVAL;
6463 }
6464
6465 switch (idsrc->sadb_ident_type) {
6466 case SADB_IDENTTYPE_PREFIX:
6467 case SADB_IDENTTYPE_FQDN:
6468 case SADB_IDENTTYPE_USERFQDN:
6469 default:
6470 /* XXX do nothing */
6471 sah->idents = NULL;
6472 sah->identd = NULL;
6473 return 0;
6474 }
6475
6476 /* make structure */
6477 KMALLOC_NOWAIT(sah->idents, struct sadb_ident *, idsrclen);
6478 if (sah->idents == NULL) {
6479 lck_mtx_unlock(sadb_mutex);
6480 KMALLOC_WAIT(sah->idents, struct sadb_ident *, idsrclen);
6481 lck_mtx_lock(sadb_mutex);
6482 if (sah->idents == NULL) {
6483 ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
6484 return ENOBUFS;
6485 }
6486 }
6487 KMALLOC_NOWAIT(sah->identd, struct sadb_ident *, iddstlen);
6488 if (sah->identd == NULL) {
6489 lck_mtx_unlock(sadb_mutex);
6490 KMALLOC_WAIT(sah->identd, struct sadb_ident *, iddstlen);
6491 lck_mtx_lock(sadb_mutex);
6492 if (sah->identd == NULL) {
6493 KFREE(sah->idents);
6494 sah->idents = NULL;
6495 ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
6496 return ENOBUFS;
6497 }
6498 }
6499 bcopy(idsrc, sah->idents, idsrclen);
6500 bcopy(iddst, sah->identd, iddstlen);
6501
6502 return 0;
6503 }
6504
6505 /*
6506 * m will not be freed on return.
6507 * it is caller's responsibility to free the result.
6508 */
6509 static struct mbuf *
6510 key_getmsgbuf_x1(
6511 struct mbuf *m,
6512 const struct sadb_msghdr *mhp)
6513 {
6514 struct mbuf *n;
6515 int mbufItems[] = {SADB_EXT_RESERVED, SADB_EXT_SA,
6516 SADB_X_EXT_SA2, SADB_EXT_ADDRESS_SRC,
6517 SADB_EXT_ADDRESS_DST, SADB_EXT_LIFETIME_HARD,
6518 SADB_EXT_LIFETIME_SOFT, SADB_EXT_IDENTITY_SRC,
6519 SADB_EXT_IDENTITY_DST};
6520
6521 /* sanity check */
6522 if (m == NULL || mhp == NULL || mhp->msg == NULL)
6523 panic("key_getmsgbuf_x1: NULL pointer is passed.\n");
6524
6525 /* create new sadb_msg to reply. */
6526 n = key_gather_mbuf(m, mhp, 1, sizeof(mbufItems)/sizeof(int), mbufItems);
6527 if (!n)
6528 return NULL;
6529
6530 if (n->m_len < sizeof(struct sadb_msg)) {
6531 n = m_pullup(n, sizeof(struct sadb_msg));
6532 if (n == NULL)
6533 return NULL;
6534 }
6535 mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
6536 mtod(n, struct sadb_msg *)->sadb_msg_len =
6537 PFKEY_UNIT64(n->m_pkthdr.len);
6538
6539 return n;
6540 }
6541
6542 static int key_delete_all(struct socket *, struct mbuf *,
6543 const struct sadb_msghdr *, u_int16_t);
6544
6545 /*
6546 * SADB_DELETE processing
6547 * receive
6548 * <base, SA(*), address(SD)>
6549 * from the ikmpd, and set SADB_SASTATE_DEAD,
6550 * and send,
6551 * <base, SA(*), address(SD)>
6552 * to the ikmpd.
6553 *
6554 * m will always be freed.
6555 */
6556 static int
6557 key_delete(
6558 struct socket *so,
6559 struct mbuf *m,
6560 const struct sadb_msghdr *mhp)
6561 {
6562 struct sadb_sa *sa0;
6563 struct sadb_address *src0, *dst0;
6564 struct secasindex saidx;
6565 struct secashead *sah;
6566 struct secasvar *sav = NULL;
6567 u_int16_t proto;
6568
6569 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
6570
6571 /* sanity check */
6572 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6573 panic("key_delete: NULL pointer is passed.\n");
6574
6575 /* map satype to proto */
6576 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6577 ipseclog((LOG_DEBUG, "key_delete: invalid satype is passed.\n"));
6578 return key_senderror(so, m, EINVAL);
6579 }
6580
6581 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6582 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
6583 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
6584 return key_senderror(so, m, EINVAL);
6585 }
6586
6587 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6588 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
6589 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
6590 return key_senderror(so, m, EINVAL);
6591 }
6592
6593 lck_mtx_lock(sadb_mutex);
6594
6595 if (mhp->ext[SADB_EXT_SA] == NULL) {
6596 /*
6597 * Caller wants us to delete all non-LARVAL SAs
6598 * that match the src/dst. This is used during
6599 * IKE INITIAL-CONTACT.
6600 */
6601 ipseclog((LOG_DEBUG, "key_delete: doing delete all.\n"));
6602 /* key_delete_all will unlock sadb_mutex */
6603 return key_delete_all(so, m, mhp, proto);
6604 } else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
6605 lck_mtx_unlock(sadb_mutex);
6606 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
6607 return key_senderror(so, m, EINVAL);
6608 }
6609
6610 sa0 = (struct sadb_sa *)(void *)mhp->ext[SADB_EXT_SA];
6611 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
6612 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
6613
6614 /* XXX boundary check against sa_len */
6615 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6616
6617 /* get a SA header */
6618 LIST_FOREACH(sah, &sahtree, chain) {
6619 if (sah->state == SADB_SASTATE_DEAD)
6620 continue;
6621 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
6622 continue;
6623
6624 /* get a SA with SPI. */
6625 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
6626 if (sav)
6627 break;
6628 }
6629 if (sah == NULL) {
6630 lck_mtx_unlock(sadb_mutex);
6631 ipseclog((LOG_DEBUG, "key_delete: no SA found.\n"));
6632 return key_senderror(so, m, ENOENT);
6633 }
6634
6635 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
6636 key_freesav(sav, KEY_SADB_LOCKED);
6637
6638 lck_mtx_unlock(sadb_mutex);
6639 sav = NULL;
6640
6641 {
6642 struct mbuf *n;
6643 struct sadb_msg *newmsg;
6644 int mbufItems[] = {SADB_EXT_RESERVED, SADB_EXT_SA,
6645 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST};
6646
6647 /* create new sadb_msg to reply. */
6648 n = key_gather_mbuf(m, mhp, 1, sizeof(mbufItems)/sizeof(int), mbufItems);
6649 if (!n)
6650 return key_senderror(so, m, ENOBUFS);
6651
6652 if (n->m_len < sizeof(struct sadb_msg)) {
6653 n = m_pullup(n, sizeof(struct sadb_msg));
6654 if (n == NULL)
6655 return key_senderror(so, m, ENOBUFS);
6656 }
6657 newmsg = mtod(n, struct sadb_msg *);
6658 newmsg->sadb_msg_errno = 0;
6659 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
6660
6661 m_freem(m);
6662 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
6663 }
6664 }
6665
6666 /*
6667 * delete all SAs for src/dst. Called from key_delete().
6668 */
6669 static int
6670 key_delete_all(
6671 struct socket *so,
6672 struct mbuf *m,
6673 const struct sadb_msghdr *mhp,
6674 u_int16_t proto)
6675 {
6676 struct sadb_address *src0, *dst0;
6677 struct secasindex saidx;
6678 struct secashead *sah;
6679 struct secasvar *sav, *nextsav;
6680 u_int stateidx, state;
6681
6682 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
6683
6684 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
6685 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
6686
6687 /* XXX boundary check against sa_len */
6688 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6689
6690 LIST_FOREACH(sah, &sahtree, chain) {
6691 if (sah->state == SADB_SASTATE_DEAD)
6692 continue;
6693 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
6694 continue;
6695
6696 /* Delete all non-LARVAL SAs. */
6697 for (stateidx = 0;
6698 stateidx < _ARRAYLEN(saorder_state_alive);
6699 stateidx++) {
6700 state = saorder_state_alive[stateidx];
6701 if (state == SADB_SASTATE_LARVAL)
6702 continue;
6703 for (sav = LIST_FIRST(&sah->savtree[state]);
6704 sav != NULL; sav = nextsav) {
6705 nextsav = LIST_NEXT(sav, chain);
6706 /* sanity check */
6707 if (sav->state != state) {
6708 ipseclog((LOG_DEBUG, "key_delete_all: "
6709 "invalid sav->state "
6710 "(queue: %d SA: %d)\n",
6711 state, sav->state));
6712 continue;
6713 }
6714
6715 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
6716 key_freesav(sav, KEY_SADB_LOCKED);
6717 }
6718 }
6719 }
6720 lck_mtx_unlock(sadb_mutex);
6721
6722 {
6723 struct mbuf *n;
6724 struct sadb_msg *newmsg;
6725 int mbufItems[] = {SADB_EXT_RESERVED, SADB_EXT_ADDRESS_SRC,
6726 SADB_EXT_ADDRESS_DST};
6727
6728 /* create new sadb_msg to reply. */
6729 n = key_gather_mbuf(m, mhp, 1, sizeof(mbufItems)/sizeof(int), mbufItems);
6730 if (!n)
6731 return key_senderror(so, m, ENOBUFS);
6732
6733 if (n->m_len < sizeof(struct sadb_msg)) {
6734 n = m_pullup(n, sizeof(struct sadb_msg));
6735 if (n == NULL)
6736 return key_senderror(so, m, ENOBUFS);
6737 }
6738 newmsg = mtod(n, struct sadb_msg *);
6739 newmsg->sadb_msg_errno = 0;
6740 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
6741
6742 m_freem(m);
6743 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
6744 }
6745 }
6746
6747 /*
6748 * SADB_GET processing
6749 * receive
6750 * <base, SA(*), address(SD)>
6751 * from the ikmpd, and get a SP and a SA to respond,
6752 * and send,
6753 * <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
6754 * (identity(SD),) (sensitivity)>
6755 * to the ikmpd.
6756 *
6757 * m will always be freed.
6758 */
6759 static int
6760 key_get(
6761 struct socket *so,
6762 struct mbuf *m,
6763 const struct sadb_msghdr *mhp)
6764 {
6765 struct sadb_sa *sa0;
6766 struct sadb_address *src0, *dst0;
6767 struct secasindex saidx;
6768 struct secashead *sah;
6769 struct secasvar *sav = NULL;
6770 u_int16_t proto;
6771
6772 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
6773
6774 /* sanity check */
6775 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6776 panic("key_get: NULL pointer is passed.\n");
6777
6778 /* map satype to proto */
6779 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6780 ipseclog((LOG_DEBUG, "key_get: invalid satype is passed.\n"));
6781 return key_senderror(so, m, EINVAL);
6782 }
6783
6784 if (mhp->ext[SADB_EXT_SA] == NULL ||
6785 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6786 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
6787 ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
6788 return key_senderror(so, m, EINVAL);
6789 }
6790 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
6791 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6792 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
6793 ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
6794 return key_senderror(so, m, EINVAL);
6795 }
6796
6797 sa0 = (struct sadb_sa *)(void *)mhp->ext[SADB_EXT_SA];
6798 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6799 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6800
6801 /* XXX boundary check against sa_len */
6802 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6803
6804 lck_mtx_lock(sadb_mutex);
6805
6806 /* get a SA header */
6807 LIST_FOREACH(sah, &sahtree, chain) {
6808 if (sah->state == SADB_SASTATE_DEAD)
6809 continue;
6810 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
6811 continue;
6812
6813 /* get a SA with SPI. */
6814 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
6815 if (sav)
6816 break;
6817 }
6818 if (sah == NULL) {
6819 lck_mtx_unlock(sadb_mutex);
6820 ipseclog((LOG_DEBUG, "key_get: no SA found.\n"));
6821 return key_senderror(so, m, ENOENT);
6822 }
6823
6824 {
6825 struct mbuf *n;
6826 u_int8_t satype;
6827
6828 /* map proto to satype */
6829 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
6830 lck_mtx_unlock(sadb_mutex);
6831 ipseclog((LOG_DEBUG, "key_get: there was invalid proto in SAD.\n"));
6832 return key_senderror(so, m, EINVAL);
6833 }
6834 lck_mtx_unlock(sadb_mutex);
6835
6836 /* create new sadb_msg to reply. */
6837 n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
6838 mhp->msg->sadb_msg_pid);
6839
6840
6841
6842 if (!n)
6843 return key_senderror(so, m, ENOBUFS);
6844
6845 m_freem(m);
6846 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
6847 }
6848 }
6849
6850 /*
6851 * get SA stats by spi.
6852 * OUT: -1 : not found
6853 * 0 : found, arg pointer to a SA stats is updated.
6854 */
6855 static int
6856 key_getsastatbyspi_one (u_int32_t spi,
6857 struct sastat *stat)
6858 {
6859 struct secashead *sah;
6860 struct secasvar *sav = NULL;
6861
6862 if ((void *)stat == NULL) {
6863 return -1;
6864 }
6865
6866 lck_mtx_lock(sadb_mutex);
6867
6868 /* get a SA header */
6869 LIST_FOREACH(sah, &sahtree, chain) {
6870 if (sah->state == SADB_SASTATE_DEAD)
6871 continue;
6872
6873 /* get a SA with SPI. */
6874 sav = key_getsavbyspi(sah, spi);
6875 if (sav) {
6876 stat->spi = sav->spi;
6877 stat->created = sav->created;
6878 if (sav->lft_c) {
6879 bcopy(sav->lft_c,&stat->lft_c, sizeof(stat->lft_c));
6880 } else {
6881 bzero(&stat->lft_c, sizeof(stat->lft_c));
6882 }
6883 lck_mtx_unlock(sadb_mutex);
6884 return 0;
6885 }
6886 }
6887
6888 lck_mtx_unlock(sadb_mutex);
6889
6890 return -1;
6891 }
6892
6893 /*
6894 * get SA stats collection by indices.
6895 * OUT: -1 : not found
6896 * 0 : found, arg pointers to a SA stats and 'maximum stats' are updated.
6897 */
6898 static int
6899 key_getsastatbyspi (struct sastat *stat_arg,
6900 u_int32_t max_stat_arg,
6901 struct sastat *stat_res,
6902 u_int32_t *max_stat_res)
6903 {
6904 int cur, found = 0;
6905
6906 if (stat_arg == NULL ||
6907 stat_res == NULL ||
6908 max_stat_res == NULL) {
6909 return -1;
6910 }
6911
6912 for (cur = 0; cur < max_stat_arg; cur++) {
6913 if (key_getsastatbyspi_one(stat_arg[cur].spi,
6914 &stat_res[found]) == 0) {
6915 found++;
6916 }
6917 }
6918 *max_stat_res = found;
6919
6920 if (found) {
6921 return 0;
6922 }
6923 return -1;
6924 }
6925
6926 /* XXX make it sysctl-configurable? */
6927 static void
6928 key_getcomb_setlifetime(
6929 struct sadb_comb *comb)
6930 {
6931
6932 comb->sadb_comb_soft_allocations = 1;
6933 comb->sadb_comb_hard_allocations = 1;
6934 comb->sadb_comb_soft_bytes = 0;
6935 comb->sadb_comb_hard_bytes = 0;
6936 comb->sadb_comb_hard_addtime = 86400; /* 1 day */
6937 comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
6938 comb->sadb_comb_soft_usetime = 28800; /* 8 hours */
6939 comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
6940 }
6941
6942 #if IPSEC_ESP
6943 /*
6944 * XXX reorder combinations by preference
6945 * XXX no idea if the user wants ESP authentication or not
6946 */
6947 static struct mbuf *
6948 key_getcomb_esp(void)
6949 {
6950 struct sadb_comb *comb;
6951 const struct esp_algorithm *algo;
6952 struct mbuf *result = NULL, *m, *n;
6953 int encmin;
6954 int i, off, o;
6955 int totlen;
6956 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
6957
6958 m = NULL;
6959 for (i = 1; i <= SADB_EALG_MAX; i++) {
6960 algo = esp_algorithm_lookup(i);
6961 if (!algo)
6962 continue;
6963
6964 if (algo->keymax < ipsec_esp_keymin)
6965 continue;
6966 if (algo->keymin < ipsec_esp_keymin)
6967 encmin = ipsec_esp_keymin;
6968 else
6969 encmin = algo->keymin;
6970
6971 if (ipsec_esp_auth)
6972 m = key_getcomb_ah();
6973 else {
6974 #if DIAGNOSTIC
6975 if (l > MLEN)
6976 panic("assumption failed in key_getcomb_esp");
6977 #endif
6978 MGET(m, M_WAITOK, MT_DATA);
6979 if (m) {
6980 M_ALIGN(m, l);
6981 m->m_len = l;
6982 m->m_next = NULL;
6983 bzero(mtod(m, caddr_t), m->m_len);
6984 }
6985 }
6986 if (!m)
6987 goto fail;
6988
6989 totlen = 0;
6990 for (n = m; n; n = n->m_next)
6991 totlen += n->m_len;
6992 #if DIAGNOSTIC
6993 if (totlen % l)
6994 panic("assumption failed in key_getcomb_esp");
6995 #endif
6996
6997 for (off = 0; off < totlen; off += l) {
6998 n = m_pulldown(m, off, l, &o);
6999 if (!n) {
7000 /* m is already freed */
7001 goto fail;
7002 }
7003 comb = (struct sadb_comb *)
7004 (void *)(mtod(n, caddr_t) + o);
7005 bzero(comb, sizeof(*comb));
7006 key_getcomb_setlifetime(comb);
7007 comb->sadb_comb_encrypt = i;
7008 comb->sadb_comb_encrypt_minbits = encmin;
7009 comb->sadb_comb_encrypt_maxbits = algo->keymax;
7010 }
7011
7012 if (!result)
7013 result = m;
7014 else
7015 m_cat(result, m);
7016 }
7017
7018 return result;
7019
7020 fail:
7021 if (result)
7022 m_freem(result);
7023 return NULL;
7024 }
7025 #endif
7026
7027 /*
7028 * XXX reorder combinations by preference
7029 */
7030 static struct mbuf *
7031 key_getcomb_ah(void)
7032 {
7033 struct sadb_comb *comb;
7034 const struct ah_algorithm *algo;
7035 struct mbuf *m;
7036 int keymin;
7037 int i;
7038 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
7039
7040 m = NULL;
7041 for (i = 1; i <= SADB_AALG_MAX; i++) {
7042 #if 1
7043 /* we prefer HMAC algorithms, not old algorithms */
7044 if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
7045 continue;
7046 #endif
7047 algo = ah_algorithm_lookup(i);
7048 if (!algo)
7049 continue;
7050
7051 if (algo->keymax < ipsec_ah_keymin)
7052 continue;
7053 if (algo->keymin < ipsec_ah_keymin)
7054 keymin = ipsec_ah_keymin;
7055 else
7056 keymin = algo->keymin;
7057
7058 if (!m) {
7059 #if DIAGNOSTIC
7060 if (l > MLEN)
7061 panic("assumption failed in key_getcomb_ah");
7062 #endif
7063 MGET(m, M_WAITOK, MT_DATA);
7064 if (m) {
7065 M_ALIGN(m, l);
7066 m->m_len = l;
7067 m->m_next = NULL;
7068 }
7069 } else
7070 M_PREPEND(m, l, M_WAITOK);
7071 if (!m)
7072 return NULL;
7073
7074 comb = mtod(m, struct sadb_comb *);
7075 bzero(comb, sizeof(*comb));
7076 key_getcomb_setlifetime(comb);
7077 comb->sadb_comb_auth = i;
7078 comb->sadb_comb_auth_minbits = keymin;
7079 comb->sadb_comb_auth_maxbits = algo->keymax;
7080 }
7081
7082 return m;
7083 }
7084
7085 /*
7086 * not really an official behavior. discussed in pf_key@inner.net in Sep2000.
7087 * XXX reorder combinations by preference
7088 */
7089 static struct mbuf *
7090 key_getcomb_ipcomp(void)
7091 {
7092 struct sadb_comb *comb;
7093 const struct ipcomp_algorithm *algo;
7094 struct mbuf *m;
7095 int i;
7096 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
7097
7098 m = NULL;
7099 for (i = 1; i <= SADB_X_CALG_MAX; i++) {
7100 algo = ipcomp_algorithm_lookup(i);
7101 if (!algo)
7102 continue;
7103
7104 if (!m) {
7105 #if DIAGNOSTIC
7106 if (l > MLEN)
7107 panic("assumption failed in key_getcomb_ipcomp");
7108 #endif
7109 MGET(m, M_WAITOK, MT_DATA);
7110 if (m) {
7111 M_ALIGN(m, l);
7112 m->m_len = l;
7113 m->m_next = NULL;
7114 }
7115 } else
7116 M_PREPEND(m, l, M_WAITOK);
7117 if (!m)
7118 return NULL;
7119
7120 comb = mtod(m, struct sadb_comb *);
7121 bzero(comb, sizeof(*comb));
7122 key_getcomb_setlifetime(comb);
7123 comb->sadb_comb_encrypt = i;
7124 /* what should we set into sadb_comb_*_{min,max}bits? */
7125 }
7126
7127 return m;
7128 }
7129
7130 /*
7131 * XXX no way to pass mode (transport/tunnel) to userland
7132 * XXX replay checking?
7133 * XXX sysctl interface to ipsec_{ah,esp}_keymin
7134 */
7135 static struct mbuf *
7136 key_getprop(
7137 const struct secasindex *saidx)
7138 {
7139 struct sadb_prop *prop;
7140 struct mbuf *m, *n;
7141 const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
7142 int totlen;
7143
7144 switch (saidx->proto) {
7145 #if IPSEC_ESP
7146 case IPPROTO_ESP:
7147 m = key_getcomb_esp();
7148 break;
7149 #endif
7150 case IPPROTO_AH:
7151 m = key_getcomb_ah();
7152 break;
7153 case IPPROTO_IPCOMP:
7154 m = key_getcomb_ipcomp();
7155 break;
7156 default:
7157 return NULL;
7158 }
7159
7160 if (!m)
7161 return NULL;
7162 M_PREPEND(m, l, M_WAITOK);
7163 if (!m)
7164 return NULL;
7165
7166 totlen = 0;
7167 for (n = m; n; n = n->m_next)
7168 totlen += n->m_len;
7169
7170 prop = mtod(m, struct sadb_prop *);
7171 bzero(prop, sizeof(*prop));
7172 prop->sadb_prop_len = PFKEY_UNIT64(totlen);
7173 prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
7174 prop->sadb_prop_replay = 32; /* XXX */
7175
7176 return m;
7177 }
7178
7179 /*
7180 * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
7181 * send
7182 * <base, SA, address(SD), (address(P)), x_policy,
7183 * (identity(SD),) (sensitivity,) proposal>
7184 * to KMD, and expect to receive
7185 * <base> with SADB_ACQUIRE if error occurred,
7186 * or
7187 * <base, src address, dst address, (SPI range)> with SADB_GETSPI
7188 * from KMD by PF_KEY.
7189 *
7190 * XXX x_policy is outside of RFC2367 (KAME extension).
7191 * XXX sensitivity is not supported.
7192 * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
7193 * see comment for key_getcomb_ipcomp().
7194 *
7195 * OUT:
7196 * 0 : succeed
7197 * others: error number
7198 */
7199 static int
7200 key_acquire(
7201 struct secasindex *saidx,
7202 struct secpolicy *sp)
7203 {
7204 struct mbuf *result = NULL, *m;
7205 #ifndef IPSEC_NONBLOCK_ACQUIRE
7206 struct secacq *newacq;
7207 #endif
7208 u_int8_t satype;
7209 int error = -1;
7210 u_int32_t seq;
7211
7212 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
7213
7214 /* sanity check */
7215 if (saidx == NULL)
7216 panic("key_acquire: NULL pointer is passed.\n");
7217 if ((satype = key_proto2satype(saidx->proto)) == 0)
7218 panic("key_acquire: invalid proto is passed.\n");
7219
7220 #ifndef IPSEC_NONBLOCK_ACQUIRE
7221 /*
7222 * We never do anything about acquirng SA. There is anather
7223 * solution that kernel blocks to send SADB_ACQUIRE message until
7224 * getting something message from IKEd. In later case, to be
7225 * managed with ACQUIRING list.
7226 */
7227 /* get a entry to check whether sending message or not. */
7228 lck_mtx_lock(sadb_mutex);
7229 if ((newacq = key_getacq(saidx)) != NULL) {
7230 if (key_blockacq_count < newacq->count) {
7231 /* reset counter and do send message. */
7232 newacq->count = 0;
7233 } else {
7234 /* increment counter and do nothing. */
7235 newacq->count++;
7236 lck_mtx_unlock(sadb_mutex);
7237 return 0;
7238 }
7239 } else {
7240 /* make new entry for blocking to send SADB_ACQUIRE. */
7241 if ((newacq = key_newacq(saidx)) == NULL) {
7242 lck_mtx_unlock(sadb_mutex);
7243 return ENOBUFS;
7244 }
7245
7246 /* add to acqtree */
7247 LIST_INSERT_HEAD(&acqtree, newacq, chain);
7248 }
7249 seq = newacq->seq;
7250 lck_mtx_unlock(sadb_mutex);
7251
7252 #else
7253 seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
7254 #endif
7255 m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
7256 if (!m) {
7257 error = ENOBUFS;
7258 goto fail;
7259 }
7260 result = m;
7261
7262 /* set sadb_address for saidx's. */
7263 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
7264 (struct sockaddr *)&saidx->src, FULLMASK, IPSEC_ULPROTO_ANY);
7265 if (!m) {
7266 error = ENOBUFS;
7267 goto fail;
7268 }
7269 m_cat(result, m);
7270
7271 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
7272 (struct sockaddr *)&saidx->dst, FULLMASK, IPSEC_ULPROTO_ANY);
7273 if (!m) {
7274 error = ENOBUFS;
7275 goto fail;
7276 }
7277 m_cat(result, m);
7278
7279 /* XXX proxy address (optional) */
7280
7281 /* set sadb_x_policy */
7282 if (sp) {
7283 m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
7284 if (!m) {
7285 error = ENOBUFS;
7286 goto fail;
7287 }
7288 m_cat(result, m);
7289 }
7290
7291 /* XXX identity (optional) */
7292 #if 0
7293 if (idexttype && fqdn) {
7294 /* create identity extension (FQDN) */
7295 struct sadb_ident *id;
7296 int fqdnlen;
7297
7298 fqdnlen = strlen(fqdn) + 1; /* +1 for terminating-NUL */
7299 id = (struct sadb_ident *)p;
7300 bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
7301 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
7302 id->sadb_ident_exttype = idexttype;
7303 id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
7304 bcopy(fqdn, id + 1, fqdnlen);
7305 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
7306 }
7307
7308 if (idexttype) {
7309 /* create identity extension (USERFQDN) */
7310 struct sadb_ident *id;
7311 int userfqdnlen;
7312
7313 if (userfqdn) {
7314 /* +1 for terminating-NUL */
7315 userfqdnlen = strlen(userfqdn) + 1;
7316 } else
7317 userfqdnlen = 0;
7318 id = (struct sadb_ident *)p;
7319 bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
7320 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
7321 id->sadb_ident_exttype = idexttype;
7322 id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
7323 /* XXX is it correct? */
7324 if (curproc && curproc->p_cred)
7325 id->sadb_ident_id = curproc->p_cred->p_ruid;
7326 if (userfqdn && userfqdnlen)
7327 bcopy(userfqdn, id + 1, userfqdnlen);
7328 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
7329 }
7330 #endif
7331
7332 /* XXX sensitivity (optional) */
7333
7334 /* create proposal/combination extension */
7335 m = key_getprop(saidx);
7336 #if 0
7337 /*
7338 * spec conformant: always attach proposal/combination extension,
7339 * the problem is that we have no way to attach it for ipcomp,
7340 * due to the way sadb_comb is declared in RFC2367.
7341 */
7342 if (!m) {
7343 error = ENOBUFS;
7344 goto fail;
7345 }
7346 m_cat(result, m);
7347 #else
7348 /*
7349 * outside of spec; make proposal/combination extension optional.
7350 */
7351 if (m)
7352 m_cat(result, m);
7353 #endif
7354
7355 if ((result->m_flags & M_PKTHDR) == 0) {
7356 error = EINVAL;
7357 goto fail;
7358 }
7359
7360 if (result->m_len < sizeof(struct sadb_msg)) {
7361 result = m_pullup(result, sizeof(struct sadb_msg));
7362 if (result == NULL) {
7363 error = ENOBUFS;
7364 goto fail;
7365 }
7366 }
7367
7368 result->m_pkthdr.len = 0;
7369 for (m = result; m; m = m->m_next)
7370 result->m_pkthdr.len += m->m_len;
7371
7372 mtod(result, struct sadb_msg *)->sadb_msg_len =
7373 PFKEY_UNIT64(result->m_pkthdr.len);
7374
7375 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
7376
7377 fail:
7378 if (result)
7379 m_freem(result);
7380 return error;
7381 }
7382
7383 #ifndef IPSEC_NONBLOCK_ACQUIRE
7384 static struct secacq *
7385 key_newacq(
7386 struct secasindex *saidx)
7387 {
7388 struct secacq *newacq;
7389 struct timeval tv;
7390
7391 /* get new entry */
7392 KMALLOC_NOWAIT(newacq, struct secacq *, sizeof(struct secacq));
7393 if (newacq == NULL) {
7394 lck_mtx_unlock(sadb_mutex);
7395 KMALLOC_WAIT(newacq, struct secacq *, sizeof(struct secacq));
7396 lck_mtx_lock(sadb_mutex);
7397 if (newacq == NULL) {
7398 ipseclog((LOG_DEBUG, "key_newacq: No more memory.\n"));
7399 return NULL;
7400 }
7401 }
7402 bzero(newacq, sizeof(*newacq));
7403
7404 /* copy secindex */
7405 bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
7406 newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
7407 microtime(&tv);
7408 newacq->created = tv.tv_sec;
7409 newacq->count = 0;
7410
7411 return newacq;
7412 }
7413
7414 static struct secacq *
7415 key_getacq(
7416 struct secasindex *saidx)
7417 {
7418 struct secacq *acq;
7419
7420 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
7421
7422 LIST_FOREACH(acq, &acqtree, chain) {
7423 if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
7424 return acq;
7425 }
7426
7427 return NULL;
7428 }
7429
7430 static struct secacq *
7431 key_getacqbyseq(
7432 u_int32_t seq)
7433 {
7434 struct secacq *acq;
7435
7436 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
7437
7438 LIST_FOREACH(acq, &acqtree, chain) {
7439 if (acq->seq == seq)
7440 return acq;
7441 }
7442
7443 return NULL;
7444 }
7445 #endif
7446
7447 static struct secspacq *
7448 key_newspacq(
7449 struct secpolicyindex *spidx)
7450 {
7451 struct secspacq *acq;
7452 struct timeval tv;
7453
7454 /* get new entry */
7455 KMALLOC_NOWAIT(acq, struct secspacq *, sizeof(struct secspacq));
7456 if (acq == NULL) {
7457 lck_mtx_unlock(sadb_mutex);
7458 KMALLOC_WAIT(acq, struct secspacq *, sizeof(struct secspacq));
7459 lck_mtx_lock(sadb_mutex);
7460 if (acq == NULL) {
7461 ipseclog((LOG_DEBUG, "key_newspacq: No more memory.\n"));
7462 return NULL;
7463 }
7464 }
7465 bzero(acq, sizeof(*acq));
7466
7467 /* copy secindex */
7468 bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
7469 microtime(&tv);
7470 acq->created = tv.tv_sec;
7471 acq->count = 0;
7472
7473 return acq;
7474 }
7475
7476 static struct secspacq *
7477 key_getspacq(
7478 struct secpolicyindex *spidx)
7479 {
7480 struct secspacq *acq;
7481
7482 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
7483
7484 LIST_FOREACH(acq, &spacqtree, chain) {
7485 if (key_cmpspidx_exactly(spidx, &acq->spidx))
7486 return acq;
7487 }
7488
7489 return NULL;
7490 }
7491
7492 /*
7493 * SADB_ACQUIRE processing,
7494 * in first situation, is receiving
7495 * <base>
7496 * from the ikmpd, and clear sequence of its secasvar entry.
7497 *
7498 * In second situation, is receiving
7499 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
7500 * from a user land process, and return
7501 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
7502 * to the socket.
7503 *
7504 * m will always be freed.
7505 */
7506 static int
7507 key_acquire2(
7508 struct socket *so,
7509 struct mbuf *m,
7510 const struct sadb_msghdr *mhp)
7511 {
7512 const struct sadb_address *src0, *dst0;
7513 struct secasindex saidx;
7514 struct secashead *sah;
7515 u_int16_t proto;
7516 int error;
7517
7518
7519 /* sanity check */
7520 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
7521 panic("key_acquire2: NULL pointer is passed.\n");
7522
7523 /*
7524 * Error message from KMd.
7525 * We assume that if error was occurred in IKEd, the length of PFKEY
7526 * message is equal to the size of sadb_msg structure.
7527 * We do not raise error even if error occurred in this function.
7528 */
7529 lck_mtx_lock(sadb_mutex);
7530
7531 if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
7532 #ifndef IPSEC_NONBLOCK_ACQUIRE
7533 struct secacq *acq;
7534 struct timeval tv;
7535
7536 /* check sequence number */
7537 if (mhp->msg->sadb_msg_seq == 0) {
7538 lck_mtx_unlock(sadb_mutex);
7539 ipseclog((LOG_DEBUG, "key_acquire2: must specify sequence number.\n"));
7540 m_freem(m);
7541 return 0;
7542 }
7543
7544 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
7545 /*
7546 * the specified larval SA is already gone, or we got
7547 * a bogus sequence number. we can silently ignore it.
7548 */
7549 lck_mtx_unlock(sadb_mutex);
7550 m_freem(m);
7551 return 0;
7552 }
7553
7554 /* reset acq counter in order to deletion by timehander. */
7555 microtime(&tv);
7556 acq->created = tv.tv_sec;
7557 acq->count = 0;
7558 #endif
7559 lck_mtx_unlock(sadb_mutex);
7560 m_freem(m);
7561 return 0;
7562 }
7563
7564 /*
7565 * This message is from user land.
7566 */
7567
7568 /* map satype to proto */
7569 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7570 lck_mtx_unlock(sadb_mutex);
7571 ipseclog((LOG_DEBUG, "key_acquire2: invalid satype is passed.\n"));
7572 return key_senderror(so, m, EINVAL);
7573 }
7574
7575 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
7576 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
7577 mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
7578 /* error */
7579 lck_mtx_unlock(sadb_mutex);
7580 ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
7581 return key_senderror(so, m, EINVAL);
7582 }
7583 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
7584 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
7585 mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
7586 /* error */
7587 lck_mtx_unlock(sadb_mutex);
7588 ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
7589 return key_senderror(so, m, EINVAL);
7590 }
7591
7592 src0 = (const struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
7593 dst0 = (const struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
7594
7595 /* XXX boundary check against sa_len */
7596 /* cast warnings */
7597 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
7598
7599 /* get a SA index */
7600 LIST_FOREACH(sah, &sahtree, chain) {
7601 if (sah->state == SADB_SASTATE_DEAD)
7602 continue;
7603 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE | CMP_REQID))
7604 break;
7605 }
7606 if (sah != NULL) {
7607 lck_mtx_unlock(sadb_mutex);
7608 ipseclog((LOG_DEBUG, "key_acquire2: a SA exists already.\n"));
7609 return key_senderror(so, m, EEXIST);
7610 }
7611 lck_mtx_unlock(sadb_mutex);
7612 error = key_acquire(&saidx, NULL);
7613 if (error != 0) {
7614 ipseclog((LOG_DEBUG, "key_acquire2: error %d returned "
7615 "from key_acquire.\n", mhp->msg->sadb_msg_errno));
7616 return key_senderror(so, m, error);
7617 }
7618
7619 return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
7620 }
7621
7622 /*
7623 * SADB_REGISTER processing.
7624 * If SATYPE_UNSPEC has been passed as satype, only return sadb_supported.
7625 * receive
7626 * <base>
7627 * from the ikmpd, and register a socket to send PF_KEY messages,
7628 * and send
7629 * <base, supported>
7630 * to KMD by PF_KEY.
7631 * If socket is detached, must free from regnode.
7632 *
7633 * m will always be freed.
7634 */
7635 static int
7636 key_register(
7637 struct socket *so,
7638 struct mbuf *m,
7639 const struct sadb_msghdr *mhp)
7640 {
7641 struct secreg *reg, *newreg = 0;
7642
7643 /* sanity check */
7644 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
7645 panic("key_register: NULL pointer is passed.\n");
7646
7647 /* check for invalid register message */
7648 if (mhp->msg->sadb_msg_satype >= sizeof(regtree)/sizeof(regtree[0]))
7649 return key_senderror(so, m, EINVAL);
7650
7651 /* When SATYPE_UNSPEC is specified, only return sadb_supported. */
7652 if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
7653 goto setmsg;
7654
7655 /* create regnode */
7656 KMALLOC_WAIT(newreg, struct secreg *, sizeof(*newreg));
7657 if (newreg == NULL) {
7658 ipseclog((LOG_DEBUG, "key_register: No more memory.\n"));
7659 return key_senderror(so, m, ENOBUFS);
7660 }
7661 bzero((caddr_t)newreg, sizeof(*newreg));
7662
7663 lck_mtx_lock(sadb_mutex);
7664 /* check whether existing or not */
7665 LIST_FOREACH(reg, &regtree[mhp->msg->sadb_msg_satype], chain) {
7666 if (reg->so == so) {
7667 lck_mtx_unlock(sadb_mutex);
7668 ipseclog((LOG_DEBUG, "key_register: socket exists already.\n"));
7669 KFREE(newreg);
7670 return key_senderror(so, m, EEXIST);
7671 }
7672 }
7673
7674 socket_lock(so, 1);
7675 newreg->so = so;
7676 ((struct keycb *)sotorawcb(so))->kp_registered++;
7677 socket_unlock(so, 1);
7678
7679 /* add regnode to regtree. */
7680 LIST_INSERT_HEAD(&regtree[mhp->msg->sadb_msg_satype], newreg, chain);
7681 lck_mtx_unlock(sadb_mutex);
7682 setmsg:
7683 {
7684 struct mbuf *n;
7685 struct sadb_msg *newmsg;
7686 struct sadb_supported *sup;
7687 u_int len, alen, elen;
7688 int off;
7689 int i;
7690 struct sadb_alg *alg;
7691
7692 /* create new sadb_msg to reply. */
7693 alen = 0;
7694 for (i = 1; i <= SADB_AALG_MAX; i++) {
7695 if (ah_algorithm_lookup(i))
7696 alen += sizeof(struct sadb_alg);
7697 }
7698 if (alen)
7699 alen += sizeof(struct sadb_supported);
7700 elen = 0;
7701 #if IPSEC_ESP
7702 for (i = 1; i <= SADB_EALG_MAX; i++) {
7703 if (esp_algorithm_lookup(i))
7704 elen += sizeof(struct sadb_alg);
7705 }
7706 if (elen)
7707 elen += sizeof(struct sadb_supported);
7708 #endif
7709
7710 len = sizeof(struct sadb_msg) + alen + elen;
7711
7712 if (len > MCLBYTES)
7713 return key_senderror(so, m, ENOBUFS);
7714
7715 MGETHDR(n, M_WAITOK, MT_DATA);
7716 if (n && len > MHLEN) {
7717 MCLGET(n, M_WAITOK);
7718 if ((n->m_flags & M_EXT) == 0) {
7719 m_freem(n);
7720 n = NULL;
7721 }
7722 }
7723 if (!n)
7724 return key_senderror(so, m, ENOBUFS);
7725
7726 n->m_pkthdr.len = n->m_len = len;
7727 n->m_next = NULL;
7728 off = 0;
7729
7730 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
7731 newmsg = mtod(n, struct sadb_msg *);
7732 newmsg->sadb_msg_errno = 0;
7733 newmsg->sadb_msg_len = PFKEY_UNIT64(len);
7734 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
7735
7736 /* for authentication algorithm */
7737 if (alen) {
7738 sup = (struct sadb_supported *)(void *)(mtod(n, caddr_t) + off);
7739 sup->sadb_supported_len = PFKEY_UNIT64(alen);
7740 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
7741 off += PFKEY_ALIGN8(sizeof(*sup));
7742
7743 for (i = 1; i <= SADB_AALG_MAX; i++) {
7744 const struct ah_algorithm *aalgo;
7745
7746 aalgo = ah_algorithm_lookup(i);
7747 if (!aalgo)
7748 continue;
7749 alg = (struct sadb_alg *)
7750 (void *)(mtod(n, caddr_t) + off);
7751 alg->sadb_alg_id = i;
7752 alg->sadb_alg_ivlen = 0;
7753 alg->sadb_alg_minbits = aalgo->keymin;
7754 alg->sadb_alg_maxbits = aalgo->keymax;
7755 off += PFKEY_ALIGN8(sizeof(*alg));
7756 }
7757 }
7758
7759 #if IPSEC_ESP
7760 /* for encryption algorithm */
7761 if (elen) {
7762 sup = (struct sadb_supported *)(void *)(mtod(n, caddr_t) + off);
7763 sup->sadb_supported_len = PFKEY_UNIT64(elen);
7764 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
7765 off += PFKEY_ALIGN8(sizeof(*sup));
7766
7767 for (i = 1; i <= SADB_EALG_MAX; i++) {
7768 const struct esp_algorithm *ealgo;
7769
7770 ealgo = esp_algorithm_lookup(i);
7771 if (!ealgo)
7772 continue;
7773 alg = (struct sadb_alg *)
7774 (void *)(mtod(n, caddr_t) + off);
7775 alg->sadb_alg_id = i;
7776 if (ealgo && ealgo->ivlen) {
7777 /*
7778 * give NULL to get the value preferred by
7779 * algorithm XXX SADB_X_EXT_DERIV ?
7780 */
7781 alg->sadb_alg_ivlen =
7782 (*ealgo->ivlen)(ealgo, NULL);
7783 } else
7784 alg->sadb_alg_ivlen = 0;
7785 alg->sadb_alg_minbits = ealgo->keymin;
7786 alg->sadb_alg_maxbits = ealgo->keymax;
7787 off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
7788 }
7789 }
7790 #endif
7791
7792 #if DIGAGNOSTIC
7793 if (off != len)
7794 panic("length assumption failed in key_register");
7795 #endif
7796
7797 m_freem(m);
7798 return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
7799 }
7800 }
7801
7802 /*
7803 * free secreg entry registered.
7804 * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
7805 */
7806 void
7807 key_freereg(
7808 struct socket *so)
7809 {
7810 struct secreg *reg;
7811 int i;
7812
7813 /* sanity check */
7814 if (so == NULL)
7815 panic("key_freereg: NULL pointer is passed.\n");
7816
7817 /*
7818 * check whether existing or not.
7819 * check all type of SA, because there is a potential that
7820 * one socket is registered to multiple type of SA.
7821 */
7822 lck_mtx_lock(sadb_mutex);
7823 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7824 LIST_FOREACH(reg, &regtree[i], chain) {
7825 if (reg->so == so
7826 && __LIST_CHAINED(reg)) {
7827 LIST_REMOVE(reg, chain);
7828 KFREE(reg);
7829 break;
7830 }
7831 }
7832 }
7833 lck_mtx_unlock(sadb_mutex);
7834 return;
7835 }
7836
7837 /*
7838 * SADB_EXPIRE processing
7839 * send
7840 * <base, SA, SA2, lifetime(C and one of HS), address(SD)>
7841 * to KMD by PF_KEY.
7842 * NOTE: We send only soft lifetime extension.
7843 *
7844 * OUT: 0 : succeed
7845 * others : error number
7846 */
7847 static int
7848 key_expire(
7849 struct secasvar *sav)
7850 {
7851 int satype;
7852 struct mbuf *result = NULL, *m;
7853 int len;
7854 int error = -1;
7855 struct sadb_lifetime *lt;
7856
7857 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
7858
7859 /* sanity check */
7860 if (sav == NULL)
7861 panic("key_expire: NULL pointer is passed.\n");
7862 if (sav->sah == NULL)
7863 panic("key_expire: Why was SA index in SA NULL.\n");
7864 if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0)
7865 panic("key_expire: invalid proto is passed.\n");
7866
7867 /* set msg header */
7868 m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
7869 if (!m) {
7870 error = ENOBUFS;
7871 goto fail;
7872 }
7873 result = m;
7874
7875 /* create SA extension */
7876 m = key_setsadbsa(sav);
7877 if (!m) {
7878 error = ENOBUFS;
7879 goto fail;
7880 }
7881 m_cat(result, m);
7882
7883 /* create SA extension */
7884 m = key_setsadbxsa2(sav->sah->saidx.mode,
7885 sav->replay ? sav->replay->count : 0,
7886 sav->sah->saidx.reqid);
7887 if (!m) {
7888 error = ENOBUFS;
7889 goto fail;
7890 }
7891 m_cat(result, m);
7892
7893 /* create lifetime extension (current and soft) */
7894 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
7895 m = key_alloc_mbuf(len);
7896 if (!m || m->m_next) { /*XXX*/
7897 if (m)
7898 m_freem(m);
7899 error = ENOBUFS;
7900 goto fail;
7901 }
7902 bzero(mtod(m, caddr_t), len);
7903 lt = mtod(m, struct sadb_lifetime *);
7904 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
7905 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
7906 lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
7907 lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
7908 lt->sadb_lifetime_addtime = sav->lft_c->sadb_lifetime_addtime;
7909 lt->sadb_lifetime_usetime = sav->lft_c->sadb_lifetime_usetime;
7910 lt = (struct sadb_lifetime *)(void *)(mtod(m, caddr_t) + len / 2);
7911 bcopy(sav->lft_s, lt, sizeof(*lt));
7912 m_cat(result, m);
7913
7914 /* set sadb_address for source */
7915 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
7916 (struct sockaddr *)&sav->sah->saidx.src,
7917 FULLMASK, IPSEC_ULPROTO_ANY);
7918 if (!m) {
7919 error = ENOBUFS;
7920 goto fail;
7921 }
7922 m_cat(result, m);
7923
7924 /* set sadb_address for destination */
7925 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
7926 (struct sockaddr *)&sav->sah->saidx.dst,
7927 FULLMASK, IPSEC_ULPROTO_ANY);
7928 if (!m) {
7929 error = ENOBUFS;
7930 goto fail;
7931 }
7932 m_cat(result, m);
7933
7934 if ((result->m_flags & M_PKTHDR) == 0) {
7935 error = EINVAL;
7936 goto fail;
7937 }
7938
7939 if (result->m_len < sizeof(struct sadb_msg)) {
7940 result = m_pullup(result, sizeof(struct sadb_msg));
7941 if (result == NULL) {
7942 error = ENOBUFS;
7943 goto fail;
7944 }
7945 }
7946
7947 result->m_pkthdr.len = 0;
7948 for (m = result; m; m = m->m_next)
7949 result->m_pkthdr.len += m->m_len;
7950
7951 mtod(result, struct sadb_msg *)->sadb_msg_len =
7952 PFKEY_UNIT64(result->m_pkthdr.len);
7953
7954 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
7955
7956 fail:
7957 if (result)
7958 m_freem(result);
7959 return error;
7960 }
7961
7962 /*
7963 * SADB_FLUSH processing
7964 * receive
7965 * <base>
7966 * from the ikmpd, and free all entries in secastree.
7967 * and send,
7968 * <base>
7969 * to the ikmpd.
7970 * NOTE: to do is only marking SADB_SASTATE_DEAD.
7971 *
7972 * m will always be freed.
7973 */
7974 static int
7975 key_flush(
7976 struct socket *so,
7977 struct mbuf *m,
7978 const struct sadb_msghdr *mhp)
7979 {
7980 struct sadb_msg *newmsg;
7981 struct secashead *sah, *nextsah;
7982 struct secasvar *sav, *nextsav;
7983 u_int16_t proto;
7984 u_int8_t state;
7985 u_int stateidx;
7986
7987 /* sanity check */
7988 if (so == NULL || mhp == NULL || mhp->msg == NULL)
7989 panic("key_flush: NULL pointer is passed.\n");
7990
7991 /* map satype to proto */
7992 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
7993 ipseclog((LOG_DEBUG, "key_flush: invalid satype is passed.\n"));
7994 return key_senderror(so, m, EINVAL);
7995 }
7996
7997 lck_mtx_lock(sadb_mutex);
7998
7999 /* no SATYPE specified, i.e. flushing all SA. */
8000 for (sah = LIST_FIRST(&sahtree);
8001 sah != NULL;
8002 sah = nextsah) {
8003 nextsah = LIST_NEXT(sah, chain);
8004
8005 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
8006 && proto != sah->saidx.proto)
8007 continue;
8008
8009 for (stateidx = 0;
8010 stateidx < _ARRAYLEN(saorder_state_alive);
8011 stateidx++) {
8012 state = saorder_state_any[stateidx];
8013 for (sav = LIST_FIRST(&sah->savtree[state]);
8014 sav != NULL;
8015 sav = nextsav) {
8016
8017 nextsav = LIST_NEXT(sav, chain);
8018
8019 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
8020 key_freesav(sav, KEY_SADB_LOCKED);
8021 }
8022 }
8023
8024 sah->state = SADB_SASTATE_DEAD;
8025 }
8026 lck_mtx_unlock(sadb_mutex);
8027
8028 if (m->m_len < sizeof(struct sadb_msg) ||
8029 sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
8030 ipseclog((LOG_DEBUG, "key_flush: No more memory.\n"));
8031 return key_senderror(so, m, ENOBUFS);
8032 }
8033
8034 if (m->m_next)
8035 m_freem(m->m_next);
8036 m->m_next = NULL;
8037 m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
8038 newmsg = mtod(m, struct sadb_msg *);
8039 newmsg->sadb_msg_errno = 0;
8040 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
8041
8042 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
8043 }
8044
8045 /*
8046 * SADB_DUMP processing
8047 * dump all entries including status of DEAD in SAD.
8048 * receive
8049 * <base>
8050 * from the ikmpd, and dump all secasvar leaves
8051 * and send,
8052 * <base> .....
8053 * to the ikmpd.
8054 *
8055 * m will always be freed.
8056 */
8057
8058 struct sav_dump_elem {
8059 struct secasvar *sav;
8060 u_int8_t satype;
8061 };
8062
8063 static int
8064 key_dump(
8065 struct socket *so,
8066 struct mbuf *m,
8067 const struct sadb_msghdr *mhp)
8068 {
8069 struct secashead *sah;
8070 struct secasvar *sav;
8071 struct sav_dump_elem *savbuf = NULL, *elem_ptr;
8072 u_int16_t proto;
8073 u_int stateidx;
8074 u_int8_t satype;
8075 u_int8_t state;
8076 int cnt = 0, cnt2, bufcount;
8077 struct mbuf *n;
8078 int error = 0;
8079
8080 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
8081
8082 /* sanity check */
8083 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
8084 panic("key_dump: NULL pointer is passed.\n");
8085
8086 /* map satype to proto */
8087 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
8088 ipseclog((LOG_DEBUG, "key_dump: invalid satype is passed.\n"));
8089 return key_senderror(so, m, EINVAL);
8090 }
8091
8092 if ((bufcount = ipsec_sav_count) <= 0) {
8093 error = ENOENT;
8094 goto end;
8095 }
8096 bufcount += 512; /* extra */
8097 KMALLOC_WAIT(savbuf, struct sav_dump_elem*, bufcount * sizeof(struct sav_dump_elem));
8098 if (savbuf == NULL) {
8099 ipseclog((LOG_DEBUG, "key_dump: No more memory.\n"));
8100 error = ENOMEM;
8101 goto end;
8102 }
8103
8104 /* count sav entries to be sent to the userland. */
8105 lck_mtx_lock(sadb_mutex);
8106 elem_ptr = savbuf;
8107 LIST_FOREACH(sah, &sahtree, chain) {
8108 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
8109 && proto != sah->saidx.proto)
8110 continue;
8111
8112 /* map proto to satype */
8113 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
8114 lck_mtx_unlock(sadb_mutex);
8115 ipseclog((LOG_DEBUG, "key_dump: there was invalid proto in SAD.\n"));
8116 error = EINVAL;
8117 goto end;
8118 }
8119
8120 for (stateidx = 0;
8121 stateidx < _ARRAYLEN(saorder_state_any);
8122 stateidx++) {
8123 state = saorder_state_any[stateidx];
8124 LIST_FOREACH(sav, &sah->savtree[state], chain) {
8125 if (cnt == bufcount)
8126 break; /* out of buffer space */
8127 elem_ptr->sav = sav;
8128 elem_ptr->satype = satype;
8129 sav->refcnt++;
8130 elem_ptr++;
8131 cnt++;
8132 }
8133 }
8134 }
8135 lck_mtx_unlock(sadb_mutex);
8136
8137 if (cnt == 0) {
8138 error = ENOENT;
8139 goto end;
8140 }
8141
8142 /* send this to the userland, one at a time. */
8143 elem_ptr = savbuf;
8144 cnt2 = cnt;
8145 while (cnt2) {
8146 n = key_setdumpsa(elem_ptr->sav, SADB_DUMP, elem_ptr->satype,
8147 --cnt2, mhp->msg->sadb_msg_pid);
8148
8149 if (!n) {
8150 error = ENOBUFS;
8151 goto end;
8152 }
8153
8154 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
8155 elem_ptr++;
8156 }
8157
8158 end:
8159 if (savbuf) {
8160 if (cnt) {
8161 elem_ptr = savbuf;
8162 lck_mtx_lock(sadb_mutex);
8163 while (cnt--)
8164 key_freesav((elem_ptr++)->sav, KEY_SADB_LOCKED);
8165 lck_mtx_unlock(sadb_mutex);
8166 }
8167 KFREE(savbuf);
8168 }
8169
8170 if (error)
8171 return key_senderror(so, m, error);
8172
8173 m_freem(m);
8174 return 0;
8175 }
8176
8177 /*
8178 * SADB_X_PROMISC processing
8179 *
8180 * m will always be freed.
8181 */
8182 static int
8183 key_promisc(
8184 struct socket *so,
8185 struct mbuf *m,
8186 const struct sadb_msghdr *mhp)
8187 {
8188 int olen;
8189
8190 /* sanity check */
8191 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
8192 panic("key_promisc: NULL pointer is passed.\n");
8193
8194 olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
8195
8196 if (olen < sizeof(struct sadb_msg)) {
8197 #if 1
8198 return key_senderror(so, m, EINVAL);
8199 #else
8200 m_freem(m);
8201 return 0;
8202 #endif
8203 } else if (olen == sizeof(struct sadb_msg)) {
8204 /* enable/disable promisc mode */
8205 struct keycb *kp;
8206
8207 socket_lock(so, 1);
8208 if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
8209 return key_senderror(so, m, EINVAL);
8210 mhp->msg->sadb_msg_errno = 0;
8211 switch (mhp->msg->sadb_msg_satype) {
8212 case 0:
8213 case 1:
8214 kp->kp_promisc = mhp->msg->sadb_msg_satype;
8215 break;
8216 default:
8217 socket_unlock(so, 1);
8218 return key_senderror(so, m, EINVAL);
8219 }
8220 socket_unlock(so, 1);
8221
8222 /* send the original message back to everyone */
8223 mhp->msg->sadb_msg_errno = 0;
8224 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
8225 } else {
8226 /* send packet as is */
8227
8228 m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
8229
8230 /* TODO: if sadb_msg_seq is specified, send to specific pid */
8231 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
8232 }
8233 }
8234
8235 static int (*key_typesw[])(struct socket *, struct mbuf *,
8236 const struct sadb_msghdr *) = {
8237 NULL, /* SADB_RESERVED */
8238 key_getspi, /* SADB_GETSPI */
8239 key_update, /* SADB_UPDATE */
8240 key_add, /* SADB_ADD */
8241 key_delete, /* SADB_DELETE */
8242 key_get, /* SADB_GET */
8243 key_acquire2, /* SADB_ACQUIRE */
8244 key_register, /* SADB_REGISTER */
8245 NULL, /* SADB_EXPIRE */
8246 key_flush, /* SADB_FLUSH */
8247 key_dump, /* SADB_DUMP */
8248 key_promisc, /* SADB_X_PROMISC */
8249 NULL, /* SADB_X_PCHANGE */
8250 key_spdadd, /* SADB_X_SPDUPDATE */
8251 key_spdadd, /* SADB_X_SPDADD */
8252 key_spddelete, /* SADB_X_SPDDELETE */
8253 key_spdget, /* SADB_X_SPDGET */
8254 NULL, /* SADB_X_SPDACQUIRE */
8255 key_spddump, /* SADB_X_SPDDUMP */
8256 key_spdflush, /* SADB_X_SPDFLUSH */
8257 key_spdadd, /* SADB_X_SPDSETIDX */
8258 NULL, /* SADB_X_SPDEXPIRE */
8259 key_spddelete2, /* SADB_X_SPDDELETE2 */
8260 key_getsastat, /* SADB_GETSASTAT */
8261 };
8262
8263 /*
8264 * parse sadb_msg buffer to process PFKEYv2,
8265 * and create a data to response if needed.
8266 * I think to be dealed with mbuf directly.
8267 * IN:
8268 * msgp : pointer to pointer to a received buffer pulluped.
8269 * This is rewrited to response.
8270 * so : pointer to socket.
8271 * OUT:
8272 * length for buffer to send to user process.
8273 */
8274 int
8275 key_parse(
8276 struct mbuf *m,
8277 struct socket *so)
8278 {
8279 struct sadb_msg *msg;
8280 struct sadb_msghdr mh;
8281 u_int orglen;
8282 int error;
8283 int target;
8284
8285 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
8286
8287 /* sanity check */
8288 if (m == NULL || so == NULL)
8289 panic("key_parse: NULL pointer is passed.\n");
8290
8291 #if 0 /*kdebug_sadb assumes msg in linear buffer*/
8292 KEYDEBUG(KEYDEBUG_KEY_DUMP,
8293 ipseclog((LOG_DEBUG, "key_parse: passed sadb_msg\n"));
8294 kdebug_sadb(msg));
8295 #endif
8296
8297 if (m->m_len < sizeof(struct sadb_msg)) {
8298 m = m_pullup(m, sizeof(struct sadb_msg));
8299 if (!m)
8300 return ENOBUFS;
8301 }
8302 msg = mtod(m, struct sadb_msg *);
8303 orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
8304 target = KEY_SENDUP_ONE;
8305
8306 if ((m->m_flags & M_PKTHDR) == 0 ||
8307 m->m_pkthdr.len != m->m_pkthdr.len) {
8308 ipseclog((LOG_DEBUG, "key_parse: invalid message length.\n"));
8309 PFKEY_STAT_INCREMENT(pfkeystat.out_invlen);
8310 error = EINVAL;
8311 goto senderror;
8312 }
8313
8314 if (msg->sadb_msg_version != PF_KEY_V2) {
8315 ipseclog((LOG_DEBUG,
8316 "key_parse: PF_KEY version %u is mismatched.\n",
8317 msg->sadb_msg_version));
8318 PFKEY_STAT_INCREMENT(pfkeystat.out_invver);
8319 error = EINVAL;
8320 goto senderror;
8321 }
8322
8323 if (msg->sadb_msg_type > SADB_MAX) {
8324 ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
8325 msg->sadb_msg_type));
8326 PFKEY_STAT_INCREMENT(pfkeystat.out_invmsgtype);
8327 error = EINVAL;
8328 goto senderror;
8329 }
8330
8331 /* for old-fashioned code - should be nuked */
8332 if (m->m_pkthdr.len > MCLBYTES) {
8333 m_freem(m);
8334 return ENOBUFS;
8335 }
8336 if (m->m_next) {
8337 struct mbuf *n;
8338
8339 MGETHDR(n, M_WAITOK, MT_DATA);
8340 if (n && m->m_pkthdr.len > MHLEN) {
8341 MCLGET(n, M_WAITOK);
8342 if ((n->m_flags & M_EXT) == 0) {
8343 m_free(n);
8344 n = NULL;
8345 }
8346 }
8347 if (!n) {
8348 m_freem(m);
8349 return ENOBUFS;
8350 }
8351 m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
8352 n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
8353 n->m_next = NULL;
8354 m_freem(m);
8355 m = n;
8356 }
8357
8358 /* align the mbuf chain so that extensions are in contiguous region. */
8359 error = key_align(m, &mh);
8360 if (error)
8361 return error;
8362
8363 if (m->m_next) { /*XXX*/
8364 m_freem(m);
8365 return ENOBUFS;
8366 }
8367
8368 msg = mh.msg;
8369
8370 /* check SA type */
8371 switch (msg->sadb_msg_satype) {
8372 case SADB_SATYPE_UNSPEC:
8373 switch (msg->sadb_msg_type) {
8374 case SADB_GETSPI:
8375 case SADB_UPDATE:
8376 case SADB_ADD:
8377 case SADB_DELETE:
8378 case SADB_GET:
8379 case SADB_ACQUIRE:
8380 case SADB_EXPIRE:
8381 ipseclog((LOG_DEBUG, "key_parse: must specify satype "
8382 "when msg type=%u.\n", msg->sadb_msg_type));
8383 PFKEY_STAT_INCREMENT(pfkeystat.out_invsatype);
8384 error = EINVAL;
8385 goto senderror;
8386 }
8387 break;
8388 case SADB_SATYPE_AH:
8389 case SADB_SATYPE_ESP:
8390 case SADB_X_SATYPE_IPCOMP:
8391 switch (msg->sadb_msg_type) {
8392 case SADB_X_SPDADD:
8393 case SADB_X_SPDDELETE:
8394 case SADB_X_SPDGET:
8395 case SADB_X_SPDDUMP:
8396 case SADB_X_SPDFLUSH:
8397 case SADB_X_SPDSETIDX:
8398 case SADB_X_SPDUPDATE:
8399 case SADB_X_SPDDELETE2:
8400 ipseclog((LOG_DEBUG, "key_parse: illegal satype=%u\n",
8401 msg->sadb_msg_type));
8402 PFKEY_STAT_INCREMENT(pfkeystat.out_invsatype);
8403 error = EINVAL;
8404 goto senderror;
8405 }
8406 break;
8407 case SADB_SATYPE_RSVP:
8408 case SADB_SATYPE_OSPFV2:
8409 case SADB_SATYPE_RIPV2:
8410 case SADB_SATYPE_MIP:
8411 ipseclog((LOG_DEBUG, "key_parse: type %u isn't supported.\n",
8412 msg->sadb_msg_satype));
8413 PFKEY_STAT_INCREMENT(pfkeystat.out_invsatype);
8414 error = EOPNOTSUPP;
8415 goto senderror;
8416 case 1: /* XXX: What does it do? */
8417 if (msg->sadb_msg_type == SADB_X_PROMISC)
8418 break;
8419 /*FALLTHROUGH*/
8420 default:
8421 ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
8422 msg->sadb_msg_satype));
8423 PFKEY_STAT_INCREMENT(pfkeystat.out_invsatype);
8424 error = EINVAL;
8425 goto senderror;
8426 }
8427
8428 /* check field of upper layer protocol and address family */
8429 if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
8430 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
8431 struct sadb_address *src0, *dst0;
8432 u_int plen;
8433
8434 src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
8435 dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
8436
8437 /* check upper layer protocol */
8438 if (src0->sadb_address_proto != dst0->sadb_address_proto) {
8439 ipseclog((LOG_DEBUG, "key_parse: upper layer protocol mismatched.\n"));
8440 PFKEY_STAT_INCREMENT(pfkeystat.out_invaddr);
8441 error = EINVAL;
8442 goto senderror;
8443 }
8444
8445 /* check family */
8446 if (PFKEY_ADDR_SADDR(src0)->sa_family !=
8447 PFKEY_ADDR_SADDR(dst0)->sa_family) {
8448 ipseclog((LOG_DEBUG, "key_parse: address family mismatched.\n"));
8449 PFKEY_STAT_INCREMENT(pfkeystat.out_invaddr);
8450 error = EINVAL;
8451 goto senderror;
8452 }
8453 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
8454 PFKEY_ADDR_SADDR(dst0)->sa_len) {
8455 ipseclog((LOG_DEBUG,
8456 "key_parse: address struct size mismatched.\n"));
8457 PFKEY_STAT_INCREMENT(pfkeystat.out_invaddr);
8458 error = EINVAL;
8459 goto senderror;
8460 }
8461
8462 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
8463 case AF_INET:
8464 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
8465 sizeof(struct sockaddr_in)) {
8466 PFKEY_STAT_INCREMENT(pfkeystat.out_invaddr);
8467 error = EINVAL;
8468 goto senderror;
8469 }
8470 break;
8471 case AF_INET6:
8472 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
8473 sizeof(struct sockaddr_in6)) {
8474 PFKEY_STAT_INCREMENT(pfkeystat.out_invaddr);
8475 error = EINVAL;
8476 goto senderror;
8477 }
8478 break;
8479 default:
8480 ipseclog((LOG_DEBUG,
8481 "key_parse: unsupported address family.\n"));
8482 PFKEY_STAT_INCREMENT(pfkeystat.out_invaddr);
8483 error = EAFNOSUPPORT;
8484 goto senderror;
8485 }
8486
8487 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
8488 case AF_INET:
8489 plen = sizeof(struct in_addr) << 3;
8490 break;
8491 case AF_INET6:
8492 plen = sizeof(struct in6_addr) << 3;
8493 break;
8494 default:
8495 plen = 0; /*fool gcc*/
8496 break;
8497 }
8498
8499 /* check max prefix length */
8500 if (src0->sadb_address_prefixlen > plen ||
8501 dst0->sadb_address_prefixlen > plen) {
8502 ipseclog((LOG_DEBUG,
8503 "key_parse: illegal prefixlen.\n"));
8504 PFKEY_STAT_INCREMENT(pfkeystat.out_invaddr);
8505 error = EINVAL;
8506 goto senderror;
8507 }
8508
8509 /*
8510 * prefixlen == 0 is valid because there can be a case when
8511 * all addresses are matched.
8512 */
8513 }
8514
8515 if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
8516 key_typesw[msg->sadb_msg_type] == NULL) {
8517 PFKEY_STAT_INCREMENT(pfkeystat.out_invmsgtype);
8518 error = EINVAL;
8519 goto senderror;
8520 }
8521
8522 return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
8523
8524 senderror:
8525 msg->sadb_msg_errno = error;
8526 return key_sendup_mbuf(so, m, target);
8527 }
8528
8529 static int
8530 key_senderror(
8531 struct socket *so,
8532 struct mbuf *m,
8533 int code)
8534 {
8535 struct sadb_msg *msg;
8536
8537 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
8538
8539 if (m->m_len < sizeof(struct sadb_msg))
8540 panic("invalid mbuf passed to key_senderror");
8541
8542 msg = mtod(m, struct sadb_msg *);
8543 msg->sadb_msg_errno = code;
8544 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
8545 }
8546
8547 /*
8548 * set the pointer to each header into message buffer.
8549 * m will be freed on error.
8550 * XXX larger-than-MCLBYTES extension?
8551 */
8552 static int
8553 key_align(
8554 struct mbuf *m,
8555 struct sadb_msghdr *mhp)
8556 {
8557 struct mbuf *n;
8558 struct sadb_ext *ext;
8559 size_t off, end;
8560 int extlen;
8561 int toff;
8562
8563 /* sanity check */
8564 if (m == NULL || mhp == NULL)
8565 panic("key_align: NULL pointer is passed.\n");
8566 if (m->m_len < sizeof(struct sadb_msg))
8567 panic("invalid mbuf passed to key_align");
8568
8569 /* initialize */
8570 bzero(mhp, sizeof(*mhp));
8571
8572 mhp->msg = mtod(m, struct sadb_msg *);
8573 mhp->ext[0] = (struct sadb_ext *)mhp->msg; /*XXX backward compat */
8574
8575 end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
8576 extlen = end; /*just in case extlen is not updated*/
8577 for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
8578 n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
8579 if (!n) {
8580 /* m is already freed */
8581 return ENOBUFS;
8582 }
8583 ext = (struct sadb_ext *)(void *)(mtod(n, caddr_t) + toff);
8584
8585 /* set pointer */
8586 switch (ext->sadb_ext_type) {
8587 case SADB_EXT_SA:
8588 case SADB_EXT_ADDRESS_SRC:
8589 case SADB_EXT_ADDRESS_DST:
8590 case SADB_EXT_ADDRESS_PROXY:
8591 case SADB_EXT_LIFETIME_CURRENT:
8592 case SADB_EXT_LIFETIME_HARD:
8593 case SADB_EXT_LIFETIME_SOFT:
8594 case SADB_EXT_KEY_AUTH:
8595 case SADB_EXT_KEY_ENCRYPT:
8596 case SADB_EXT_IDENTITY_SRC:
8597 case SADB_EXT_IDENTITY_DST:
8598 case SADB_EXT_SENSITIVITY:
8599 case SADB_EXT_PROPOSAL:
8600 case SADB_EXT_SUPPORTED_AUTH:
8601 case SADB_EXT_SUPPORTED_ENCRYPT:
8602 case SADB_EXT_SPIRANGE:
8603 case SADB_X_EXT_POLICY:
8604 case SADB_X_EXT_SA2:
8605 case SADB_EXT_SESSION_ID:
8606 case SADB_EXT_SASTAT:
8607 /* duplicate check */
8608 /*
8609 * XXX Are there duplication payloads of either
8610 * KEY_AUTH or KEY_ENCRYPT ?
8611 */
8612 if (mhp->ext[ext->sadb_ext_type] != NULL) {
8613 ipseclog((LOG_DEBUG,
8614 "key_align: duplicate ext_type %u "
8615 "is passed.\n", ext->sadb_ext_type));
8616 m_freem(m);
8617 PFKEY_STAT_INCREMENT(pfkeystat.out_dupext);
8618 return EINVAL;
8619 }
8620 break;
8621 default:
8622 ipseclog((LOG_DEBUG,
8623 "key_align: invalid ext_type %u is passed.\n",
8624 ext->sadb_ext_type));
8625 m_freem(m);
8626 PFKEY_STAT_INCREMENT(pfkeystat.out_invexttype);
8627 return EINVAL;
8628 }
8629
8630 extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
8631
8632 if (key_validate_ext(ext, extlen)) {
8633 m_freem(m);
8634 PFKEY_STAT_INCREMENT(pfkeystat.out_invlen);
8635 return EINVAL;
8636 }
8637
8638 n = m_pulldown(m, off, extlen, &toff);
8639 if (!n) {
8640 /* m is already freed */
8641 return ENOBUFS;
8642 }
8643 ext = (struct sadb_ext *)(void *)(mtod(n, caddr_t) + toff);
8644
8645 mhp->ext[ext->sadb_ext_type] = ext;
8646 mhp->extoff[ext->sadb_ext_type] = off;
8647 mhp->extlen[ext->sadb_ext_type] = extlen;
8648 }
8649
8650 if (off != end) {
8651 m_freem(m);
8652 PFKEY_STAT_INCREMENT(pfkeystat.out_invlen);
8653 return EINVAL;
8654 }
8655
8656 return 0;
8657 }
8658
8659 static int
8660 key_validate_ext(
8661 const struct sadb_ext *ext,
8662 int len)
8663 {
8664 struct sockaddr *sa;
8665 enum { NONE, ADDR } checktype = NONE;
8666 int baselen;
8667 const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
8668
8669 if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
8670 return EINVAL;
8671
8672 /* if it does not match minimum/maximum length, bail */
8673 if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
8674 ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
8675 return EINVAL;
8676 if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
8677 return EINVAL;
8678 if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
8679 return EINVAL;
8680
8681 /* more checks based on sadb_ext_type XXX need more */
8682 switch (ext->sadb_ext_type) {
8683 case SADB_EXT_ADDRESS_SRC:
8684 case SADB_EXT_ADDRESS_DST:
8685 case SADB_EXT_ADDRESS_PROXY:
8686 baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
8687 checktype = ADDR;
8688 break;
8689 case SADB_EXT_IDENTITY_SRC:
8690 case SADB_EXT_IDENTITY_DST:
8691 if (((struct sadb_ident *)(uintptr_t)(size_t)ext)->
8692 sadb_ident_type == SADB_X_IDENTTYPE_ADDR) {
8693 baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
8694 checktype = ADDR;
8695 } else
8696 checktype = NONE;
8697 break;
8698 default:
8699 checktype = NONE;
8700 break;
8701 }
8702
8703 switch (checktype) {
8704 case NONE:
8705 break;
8706 case ADDR:
8707 sa = (struct sockaddr *)((caddr_t)(uintptr_t)ext + baselen);
8708
8709 if (len < baselen + sal)
8710 return EINVAL;
8711 if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
8712 return EINVAL;
8713 break;
8714 }
8715
8716 return 0;
8717 }
8718
8719 void
8720 key_domain_init(void)
8721 {
8722 return;
8723 }
8724
8725 /*
8726 * XXX: maybe This function is called after INBOUND IPsec processing.
8727 *
8728 * Special check for tunnel-mode packets.
8729 * We must make some checks for consistency between inner and outer IP header.
8730 *
8731 * xxx more checks to be provided
8732 */
8733 int
8734 key_checktunnelsanity(
8735 struct secasvar *sav,
8736 __unused u_int family,
8737 __unused caddr_t src,
8738 __unused caddr_t dst)
8739 {
8740
8741 /* sanity check */
8742 if (sav->sah == NULL)
8743 panic("sav->sah == NULL at key_checktunnelsanity");
8744
8745 /* XXX: check inner IP header */
8746
8747 return 1;
8748 }
8749
8750 /* record data transfer on SA, and update timestamps */
8751 void
8752 key_sa_recordxfer(
8753 struct secasvar *sav,
8754 struct mbuf *m)
8755 {
8756
8757
8758 if (!sav)
8759 panic("key_sa_recordxfer called with sav == NULL");
8760 if (!m)
8761 panic("key_sa_recordxfer called with m == NULL");
8762 if (!sav->lft_c)
8763 return;
8764
8765 lck_mtx_lock(sadb_mutex);
8766 /*
8767 * XXX Currently, there is a difference of bytes size
8768 * between inbound and outbound processing.
8769 */
8770 sav->lft_c->sadb_lifetime_bytes += m->m_pkthdr.len;
8771 /* to check bytes lifetime is done in key_timehandler(). */
8772
8773 /*
8774 * We use the number of packets as the unit of
8775 * sadb_lifetime_allocations. We increment the variable
8776 * whenever {esp,ah}_{in,out}put is called.
8777 */
8778 sav->lft_c->sadb_lifetime_allocations++;
8779 /* XXX check for expires? */
8780
8781 /*
8782 * NOTE: We record CURRENT sadb_lifetime_usetime by using wall clock,
8783 * in seconds. HARD and SOFT lifetime are measured by the time
8784 * difference (again in seconds) from sadb_lifetime_usetime.
8785 *
8786 * usetime
8787 * v expire expire
8788 * -----+-----+--------+---> t
8789 * <--------------> HARD
8790 * <-----> SOFT
8791 */
8792 {
8793 struct timeval tv;
8794 microtime(&tv);
8795 sav->lft_c->sadb_lifetime_usetime = tv.tv_sec;
8796 /* XXX check for expires? */
8797 }
8798 lck_mtx_unlock(sadb_mutex);
8799
8800 return;
8801 }
8802
8803 /* dumb version */
8804 void
8805 key_sa_routechange(
8806 struct sockaddr *dst)
8807 {
8808 struct secashead *sah;
8809 struct route *ro;
8810
8811 lck_mtx_lock(sadb_mutex);
8812 LIST_FOREACH(sah, &sahtree, chain) {
8813 ro = &sah->sa_route;
8814 if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
8815 && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
8816 rtfree(ro->ro_rt);
8817 ro->ro_rt = (struct rtentry *)NULL;
8818 }
8819 }
8820 lck_mtx_unlock(sadb_mutex);
8821
8822 return;
8823 }
8824
8825 void
8826 key_sa_chgstate(
8827 struct secasvar *sav,
8828 u_int8_t state)
8829 {
8830
8831 if (sav == NULL)
8832 panic("key_sa_chgstate called with sav == NULL");
8833
8834 if (sav->state == state)
8835 return;
8836
8837 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
8838
8839 if (__LIST_CHAINED(sav))
8840 LIST_REMOVE(sav, chain);
8841
8842 sav->state = state;
8843 LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
8844
8845 }
8846
8847 void
8848 key_sa_stir_iv(
8849 struct secasvar *sav)
8850 {
8851 lck_mtx_lock(sadb_mutex);
8852 if (!sav->iv)
8853 panic("key_sa_stir_iv called with sav == NULL");
8854 key_randomfill(sav->iv, sav->ivlen);
8855 lck_mtx_unlock(sadb_mutex);
8856 }
8857
8858 /* XXX too much? */
8859 static struct mbuf *
8860 key_alloc_mbuf(
8861 int l)
8862 {
8863 struct mbuf *m = NULL, *n;
8864 int len, t;
8865
8866 len = l;
8867 while (len > 0) {
8868 MGET(n, M_DONTWAIT, MT_DATA);
8869 if (n && len > MLEN)
8870 MCLGET(n, M_DONTWAIT);
8871 if (!n) {
8872 m_freem(m);
8873 return NULL;
8874 }
8875
8876 n->m_next = NULL;
8877 n->m_len = 0;
8878 n->m_len = M_TRAILINGSPACE(n);
8879 /* use the bottom of mbuf, hoping we can prepend afterwards */
8880 if (n->m_len > len) {
8881 t = (n->m_len - len) & ~(sizeof(long) - 1);
8882 n->m_data += t;
8883 n->m_len = len;
8884 }
8885
8886 len -= n->m_len;
8887
8888 if (m)
8889 m_cat(m, n);
8890 else
8891 m = n;
8892 }
8893
8894 return m;
8895 }
8896
8897 static struct mbuf *
8898 key_setdumpsastats (u_int32_t dir,
8899 struct sastat *stats,
8900 u_int32_t max_stats,
8901 u_int64_t session_ids[],
8902 u_int32_t seq,
8903 u_int32_t pid)
8904 {
8905 struct mbuf *result = NULL, *m = NULL;
8906
8907 m = key_setsadbmsg(SADB_GETSASTAT, 0, 0, seq, pid, 0);
8908 if (!m) {
8909 goto fail;
8910 }
8911 result = m;
8912
8913 m = key_setsadbsession_id(session_ids);
8914 if (!m) {
8915 goto fail;
8916 }
8917 m_cat(result, m);
8918
8919 m = key_setsadbsastat(dir,
8920 stats,
8921 max_stats);
8922 if (!m) {
8923 goto fail;
8924 }
8925 m_cat(result, m);
8926
8927 if ((result->m_flags & M_PKTHDR) == 0) {
8928 goto fail;
8929 }
8930
8931 if (result->m_len < sizeof(struct sadb_msg)) {
8932 result = m_pullup(result, sizeof(struct sadb_msg));
8933 if (result == NULL) {
8934 goto fail;
8935 }
8936 }
8937
8938 result->m_pkthdr.len = 0;
8939 for (m = result; m; m = m->m_next) {
8940 result->m_pkthdr.len += m->m_len;
8941 }
8942
8943 mtod(result, struct sadb_msg *)->sadb_msg_len =
8944 PFKEY_UNIT64(result->m_pkthdr.len);
8945
8946 return result;
8947
8948 fail:
8949 if (result) {
8950 m_freem(result);
8951 }
8952 return NULL;
8953 }
8954
8955 /*
8956 * SADB_GETSASTAT processing
8957 * dump all stats for matching entries in SAD.
8958 *
8959 * m will always be freed.
8960 */
8961
8962 static int
8963 key_getsastat (struct socket *so,
8964 struct mbuf *m,
8965 const struct sadb_msghdr *mhp)
8966 {
8967 struct sadb_session_id *session_id;
8968 u_int32_t bufsize, arg_count, res_count;
8969 struct sadb_sastat *sa_stats_arg;
8970 struct sastat *sa_stats_sav = NULL;
8971 struct mbuf *n;
8972 int error = 0;
8973
8974 /* sanity check */
8975 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
8976 panic("%s: NULL pointer is passed.\n", __FUNCTION__);
8977
8978 if (mhp->ext[SADB_EXT_SESSION_ID] == NULL) {
8979 printf("%s: invalid message is passed. missing session-id.\n", __FUNCTION__);
8980 return key_senderror(so, m, EINVAL);
8981 }
8982 if (mhp->extlen[SADB_EXT_SESSION_ID] < sizeof(struct sadb_session_id)) {
8983 printf("%s: invalid message is passed. short session-id.\n", __FUNCTION__);
8984 return key_senderror(so, m, EINVAL);
8985 }
8986 if (mhp->ext[SADB_EXT_SASTAT] == NULL) {
8987 printf("%s: invalid message is passed. missing stat args.\n", __FUNCTION__);
8988 return key_senderror(so, m, EINVAL);
8989 }
8990 if (mhp->extlen[SADB_EXT_SASTAT] < sizeof(*sa_stats_arg)) {
8991 printf("%s: invalid message is passed. short stat args.\n", __FUNCTION__);
8992 return key_senderror(so, m, EINVAL);
8993 }
8994
8995 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_NOTOWNED);
8996
8997 // exit early if there are no active SAs
8998 if (ipsec_sav_count <= 0) {
8999 printf("%s: No active SAs.\n", __FUNCTION__);
9000 error = ENOENT;
9001 goto end;
9002 }
9003 bufsize = (ipsec_sav_count + 1) * sizeof(*sa_stats_sav);
9004
9005 KMALLOC_WAIT(sa_stats_sav, __typeof__(sa_stats_sav), bufsize);
9006 if (sa_stats_sav == NULL) {
9007 printf("%s: No more memory.\n", __FUNCTION__);
9008 error = ENOMEM;
9009 goto end;
9010 }
9011 bzero(sa_stats_sav, bufsize);
9012
9013 sa_stats_arg = (__typeof__(sa_stats_arg))
9014 (void *)mhp->ext[SADB_EXT_SASTAT];
9015 arg_count = sa_stats_arg->sadb_sastat_list_len;
9016 // exit early if there are no requested SAs
9017 if (arg_count == 0) {
9018 printf("%s: No SAs requested.\n", __FUNCTION__);
9019 error = ENOENT;
9020 goto end;
9021 }
9022 res_count = 0;
9023
9024 if (key_getsastatbyspi((struct sastat *)(sa_stats_arg + 1),
9025 arg_count,
9026 sa_stats_sav,
9027 &res_count)) {
9028 printf("%s: Error finding SAs.\n", __FUNCTION__);
9029 error = ENOENT;
9030 goto end;
9031 }
9032 if (!res_count) {
9033 printf("%s: No SAs found.\n", __FUNCTION__);
9034 error = ENOENT;
9035 goto end;
9036 }
9037
9038 session_id = (__typeof__(session_id))
9039 (void *)mhp->ext[SADB_EXT_SESSION_ID];
9040
9041 /* send this to the userland. */
9042 n = key_setdumpsastats(sa_stats_arg->sadb_sastat_dir,
9043 sa_stats_sav,
9044 res_count,
9045 session_id->sadb_session_id_v,
9046 mhp->msg->sadb_msg_seq,
9047 mhp->msg->sadb_msg_pid);
9048 if (!n) {
9049 printf("%s: No bufs to dump stats.\n", __FUNCTION__);
9050 error = ENOBUFS;
9051 goto end;
9052 }
9053
9054 key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
9055 end:
9056 if (sa_stats_sav) {
9057 KFREE(sa_stats_sav);
9058 }
9059
9060 if (error)
9061 return key_senderror(so, m, error);
9062
9063 m_freem(m);
9064 return 0;
9065 }
9066
9067 static void
9068 key_update_natt_keepalive_timestamp (struct secasvar *sav_sent,
9069 struct secasvar *sav_update)
9070 {
9071 struct secasindex saidx_swap_sent_addr;
9072
9073 // exit early if two SAs are identical, or if sav_update is current
9074 if (sav_sent == sav_update ||
9075 sav_update->natt_last_activity == natt_now) {
9076 return;
9077 }
9078
9079 // assuming that (sav_update->remote_ike_port != 0 && (esp_udp_encap_port & 0xFFFF) != 0)
9080
9081 bzero(&saidx_swap_sent_addr, sizeof(saidx_swap_sent_addr));
9082 memcpy(&saidx_swap_sent_addr.src, &sav_sent->sah->saidx.dst, sizeof(saidx_swap_sent_addr.src));
9083 memcpy(&saidx_swap_sent_addr.dst, &sav_sent->sah->saidx.src, sizeof(saidx_swap_sent_addr.dst));
9084 saidx_swap_sent_addr.proto = sav_sent->sah->saidx.proto;
9085 saidx_swap_sent_addr.mode = sav_sent->sah->saidx.mode;
9086 // we ignore reqid for split-tunnel setups
9087
9088 if (key_cmpsaidx(&sav_sent->sah->saidx, &sav_update->sah->saidx, CMP_MODE | CMP_PORT) ||
9089 key_cmpsaidx(&saidx_swap_sent_addr, &sav_update->sah->saidx, CMP_MODE | CMP_PORT)) {
9090 sav_update->natt_last_activity = natt_now;
9091 }
9092 }