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