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