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