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