]> git.saurik.com Git - apple/xnu.git/blob - bsd/netkey/key.c
xnu-792.17.14.tar.gz
[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 if (newsav->spihash.le_prev || newsav->spihash.le_next)
2854 LIST_REMOVE(newsav, spihash);
2855 KFREE(newsav);
2856 return NULL;
2857 }
2858 }
2859
2860 /* reset created */
2861 {
2862 struct timeval tv;
2863 microtime(&tv);
2864 newsav->created = tv.tv_sec;
2865 }
2866
2867 newsav->pid = mhp->msg->sadb_msg_pid;
2868
2869 /* add to satree */
2870 newsav->sah = sah;
2871 newsav->refcnt = 1;
2872 newsav->state = SADB_SASTATE_LARVAL;
2873 LIST_INSERT_TAIL(&sah->savtree[SADB_SASTATE_LARVAL], newsav,
2874 secasvar, chain);
2875
2876 return newsav;
2877 }
2878
2879 /*
2880 * free() SA variable entry.
2881 */
2882 static void
2883 key_delsav(sav)
2884 struct secasvar *sav;
2885 {
2886 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
2887
2888 /* sanity check */
2889 if (sav == NULL)
2890 panic("key_delsav: NULL pointer is passed.\n");
2891
2892 if (sav->refcnt > 0)
2893 return; /* can't free */
2894
2895 /* remove from SA header */
2896 if (__LIST_CHAINED(sav))
2897 LIST_REMOVE(sav, chain);
2898
2899 if (sav->spihash.le_prev || sav->spihash.le_next)
2900 LIST_REMOVE(sav, spihash);
2901
2902 if (sav->key_auth != NULL) {
2903 bzero(_KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
2904 KFREE(sav->key_auth);
2905 sav->key_auth = NULL;
2906 }
2907 if (sav->key_enc != NULL) {
2908 bzero(_KEYBUF(sav->key_enc), _KEYLEN(sav->key_enc));
2909 KFREE(sav->key_enc);
2910 sav->key_enc = NULL;
2911 }
2912 if (sav->sched) {
2913 bzero(sav->sched, sav->schedlen);
2914 KFREE(sav->sched);
2915 sav->sched = NULL;
2916 }
2917 if (sav->replay != NULL) {
2918 keydb_delsecreplay(sav->replay);
2919 sav->replay = NULL;
2920 }
2921 if (sav->lft_c != NULL) {
2922 KFREE(sav->lft_c);
2923 sav->lft_c = NULL;
2924 }
2925 if (sav->lft_h != NULL) {
2926 KFREE(sav->lft_h);
2927 sav->lft_h = NULL;
2928 }
2929 if (sav->lft_s != NULL) {
2930 KFREE(sav->lft_s);
2931 sav->lft_s = NULL;
2932 }
2933 if (sav->iv != NULL) {
2934 KFREE(sav->iv);
2935 sav->iv = NULL;
2936 }
2937
2938 KFREE(sav);
2939
2940 return;
2941 }
2942
2943 /*
2944 * search SAD.
2945 * OUT:
2946 * NULL : not found
2947 * others : found, pointer to a SA.
2948 */
2949 static struct secashead *
2950 key_getsah(saidx)
2951 struct secasindex *saidx;
2952 {
2953 struct secashead *sah;
2954
2955 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
2956
2957 LIST_FOREACH(sah, &sahtree, chain) {
2958 if (sah->state == SADB_SASTATE_DEAD)
2959 continue;
2960 if (key_cmpsaidx(&sah->saidx, saidx, CMP_REQID))
2961 return sah;
2962 }
2963
2964 return NULL;
2965 }
2966
2967 /*
2968 * check not to be duplicated SPI.
2969 * NOTE: this function is too slow due to searching all SAD.
2970 * OUT:
2971 * NULL : not found
2972 * others : found, pointer to a SA.
2973 */
2974 static struct secasvar *
2975 key_checkspidup(saidx, spi)
2976 struct secasindex *saidx;
2977 u_int32_t spi;
2978 {
2979 struct secasvar *sav;
2980 u_int stateidx, state;
2981
2982 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
2983
2984 /* check address family */
2985 if (saidx->src.ss_family != saidx->dst.ss_family) {
2986 ipseclog((LOG_DEBUG, "key_checkspidup: address family mismatched.\n"));
2987 return NULL;
2988 }
2989
2990 /* check all SAD */
2991 LIST_FOREACH(sav, &spihash[SPIHASH(spi)], spihash) {
2992 if (sav->spi != spi)
2993 continue;
2994 for (stateidx = 0;
2995 stateidx < _ARRAYLEN(saorder_state_alive);
2996 stateidx++) {
2997 state = saorder_state_alive[stateidx];
2998 if (sav->state == state &&
2999 key_ismyaddr((struct sockaddr *)&sav->sah->saidx.dst))
3000 return sav;
3001 }
3002 }
3003
3004 return NULL;
3005 }
3006
3007 static void
3008 key_setspi(sav, spi)
3009 struct secasvar *sav;
3010 u_int32_t spi;
3011 {
3012
3013 sav->spi = spi;
3014 if (sav->spihash.le_prev || sav->spihash.le_next)
3015 LIST_REMOVE(sav, spihash);
3016 LIST_INSERT_HEAD(&spihash[SPIHASH(spi)], sav, spihash);
3017 }
3018
3019
3020 /*
3021 * search SAD litmited alive SA, protocol, SPI.
3022 * OUT:
3023 * NULL : not found
3024 * others : found, pointer to a SA.
3025 */
3026 static struct secasvar *
3027 key_getsavbyspi(sah, spi)
3028 struct secashead *sah;
3029 u_int32_t spi;
3030 {
3031 struct secasvar *sav, *match;
3032 u_int stateidx, state, matchidx;
3033
3034 match = NULL;
3035 matchidx = _ARRAYLEN(saorder_state_alive);
3036 LIST_FOREACH(sav, &spihash[SPIHASH(spi)], spihash) {
3037 if (sav->spi != spi)
3038 continue;
3039 if (sav->sah != sah)
3040 continue;
3041 for (stateidx = 0; stateidx < matchidx; stateidx++) {
3042 state = saorder_state_alive[stateidx];
3043 if (sav->state == state) {
3044 match = sav;
3045 matchidx = stateidx;
3046 break;
3047 }
3048 }
3049 }
3050
3051 return match;
3052 }
3053
3054 /*
3055 * copy SA values from PF_KEY message except *SPI, SEQ, PID, STATE and TYPE*.
3056 * You must update these if need.
3057 * OUT: 0: success.
3058 * !0: failure.
3059 *
3060 * does not modify mbuf. does not free mbuf on error.
3061 */
3062 static int
3063 key_setsaval(sav, m, mhp)
3064 struct secasvar *sav;
3065 struct mbuf *m;
3066 const struct sadb_msghdr *mhp;
3067 {
3068 #if IPSEC_ESP
3069 const struct esp_algorithm *algo;
3070 #endif
3071 int error = 0;
3072 struct timeval tv;
3073
3074 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
3075
3076 /* sanity check */
3077 if (m == NULL || mhp == NULL || mhp->msg == NULL)
3078 panic("key_setsaval: NULL pointer is passed.\n");
3079
3080 /* initialization */
3081 sav->replay = NULL;
3082 sav->key_auth = NULL;
3083 sav->key_enc = NULL;
3084 sav->sched = NULL;
3085 sav->schedlen = 0;
3086 sav->iv = NULL;
3087 sav->lft_c = NULL;
3088 sav->lft_h = NULL;
3089 sav->lft_s = NULL;
3090 sav->remote_ike_port = 0;
3091 sav->natt_last_activity = natt_now;
3092
3093 /* SA */
3094 if (mhp->ext[SADB_EXT_SA] != NULL) {
3095 const struct sadb_sa *sa0;
3096
3097 sa0 = (const struct sadb_sa *)mhp->ext[SADB_EXT_SA];
3098 if (mhp->extlen[SADB_EXT_SA] < sizeof(*sa0)) {
3099 ipseclog((LOG_DEBUG, "key_setsaval: invalid message size.\n"));
3100 error = EINVAL;
3101 goto fail;
3102 }
3103
3104 sav->alg_auth = sa0->sadb_sa_auth;
3105 sav->alg_enc = sa0->sadb_sa_encrypt;
3106 sav->flags = sa0->sadb_sa_flags;
3107
3108 /*
3109 * Verify that a nat-traversal port was specified if
3110 * the nat-traversal flag is set.
3111 */
3112 if ((sav->flags & SADB_X_EXT_NATT) != 0) {
3113 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa_2) ||
3114 ((struct sadb_sa_2*)(sa0))->sadb_sa_natt_port == 0) {
3115 ipseclog((LOG_DEBUG, "key_setsaval: natt port not set.\n"));
3116 error = EINVAL;
3117 goto fail;
3118 }
3119 sav->remote_ike_port = ((struct sadb_sa_2*)(sa0))->sadb_sa_natt_port;
3120 }
3121
3122 /* replay window */
3123 if ((sa0->sadb_sa_flags & SADB_X_EXT_OLD) == 0) {
3124 sav->replay = keydb_newsecreplay(sa0->sadb_sa_replay);
3125 if (sav->replay == NULL) {
3126 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3127 error = ENOBUFS;
3128 goto fail;
3129 }
3130 }
3131 }
3132
3133 /* Authentication keys */
3134 if (mhp->ext[SADB_EXT_KEY_AUTH] != NULL) {
3135 const struct sadb_key *key0;
3136 int len;
3137
3138 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_AUTH];
3139 len = mhp->extlen[SADB_EXT_KEY_AUTH];
3140
3141 error = 0;
3142 if (len < sizeof(*key0)) {
3143 ipseclog((LOG_DEBUG, "key_setsaval: invalid auth key ext len. len = %d\n", len));
3144 error = EINVAL;
3145 goto fail;
3146 }
3147 switch (mhp->msg->sadb_msg_satype) {
3148 case SADB_SATYPE_AH:
3149 case SADB_SATYPE_ESP:
3150 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3151 sav->alg_auth != SADB_X_AALG_NULL)
3152 error = EINVAL;
3153 break;
3154 case SADB_X_SATYPE_IPCOMP:
3155 default:
3156 error = EINVAL;
3157 break;
3158 }
3159 if (error) {
3160 ipseclog((LOG_DEBUG, "key_setsaval: invalid key_auth values.\n"));
3161 goto fail;
3162 }
3163
3164 sav->key_auth = (struct sadb_key *)key_newbuf(key0, len);
3165 if (sav->key_auth == NULL) {
3166 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3167 error = ENOBUFS;
3168 goto fail;
3169 }
3170 }
3171
3172 /* Encryption key */
3173 if (mhp->ext[SADB_EXT_KEY_ENCRYPT] != NULL) {
3174 const struct sadb_key *key0;
3175 int len;
3176
3177 key0 = (const struct sadb_key *)mhp->ext[SADB_EXT_KEY_ENCRYPT];
3178 len = mhp->extlen[SADB_EXT_KEY_ENCRYPT];
3179
3180 error = 0;
3181 if (len < sizeof(*key0)) {
3182 ipseclog((LOG_DEBUG, "key_setsaval: invalid encryption key ext len. len = %d\n", len));
3183 error = EINVAL;
3184 goto fail;
3185 }
3186 switch (mhp->msg->sadb_msg_satype) {
3187 case SADB_SATYPE_ESP:
3188 if (len == PFKEY_ALIGN8(sizeof(struct sadb_key)) &&
3189 sav->alg_enc != SADB_EALG_NULL) {
3190 ipseclog((LOG_DEBUG, "key_setsaval: invalid ESP algorithm.\n"));
3191 error = EINVAL;
3192 break;
3193 }
3194 sav->key_enc = (struct sadb_key *)key_newbuf(key0, len);
3195 if (sav->key_enc == NULL) {
3196 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3197 error = ENOBUFS;
3198 goto fail;
3199 }
3200 break;
3201 case SADB_X_SATYPE_IPCOMP:
3202 if (len != PFKEY_ALIGN8(sizeof(struct sadb_key)))
3203 error = EINVAL;
3204 sav->key_enc = NULL; /*just in case*/
3205 break;
3206 case SADB_SATYPE_AH:
3207 default:
3208 error = EINVAL;
3209 break;
3210 }
3211 if (error) {
3212 ipseclog((LOG_DEBUG, "key_setsaval: invalid key_enc value.\n"));
3213 goto fail;
3214 }
3215 }
3216
3217 /* set iv */
3218 sav->ivlen = 0;
3219
3220 switch (mhp->msg->sadb_msg_satype) {
3221 case SADB_SATYPE_ESP:
3222 #if IPSEC_ESP
3223 algo = esp_algorithm_lookup(sav->alg_enc);
3224 if (algo && algo->ivlen)
3225 sav->ivlen = (*algo->ivlen)(algo, sav);
3226 if (sav->ivlen == 0)
3227 break;
3228 KMALLOC(sav->iv, caddr_t, sav->ivlen);
3229 if (sav->iv == 0) {
3230 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3231 error = ENOBUFS;
3232 goto fail;
3233 }
3234
3235 /* initialize */
3236 key_randomfill(sav->iv, sav->ivlen);
3237 #endif
3238 break;
3239 case SADB_SATYPE_AH:
3240 case SADB_X_SATYPE_IPCOMP:
3241 break;
3242 default:
3243 ipseclog((LOG_DEBUG, "key_setsaval: invalid SA type.\n"));
3244 error = EINVAL;
3245 goto fail;
3246 }
3247
3248 /* reset created */
3249 microtime(&tv);
3250 sav->created = tv.tv_sec;
3251
3252 /* make lifetime for CURRENT */
3253 KMALLOC(sav->lft_c, struct sadb_lifetime *,
3254 sizeof(struct sadb_lifetime));
3255 if (sav->lft_c == NULL) {
3256 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3257 error = ENOBUFS;
3258 goto fail;
3259 }
3260
3261 microtime(&tv);
3262
3263 sav->lft_c->sadb_lifetime_len =
3264 PFKEY_UNIT64(sizeof(struct sadb_lifetime));
3265 sav->lft_c->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
3266 sav->lft_c->sadb_lifetime_allocations = 0;
3267 sav->lft_c->sadb_lifetime_bytes = 0;
3268 sav->lft_c->sadb_lifetime_addtime = tv.tv_sec;
3269 sav->lft_c->sadb_lifetime_usetime = 0;
3270
3271 /* lifetimes for HARD and SOFT */
3272 {
3273 const struct sadb_lifetime *lft0;
3274
3275 lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_HARD];
3276 if (lft0 != NULL) {
3277 if (mhp->extlen[SADB_EXT_LIFETIME_HARD] < sizeof(*lft0)) {
3278 ipseclog((LOG_DEBUG, "key_setsaval: invalid hard lifetime ext len.\n"));
3279 error = EINVAL;
3280 goto fail;
3281 }
3282 sav->lft_h = (struct sadb_lifetime *)key_newbuf(lft0,
3283 sizeof(*lft0));
3284 if (sav->lft_h == NULL) {
3285 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3286 error = ENOBUFS;
3287 goto fail;
3288 }
3289 /* to be initialize ? */
3290 }
3291
3292 lft0 = (struct sadb_lifetime *)mhp->ext[SADB_EXT_LIFETIME_SOFT];
3293 if (lft0 != NULL) {
3294 if (mhp->extlen[SADB_EXT_LIFETIME_SOFT] < sizeof(*lft0)) {
3295 ipseclog((LOG_DEBUG, "key_setsaval: invalid soft lifetime ext len.\n"));
3296 error = EINVAL;
3297 goto fail;
3298 }
3299 sav->lft_s = (struct sadb_lifetime *)key_newbuf(lft0,
3300 sizeof(*lft0));
3301 if (sav->lft_s == NULL) {
3302 ipseclog((LOG_DEBUG, "key_setsaval: No more memory.\n"));
3303 error = ENOBUFS;
3304 goto fail;
3305 }
3306 /* to be initialize ? */
3307 }
3308 }
3309
3310 return 0;
3311
3312 fail:
3313 /* initialization */
3314 if (sav->replay != NULL) {
3315 keydb_delsecreplay(sav->replay);
3316 sav->replay = NULL;
3317 }
3318 if (sav->key_auth != NULL) {
3319 bzero(_KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
3320 KFREE(sav->key_auth);
3321 sav->key_auth = NULL;
3322 }
3323 if (sav->key_enc != NULL) {
3324 bzero(_KEYBUF(sav->key_enc), _KEYLEN(sav->key_enc));
3325 KFREE(sav->key_enc);
3326 sav->key_enc = NULL;
3327 }
3328 if (sav->sched) {
3329 bzero(sav->sched, sav->schedlen);
3330 KFREE(sav->sched);
3331 sav->sched = NULL;
3332 }
3333 if (sav->iv != NULL) {
3334 KFREE(sav->iv);
3335 sav->iv = NULL;
3336 }
3337 if (sav->lft_c != NULL) {
3338 KFREE(sav->lft_c);
3339 sav->lft_c = NULL;
3340 }
3341 if (sav->lft_h != NULL) {
3342 KFREE(sav->lft_h);
3343 sav->lft_h = NULL;
3344 }
3345 if (sav->lft_s != NULL) {
3346 KFREE(sav->lft_s);
3347 sav->lft_s = NULL;
3348 }
3349
3350 return error;
3351 }
3352
3353 /*
3354 * validation with a secasvar entry, and set SADB_SATYPE_MATURE.
3355 * OUT: 0: valid
3356 * other: errno
3357 */
3358 static int
3359 key_mature(sav)
3360 struct secasvar *sav;
3361 {
3362 int mature;
3363 int checkmask = 0; /* 2^0: ealg 2^1: aalg 2^2: calg */
3364 int mustmask = 0; /* 2^0: ealg 2^1: aalg 2^2: calg */
3365
3366 mature = 0;
3367
3368 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
3369
3370 /* check SPI value */
3371 switch (sav->sah->saidx.proto) {
3372 case IPPROTO_ESP:
3373 case IPPROTO_AH:
3374 if (ntohl(sav->spi) >= 0 && ntohl(sav->spi) <= 255) {
3375 ipseclog((LOG_DEBUG,
3376 "key_mature: illegal range of SPI %u.\n",
3377 (u_int32_t)ntohl(sav->spi)));
3378 return EINVAL;
3379 }
3380 break;
3381 }
3382
3383 /* check satype */
3384 switch (sav->sah->saidx.proto) {
3385 case IPPROTO_ESP:
3386 /* check flags */
3387 if ((sav->flags & SADB_X_EXT_OLD)
3388 && (sav->flags & SADB_X_EXT_DERIV)) {
3389 ipseclog((LOG_DEBUG, "key_mature: "
3390 "invalid flag (derived) given to old-esp.\n"));
3391 return EINVAL;
3392 }
3393 if (sav->alg_auth == SADB_AALG_NONE)
3394 checkmask = 1;
3395 else
3396 checkmask = 3;
3397 mustmask = 1;
3398 break;
3399 case IPPROTO_AH:
3400 /* check flags */
3401 if (sav->flags & SADB_X_EXT_DERIV) {
3402 ipseclog((LOG_DEBUG, "key_mature: "
3403 "invalid flag (derived) given to AH SA.\n"));
3404 return EINVAL;
3405 }
3406 if (sav->alg_enc != SADB_EALG_NONE) {
3407 ipseclog((LOG_DEBUG, "key_mature: "
3408 "protocol and algorithm mismated.\n"));
3409 return(EINVAL);
3410 }
3411 checkmask = 2;
3412 mustmask = 2;
3413 break;
3414 case IPPROTO_IPCOMP:
3415 if (sav->alg_auth != SADB_AALG_NONE) {
3416 ipseclog((LOG_DEBUG, "key_mature: "
3417 "protocol and algorithm mismated.\n"));
3418 return(EINVAL);
3419 }
3420 if ((sav->flags & SADB_X_EXT_RAWCPI) == 0
3421 && ntohl(sav->spi) >= 0x10000) {
3422 ipseclog((LOG_DEBUG, "key_mature: invalid cpi for IPComp.\n"));
3423 return(EINVAL);
3424 }
3425 checkmask = 4;
3426 mustmask = 4;
3427 break;
3428 default:
3429 ipseclog((LOG_DEBUG, "key_mature: Invalid satype.\n"));
3430 return EPROTONOSUPPORT;
3431 }
3432
3433 /* check authentication algorithm */
3434 if ((checkmask & 2) != 0) {
3435 const struct ah_algorithm *algo;
3436 int keylen;
3437
3438 algo = ah_algorithm_lookup(sav->alg_auth);
3439 if (!algo) {
3440 ipseclog((LOG_DEBUG,"key_mature: "
3441 "unknown authentication algorithm.\n"));
3442 return EINVAL;
3443 }
3444
3445 /* algorithm-dependent check */
3446 if (sav->key_auth)
3447 keylen = sav->key_auth->sadb_key_bits;
3448 else
3449 keylen = 0;
3450 if (keylen < algo->keymin || algo->keymax < keylen) {
3451 ipseclog((LOG_DEBUG,
3452 "key_mature: invalid AH key length %d "
3453 "(%d-%d allowed)\n",
3454 keylen, algo->keymin, algo->keymax));
3455 return EINVAL;
3456 }
3457
3458 if (algo->mature) {
3459 if ((*algo->mature)(sav)) {
3460 /* message generated in per-algorithm function*/
3461 return EINVAL;
3462 } else
3463 mature = SADB_SATYPE_AH;
3464 }
3465
3466 if ((mustmask & 2) != 0 && mature != SADB_SATYPE_AH) {
3467 ipseclog((LOG_DEBUG, "key_mature: no satisfy algorithm for AH\n"));
3468 return EINVAL;
3469 }
3470 }
3471
3472 /* check encryption algorithm */
3473 if ((checkmask & 1) != 0) {
3474 #if IPSEC_ESP
3475 const struct esp_algorithm *algo;
3476 int keylen;
3477
3478 algo = esp_algorithm_lookup(sav->alg_enc);
3479 if (!algo) {
3480 ipseclog((LOG_DEBUG, "key_mature: unknown encryption algorithm.\n"));
3481 return EINVAL;
3482 }
3483
3484 /* algorithm-dependent check */
3485 if (sav->key_enc)
3486 keylen = sav->key_enc->sadb_key_bits;
3487 else
3488 keylen = 0;
3489 if (keylen < algo->keymin || algo->keymax < keylen) {
3490 ipseclog((LOG_DEBUG,
3491 "key_mature: invalid ESP key length %d "
3492 "(%d-%d allowed)\n",
3493 keylen, algo->keymin, algo->keymax));
3494 return EINVAL;
3495 }
3496
3497 if (algo->mature) {
3498 if ((*algo->mature)(sav)) {
3499 /* message generated in per-algorithm function*/
3500 return EINVAL;
3501 } else
3502 mature = SADB_SATYPE_ESP;
3503 }
3504
3505 if ((mustmask & 1) != 0 && mature != SADB_SATYPE_ESP) {
3506 ipseclog((LOG_DEBUG, "key_mature: no satisfy algorithm for ESP\n"));
3507 return EINVAL;
3508 }
3509 #else /*IPSEC_ESP*/
3510 ipseclog((LOG_DEBUG, "key_mature: ESP not supported in this configuration\n"));
3511 return EINVAL;
3512 #endif
3513 }
3514
3515 /* check compression algorithm */
3516 if ((checkmask & 4) != 0) {
3517 const struct ipcomp_algorithm *algo;
3518
3519 /* algorithm-dependent check */
3520 algo = ipcomp_algorithm_lookup(sav->alg_enc);
3521 if (!algo) {
3522 ipseclog((LOG_DEBUG, "key_mature: unknown compression algorithm.\n"));
3523 return EINVAL;
3524 }
3525 }
3526
3527 key_sa_chgstate(sav, SADB_SASTATE_MATURE);
3528
3529 return 0;
3530 }
3531
3532 /*
3533 * subroutine for SADB_GET and SADB_DUMP.
3534 */
3535 static struct mbuf *
3536 key_setdumpsa(sav, type, satype, seq, pid)
3537 struct secasvar *sav;
3538 u_int8_t type, satype;
3539 u_int32_t seq, pid;
3540 {
3541 struct mbuf *result = NULL, *tres = NULL, *m;
3542 int l = 0;
3543 int i;
3544 void *p;
3545 int dumporder[] = {
3546 SADB_EXT_SA, SADB_X_EXT_SA2,
3547 SADB_EXT_LIFETIME_HARD, SADB_EXT_LIFETIME_SOFT,
3548 SADB_EXT_LIFETIME_CURRENT, SADB_EXT_ADDRESS_SRC,
3549 SADB_EXT_ADDRESS_DST, SADB_EXT_ADDRESS_PROXY, SADB_EXT_KEY_AUTH,
3550 SADB_EXT_KEY_ENCRYPT, SADB_EXT_IDENTITY_SRC,
3551 SADB_EXT_IDENTITY_DST, SADB_EXT_SENSITIVITY,
3552 };
3553
3554 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
3555
3556 m = key_setsadbmsg(type, 0, satype, seq, pid, sav->refcnt);
3557 if (m == NULL)
3558 goto fail;
3559 result = m;
3560
3561 for (i = sizeof(dumporder)/sizeof(dumporder[0]) - 1; i >= 0; i--) {
3562 m = NULL;
3563 p = NULL;
3564 switch (dumporder[i]) {
3565 case SADB_EXT_SA:
3566 m = key_setsadbsa(sav);
3567 if (!m)
3568 goto fail;
3569 break;
3570
3571 case SADB_X_EXT_SA2:
3572 m = key_setsadbxsa2(sav->sah->saidx.mode,
3573 sav->replay ? sav->replay->count : 0,
3574 sav->sah->saidx.reqid);
3575 if (!m)
3576 goto fail;
3577 break;
3578
3579 case SADB_EXT_ADDRESS_SRC:
3580 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
3581 (struct sockaddr *)&sav->sah->saidx.src,
3582 FULLMASK, IPSEC_ULPROTO_ANY);
3583 if (!m)
3584 goto fail;
3585 break;
3586
3587 case SADB_EXT_ADDRESS_DST:
3588 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
3589 (struct sockaddr *)&sav->sah->saidx.dst,
3590 FULLMASK, IPSEC_ULPROTO_ANY);
3591 if (!m)
3592 goto fail;
3593 break;
3594
3595 case SADB_EXT_KEY_AUTH:
3596 if (!sav->key_auth)
3597 continue;
3598 l = PFKEY_UNUNIT64(sav->key_auth->sadb_key_len);
3599 p = sav->key_auth;
3600 break;
3601
3602 case SADB_EXT_KEY_ENCRYPT:
3603 if (!sav->key_enc)
3604 continue;
3605 l = PFKEY_UNUNIT64(sav->key_enc->sadb_key_len);
3606 p = sav->key_enc;
3607 break;
3608
3609 case SADB_EXT_LIFETIME_CURRENT:
3610 if (!sav->lft_c)
3611 continue;
3612 l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_c)->sadb_ext_len);
3613 p = sav->lft_c;
3614 break;
3615
3616 case SADB_EXT_LIFETIME_HARD:
3617 if (!sav->lft_h)
3618 continue;
3619 l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_h)->sadb_ext_len);
3620 p = sav->lft_h;
3621 break;
3622
3623 case SADB_EXT_LIFETIME_SOFT:
3624 if (!sav->lft_s)
3625 continue;
3626 l = PFKEY_UNUNIT64(((struct sadb_ext *)sav->lft_s)->sadb_ext_len);
3627 p = sav->lft_s;
3628 break;
3629
3630 case SADB_EXT_ADDRESS_PROXY:
3631 case SADB_EXT_IDENTITY_SRC:
3632 case SADB_EXT_IDENTITY_DST:
3633 /* XXX: should we brought from SPD ? */
3634 case SADB_EXT_SENSITIVITY:
3635 default:
3636 continue;
3637 }
3638
3639 if ((!m && !p) || (m && p))
3640 goto fail;
3641 if (p && tres) {
3642 M_PREPEND(tres, l, M_DONTWAIT);
3643 if (!tres)
3644 goto fail;
3645 bcopy(p, mtod(tres, caddr_t), l);
3646 continue;
3647 }
3648 if (p) {
3649 m = key_alloc_mbuf(l);
3650 if (!m)
3651 goto fail;
3652 m_copyback(m, 0, l, p);
3653 }
3654
3655 if (tres)
3656 m_cat(m, tres);
3657 tres = m;
3658 }
3659
3660 m_cat(result, tres);
3661
3662 if (result->m_len < sizeof(struct sadb_msg)) {
3663 result = m_pullup(result, sizeof(struct sadb_msg));
3664 if (result == NULL)
3665 goto fail;
3666 }
3667
3668 result->m_pkthdr.len = 0;
3669 for (m = result; m; m = m->m_next)
3670 result->m_pkthdr.len += m->m_len;
3671
3672 mtod(result, struct sadb_msg *)->sadb_msg_len =
3673 PFKEY_UNIT64(result->m_pkthdr.len);
3674
3675 return result;
3676
3677 fail:
3678 m_freem(result);
3679 m_freem(tres);
3680 return NULL;
3681 }
3682
3683 /*
3684 * set data into sadb_msg.
3685 */
3686 static struct mbuf *
3687 key_setsadbmsg(type, tlen, satype, seq, pid, reserved)
3688 u_int8_t type, satype;
3689 u_int16_t tlen;
3690 u_int32_t seq;
3691 pid_t pid;
3692 u_int16_t reserved;
3693 {
3694 struct mbuf *m;
3695 struct sadb_msg *p;
3696 int len;
3697
3698 len = PFKEY_ALIGN8(sizeof(struct sadb_msg));
3699 if (len > MCLBYTES)
3700 return NULL;
3701 MGETHDR(m, M_DONTWAIT, MT_DATA);
3702 if (m && len > MHLEN) {
3703 MCLGET(m, M_DONTWAIT);
3704 if ((m->m_flags & M_EXT) == 0) {
3705 m_freem(m);
3706 m = NULL;
3707 }
3708 }
3709 if (!m)
3710 return NULL;
3711 m->m_pkthdr.len = m->m_len = len;
3712 m->m_next = NULL;
3713
3714 p = mtod(m, struct sadb_msg *);
3715
3716 bzero(p, len);
3717 p->sadb_msg_version = PF_KEY_V2;
3718 p->sadb_msg_type = type;
3719 p->sadb_msg_errno = 0;
3720 p->sadb_msg_satype = satype;
3721 p->sadb_msg_len = PFKEY_UNIT64(tlen);
3722 p->sadb_msg_reserved = reserved;
3723 p->sadb_msg_seq = seq;
3724 p->sadb_msg_pid = (u_int32_t)pid;
3725
3726 return m;
3727 }
3728
3729 /*
3730 * copy secasvar data into sadb_address.
3731 */
3732 static struct mbuf *
3733 key_setsadbsa(sav)
3734 struct secasvar *sav;
3735 {
3736 struct mbuf *m;
3737 struct sadb_sa *p;
3738 int len;
3739
3740 len = PFKEY_ALIGN8(sizeof(struct sadb_sa));
3741 m = key_alloc_mbuf(len);
3742 if (!m || m->m_next) { /*XXX*/
3743 if (m)
3744 m_freem(m);
3745 return NULL;
3746 }
3747
3748 p = mtod(m, struct sadb_sa *);
3749
3750 bzero(p, len);
3751 p->sadb_sa_len = PFKEY_UNIT64(len);
3752 p->sadb_sa_exttype = SADB_EXT_SA;
3753 p->sadb_sa_spi = sav->spi;
3754 p->sadb_sa_replay = (sav->replay != NULL ? sav->replay->wsize : 0);
3755 p->sadb_sa_state = sav->state;
3756 p->sadb_sa_auth = sav->alg_auth;
3757 p->sadb_sa_encrypt = sav->alg_enc;
3758 p->sadb_sa_flags = sav->flags;
3759
3760 return m;
3761 }
3762
3763 /*
3764 * set data into sadb_address.
3765 */
3766 static struct mbuf *
3767 key_setsadbaddr(exttype, saddr, prefixlen, ul_proto)
3768 u_int16_t exttype;
3769 struct sockaddr *saddr;
3770 u_int8_t prefixlen;
3771 u_int16_t ul_proto;
3772 {
3773 struct mbuf *m;
3774 struct sadb_address *p;
3775 size_t len;
3776
3777 len = PFKEY_ALIGN8(sizeof(struct sadb_address)) +
3778 PFKEY_ALIGN8(saddr->sa_len);
3779 m = key_alloc_mbuf(len);
3780 if (!m || m->m_next) { /*XXX*/
3781 if (m)
3782 m_freem(m);
3783 return NULL;
3784 }
3785
3786 p = mtod(m, struct sadb_address *);
3787
3788 bzero(p, len);
3789 p->sadb_address_len = PFKEY_UNIT64(len);
3790 p->sadb_address_exttype = exttype;
3791 p->sadb_address_proto = ul_proto;
3792 if (prefixlen == FULLMASK) {
3793 switch (saddr->sa_family) {
3794 case AF_INET:
3795 prefixlen = sizeof(struct in_addr) << 3;
3796 break;
3797 case AF_INET6:
3798 prefixlen = sizeof(struct in6_addr) << 3;
3799 break;
3800 default:
3801 ; /*XXX*/
3802 }
3803 }
3804 p->sadb_address_prefixlen = prefixlen;
3805 p->sadb_address_reserved = 0;
3806
3807 bcopy(saddr,
3808 mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_address)),
3809 saddr->sa_len);
3810
3811 return m;
3812 }
3813
3814 #if 0
3815 /*
3816 * set data into sadb_ident.
3817 */
3818 static struct mbuf *
3819 key_setsadbident(exttype, idtype, string, stringlen, id)
3820 u_int16_t exttype, idtype;
3821 caddr_t string;
3822 int stringlen;
3823 u_int64_t id;
3824 {
3825 struct mbuf *m;
3826 struct sadb_ident *p;
3827 size_t len;
3828
3829 len = PFKEY_ALIGN8(sizeof(struct sadb_ident)) + PFKEY_ALIGN8(stringlen);
3830 m = key_alloc_mbuf(len);
3831 if (!m || m->m_next) { /*XXX*/
3832 if (m)
3833 m_freem(m);
3834 return NULL;
3835 }
3836
3837 p = mtod(m, struct sadb_ident *);
3838
3839 bzero(p, len);
3840 p->sadb_ident_len = PFKEY_UNIT64(len);
3841 p->sadb_ident_exttype = exttype;
3842 p->sadb_ident_type = idtype;
3843 p->sadb_ident_reserved = 0;
3844 p->sadb_ident_id = id;
3845
3846 bcopy(string,
3847 mtod(m, caddr_t) + PFKEY_ALIGN8(sizeof(struct sadb_ident)),
3848 stringlen);
3849
3850 return m;
3851 }
3852 #endif
3853
3854 /*
3855 * set data into sadb_x_sa2.
3856 */
3857 static struct mbuf *
3858 key_setsadbxsa2(mode, seq, reqid)
3859 u_int8_t mode;
3860 u_int32_t seq, reqid;
3861 {
3862 struct mbuf *m;
3863 struct sadb_x_sa2 *p;
3864 size_t len;
3865
3866 len = PFKEY_ALIGN8(sizeof(struct sadb_x_sa2));
3867 m = key_alloc_mbuf(len);
3868 if (!m || m->m_next) { /*XXX*/
3869 if (m)
3870 m_freem(m);
3871 return NULL;
3872 }
3873
3874 p = mtod(m, struct sadb_x_sa2 *);
3875
3876 bzero(p, len);
3877 p->sadb_x_sa2_len = PFKEY_UNIT64(len);
3878 p->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
3879 p->sadb_x_sa2_mode = mode;
3880 p->sadb_x_sa2_reserved1 = 0;
3881 p->sadb_x_sa2_reserved2 = 0;
3882 p->sadb_x_sa2_sequence = seq;
3883 p->sadb_x_sa2_reqid = reqid;
3884
3885 return m;
3886 }
3887
3888 /*
3889 * set data into sadb_x_policy
3890 */
3891 static struct mbuf *
3892 key_setsadbxpolicy(type, dir, id)
3893 u_int16_t type;
3894 u_int8_t dir;
3895 u_int32_t id;
3896 {
3897 struct mbuf *m;
3898 struct sadb_x_policy *p;
3899 size_t len;
3900
3901 len = PFKEY_ALIGN8(sizeof(struct sadb_x_policy));
3902 m = key_alloc_mbuf(len);
3903 if (!m || m->m_next) { /*XXX*/
3904 if (m)
3905 m_freem(m);
3906 return NULL;
3907 }
3908
3909 p = mtod(m, struct sadb_x_policy *);
3910
3911 bzero(p, len);
3912 p->sadb_x_policy_len = PFKEY_UNIT64(len);
3913 p->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3914 p->sadb_x_policy_type = type;
3915 p->sadb_x_policy_dir = dir;
3916 p->sadb_x_policy_id = id;
3917
3918 return m;
3919 }
3920
3921 /* %%% utilities */
3922 /*
3923 * copy a buffer into the new buffer allocated.
3924 */
3925 static void *
3926 key_newbuf(src, len)
3927 const void *src;
3928 u_int len;
3929 {
3930 caddr_t new;
3931
3932 KMALLOC(new, caddr_t, len);
3933 if (new == NULL) {
3934 ipseclog((LOG_DEBUG, "key_newbuf: No more memory.\n"));
3935 return NULL;
3936 }
3937 bcopy(src, new, len);
3938
3939 return new;
3940 }
3941
3942 /* compare my own address
3943 * OUT: 1: true, i.e. my address.
3944 * 0: false
3945 */
3946 int
3947 key_ismyaddr(sa)
3948 struct sockaddr *sa;
3949 {
3950 #if INET
3951 struct sockaddr_in *sin;
3952 struct in_ifaddr *ia;
3953 #endif
3954
3955 /* sanity check */
3956 if (sa == NULL)
3957 panic("key_ismyaddr: NULL pointer is passed.\n");
3958
3959 switch (sa->sa_family) {
3960 #if INET
3961 case AF_INET:
3962 lck_mtx_lock(rt_mtx);
3963 sin = (struct sockaddr_in *)sa;
3964 for (ia = in_ifaddrhead.tqh_first; ia;
3965 ia = ia->ia_link.tqe_next)
3966 {
3967 if (sin->sin_family == ia->ia_addr.sin_family &&
3968 sin->sin_len == ia->ia_addr.sin_len &&
3969 sin->sin_addr.s_addr == ia->ia_addr.sin_addr.s_addr)
3970 {
3971 lck_mtx_unlock(rt_mtx);
3972 return 1;
3973 }
3974 }
3975 lck_mtx_unlock(rt_mtx);
3976 break;
3977 #endif
3978 #if INET6
3979 case AF_INET6:
3980 return key_ismyaddr6((struct sockaddr_in6 *)sa);
3981 #endif
3982 }
3983
3984 return 0;
3985 }
3986
3987 #if INET6
3988 /*
3989 * compare my own address for IPv6.
3990 * 1: ours
3991 * 0: other
3992 * NOTE: derived ip6_input() in KAME. This is necessary to modify more.
3993 */
3994 #include <netinet6/in6_var.h>
3995
3996 static int
3997 key_ismyaddr6(sin6)
3998 struct sockaddr_in6 *sin6;
3999 {
4000 struct in6_ifaddr *ia;
4001 struct in6_multi *in6m;
4002
4003 lck_mtx_lock(nd6_mutex);
4004 for (ia = in6_ifaddrs; ia; ia = ia->ia_next) {
4005 if (key_sockaddrcmp((struct sockaddr *)&sin6,
4006 (struct sockaddr *)&ia->ia_addr, 0) == 0) {
4007 lck_mtx_unlock(nd6_mutex);
4008 return 1;
4009 }
4010
4011 /*
4012 * XXX Multicast
4013 * XXX why do we care about multlicast here while we don't care
4014 * about IPv4 multicast??
4015 * XXX scope
4016 */
4017 in6m = NULL;
4018 IN6_LOOKUP_MULTI(sin6->sin6_addr, ia->ia_ifp, in6m);
4019 if (in6m) {
4020 lck_mtx_unlock(nd6_mutex);
4021 return 1;
4022 }
4023 }
4024 lck_mtx_unlock(nd6_mutex);
4025
4026 /* loopback, just for safety */
4027 if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))
4028 return 1;
4029
4030 return 0;
4031 }
4032 #endif /*INET6*/
4033
4034 /*
4035 * compare two secasindex structure.
4036 * flag can specify to compare 2 saidxes.
4037 * compare two secasindex structure without both mode and reqid.
4038 * don't compare port.
4039 * IN:
4040 * saidx0: source, it can be in SAD.
4041 * saidx1: object.
4042 * OUT:
4043 * 1 : equal
4044 * 0 : not equal
4045 */
4046 static int
4047 key_cmpsaidx(saidx0, saidx1, flag)
4048 struct secasindex *saidx0, *saidx1;
4049 int flag;
4050 {
4051 /* sanity */
4052 if (saidx0 == NULL && saidx1 == NULL)
4053 return 1;
4054
4055 if (saidx0 == NULL || saidx1 == NULL)
4056 return 0;
4057
4058 if (saidx0->proto != saidx1->proto)
4059 return 0;
4060
4061 if (flag == CMP_EXACTLY) {
4062 if (saidx0->mode != saidx1->mode)
4063 return 0;
4064 if (saidx0->reqid != saidx1->reqid)
4065 return 0;
4066 if (bcmp(&saidx0->src, &saidx1->src, saidx0->src.ss_len) != 0 ||
4067 bcmp(&saidx0->dst, &saidx1->dst, saidx0->dst.ss_len) != 0)
4068 return 0;
4069 } else {
4070
4071 /* CMP_MODE_REQID, CMP_REQID, CMP_HEAD */
4072 if (flag == CMP_MODE_REQID
4073 ||flag == CMP_REQID) {
4074 /*
4075 * If reqid of SPD is non-zero, unique SA is required.
4076 * The result must be of same reqid in this case.
4077 */
4078 if (saidx1->reqid != 0 && saidx0->reqid != saidx1->reqid)
4079 return 0;
4080 }
4081
4082 if (flag == CMP_MODE_REQID) {
4083 if (saidx0->mode != IPSEC_MODE_ANY
4084 && saidx0->mode != saidx1->mode)
4085 return 0;
4086 }
4087
4088 if (key_sockaddrcmp((struct sockaddr *)&saidx0->src,
4089 (struct sockaddr *)&saidx1->src, 0) != 0) {
4090 return 0;
4091 }
4092 if (key_sockaddrcmp((struct sockaddr *)&saidx0->dst,
4093 (struct sockaddr *)&saidx1->dst, 0) != 0) {
4094 return 0;
4095 }
4096 }
4097
4098 return 1;
4099 }
4100
4101 /*
4102 * compare two secindex structure exactly.
4103 * IN:
4104 * spidx0: source, it is often in SPD.
4105 * spidx1: object, it is often from PFKEY message.
4106 * OUT:
4107 * 1 : equal
4108 * 0 : not equal
4109 */
4110 static int
4111 key_cmpspidx_exactly(spidx0, spidx1)
4112 struct secpolicyindex *spidx0, *spidx1;
4113 {
4114 /* sanity */
4115 if (spidx0 == NULL && spidx1 == NULL)
4116 return 1;
4117
4118 if (spidx0 == NULL || spidx1 == NULL)
4119 return 0;
4120
4121 if (spidx0->prefs != spidx1->prefs
4122 || spidx0->prefd != spidx1->prefd
4123 || spidx0->ul_proto != spidx1->ul_proto)
4124 return 0;
4125
4126 if (key_sockaddrcmp((struct sockaddr *)&spidx0->src,
4127 (struct sockaddr *)&spidx1->src, 1) != 0) {
4128 return 0;
4129 }
4130 if (key_sockaddrcmp((struct sockaddr *)&spidx0->dst,
4131 (struct sockaddr *)&spidx1->dst, 1) != 0) {
4132 return 0;
4133 }
4134
4135 return 1;
4136 }
4137
4138 /*
4139 * compare two secindex structure with mask.
4140 * IN:
4141 * spidx0: source, it is often in SPD.
4142 * spidx1: object, it is often from IP header.
4143 * OUT:
4144 * 1 : equal
4145 * 0 : not equal
4146 */
4147 static int
4148 key_cmpspidx_withmask(spidx0, spidx1)
4149 struct secpolicyindex *spidx0, *spidx1;
4150 {
4151 /* sanity */
4152 if (spidx0 == NULL && spidx1 == NULL)
4153 return 1;
4154
4155 if (spidx0 == NULL || spidx1 == NULL)
4156 return 0;
4157
4158 if (spidx0->src.ss_family != spidx1->src.ss_family ||
4159 spidx0->dst.ss_family != spidx1->dst.ss_family ||
4160 spidx0->src.ss_len != spidx1->src.ss_len ||
4161 spidx0->dst.ss_len != spidx1->dst.ss_len)
4162 return 0;
4163
4164 /* if spidx.ul_proto == IPSEC_ULPROTO_ANY, ignore. */
4165 if (spidx0->ul_proto != (u_int16_t)IPSEC_ULPROTO_ANY
4166 && spidx0->ul_proto != spidx1->ul_proto)
4167 return 0;
4168
4169 switch (spidx0->src.ss_family) {
4170 case AF_INET:
4171 if (satosin(&spidx0->src)->sin_port != IPSEC_PORT_ANY
4172 && satosin(&spidx0->src)->sin_port !=
4173 satosin(&spidx1->src)->sin_port)
4174 return 0;
4175 if (!key_bbcmp((caddr_t)&satosin(&spidx0->src)->sin_addr,
4176 (caddr_t)&satosin(&spidx1->src)->sin_addr, spidx0->prefs))
4177 return 0;
4178 break;
4179 case AF_INET6:
4180 if (satosin6(&spidx0->src)->sin6_port != IPSEC_PORT_ANY
4181 && satosin6(&spidx0->src)->sin6_port !=
4182 satosin6(&spidx1->src)->sin6_port)
4183 return 0;
4184 /*
4185 * scope_id check. if sin6_scope_id is 0, we regard it
4186 * as a wildcard scope, which matches any scope zone ID.
4187 */
4188 if (satosin6(&spidx0->src)->sin6_scope_id &&
4189 satosin6(&spidx1->src)->sin6_scope_id &&
4190 satosin6(&spidx0->src)->sin6_scope_id !=
4191 satosin6(&spidx1->src)->sin6_scope_id)
4192 return 0;
4193 if (!key_bbcmp((caddr_t)&satosin6(&spidx0->src)->sin6_addr,
4194 (caddr_t)&satosin6(&spidx1->src)->sin6_addr, spidx0->prefs))
4195 return 0;
4196 break;
4197 default:
4198 /* XXX */
4199 if (bcmp(&spidx0->src, &spidx1->src, spidx0->src.ss_len) != 0)
4200 return 0;
4201 break;
4202 }
4203
4204 switch (spidx0->dst.ss_family) {
4205 case AF_INET:
4206 if (satosin(&spidx0->dst)->sin_port != IPSEC_PORT_ANY
4207 && satosin(&spidx0->dst)->sin_port !=
4208 satosin(&spidx1->dst)->sin_port)
4209 return 0;
4210 if (!key_bbcmp((caddr_t)&satosin(&spidx0->dst)->sin_addr,
4211 (caddr_t)&satosin(&spidx1->dst)->sin_addr, spidx0->prefd))
4212 return 0;
4213 break;
4214 case AF_INET6:
4215 if (satosin6(&spidx0->dst)->sin6_port != IPSEC_PORT_ANY
4216 && satosin6(&spidx0->dst)->sin6_port !=
4217 satosin6(&spidx1->dst)->sin6_port)
4218 return 0;
4219 /*
4220 * scope_id check. if sin6_scope_id is 0, we regard it
4221 * as a wildcard scope, which matches any scope zone ID.
4222 */
4223 if (satosin6(&spidx0->src)->sin6_scope_id &&
4224 satosin6(&spidx1->src)->sin6_scope_id &&
4225 satosin6(&spidx0->dst)->sin6_scope_id !=
4226 satosin6(&spidx1->dst)->sin6_scope_id)
4227 return 0;
4228 if (!key_bbcmp((caddr_t)&satosin6(&spidx0->dst)->sin6_addr,
4229 (caddr_t)&satosin6(&spidx1->dst)->sin6_addr, spidx0->prefd))
4230 return 0;
4231 break;
4232 default:
4233 /* XXX */
4234 if (bcmp(&spidx0->dst, &spidx1->dst, spidx0->dst.ss_len) != 0)
4235 return 0;
4236 break;
4237 }
4238
4239 /* XXX Do we check other field ? e.g. flowinfo */
4240
4241 return 1;
4242 }
4243
4244 /* returns 0 on match */
4245 static int
4246 key_sockaddrcmp(sa1, sa2, port)
4247 struct sockaddr *sa1;
4248 struct sockaddr *sa2;
4249 int port;
4250 {
4251 if (sa1->sa_family != sa2->sa_family || sa1->sa_len != sa2->sa_len)
4252 return 1;
4253
4254 switch (sa1->sa_family) {
4255 case AF_INET:
4256 if (sa1->sa_len != sizeof(struct sockaddr_in))
4257 return 1;
4258 if (satosin(sa1)->sin_addr.s_addr !=
4259 satosin(sa2)->sin_addr.s_addr) {
4260 return 1;
4261 }
4262 if (port && satosin(sa1)->sin_port != satosin(sa2)->sin_port)
4263 return 1;
4264 break;
4265 case AF_INET6:
4266 if (sa1->sa_len != sizeof(struct sockaddr_in6))
4267 return 1; /*EINVAL*/
4268 if (satosin6(sa1)->sin6_scope_id !=
4269 satosin6(sa2)->sin6_scope_id) {
4270 return 1;
4271 }
4272 if (!IN6_ARE_ADDR_EQUAL(&satosin6(sa1)->sin6_addr,
4273 &satosin6(sa2)->sin6_addr)) {
4274 return 1;
4275 }
4276 if (port &&
4277 satosin6(sa1)->sin6_port != satosin6(sa2)->sin6_port) {
4278 return 1;
4279 }
4280 default:
4281 if (bcmp(sa1, sa2, sa1->sa_len) != 0)
4282 return 1;
4283 break;
4284 }
4285
4286 return 0;
4287 }
4288
4289 /*
4290 * compare two buffers with mask.
4291 * IN:
4292 * addr1: source
4293 * addr2: object
4294 * bits: Number of bits to compare
4295 * OUT:
4296 * 1 : equal
4297 * 0 : not equal
4298 */
4299 static int
4300 key_bbcmp(p1, p2, bits)
4301 caddr_t p1, p2;
4302 u_int bits;
4303 {
4304 u_int8_t mask;
4305
4306 /* XXX: This could be considerably faster if we compare a word
4307 * at a time, but it is complicated on LSB Endian machines */
4308
4309 /* Handle null pointers */
4310 if (p1 == NULL || p2 == NULL)
4311 return (p1 == p2);
4312
4313 while (bits >= 8) {
4314 if (*p1++ != *p2++)
4315 return 0;
4316 bits -= 8;
4317 }
4318
4319 if (bits > 0) {
4320 mask = ~((1<<(8-bits))-1);
4321 if ((*p1 & mask) != (*p2 & mask))
4322 return 0;
4323 }
4324 return 1; /* Match! */
4325 }
4326
4327 /*
4328 * time handler.
4329 * scanning SPD and SAD to check status for each entries,
4330 * and do to remove or to expire.
4331 * XXX: year 2038 problem may remain.
4332 */
4333
4334 void
4335 key_timehandler(void)
4336 {
4337 u_int dir;
4338 int s;
4339 struct timeval tv;
4340
4341 microtime(&tv);
4342
4343 lck_mtx_lock(sadb_mutex);
4344 /* SPD */
4345 {
4346 struct secpolicy *sp, *nextsp;
4347
4348 for (dir = 0; dir < IPSEC_DIR_MAX; dir++) {
4349 for (sp = LIST_FIRST(&sptree[dir]);
4350 sp != NULL;
4351 sp = nextsp) {
4352
4353 nextsp = LIST_NEXT(sp, chain);
4354
4355 if (sp->state == IPSEC_SPSTATE_DEAD) {
4356 key_freesp(sp);
4357 continue;
4358 }
4359
4360 if (sp->lifetime == 0 && sp->validtime == 0)
4361 continue;
4362
4363 /* the deletion will occur next time */
4364 if ((sp->lifetime
4365 && tv.tv_sec - sp->created > sp->lifetime)
4366 || (sp->validtime
4367 && tv.tv_sec - sp->lastused > sp->validtime)) {
4368 sp->state = IPSEC_SPSTATE_DEAD;
4369 key_spdexpire(sp);
4370 continue;
4371 }
4372 }
4373 }
4374 }
4375
4376 /* SAD */
4377 {
4378 struct secashead *sah, *nextsah;
4379 struct secasvar *sav, *nextsav;
4380
4381 for (sah = LIST_FIRST(&sahtree);
4382 sah != NULL;
4383 sah = nextsah) {
4384
4385 nextsah = LIST_NEXT(sah, chain);
4386
4387 /* if sah has been dead, then delete it and process next sah. */
4388 if (sah->state == SADB_SASTATE_DEAD) {
4389 key_delsah(sah);
4390 continue;
4391 }
4392
4393 /* if LARVAL entry doesn't become MATURE, delete it. */
4394 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_LARVAL]);
4395 sav != NULL;
4396 sav = nextsav) {
4397
4398 nextsav = LIST_NEXT(sav, chain);
4399
4400 if (tv.tv_sec - sav->created > key_larval_lifetime) {
4401 key_freesav(sav);
4402 }
4403 }
4404
4405 /*
4406 * If this is a NAT traversal SA with no activity,
4407 * we need to send a keep alive.
4408 *
4409 * Performed outside of the loop before so we will
4410 * only ever send one keepalive. The first SA on
4411 * the list is the one that will be used for sending
4412 * traffic, so this is the one we use for determining
4413 * when to send the keepalive.
4414 */
4415 sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_MATURE]);
4416 if (natt_keepalive_interval && sav && (sav->flags & SADB_X_EXT_NATT_KEEPALIVE) != 0 &&
4417 (natt_now - sav->natt_last_activity) >= natt_keepalive_interval) {
4418 ipsec_send_natt_keepalive(sav);
4419 }
4420
4421 /*
4422 * check MATURE entry to start to send expire message
4423 * whether or not.
4424 */
4425 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_MATURE]);
4426 sav != NULL;
4427 sav = nextsav) {
4428
4429 nextsav = LIST_NEXT(sav, chain);
4430
4431 /* we don't need to check. */
4432 if (sav->lft_s == NULL)
4433 continue;
4434
4435 /* sanity check */
4436 if (sav->lft_c == NULL) {
4437 ipseclog((LOG_DEBUG,"key_timehandler: "
4438 "There is no CURRENT time, why?\n"));
4439 continue;
4440 }
4441
4442 /* check SOFT lifetime */
4443 if (sav->lft_s->sadb_lifetime_addtime != 0
4444 && tv.tv_sec - sav->created > sav->lft_s->sadb_lifetime_addtime) {
4445 /*
4446 * check the SA if it has been used.
4447 * when it hasn't been used, delete it.
4448 * i don't think such SA will be used.
4449 */
4450 if (sav->lft_c->sadb_lifetime_usetime == 0) {
4451 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4452 key_freesav(sav);
4453 sav = NULL;
4454 } else {
4455 key_sa_chgstate(sav, SADB_SASTATE_DYING);
4456 /*
4457 * XXX If we keep to send expire
4458 * message in the status of
4459 * DYING. Do remove below code.
4460 */
4461 key_expire(sav);
4462 }
4463 }
4464
4465 /* check SOFT lifetime by bytes */
4466 /*
4467 * XXX I don't know the way to delete this SA
4468 * when new SA is installed. Caution when it's
4469 * installed too big lifetime by time.
4470 */
4471 else if (sav->lft_s->sadb_lifetime_bytes != 0
4472 && sav->lft_s->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
4473
4474 key_sa_chgstate(sav, SADB_SASTATE_DYING);
4475 /*
4476 * XXX If we keep to send expire
4477 * message in the status of
4478 * DYING. Do remove below code.
4479 */
4480 key_expire(sav);
4481 }
4482 }
4483
4484 /* check DYING entry to change status to DEAD. */
4485 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DYING]);
4486 sav != NULL;
4487 sav = nextsav) {
4488
4489 nextsav = LIST_NEXT(sav, chain);
4490
4491 /* we don't need to check. */
4492 if (sav->lft_h == NULL)
4493 continue;
4494
4495 /* sanity check */
4496 if (sav->lft_c == NULL) {
4497 ipseclog((LOG_DEBUG, "key_timehandler: "
4498 "There is no CURRENT time, why?\n"));
4499 continue;
4500 }
4501
4502 if (sav->lft_h->sadb_lifetime_addtime != 0
4503 && tv.tv_sec - sav->created > sav->lft_h->sadb_lifetime_addtime) {
4504 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4505 key_freesav(sav);
4506 sav = NULL;
4507 }
4508 #if 0 /* XXX Should we keep to send expire message until HARD lifetime ? */
4509 else if (sav->lft_s != NULL
4510 && sav->lft_s->sadb_lifetime_addtime != 0
4511 && tv.tv_sec - sav->created > sav->lft_s->sadb_lifetime_addtime) {
4512 /*
4513 * XXX: should be checked to be
4514 * installed the valid SA.
4515 */
4516
4517 /*
4518 * If there is no SA then sending
4519 * expire message.
4520 */
4521 key_expire(sav);
4522 }
4523 #endif
4524 /* check HARD lifetime by bytes */
4525 else if (sav->lft_h->sadb_lifetime_bytes != 0
4526 && sav->lft_h->sadb_lifetime_bytes < sav->lft_c->sadb_lifetime_bytes) {
4527 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
4528 key_freesav(sav);
4529 sav = NULL;
4530 }
4531 }
4532
4533 /* delete entry in DEAD */
4534 for (sav = LIST_FIRST(&sah->savtree[SADB_SASTATE_DEAD]);
4535 sav != NULL;
4536 sav = nextsav) {
4537
4538 nextsav = LIST_NEXT(sav, chain);
4539
4540 /* sanity check */
4541 if (sav->state != SADB_SASTATE_DEAD) {
4542 ipseclog((LOG_DEBUG, "key_timehandler: "
4543 "invalid sav->state "
4544 "(queue: %d SA: %d): "
4545 "kill it anyway\n",
4546 SADB_SASTATE_DEAD, sav->state));
4547 }
4548
4549 /*
4550 * do not call key_freesav() here.
4551 * sav should already be freed, and sav->refcnt
4552 * shows other references to sav
4553 * (such as from SPD).
4554 */
4555 }
4556 }
4557 }
4558
4559 #ifndef IPSEC_NONBLOCK_ACQUIRE
4560 /* ACQ tree */
4561 {
4562 struct secacq *acq, *nextacq;
4563
4564 for (acq = LIST_FIRST(&acqtree);
4565 acq != NULL;
4566 acq = nextacq) {
4567
4568 nextacq = LIST_NEXT(acq, chain);
4569
4570 if (tv.tv_sec - acq->created > key_blockacq_lifetime
4571 && __LIST_CHAINED(acq)) {
4572 LIST_REMOVE(acq, chain);
4573 KFREE(acq);
4574 }
4575 }
4576 }
4577 #endif
4578
4579 /* SP ACQ tree */
4580 {
4581 struct secspacq *acq, *nextacq;
4582
4583 for (acq = LIST_FIRST(&spacqtree);
4584 acq != NULL;
4585 acq = nextacq) {
4586
4587 nextacq = LIST_NEXT(acq, chain);
4588
4589 if (tv.tv_sec - acq->created > key_blockacq_lifetime
4590 && __LIST_CHAINED(acq)) {
4591 LIST_REMOVE(acq, chain);
4592 KFREE(acq);
4593 }
4594 }
4595 }
4596
4597 /* initialize random seed */
4598 if (key_tick_init_random++ > key_int_random) {
4599 key_tick_init_random = 0;
4600 key_srandom();
4601 }
4602
4603 natt_now++;
4604
4605 lck_mtx_unlock(sadb_mutex);
4606 #ifndef IPSEC_DEBUG2
4607 /* do exchange to tick time !! */
4608 (void)timeout((void *)key_timehandler, (void *)0, hz);
4609 #endif /* IPSEC_DEBUG2 */
4610
4611 return;
4612 }
4613
4614 /*
4615 * to initialize a seed for random()
4616 */
4617 static void
4618 key_srandom()
4619 {
4620 #ifdef __APPLE__
4621 /* Our PRNG is based on Yarrow and doesn't need to be seeded */
4622 random();
4623 #else
4624 struct timeval tv;
4625
4626 microtime(&tv);
4627
4628 srandom(tv.tv_usec);
4629 #endif
4630
4631 return;
4632 }
4633
4634 u_long
4635 key_random()
4636 {
4637 u_long value;
4638
4639 key_randomfill(&value, sizeof(value));
4640 return value;
4641 }
4642
4643 void
4644 key_randomfill(p, l)
4645 void *p;
4646 size_t l;
4647 {
4648 size_t n;
4649 u_long v;
4650 static int warn = 1;
4651 #ifdef __APPLE__
4652
4653 read_random(p, (u_int)l);
4654 #else
4655 n = 0;
4656 n = (size_t)read_random(p, (u_int)l);
4657 /* last resort */
4658 while (n < l) {
4659 v = random();
4660 bcopy(&v, (u_int8_t *)p + n,
4661 l - n < sizeof(v) ? l - n : sizeof(v));
4662 n += sizeof(v);
4663
4664 if (warn) {
4665 printf("WARNING: pseudo-random number generator "
4666 "used for IPsec processing\n");
4667 warn = 0;
4668 }
4669 }
4670 #endif
4671 }
4672
4673 /*
4674 * map SADB_SATYPE_* to IPPROTO_*.
4675 * if satype == SADB_SATYPE then satype is mapped to ~0.
4676 * OUT:
4677 * 0: invalid satype.
4678 */
4679 static u_int16_t
4680 key_satype2proto(satype)
4681 u_int8_t satype;
4682 {
4683 switch (satype) {
4684 case SADB_SATYPE_UNSPEC:
4685 return IPSEC_PROTO_ANY;
4686 case SADB_SATYPE_AH:
4687 return IPPROTO_AH;
4688 case SADB_SATYPE_ESP:
4689 return IPPROTO_ESP;
4690 case SADB_X_SATYPE_IPCOMP:
4691 return IPPROTO_IPCOMP;
4692 break;
4693 default:
4694 return 0;
4695 }
4696 /* NOTREACHED */
4697 }
4698
4699 /*
4700 * map IPPROTO_* to SADB_SATYPE_*
4701 * OUT:
4702 * 0: invalid protocol type.
4703 */
4704 static u_int8_t
4705 key_proto2satype(proto)
4706 u_int16_t proto;
4707 {
4708 switch (proto) {
4709 case IPPROTO_AH:
4710 return SADB_SATYPE_AH;
4711 case IPPROTO_ESP:
4712 return SADB_SATYPE_ESP;
4713 case IPPROTO_IPCOMP:
4714 return SADB_X_SATYPE_IPCOMP;
4715 break;
4716 default:
4717 return 0;
4718 }
4719 /* NOTREACHED */
4720 }
4721
4722 /* %%% PF_KEY */
4723 /*
4724 * SADB_GETSPI processing is to receive
4725 * <base, (SA2), src address, dst address, (SPI range)>
4726 * from the IKMPd, to assign a unique spi value, to hang on the INBOUND
4727 * tree with the status of LARVAL, and send
4728 * <base, SA(*), address(SD)>
4729 * to the IKMPd.
4730 *
4731 * IN: mhp: pointer to the pointer to each header.
4732 * OUT: NULL if fail.
4733 * other if success, return pointer to the message to send.
4734 */
4735 static int
4736 key_getspi(so, m, mhp)
4737 struct socket *so;
4738 struct mbuf *m;
4739 const struct sadb_msghdr *mhp;
4740 {
4741 struct sadb_address *src0, *dst0;
4742 struct secasindex saidx;
4743 struct secashead *newsah;
4744 struct secasvar *newsav;
4745 u_int8_t proto;
4746 u_int32_t spi;
4747 u_int8_t mode;
4748 u_int32_t reqid;
4749 int error;
4750
4751 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
4752
4753 /* sanity check */
4754 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
4755 panic("key_getspi: NULL pointer is passed.\n");
4756
4757 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
4758 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
4759 ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
4760 return key_senderror(so, m, EINVAL);
4761 }
4762 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
4763 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
4764 ipseclog((LOG_DEBUG, "key_getspi: invalid message is passed.\n"));
4765 return key_senderror(so, m, EINVAL);
4766 }
4767 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
4768 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
4769 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
4770 } else {
4771 mode = IPSEC_MODE_ANY;
4772 reqid = 0;
4773 }
4774
4775 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
4776 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
4777
4778 /* map satype to proto */
4779 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
4780 ipseclog((LOG_DEBUG, "key_getspi: invalid satype is passed.\n"));
4781 return key_senderror(so, m, EINVAL);
4782 }
4783
4784 /* make sure if port number is zero. */
4785 switch (((struct sockaddr *)(src0 + 1))->sa_family) {
4786 case AF_INET:
4787 if (((struct sockaddr *)(src0 + 1))->sa_len !=
4788 sizeof(struct sockaddr_in))
4789 return key_senderror(so, m, EINVAL);
4790 ((struct sockaddr_in *)(src0 + 1))->sin_port = 0;
4791 break;
4792 case AF_INET6:
4793 if (((struct sockaddr *)(src0 + 1))->sa_len !=
4794 sizeof(struct sockaddr_in6))
4795 return key_senderror(so, m, EINVAL);
4796 ((struct sockaddr_in6 *)(src0 + 1))->sin6_port = 0;
4797 break;
4798 default:
4799 ; /*???*/
4800 }
4801 switch (((struct sockaddr *)(dst0 + 1))->sa_family) {
4802 case AF_INET:
4803 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4804 sizeof(struct sockaddr_in))
4805 return key_senderror(so, m, EINVAL);
4806 ((struct sockaddr_in *)(dst0 + 1))->sin_port = 0;
4807 break;
4808 case AF_INET6:
4809 if (((struct sockaddr *)(dst0 + 1))->sa_len !=
4810 sizeof(struct sockaddr_in6))
4811 return key_senderror(so, m, EINVAL);
4812 ((struct sockaddr_in6 *)(dst0 + 1))->sin6_port = 0;
4813 break;
4814 default:
4815 ; /*???*/
4816 }
4817
4818 /* XXX boundary check against sa_len */
4819 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
4820
4821 /* SPI allocation */
4822 spi = key_do_getnewspi((struct sadb_spirange *)mhp->ext[SADB_EXT_SPIRANGE],
4823 &saidx);
4824 if (spi == 0)
4825 return key_senderror(so, m, EINVAL);
4826
4827 /* get a SA index */
4828 if ((newsah = key_getsah(&saidx)) == NULL) {
4829 /* create a new SA index */
4830 if ((newsah = key_newsah(&saidx)) == NULL) {
4831 ipseclog((LOG_DEBUG, "key_getspi: No more memory.\n"));
4832 return key_senderror(so, m, ENOBUFS);
4833 }
4834 }
4835
4836 /* get a new SA */
4837 /* XXX rewrite */
4838 newsav = key_newsav(m, mhp, newsah, &error);
4839 if (newsav == NULL) {
4840 /* XXX don't free new SA index allocated in above. */
4841 return key_senderror(so, m, error);
4842 }
4843
4844 /* set spi */
4845 key_setspi(newsav, htonl(spi));
4846
4847 #ifndef IPSEC_NONBLOCK_ACQUIRE
4848 /* delete the entry in acqtree */
4849 if (mhp->msg->sadb_msg_seq != 0) {
4850 struct secacq *acq;
4851 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) != NULL) {
4852 /* reset counter in order to deletion by timehandler. */
4853 struct timeval tv;
4854 microtime(&tv);
4855 acq->created = tv.tv_sec;
4856 acq->count = 0;
4857 }
4858 }
4859 #endif
4860
4861 {
4862 struct mbuf *n, *nn;
4863 struct sadb_sa *m_sa;
4864 struct sadb_msg *newmsg;
4865 int off, len;
4866
4867 /* create new sadb_msg to reply. */
4868 len = PFKEY_ALIGN8(sizeof(struct sadb_msg)) +
4869 PFKEY_ALIGN8(sizeof(struct sadb_sa));
4870 if (len > MCLBYTES)
4871 return key_senderror(so, m, ENOBUFS);
4872
4873 MGETHDR(n, M_DONTWAIT, MT_DATA);
4874 if (len > MHLEN) {
4875 MCLGET(n, M_DONTWAIT);
4876 if ((n->m_flags & M_EXT) == 0) {
4877 m_freem(n);
4878 n = NULL;
4879 }
4880 }
4881 if (!n)
4882 return key_senderror(so, m, ENOBUFS);
4883
4884 n->m_len = len;
4885 n->m_next = NULL;
4886 off = 0;
4887
4888 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
4889 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
4890
4891 m_sa = (struct sadb_sa *)(mtod(n, caddr_t) + off);
4892 m_sa->sadb_sa_len = PFKEY_UNIT64(sizeof(struct sadb_sa));
4893 m_sa->sadb_sa_exttype = SADB_EXT_SA;
4894 m_sa->sadb_sa_spi = htonl(spi);
4895 off += PFKEY_ALIGN8(sizeof(struct sadb_sa));
4896
4897 #if DIAGNOSTIC
4898 if (off != len)
4899 panic("length inconsistency in key_getspi");
4900 #endif
4901 {
4902 int mbufItems[] = {SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST};
4903 n->m_next = key_gather_mbuf(m, mhp, 0, sizeof(mbufItems)/sizeof(int), mbufItems);
4904 if (!n->m_next) {
4905 m_freem(n);
4906 return key_senderror(so, m, ENOBUFS);
4907 }
4908 }
4909
4910 if (n->m_len < sizeof(struct sadb_msg)) {
4911 n = m_pullup(n, sizeof(struct sadb_msg));
4912 if (n == NULL)
4913 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
4914 }
4915
4916 n->m_pkthdr.len = 0;
4917 for (nn = n; nn; nn = nn->m_next)
4918 n->m_pkthdr.len += nn->m_len;
4919
4920 newmsg = mtod(n, struct sadb_msg *);
4921 newmsg->sadb_msg_seq = newsav->seq;
4922 newmsg->sadb_msg_errno = 0;
4923 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
4924
4925 m_freem(m);
4926 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
4927 }
4928 }
4929
4930 /*
4931 * allocating new SPI
4932 * called by key_getspi().
4933 * OUT:
4934 * 0: failure.
4935 * others: success.
4936 */
4937 static u_int32_t
4938 key_do_getnewspi(spirange, saidx)
4939 struct sadb_spirange *spirange;
4940 struct secasindex *saidx;
4941 {
4942 u_int32_t newspi;
4943 u_int32_t min, max;
4944 int count = key_spi_trycnt;
4945
4946 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
4947
4948 /* set spi range to allocate */
4949 if (spirange != NULL) {
4950 min = spirange->sadb_spirange_min;
4951 max = spirange->sadb_spirange_max;
4952 } else {
4953 min = key_spi_minval;
4954 max = key_spi_maxval;
4955 }
4956 /* IPCOMP needs 2-byte SPI */
4957 if (saidx->proto == IPPROTO_IPCOMP) {
4958 u_int32_t t;
4959 if (min >= 0x10000)
4960 min = 0xffff;
4961 if (max >= 0x10000)
4962 max = 0xffff;
4963 if (min > max) {
4964 t = min; min = max; max = t;
4965 }
4966 }
4967
4968 if (min == max) {
4969 if (key_checkspidup(saidx, min) != NULL) {
4970 ipseclog((LOG_DEBUG, "key_do_getnewspi: SPI %u exists already.\n", min));
4971 return 0;
4972 }
4973
4974 count--; /* taking one cost. */
4975 newspi = min;
4976
4977 } else {
4978
4979 /* init SPI */
4980 newspi = 0;
4981
4982 /* when requesting to allocate spi ranged */
4983 while (count--) {
4984 /* generate pseudo-random SPI value ranged. */
4985 newspi = min + (key_random() % (max - min + 1));
4986
4987 if (key_checkspidup(saidx, newspi) == NULL)
4988 break;
4989 }
4990
4991 if (count == 0 || newspi == 0) {
4992 ipseclog((LOG_DEBUG, "key_do_getnewspi: to allocate spi is failed.\n"));
4993 return 0;
4994 }
4995 }
4996
4997 /* statistics */
4998 keystat.getspi_count =
4999 (keystat.getspi_count + key_spi_trycnt - count) / 2;
5000
5001 return newspi;
5002 }
5003
5004 /*
5005 * SADB_UPDATE processing
5006 * receive
5007 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5008 * key(AE), (identity(SD),) (sensitivity)>
5009 * from the ikmpd, and update a secasvar entry whose status is SADB_SASTATE_LARVAL.
5010 * and send
5011 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5012 * (identity(SD),) (sensitivity)>
5013 * to the ikmpd.
5014 *
5015 * m will always be freed.
5016 */
5017 static int
5018 key_update(so, m, mhp)
5019 struct socket *so;
5020 struct mbuf *m;
5021 const struct sadb_msghdr *mhp;
5022 {
5023 struct sadb_sa *sa0;
5024 struct sadb_address *src0, *dst0;
5025 struct secasindex saidx;
5026 struct secashead *sah;
5027 struct secasvar *sav;
5028 u_int16_t proto;
5029 u_int8_t mode;
5030 u_int32_t reqid;
5031 int error;
5032
5033 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
5034
5035 /* sanity check */
5036 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5037 panic("key_update: NULL pointer is passed.\n");
5038
5039 /* map satype to proto */
5040 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5041 ipseclog((LOG_DEBUG, "key_update: invalid satype is passed.\n"));
5042 return key_senderror(so, m, EINVAL);
5043 }
5044
5045 if (mhp->ext[SADB_EXT_SA] == NULL ||
5046 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5047 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5048 (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5049 mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5050 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5051 mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5052 (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5053 mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5054 (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5055 mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5056 ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
5057 return key_senderror(so, m, EINVAL);
5058 }
5059 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5060 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5061 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5062 ipseclog((LOG_DEBUG, "key_update: invalid message is passed.\n"));
5063 return key_senderror(so, m, EINVAL);
5064 }
5065 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5066 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5067 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5068 } else {
5069 mode = IPSEC_MODE_ANY;
5070 reqid = 0;
5071 }
5072 /* XXX boundary checking for other extensions */
5073
5074 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5075 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5076 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5077
5078 /* XXX boundary check against sa_len */
5079 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5080
5081 /* get a SA header */
5082 if ((sah = key_getsah(&saidx)) == NULL) {
5083 ipseclog((LOG_DEBUG, "key_update: no SA index found.\n"));
5084 return key_senderror(so, m, ENOENT);
5085 }
5086
5087 /* set spidx if there */
5088 /* XXX rewrite */
5089 error = key_setident(sah, m, mhp);
5090 if (error)
5091 return key_senderror(so, m, error);
5092
5093 /* find a SA with sequence number. */
5094 #if IPSEC_DOSEQCHECK
5095 if (mhp->msg->sadb_msg_seq != 0
5096 && (sav = key_getsavbyseq(sah, mhp->msg->sadb_msg_seq)) == NULL) {
5097 ipseclog((LOG_DEBUG,
5098 "key_update: no larval SA with sequence %u exists.\n",
5099 mhp->msg->sadb_msg_seq));
5100 return key_senderror(so, m, ENOENT);
5101 }
5102 #else
5103 if ((sav = key_getsavbyspi(sah, sa0->sadb_sa_spi)) == NULL) {
5104 ipseclog((LOG_DEBUG,
5105 "key_update: no such a SA found (spi:%u)\n",
5106 (u_int32_t)ntohl(sa0->sadb_sa_spi)));
5107 return key_senderror(so, m, EINVAL);
5108 }
5109 #endif
5110
5111 /* validity check */
5112 if (sav->sah->saidx.proto != proto) {
5113 ipseclog((LOG_DEBUG,
5114 "key_update: protocol mismatched (DB=%u param=%u)\n",
5115 sav->sah->saidx.proto, proto));
5116 return key_senderror(so, m, EINVAL);
5117 }
5118 #if IPSEC_DOSEQCHECK
5119 if (sav->spi != sa0->sadb_sa_spi) {
5120 ipseclog((LOG_DEBUG,
5121 "key_update: SPI mismatched (DB:%u param:%u)\n",
5122 (u_int32_t)ntohl(sav->spi),
5123 (u_int32_t)ntohl(sa0->sadb_sa_spi)));
5124 return key_senderror(so, m, EINVAL);
5125 }
5126 #endif
5127 if (sav->pid != mhp->msg->sadb_msg_pid) {
5128 ipseclog((LOG_DEBUG,
5129 "key_update: pid mismatched (DB:%u param:%u)\n",
5130 sav->pid, mhp->msg->sadb_msg_pid));
5131 return key_senderror(so, m, EINVAL);
5132 }
5133
5134 /* copy sav values */
5135 error = key_setsaval(sav, m, mhp);
5136 if (error) {
5137 key_freesav(sav);
5138 return key_senderror(so, m, error);
5139 }
5140
5141 /* check SA values to be mature. */
5142 if ((error = key_mature(sav)) != 0) {
5143 key_freesav(sav);
5144 return key_senderror(so, m, error);
5145 }
5146
5147 {
5148 struct mbuf *n;
5149
5150 /* set msg buf from mhp */
5151 n = key_getmsgbuf_x1(m, mhp);
5152 if (n == NULL) {
5153 ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
5154 return key_senderror(so, m, ENOBUFS);
5155 }
5156
5157 m_freem(m);
5158 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5159 }
5160 }
5161
5162 /*
5163 * search SAD with sequence for a SA which state is SADB_SASTATE_LARVAL.
5164 * only called by key_update().
5165 * OUT:
5166 * NULL : not found
5167 * others : found, pointer to a SA.
5168 */
5169 #if IPSEC_DOSEQCHECK
5170 static struct secasvar *
5171 key_getsavbyseq(sah, seq)
5172 struct secashead *sah;
5173 u_int32_t seq;
5174 {
5175 struct secasvar *sav;
5176 u_int state;
5177
5178 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
5179
5180 state = SADB_SASTATE_LARVAL;
5181
5182 /* search SAD with sequence number ? */
5183 LIST_FOREACH(sav, &sah->savtree[state], chain) {
5184
5185 KEY_CHKSASTATE(state, sav->state, "key_getsabyseq");
5186
5187 if (sav->seq == seq) {
5188 sav->refcnt++;
5189 KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
5190 printf("DP key_getsavbyseq cause "
5191 "refcnt++:%d SA:%p\n",
5192 sav->refcnt, sav));
5193 return sav;
5194 }
5195 }
5196
5197 return NULL;
5198 }
5199 #endif
5200
5201 /*
5202 * SADB_ADD processing
5203 * add a entry to SA database, when received
5204 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5205 * key(AE), (identity(SD),) (sensitivity)>
5206 * from the ikmpd,
5207 * and send
5208 * <base, SA, (SA2), (lifetime(HSC),) address(SD), (address(P),)
5209 * (identity(SD),) (sensitivity)>
5210 * to the ikmpd.
5211 *
5212 * IGNORE identity and sensitivity messages.
5213 *
5214 * m will always be freed.
5215 */
5216 static int
5217 key_add(so, m, mhp)
5218 struct socket *so;
5219 struct mbuf *m;
5220 const struct sadb_msghdr *mhp;
5221 {
5222 struct sadb_sa *sa0;
5223 struct sadb_address *src0, *dst0;
5224 struct secasindex saidx;
5225 struct secashead *newsah;
5226 struct secasvar *newsav;
5227 u_int16_t proto;
5228 u_int8_t mode;
5229 u_int32_t reqid;
5230 int error;
5231
5232 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
5233
5234 /* sanity check */
5235 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5236 panic("key_add: NULL pointer is passed.\n");
5237
5238 /* map satype to proto */
5239 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5240 ipseclog((LOG_DEBUG, "key_add: invalid satype is passed.\n"));
5241 return key_senderror(so, m, EINVAL);
5242 }
5243
5244 if (mhp->ext[SADB_EXT_SA] == NULL ||
5245 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5246 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
5247 (mhp->msg->sadb_msg_satype == SADB_SATYPE_ESP &&
5248 mhp->ext[SADB_EXT_KEY_ENCRYPT] == NULL) ||
5249 (mhp->msg->sadb_msg_satype == SADB_SATYPE_AH &&
5250 mhp->ext[SADB_EXT_KEY_AUTH] == NULL) ||
5251 (mhp->ext[SADB_EXT_LIFETIME_HARD] != NULL &&
5252 mhp->ext[SADB_EXT_LIFETIME_SOFT] == NULL) ||
5253 (mhp->ext[SADB_EXT_LIFETIME_HARD] == NULL &&
5254 mhp->ext[SADB_EXT_LIFETIME_SOFT] != NULL)) {
5255 ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
5256 return key_senderror(so, m, EINVAL);
5257 }
5258 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5259 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5260 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5261 /* XXX need more */
5262 ipseclog((LOG_DEBUG, "key_add: invalid message is passed.\n"));
5263 return key_senderror(so, m, EINVAL);
5264 }
5265 if (mhp->ext[SADB_X_EXT_SA2] != NULL) {
5266 mode = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_mode;
5267 reqid = ((struct sadb_x_sa2 *)mhp->ext[SADB_X_EXT_SA2])->sadb_x_sa2_reqid;
5268 } else {
5269 mode = IPSEC_MODE_ANY;
5270 reqid = 0;
5271 }
5272
5273 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5274 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5275 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5276
5277 /* XXX boundary check against sa_len */
5278 KEY_SETSECASIDX(proto, mode, reqid, src0 + 1, dst0 + 1, &saidx);
5279
5280 /* get a SA header */
5281 if ((newsah = key_getsah(&saidx)) == NULL) {
5282 /* create a new SA header */
5283 if ((newsah = key_newsah(&saidx)) == NULL) {
5284 ipseclog((LOG_DEBUG, "key_add: No more memory.\n"));
5285 return key_senderror(so, m, ENOBUFS);
5286 }
5287 }
5288
5289 /* set spidx if there */
5290 /* XXX rewrite */
5291 error = key_setident(newsah, m, mhp);
5292 if (error) {
5293 return key_senderror(so, m, error);
5294 }
5295
5296 /* create new SA entry. */
5297 /* We can create new SA only if SPI is differenct. */
5298 if (key_getsavbyspi(newsah, sa0->sadb_sa_spi)) {
5299 ipseclog((LOG_DEBUG, "key_add: SA already exists.\n"));
5300 return key_senderror(so, m, EEXIST);
5301 }
5302 newsav = key_newsav(m, mhp, newsah, &error);
5303 if (newsav == NULL) {
5304 return key_senderror(so, m, error);
5305 }
5306
5307 /* check SA values to be mature. */
5308 if ((error = key_mature(newsav)) != 0) {
5309 key_freesav(newsav);
5310 return key_senderror(so, m, error);
5311 }
5312
5313 /*
5314 * don't call key_freesav() here, as we would like to keep the SA
5315 * in the database on success.
5316 */
5317
5318 {
5319 struct mbuf *n;
5320
5321 /* set msg buf from mhp */
5322 n = key_getmsgbuf_x1(m, mhp);
5323 if (n == NULL) {
5324 ipseclog((LOG_DEBUG, "key_update: No more memory.\n"));
5325 return key_senderror(so, m, ENOBUFS);
5326 }
5327
5328 m_freem(m);
5329 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5330 }
5331 }
5332
5333 /* m is retained */
5334 static int
5335 key_setident(sah, m, mhp)
5336 struct secashead *sah;
5337 struct mbuf *m;
5338 const struct sadb_msghdr *mhp;
5339 {
5340 const struct sadb_ident *idsrc, *iddst;
5341 int idsrclen, iddstlen;
5342
5343 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
5344
5345 /* sanity check */
5346 if (sah == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5347 panic("key_setident: NULL pointer is passed.\n");
5348
5349 /* don't make buffer if not there */
5350 if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL &&
5351 mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5352 sah->idents = NULL;
5353 sah->identd = NULL;
5354 return 0;
5355 }
5356
5357 if (mhp->ext[SADB_EXT_IDENTITY_SRC] == NULL ||
5358 mhp->ext[SADB_EXT_IDENTITY_DST] == NULL) {
5359 ipseclog((LOG_DEBUG, "key_setident: invalid identity.\n"));
5360 return EINVAL;
5361 }
5362
5363 idsrc = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_SRC];
5364 iddst = (const struct sadb_ident *)mhp->ext[SADB_EXT_IDENTITY_DST];
5365 idsrclen = mhp->extlen[SADB_EXT_IDENTITY_SRC];
5366 iddstlen = mhp->extlen[SADB_EXT_IDENTITY_DST];
5367
5368 /* validity check */
5369 if (idsrc->sadb_ident_type != iddst->sadb_ident_type) {
5370 ipseclog((LOG_DEBUG, "key_setident: ident type mismatch.\n"));
5371 return EINVAL;
5372 }
5373
5374 switch (idsrc->sadb_ident_type) {
5375 case SADB_IDENTTYPE_PREFIX:
5376 case SADB_IDENTTYPE_FQDN:
5377 case SADB_IDENTTYPE_USERFQDN:
5378 default:
5379 /* XXX do nothing */
5380 sah->idents = NULL;
5381 sah->identd = NULL;
5382 return 0;
5383 }
5384
5385 /* make structure */
5386 KMALLOC(sah->idents, struct sadb_ident *, idsrclen);
5387 if (sah->idents == NULL) {
5388 ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
5389 return ENOBUFS;
5390 }
5391 KMALLOC(sah->identd, struct sadb_ident *, iddstlen);
5392 if (sah->identd == NULL) {
5393 KFREE(sah->idents);
5394 sah->idents = NULL;
5395 ipseclog((LOG_DEBUG, "key_setident: No more memory.\n"));
5396 return ENOBUFS;
5397 }
5398 bcopy(idsrc, sah->idents, idsrclen);
5399 bcopy(iddst, sah->identd, iddstlen);
5400
5401 return 0;
5402 }
5403
5404 /*
5405 * m will not be freed on return.
5406 * it is caller's responsibility to free the result.
5407 */
5408 static struct mbuf *
5409 key_getmsgbuf_x1(m, mhp)
5410 struct mbuf *m;
5411 const struct sadb_msghdr *mhp;
5412 {
5413 struct mbuf *n;
5414 int mbufItems[] = {SADB_EXT_RESERVED, SADB_EXT_SA,
5415 SADB_X_EXT_SA2, SADB_EXT_ADDRESS_SRC,
5416 SADB_EXT_ADDRESS_DST, SADB_EXT_LIFETIME_HARD,
5417 SADB_EXT_LIFETIME_SOFT, SADB_EXT_IDENTITY_SRC,
5418 SADB_EXT_IDENTITY_DST};
5419
5420 /* sanity check */
5421 if (m == NULL || mhp == NULL || mhp->msg == NULL)
5422 panic("key_getmsgbuf_x1: NULL pointer is passed.\n");
5423
5424 /* create new sadb_msg to reply. */
5425 n = key_gather_mbuf(m, mhp, 1, sizeof(mbufItems)/sizeof(int), mbufItems);
5426 if (!n)
5427 return NULL;
5428
5429 if (n->m_len < sizeof(struct sadb_msg)) {
5430 n = m_pullup(n, sizeof(struct sadb_msg));
5431 if (n == NULL)
5432 return NULL;
5433 }
5434 mtod(n, struct sadb_msg *)->sadb_msg_errno = 0;
5435 mtod(n, struct sadb_msg *)->sadb_msg_len =
5436 PFKEY_UNIT64(n->m_pkthdr.len);
5437
5438 return n;
5439 }
5440
5441 static int key_delete_all(struct socket *, struct mbuf *,
5442 const struct sadb_msghdr *, u_int16_t);
5443
5444 /*
5445 * SADB_DELETE processing
5446 * receive
5447 * <base, SA(*), address(SD)>
5448 * from the ikmpd, and set SADB_SASTATE_DEAD,
5449 * and send,
5450 * <base, SA(*), address(SD)>
5451 * to the ikmpd.
5452 *
5453 * m will always be freed.
5454 */
5455 static int
5456 key_delete(so, m, mhp)
5457 struct socket *so;
5458 struct mbuf *m;
5459 const struct sadb_msghdr *mhp;
5460 {
5461 struct sadb_sa *sa0;
5462 struct sadb_address *src0, *dst0;
5463 struct secasindex saidx;
5464 struct secashead *sah;
5465 struct secasvar *sav = NULL;
5466 u_int16_t proto;
5467
5468 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
5469
5470 /* sanity check */
5471 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5472 panic("key_delete: NULL pointer is passed.\n");
5473
5474 /* map satype to proto */
5475 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5476 ipseclog((LOG_DEBUG, "key_delete: invalid satype is passed.\n"));
5477 return key_senderror(so, m, EINVAL);
5478 }
5479
5480 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5481 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5482 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
5483 return key_senderror(so, m, EINVAL);
5484 }
5485
5486 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5487 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5488 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
5489 return key_senderror(so, m, EINVAL);
5490 }
5491
5492 if (mhp->ext[SADB_EXT_SA] == NULL) {
5493 /*
5494 * Caller wants us to delete all non-LARVAL SAs
5495 * that match the src/dst. This is used during
5496 * IKE INITIAL-CONTACT.
5497 */
5498 ipseclog((LOG_DEBUG, "key_delete: doing delete all.\n"));
5499 return key_delete_all(so, m, mhp, proto);
5500 } else if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa)) {
5501 ipseclog((LOG_DEBUG, "key_delete: invalid message is passed.\n"));
5502 return key_senderror(so, m, EINVAL);
5503 }
5504
5505 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5506 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5507 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5508
5509 /* XXX boundary check against sa_len */
5510 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5511
5512 /* get a SA header */
5513 LIST_FOREACH(sah, &sahtree, chain) {
5514 if (sah->state == SADB_SASTATE_DEAD)
5515 continue;
5516 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5517 continue;
5518
5519 /* get a SA with SPI. */
5520 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5521 if (sav)
5522 break;
5523 }
5524 if (sah == NULL) {
5525 ipseclog((LOG_DEBUG, "key_delete: no SA found.\n"));
5526 return key_senderror(so, m, ENOENT);
5527 }
5528
5529 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5530 key_freesav(sav);
5531 sav = NULL;
5532
5533 {
5534 struct mbuf *n;
5535 struct sadb_msg *newmsg;
5536 int mbufItems[] = {SADB_EXT_RESERVED, SADB_EXT_SA,
5537 SADB_EXT_ADDRESS_SRC, SADB_EXT_ADDRESS_DST};
5538
5539 /* create new sadb_msg to reply. */
5540 n = key_gather_mbuf(m, mhp, 1, sizeof(mbufItems)/sizeof(int), mbufItems);
5541 if (!n)
5542 return key_senderror(so, m, ENOBUFS);
5543
5544 if (n->m_len < sizeof(struct sadb_msg)) {
5545 n = m_pullup(n, sizeof(struct sadb_msg));
5546 if (n == NULL)
5547 return key_senderror(so, m, ENOBUFS);
5548 }
5549 newmsg = mtod(n, struct sadb_msg *);
5550 newmsg->sadb_msg_errno = 0;
5551 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5552
5553 m_freem(m);
5554 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5555 }
5556 }
5557
5558 /*
5559 * delete all SAs for src/dst. Called from key_delete().
5560 */
5561 static int
5562 key_delete_all(so, m, mhp, proto)
5563 struct socket *so;
5564 struct mbuf *m;
5565 const struct sadb_msghdr *mhp;
5566 u_int16_t proto;
5567 {
5568 struct sadb_address *src0, *dst0;
5569 struct secasindex saidx;
5570 struct secashead *sah;
5571 struct secasvar *sav, *nextsav;
5572 u_int stateidx, state;
5573
5574 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
5575
5576 src0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_SRC]);
5577 dst0 = (struct sadb_address *)(mhp->ext[SADB_EXT_ADDRESS_DST]);
5578
5579 /* XXX boundary check against sa_len */
5580 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5581
5582 LIST_FOREACH(sah, &sahtree, chain) {
5583 if (sah->state == SADB_SASTATE_DEAD)
5584 continue;
5585 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5586 continue;
5587
5588 /* Delete all non-LARVAL SAs. */
5589 for (stateidx = 0;
5590 stateidx < _ARRAYLEN(saorder_state_alive);
5591 stateidx++) {
5592 state = saorder_state_alive[stateidx];
5593 if (state == SADB_SASTATE_LARVAL)
5594 continue;
5595 for (sav = LIST_FIRST(&sah->savtree[state]);
5596 sav != NULL; sav = nextsav) {
5597 nextsav = LIST_NEXT(sav, chain);
5598 /* sanity check */
5599 if (sav->state != state) {
5600 ipseclog((LOG_DEBUG, "key_delete_all: "
5601 "invalid sav->state "
5602 "(queue: %d SA: %d)\n",
5603 state, sav->state));
5604 continue;
5605 }
5606
5607 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
5608 key_freesav(sav);
5609 }
5610 }
5611 }
5612 {
5613 struct mbuf *n;
5614 struct sadb_msg *newmsg;
5615 int mbufItems[] = {SADB_EXT_RESERVED, SADB_EXT_ADDRESS_SRC,
5616 SADB_EXT_ADDRESS_DST};
5617
5618 /* create new sadb_msg to reply. */
5619 n = key_gather_mbuf(m, mhp, 1, sizeof(mbufItems)/sizeof(int), mbufItems);
5620 if (!n)
5621 return key_senderror(so, m, ENOBUFS);
5622
5623 if (n->m_len < sizeof(struct sadb_msg)) {
5624 n = m_pullup(n, sizeof(struct sadb_msg));
5625 if (n == NULL)
5626 return key_senderror(so, m, ENOBUFS);
5627 }
5628 newmsg = mtod(n, struct sadb_msg *);
5629 newmsg->sadb_msg_errno = 0;
5630 newmsg->sadb_msg_len = PFKEY_UNIT64(n->m_pkthdr.len);
5631
5632 m_freem(m);
5633 return key_sendup_mbuf(so, n, KEY_SENDUP_ALL);
5634 }
5635 }
5636
5637 /*
5638 * SADB_GET processing
5639 * receive
5640 * <base, SA(*), address(SD)>
5641 * from the ikmpd, and get a SP and a SA to respond,
5642 * and send,
5643 * <base, SA, (lifetime(HSC),) address(SD), (address(P),) key(AE),
5644 * (identity(SD),) (sensitivity)>
5645 * to the ikmpd.
5646 *
5647 * m will always be freed.
5648 */
5649 static int
5650 key_get(so, m, mhp)
5651 struct socket *so;
5652 struct mbuf *m;
5653 const struct sadb_msghdr *mhp;
5654 {
5655 struct sadb_sa *sa0;
5656 struct sadb_address *src0, *dst0;
5657 struct secasindex saidx;
5658 struct secashead *sah;
5659 struct secasvar *sav = NULL;
5660 u_int16_t proto;
5661
5662 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
5663
5664 /* sanity check */
5665 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
5666 panic("key_get: NULL pointer is passed.\n");
5667
5668 /* map satype to proto */
5669 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
5670 ipseclog((LOG_DEBUG, "key_get: invalid satype is passed.\n"));
5671 return key_senderror(so, m, EINVAL);
5672 }
5673
5674 if (mhp->ext[SADB_EXT_SA] == NULL ||
5675 mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
5676 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL) {
5677 ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
5678 return key_senderror(so, m, EINVAL);
5679 }
5680 if (mhp->extlen[SADB_EXT_SA] < sizeof(struct sadb_sa) ||
5681 mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
5682 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address)) {
5683 ipseclog((LOG_DEBUG, "key_get: invalid message is passed.\n"));
5684 return key_senderror(so, m, EINVAL);
5685 }
5686
5687 sa0 = (struct sadb_sa *)mhp->ext[SADB_EXT_SA];
5688 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
5689 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
5690
5691 /* XXX boundary check against sa_len */
5692 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
5693
5694 /* get a SA header */
5695 LIST_FOREACH(sah, &sahtree, chain) {
5696 if (sah->state == SADB_SASTATE_DEAD)
5697 continue;
5698 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_HEAD) == 0)
5699 continue;
5700
5701 /* get a SA with SPI. */
5702 sav = key_getsavbyspi(sah, sa0->sadb_sa_spi);
5703 if (sav)
5704 break;
5705 }
5706 if (sah == NULL) {
5707 ipseclog((LOG_DEBUG, "key_get: no SA found.\n"));
5708 return key_senderror(so, m, ENOENT);
5709 }
5710
5711 {
5712 struct mbuf *n;
5713 u_int8_t satype;
5714
5715 /* map proto to satype */
5716 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
5717 ipseclog((LOG_DEBUG, "key_get: there was invalid proto in SAD.\n"));
5718 return key_senderror(so, m, EINVAL);
5719 }
5720
5721 /* create new sadb_msg to reply. */
5722 n = key_setdumpsa(sav, SADB_GET, satype, mhp->msg->sadb_msg_seq,
5723 mhp->msg->sadb_msg_pid);
5724 if (!n)
5725 return key_senderror(so, m, ENOBUFS);
5726
5727 m_freem(m);
5728 return key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
5729 }
5730 }
5731
5732 /* XXX make it sysctl-configurable? */
5733 static void
5734 key_getcomb_setlifetime(comb)
5735 struct sadb_comb *comb;
5736 {
5737
5738 comb->sadb_comb_soft_allocations = 1;
5739 comb->sadb_comb_hard_allocations = 1;
5740 comb->sadb_comb_soft_bytes = 0;
5741 comb->sadb_comb_hard_bytes = 0;
5742 comb->sadb_comb_hard_addtime = 86400; /* 1 day */
5743 comb->sadb_comb_soft_addtime = comb->sadb_comb_soft_addtime * 80 / 100;
5744 comb->sadb_comb_soft_usetime = 28800; /* 8 hours */
5745 comb->sadb_comb_hard_usetime = comb->sadb_comb_hard_usetime * 80 / 100;
5746 }
5747
5748 #if IPSEC_ESP
5749 /*
5750 * XXX reorder combinations by preference
5751 * XXX no idea if the user wants ESP authentication or not
5752 */
5753 static struct mbuf *
5754 key_getcomb_esp()
5755 {
5756 struct sadb_comb *comb;
5757 const struct esp_algorithm *algo;
5758 struct mbuf *result = NULL, *m, *n;
5759 int encmin;
5760 int i, off, o;
5761 int totlen;
5762 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5763
5764 m = NULL;
5765 for (i = 1; i <= SADB_EALG_MAX; i++) {
5766 algo = esp_algorithm_lookup(i);
5767 if (!algo)
5768 continue;
5769
5770 if (algo->keymax < ipsec_esp_keymin)
5771 continue;
5772 if (algo->keymin < ipsec_esp_keymin)
5773 encmin = ipsec_esp_keymin;
5774 else
5775 encmin = algo->keymin;
5776
5777 if (ipsec_esp_auth)
5778 m = key_getcomb_ah();
5779 else {
5780 #if DIAGNOSTIC
5781 if (l > MLEN)
5782 panic("assumption failed in key_getcomb_esp");
5783 #endif
5784 MGET(m, M_DONTWAIT, MT_DATA);
5785 if (m) {
5786 M_ALIGN(m, l);
5787 m->m_len = l;
5788 m->m_next = NULL;
5789 bzero(mtod(m, caddr_t), m->m_len);
5790 }
5791 }
5792 if (!m)
5793 goto fail;
5794
5795 totlen = 0;
5796 for (n = m; n; n = n->m_next)
5797 totlen += n->m_len;
5798 #if DIAGNOSTIC
5799 if (totlen % l)
5800 panic("assumption failed in key_getcomb_esp");
5801 #endif
5802
5803 for (off = 0; off < totlen; off += l) {
5804 n = m_pulldown(m, off, l, &o);
5805 if (!n) {
5806 /* m is already freed */
5807 goto fail;
5808 }
5809 comb = (struct sadb_comb *)(mtod(n, caddr_t) + o);
5810 bzero(comb, sizeof(*comb));
5811 key_getcomb_setlifetime(comb);
5812 comb->sadb_comb_encrypt = i;
5813 comb->sadb_comb_encrypt_minbits = encmin;
5814 comb->sadb_comb_encrypt_maxbits = algo->keymax;
5815 }
5816
5817 if (!result)
5818 result = m;
5819 else
5820 m_cat(result, m);
5821 }
5822
5823 return result;
5824
5825 fail:
5826 if (result)
5827 m_freem(result);
5828 return NULL;
5829 }
5830 #endif
5831
5832 /*
5833 * XXX reorder combinations by preference
5834 */
5835 static struct mbuf *
5836 key_getcomb_ah()
5837 {
5838 struct sadb_comb *comb;
5839 const struct ah_algorithm *algo;
5840 struct mbuf *m;
5841 int min;
5842 int i;
5843 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5844
5845 m = NULL;
5846 for (i = 1; i <= SADB_AALG_MAX; i++) {
5847 #if 1
5848 /* we prefer HMAC algorithms, not old algorithms */
5849 if (i != SADB_AALG_SHA1HMAC && i != SADB_AALG_MD5HMAC)
5850 continue;
5851 #endif
5852 algo = ah_algorithm_lookup(i);
5853 if (!algo)
5854 continue;
5855
5856 if (algo->keymax < ipsec_ah_keymin)
5857 continue;
5858 if (algo->keymin < ipsec_ah_keymin)
5859 min = ipsec_ah_keymin;
5860 else
5861 min = algo->keymin;
5862
5863 if (!m) {
5864 #if DIAGNOSTIC
5865 if (l > MLEN)
5866 panic("assumption failed in key_getcomb_ah");
5867 #endif
5868 MGET(m, M_DONTWAIT, MT_DATA);
5869 if (m) {
5870 M_ALIGN(m, l);
5871 m->m_len = l;
5872 m->m_next = NULL;
5873 }
5874 } else
5875 M_PREPEND(m, l, M_DONTWAIT);
5876 if (!m)
5877 return NULL;
5878
5879 comb = mtod(m, struct sadb_comb *);
5880 bzero(comb, sizeof(*comb));
5881 key_getcomb_setlifetime(comb);
5882 comb->sadb_comb_auth = i;
5883 comb->sadb_comb_auth_minbits = min;
5884 comb->sadb_comb_auth_maxbits = algo->keymax;
5885 }
5886
5887 return m;
5888 }
5889
5890 /*
5891 * not really an official behavior. discussed in pf_key@inner.net in Sep2000.
5892 * XXX reorder combinations by preference
5893 */
5894 static struct mbuf *
5895 key_getcomb_ipcomp()
5896 {
5897 struct sadb_comb *comb;
5898 const struct ipcomp_algorithm *algo;
5899 struct mbuf *m;
5900 int i;
5901 const int l = PFKEY_ALIGN8(sizeof(struct sadb_comb));
5902
5903 m = NULL;
5904 for (i = 1; i <= SADB_X_CALG_MAX; i++) {
5905 algo = ipcomp_algorithm_lookup(i);
5906 if (!algo)
5907 continue;
5908
5909 if (!m) {
5910 #if DIAGNOSTIC
5911 if (l > MLEN)
5912 panic("assumption failed in key_getcomb_ipcomp");
5913 #endif
5914 MGET(m, M_DONTWAIT, MT_DATA);
5915 if (m) {
5916 M_ALIGN(m, l);
5917 m->m_len = l;
5918 m->m_next = NULL;
5919 }
5920 } else
5921 M_PREPEND(m, l, M_DONTWAIT);
5922 if (!m)
5923 return NULL;
5924
5925 comb = mtod(m, struct sadb_comb *);
5926 bzero(comb, sizeof(*comb));
5927 key_getcomb_setlifetime(comb);
5928 comb->sadb_comb_encrypt = i;
5929 /* what should we set into sadb_comb_*_{min,max}bits? */
5930 }
5931
5932 return m;
5933 }
5934
5935 /*
5936 * XXX no way to pass mode (transport/tunnel) to userland
5937 * XXX replay checking?
5938 * XXX sysctl interface to ipsec_{ah,esp}_keymin
5939 */
5940 static struct mbuf *
5941 key_getprop(saidx)
5942 const struct secasindex *saidx;
5943 {
5944 struct sadb_prop *prop;
5945 struct mbuf *m, *n;
5946 const int l = PFKEY_ALIGN8(sizeof(struct sadb_prop));
5947 int totlen;
5948
5949 switch (saidx->proto) {
5950 #if IPSEC_ESP
5951 case IPPROTO_ESP:
5952 m = key_getcomb_esp();
5953 break;
5954 #endif
5955 case IPPROTO_AH:
5956 m = key_getcomb_ah();
5957 break;
5958 case IPPROTO_IPCOMP:
5959 m = key_getcomb_ipcomp();
5960 break;
5961 default:
5962 return NULL;
5963 }
5964
5965 if (!m)
5966 return NULL;
5967 M_PREPEND(m, l, M_DONTWAIT);
5968 if (!m)
5969 return NULL;
5970
5971 totlen = 0;
5972 for (n = m; n; n = n->m_next)
5973 totlen += n->m_len;
5974
5975 prop = mtod(m, struct sadb_prop *);
5976 bzero(prop, sizeof(*prop));
5977 prop->sadb_prop_len = PFKEY_UNIT64(totlen);
5978 prop->sadb_prop_exttype = SADB_EXT_PROPOSAL;
5979 prop->sadb_prop_replay = 32; /* XXX */
5980
5981 return m;
5982 }
5983
5984 /*
5985 * SADB_ACQUIRE processing called by key_checkrequest() and key_acquire2().
5986 * send
5987 * <base, SA, address(SD), (address(P)), x_policy,
5988 * (identity(SD),) (sensitivity,) proposal>
5989 * to KMD, and expect to receive
5990 * <base> with SADB_ACQUIRE if error occurred,
5991 * or
5992 * <base, src address, dst address, (SPI range)> with SADB_GETSPI
5993 * from KMD by PF_KEY.
5994 *
5995 * XXX x_policy is outside of RFC2367 (KAME extension).
5996 * XXX sensitivity is not supported.
5997 * XXX for ipcomp, RFC2367 does not define how to fill in proposal.
5998 * see comment for key_getcomb_ipcomp().
5999 *
6000 * OUT:
6001 * 0 : succeed
6002 * others: error number
6003 */
6004 static int
6005 key_acquire(saidx, sp)
6006 struct secasindex *saidx;
6007 struct secpolicy *sp;
6008 {
6009 struct mbuf *result = NULL, *m;
6010 #ifndef IPSEC_NONBLOCK_ACQUIRE
6011 struct secacq *newacq;
6012 #endif
6013 u_int8_t satype;
6014 int error = -1;
6015 u_int32_t seq;
6016
6017 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
6018
6019 /* sanity check */
6020 if (saidx == NULL)
6021 panic("key_acquire: NULL pointer is passed.\n");
6022 if ((satype = key_proto2satype(saidx->proto)) == 0)
6023 panic("key_acquire: invalid proto is passed.\n");
6024
6025 #ifndef IPSEC_NONBLOCK_ACQUIRE
6026 /*
6027 * We never do anything about acquirng SA. There is anather
6028 * solution that kernel blocks to send SADB_ACQUIRE message until
6029 * getting something message from IKEd. In later case, to be
6030 * managed with ACQUIRING list.
6031 */
6032 /* get a entry to check whether sending message or not. */
6033 if ((newacq = key_getacq(saidx)) != NULL) {
6034 if (key_blockacq_count < newacq->count) {
6035 /* reset counter and do send message. */
6036 newacq->count = 0;
6037 } else {
6038 /* increment counter and do nothing. */
6039 newacq->count++;
6040 return 0;
6041 }
6042 } else {
6043 /* make new entry for blocking to send SADB_ACQUIRE. */
6044 if ((newacq = key_newacq(saidx)) == NULL)
6045 return ENOBUFS;
6046
6047 /* add to acqtree */
6048 LIST_INSERT_HEAD(&acqtree, newacq, chain);
6049 }
6050 #endif
6051
6052
6053 #ifndef IPSEC_NONBLOCK_ACQUIRE
6054 seq = newacq->seq;
6055 #else
6056 seq = (acq_seq = (acq_seq == ~0 ? 1 : ++acq_seq));
6057 #endif
6058 m = key_setsadbmsg(SADB_ACQUIRE, 0, satype, seq, 0, 0);
6059 if (!m) {
6060 error = ENOBUFS;
6061 goto fail;
6062 }
6063 result = m;
6064
6065 /* set sadb_address for saidx's. */
6066 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6067 (struct sockaddr *)&saidx->src, FULLMASK, IPSEC_ULPROTO_ANY);
6068 if (!m) {
6069 error = ENOBUFS;
6070 goto fail;
6071 }
6072 m_cat(result, m);
6073
6074 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6075 (struct sockaddr *)&saidx->dst, FULLMASK, IPSEC_ULPROTO_ANY);
6076 if (!m) {
6077 error = ENOBUFS;
6078 goto fail;
6079 }
6080 m_cat(result, m);
6081
6082 /* XXX proxy address (optional) */
6083
6084 /* set sadb_x_policy */
6085 if (sp) {
6086 m = key_setsadbxpolicy(sp->policy, sp->spidx.dir, sp->id);
6087 if (!m) {
6088 error = ENOBUFS;
6089 goto fail;
6090 }
6091 m_cat(result, m);
6092 }
6093
6094 /* XXX identity (optional) */
6095 #if 0
6096 if (idexttype && fqdn) {
6097 /* create identity extension (FQDN) */
6098 struct sadb_ident *id;
6099 int fqdnlen;
6100
6101 fqdnlen = strlen(fqdn) + 1; /* +1 for terminating-NUL */
6102 id = (struct sadb_ident *)p;
6103 bzero(id, sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6104 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(fqdnlen));
6105 id->sadb_ident_exttype = idexttype;
6106 id->sadb_ident_type = SADB_IDENTTYPE_FQDN;
6107 bcopy(fqdn, id + 1, fqdnlen);
6108 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(fqdnlen);
6109 }
6110
6111 if (idexttype) {
6112 /* create identity extension (USERFQDN) */
6113 struct sadb_ident *id;
6114 int userfqdnlen;
6115
6116 if (userfqdn) {
6117 /* +1 for terminating-NUL */
6118 userfqdnlen = strlen(userfqdn) + 1;
6119 } else
6120 userfqdnlen = 0;
6121 id = (struct sadb_ident *)p;
6122 bzero(id, sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6123 id->sadb_ident_len = PFKEY_UNIT64(sizeof(*id) + PFKEY_ALIGN8(userfqdnlen));
6124 id->sadb_ident_exttype = idexttype;
6125 id->sadb_ident_type = SADB_IDENTTYPE_USERFQDN;
6126 /* XXX is it correct? */
6127 if (curproc && curproc->p_cred)
6128 id->sadb_ident_id = curproc->p_cred->p_ruid;
6129 if (userfqdn && userfqdnlen)
6130 bcopy(userfqdn, id + 1, userfqdnlen);
6131 p += sizeof(struct sadb_ident) + PFKEY_ALIGN8(userfqdnlen);
6132 }
6133 #endif
6134
6135 /* XXX sensitivity (optional) */
6136
6137 /* create proposal/combination extension */
6138 m = key_getprop(saidx);
6139 #if 0
6140 /*
6141 * spec conformant: always attach proposal/combination extension,
6142 * the problem is that we have no way to attach it for ipcomp,
6143 * due to the way sadb_comb is declared in RFC2367.
6144 */
6145 if (!m) {
6146 error = ENOBUFS;
6147 goto fail;
6148 }
6149 m_cat(result, m);
6150 #else
6151 /*
6152 * outside of spec; make proposal/combination extension optional.
6153 */
6154 if (m)
6155 m_cat(result, m);
6156 #endif
6157
6158 if ((result->m_flags & M_PKTHDR) == 0) {
6159 error = EINVAL;
6160 goto fail;
6161 }
6162
6163 if (result->m_len < sizeof(struct sadb_msg)) {
6164 result = m_pullup(result, sizeof(struct sadb_msg));
6165 if (result == NULL) {
6166 error = ENOBUFS;
6167 goto fail;
6168 }
6169 }
6170
6171 result->m_pkthdr.len = 0;
6172 for (m = result; m; m = m->m_next)
6173 result->m_pkthdr.len += m->m_len;
6174
6175 mtod(result, struct sadb_msg *)->sadb_msg_len =
6176 PFKEY_UNIT64(result->m_pkthdr.len);
6177
6178 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6179
6180 fail:
6181 if (result)
6182 m_freem(result);
6183 return error;
6184 }
6185
6186 #ifndef IPSEC_NONBLOCK_ACQUIRE
6187 static struct secacq *
6188 key_newacq(saidx)
6189 struct secasindex *saidx;
6190 {
6191 struct secacq *newacq;
6192 struct timeval tv;
6193
6194 /* get new entry */
6195 KMALLOC(newacq, struct secacq *, sizeof(struct secacq));
6196 if (newacq == NULL) {
6197 ipseclog((LOG_DEBUG, "key_newacq: No more memory.\n"));
6198 return NULL;
6199 }
6200 bzero(newacq, sizeof(*newacq));
6201
6202 /* copy secindex */
6203 bcopy(saidx, &newacq->saidx, sizeof(newacq->saidx));
6204 newacq->seq = (acq_seq == ~0 ? 1 : ++acq_seq);
6205 microtime(&tv);
6206 newacq->created = tv.tv_sec;
6207 newacq->count = 0;
6208
6209 return newacq;
6210 }
6211
6212 static struct secacq *
6213 key_getacq(saidx)
6214 struct secasindex *saidx;
6215 {
6216 struct secacq *acq;
6217
6218 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
6219
6220 LIST_FOREACH(acq, &acqtree, chain) {
6221 if (key_cmpsaidx(saidx, &acq->saidx, CMP_EXACTLY))
6222 return acq;
6223 }
6224
6225 return NULL;
6226 }
6227
6228 static struct secacq *
6229 key_getacqbyseq(seq)
6230 u_int32_t seq;
6231 {
6232 struct secacq *acq;
6233
6234 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
6235
6236 LIST_FOREACH(acq, &acqtree, chain) {
6237 if (acq->seq == seq)
6238 return acq;
6239 }
6240
6241 return NULL;
6242 }
6243 #endif
6244
6245 static struct secspacq *
6246 key_newspacq(spidx)
6247 struct secpolicyindex *spidx;
6248 {
6249 struct secspacq *acq;
6250 struct timeval tv;
6251
6252 /* get new entry */
6253 KMALLOC(acq, struct secspacq *, sizeof(struct secspacq));
6254 if (acq == NULL) {
6255 ipseclog((LOG_DEBUG, "key_newspacq: No more memory.\n"));
6256 return NULL;
6257 }
6258 bzero(acq, sizeof(*acq));
6259
6260 /* copy secindex */
6261 bcopy(spidx, &acq->spidx, sizeof(acq->spidx));
6262 microtime(&tv);
6263 acq->created = tv.tv_sec;
6264 acq->count = 0;
6265
6266 return acq;
6267 }
6268
6269 static struct secspacq *
6270 key_getspacq(spidx)
6271 struct secpolicyindex *spidx;
6272 {
6273 struct secspacq *acq;
6274
6275 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
6276
6277 LIST_FOREACH(acq, &spacqtree, chain) {
6278 if (key_cmpspidx_exactly(spidx, &acq->spidx))
6279 return acq;
6280 }
6281
6282 return NULL;
6283 }
6284
6285 /*
6286 * SADB_ACQUIRE processing,
6287 * in first situation, is receiving
6288 * <base>
6289 * from the ikmpd, and clear sequence of its secasvar entry.
6290 *
6291 * In second situation, is receiving
6292 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6293 * from a user land process, and return
6294 * <base, address(SD), (address(P),) (identity(SD),) (sensitivity,) proposal>
6295 * to the socket.
6296 *
6297 * m will always be freed.
6298 */
6299 static int
6300 key_acquire2(so, m, mhp)
6301 struct socket *so;
6302 struct mbuf *m;
6303 const struct sadb_msghdr *mhp;
6304 {
6305 const struct sadb_address *src0, *dst0;
6306 struct secasindex saidx;
6307 struct secashead *sah;
6308 u_int16_t proto;
6309 int error;
6310
6311 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
6312
6313 /* sanity check */
6314 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6315 panic("key_acquire2: NULL pointer is passed.\n");
6316
6317 /*
6318 * Error message from KMd.
6319 * We assume that if error was occurred in IKEd, the length of PFKEY
6320 * message is equal to the size of sadb_msg structure.
6321 * We do not raise error even if error occurred in this function.
6322 */
6323 if (mhp->msg->sadb_msg_len == PFKEY_UNIT64(sizeof(struct sadb_msg))) {
6324 #ifndef IPSEC_NONBLOCK_ACQUIRE
6325 struct secacq *acq;
6326 struct timeval tv;
6327
6328 /* check sequence number */
6329 if (mhp->msg->sadb_msg_seq == 0) {
6330 ipseclog((LOG_DEBUG, "key_acquire2: must specify sequence number.\n"));
6331 m_freem(m);
6332 return 0;
6333 }
6334
6335 if ((acq = key_getacqbyseq(mhp->msg->sadb_msg_seq)) == NULL) {
6336 /*
6337 * the specified larval SA is already gone, or we got
6338 * a bogus sequence number. we can silently ignore it.
6339 */
6340 m_freem(m);
6341 return 0;
6342 }
6343
6344 /* reset acq counter in order to deletion by timehander. */
6345 microtime(&tv);
6346 acq->created = tv.tv_sec;
6347 acq->count = 0;
6348 #endif
6349 m_freem(m);
6350 return 0;
6351 }
6352
6353 /*
6354 * This message is from user land.
6355 */
6356
6357 /* map satype to proto */
6358 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6359 ipseclog((LOG_DEBUG, "key_acquire2: invalid satype is passed.\n"));
6360 return key_senderror(so, m, EINVAL);
6361 }
6362
6363 if (mhp->ext[SADB_EXT_ADDRESS_SRC] == NULL ||
6364 mhp->ext[SADB_EXT_ADDRESS_DST] == NULL ||
6365 mhp->ext[SADB_EXT_PROPOSAL] == NULL) {
6366 /* error */
6367 ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
6368 return key_senderror(so, m, EINVAL);
6369 }
6370 if (mhp->extlen[SADB_EXT_ADDRESS_SRC] < sizeof(struct sadb_address) ||
6371 mhp->extlen[SADB_EXT_ADDRESS_DST] < sizeof(struct sadb_address) ||
6372 mhp->extlen[SADB_EXT_PROPOSAL] < sizeof(struct sadb_prop)) {
6373 /* error */
6374 ipseclog((LOG_DEBUG, "key_acquire2: invalid message is passed.\n"));
6375 return key_senderror(so, m, EINVAL);
6376 }
6377
6378 src0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_SRC];
6379 dst0 = (struct sadb_address *)mhp->ext[SADB_EXT_ADDRESS_DST];
6380
6381 /* XXX boundary check against sa_len */
6382 KEY_SETSECASIDX(proto, IPSEC_MODE_ANY, 0, src0 + 1, dst0 + 1, &saidx);
6383
6384 /* get a SA index */
6385 LIST_FOREACH(sah, &sahtree, chain) {
6386 if (sah->state == SADB_SASTATE_DEAD)
6387 continue;
6388 if (key_cmpsaidx(&sah->saidx, &saidx, CMP_MODE_REQID))
6389 break;
6390 }
6391 if (sah != NULL) {
6392 ipseclog((LOG_DEBUG, "key_acquire2: a SA exists already.\n"));
6393 return key_senderror(so, m, EEXIST);
6394 }
6395
6396 error = key_acquire(&saidx, NULL);
6397 if (error != 0) {
6398 ipseclog((LOG_DEBUG, "key_acquire2: error %d returned "
6399 "from key_acquire.\n", mhp->msg->sadb_msg_errno));
6400 return key_senderror(so, m, error);
6401 }
6402
6403 return key_sendup_mbuf(so, m, KEY_SENDUP_REGISTERED);
6404 }
6405
6406 /*
6407 * SADB_REGISTER processing.
6408 * If SATYPE_UNSPEC has been passed as satype, only return sabd_supported.
6409 * receive
6410 * <base>
6411 * from the ikmpd, and register a socket to send PF_KEY messages,
6412 * and send
6413 * <base, supported>
6414 * to KMD by PF_KEY.
6415 * If socket is detached, must free from regnode.
6416 *
6417 * m will always be freed.
6418 */
6419 static int
6420 key_register(so, m, mhp)
6421 struct socket *so;
6422 struct mbuf *m;
6423 const struct sadb_msghdr *mhp;
6424 {
6425 struct secreg *reg, *newreg = 0;
6426
6427 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
6428
6429 /* sanity check */
6430 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6431 panic("key_register: NULL pointer is passed.\n");
6432
6433 /* check for invalid register message */
6434 if (mhp->msg->sadb_msg_satype >= sizeof(regtree)/sizeof(regtree[0]))
6435 return key_senderror(so, m, EINVAL);
6436
6437 /* When SATYPE_UNSPEC is specified, only return sabd_supported. */
6438 if (mhp->msg->sadb_msg_satype == SADB_SATYPE_UNSPEC)
6439 goto setmsg;
6440
6441 /* check whether existing or not */
6442 LIST_FOREACH(reg, &regtree[mhp->msg->sadb_msg_satype], chain) {
6443 if (reg->so == so) {
6444 ipseclog((LOG_DEBUG, "key_register: socket exists already.\n"));
6445 return key_senderror(so, m, EEXIST);
6446 }
6447 }
6448
6449 /* create regnode */
6450 KMALLOC(newreg, struct secreg *, sizeof(*newreg));
6451 if (newreg == NULL) {
6452 ipseclog((LOG_DEBUG, "key_register: No more memory.\n"));
6453 return key_senderror(so, m, ENOBUFS);
6454 }
6455 bzero((caddr_t)newreg, sizeof(*newreg));
6456
6457 socket_lock(so, 1);
6458 newreg->so = so;
6459 ((struct keycb *)sotorawcb(so))->kp_registered++;
6460 socket_unlock(so, 1);
6461
6462 /* add regnode to regtree. */
6463 LIST_INSERT_HEAD(&regtree[mhp->msg->sadb_msg_satype], newreg, chain);
6464
6465 setmsg:
6466 {
6467 struct mbuf *n;
6468 struct sadb_msg *newmsg;
6469 struct sadb_supported *sup;
6470 u_int len, alen, elen;
6471 int off;
6472 int i;
6473 struct sadb_alg *alg;
6474
6475 /* create new sadb_msg to reply. */
6476 alen = 0;
6477 for (i = 1; i <= SADB_AALG_MAX; i++) {
6478 if (ah_algorithm_lookup(i))
6479 alen += sizeof(struct sadb_alg);
6480 }
6481 if (alen)
6482 alen += sizeof(struct sadb_supported);
6483 elen = 0;
6484 #if IPSEC_ESP
6485 for (i = 1; i <= SADB_EALG_MAX; i++) {
6486 if (esp_algorithm_lookup(i))
6487 elen += sizeof(struct sadb_alg);
6488 }
6489 if (elen)
6490 elen += sizeof(struct sadb_supported);
6491 #endif
6492
6493 len = sizeof(struct sadb_msg) + alen + elen;
6494
6495 if (len > MCLBYTES)
6496 return key_senderror(so, m, ENOBUFS);
6497
6498 MGETHDR(n, M_DONTWAIT, MT_DATA);
6499 if (len > MHLEN) {
6500 MCLGET(n, M_DONTWAIT);
6501 if ((n->m_flags & M_EXT) == 0) {
6502 m_freem(n);
6503 n = NULL;
6504 }
6505 }
6506 if (!n)
6507 return key_senderror(so, m, ENOBUFS);
6508
6509 n->m_pkthdr.len = n->m_len = len;
6510 n->m_next = NULL;
6511 off = 0;
6512
6513 m_copydata(m, 0, sizeof(struct sadb_msg), mtod(n, caddr_t) + off);
6514 newmsg = mtod(n, struct sadb_msg *);
6515 newmsg->sadb_msg_errno = 0;
6516 newmsg->sadb_msg_len = PFKEY_UNIT64(len);
6517 off += PFKEY_ALIGN8(sizeof(struct sadb_msg));
6518
6519 /* for authentication algorithm */
6520 if (alen) {
6521 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6522 sup->sadb_supported_len = PFKEY_UNIT64(alen);
6523 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
6524 off += PFKEY_ALIGN8(sizeof(*sup));
6525
6526 for (i = 1; i <= SADB_AALG_MAX; i++) {
6527 const struct ah_algorithm *aalgo;
6528
6529 aalgo = ah_algorithm_lookup(i);
6530 if (!aalgo)
6531 continue;
6532 alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6533 alg->sadb_alg_id = i;
6534 alg->sadb_alg_ivlen = 0;
6535 alg->sadb_alg_minbits = aalgo->keymin;
6536 alg->sadb_alg_maxbits = aalgo->keymax;
6537 off += PFKEY_ALIGN8(sizeof(*alg));
6538 }
6539 }
6540
6541 #if IPSEC_ESP
6542 /* for encryption algorithm */
6543 if (elen) {
6544 sup = (struct sadb_supported *)(mtod(n, caddr_t) + off);
6545 sup->sadb_supported_len = PFKEY_UNIT64(elen);
6546 sup->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
6547 off += PFKEY_ALIGN8(sizeof(*sup));
6548
6549 for (i = 1; i <= SADB_EALG_MAX; i++) {
6550 const struct esp_algorithm *ealgo;
6551
6552 ealgo = esp_algorithm_lookup(i);
6553 if (!ealgo)
6554 continue;
6555 alg = (struct sadb_alg *)(mtod(n, caddr_t) + off);
6556 alg->sadb_alg_id = i;
6557 if (ealgo && ealgo->ivlen) {
6558 /*
6559 * give NULL to get the value preferred by
6560 * algorithm XXX SADB_X_EXT_DERIV ?
6561 */
6562 alg->sadb_alg_ivlen =
6563 (*ealgo->ivlen)(ealgo, NULL);
6564 } else
6565 alg->sadb_alg_ivlen = 0;
6566 alg->sadb_alg_minbits = ealgo->keymin;
6567 alg->sadb_alg_maxbits = ealgo->keymax;
6568 off += PFKEY_ALIGN8(sizeof(struct sadb_alg));
6569 }
6570 }
6571 #endif
6572
6573 #if DIGAGNOSTIC
6574 if (off != len)
6575 panic("length assumption failed in key_register");
6576 #endif
6577
6578 m_freem(m);
6579 return key_sendup_mbuf(so, n, KEY_SENDUP_REGISTERED);
6580 }
6581 }
6582
6583 /*
6584 * free secreg entry registered.
6585 * XXX: I want to do free a socket marked done SADB_RESIGER to socket.
6586 */
6587 void
6588 key_freereg(so)
6589 struct socket *so;
6590 {
6591 struct secreg *reg;
6592 int i;
6593
6594 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
6595
6596 /* sanity check */
6597 if (so == NULL)
6598 panic("key_freereg: NULL pointer is passed.\n");
6599
6600 /*
6601 * check whether existing or not.
6602 * check all type of SA, because there is a potential that
6603 * one socket is registered to multiple type of SA.
6604 */
6605 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
6606 LIST_FOREACH(reg, &regtree[i], chain) {
6607 if (reg->so == so
6608 && __LIST_CHAINED(reg)) {
6609 LIST_REMOVE(reg, chain);
6610 KFREE(reg);
6611 break;
6612 }
6613 }
6614 }
6615
6616 return;
6617 }
6618
6619 /*
6620 * SADB_EXPIRE processing
6621 * send
6622 * <base, SA, SA2, lifetime(C and one of HS), address(SD)>
6623 * to KMD by PF_KEY.
6624 * NOTE: We send only soft lifetime extension.
6625 *
6626 * OUT: 0 : succeed
6627 * others : error number
6628 */
6629 static int
6630 key_expire(sav)
6631 struct secasvar *sav;
6632 {
6633 int s;
6634 int satype;
6635 struct mbuf *result = NULL, *m;
6636 int len;
6637 int error = -1;
6638 struct sadb_lifetime *lt;
6639
6640 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
6641
6642 /* sanity check */
6643 if (sav == NULL)
6644 panic("key_expire: NULL pointer is passed.\n");
6645 if (sav->sah == NULL)
6646 panic("key_expire: Why was SA index in SA NULL.\n");
6647 if ((satype = key_proto2satype(sav->sah->saidx.proto)) == 0)
6648 panic("key_expire: invalid proto is passed.\n");
6649
6650 /* set msg header */
6651 m = key_setsadbmsg(SADB_EXPIRE, 0, satype, sav->seq, 0, sav->refcnt);
6652 if (!m) {
6653 error = ENOBUFS;
6654 goto fail;
6655 }
6656 result = m;
6657
6658 /* create SA extension */
6659 m = key_setsadbsa(sav);
6660 if (!m) {
6661 error = ENOBUFS;
6662 goto fail;
6663 }
6664 m_cat(result, m);
6665
6666 /* create SA extension */
6667 m = key_setsadbxsa2(sav->sah->saidx.mode,
6668 sav->replay ? sav->replay->count : 0,
6669 sav->sah->saidx.reqid);
6670 if (!m) {
6671 error = ENOBUFS;
6672 goto fail;
6673 }
6674 m_cat(result, m);
6675
6676 /* create lifetime extension (current and soft) */
6677 len = PFKEY_ALIGN8(sizeof(*lt)) * 2;
6678 m = key_alloc_mbuf(len);
6679 if (!m || m->m_next) { /*XXX*/
6680 if (m)
6681 m_freem(m);
6682 error = ENOBUFS;
6683 goto fail;
6684 }
6685 bzero(mtod(m, caddr_t), len);
6686 lt = mtod(m, struct sadb_lifetime *);
6687 lt->sadb_lifetime_len = PFKEY_UNIT64(sizeof(struct sadb_lifetime));
6688 lt->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
6689 lt->sadb_lifetime_allocations = sav->lft_c->sadb_lifetime_allocations;
6690 lt->sadb_lifetime_bytes = sav->lft_c->sadb_lifetime_bytes;
6691 lt->sadb_lifetime_addtime = sav->lft_c->sadb_lifetime_addtime;
6692 lt->sadb_lifetime_usetime = sav->lft_c->sadb_lifetime_usetime;
6693 lt = (struct sadb_lifetime *)(mtod(m, caddr_t) + len / 2);
6694 bcopy(sav->lft_s, lt, sizeof(*lt));
6695 m_cat(result, m);
6696
6697 /* set sadb_address for source */
6698 m = key_setsadbaddr(SADB_EXT_ADDRESS_SRC,
6699 (struct sockaddr *)&sav->sah->saidx.src,
6700 FULLMASK, IPSEC_ULPROTO_ANY);
6701 if (!m) {
6702 error = ENOBUFS;
6703 goto fail;
6704 }
6705 m_cat(result, m);
6706
6707 /* set sadb_address for destination */
6708 m = key_setsadbaddr(SADB_EXT_ADDRESS_DST,
6709 (struct sockaddr *)&sav->sah->saidx.dst,
6710 FULLMASK, IPSEC_ULPROTO_ANY);
6711 if (!m) {
6712 error = ENOBUFS;
6713 goto fail;
6714 }
6715 m_cat(result, m);
6716
6717 if ((result->m_flags & M_PKTHDR) == 0) {
6718 error = EINVAL;
6719 goto fail;
6720 }
6721
6722 if (result->m_len < sizeof(struct sadb_msg)) {
6723 result = m_pullup(result, sizeof(struct sadb_msg));
6724 if (result == NULL) {
6725 error = ENOBUFS;
6726 goto fail;
6727 }
6728 }
6729
6730 result->m_pkthdr.len = 0;
6731 for (m = result; m; m = m->m_next)
6732 result->m_pkthdr.len += m->m_len;
6733
6734 mtod(result, struct sadb_msg *)->sadb_msg_len =
6735 PFKEY_UNIT64(result->m_pkthdr.len);
6736
6737 splx(s);
6738 return key_sendup_mbuf(NULL, result, KEY_SENDUP_REGISTERED);
6739
6740 fail:
6741 if (result)
6742 m_freem(result);
6743 splx(s);
6744 return error;
6745 }
6746
6747 /*
6748 * SADB_FLUSH processing
6749 * receive
6750 * <base>
6751 * from the ikmpd, and free all entries in secastree.
6752 * and send,
6753 * <base>
6754 * to the ikmpd.
6755 * NOTE: to do is only marking SADB_SASTATE_DEAD.
6756 *
6757 * m will always be freed.
6758 */
6759 static int
6760 key_flush(so, m, mhp)
6761 struct socket *so;
6762 struct mbuf *m;
6763 const struct sadb_msghdr *mhp;
6764 {
6765 struct sadb_msg *newmsg;
6766 struct secashead *sah, *nextsah;
6767 struct secasvar *sav, *nextsav;
6768 u_int16_t proto;
6769 u_int8_t state;
6770 u_int stateidx;
6771
6772 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
6773
6774 /* sanity check */
6775 if (so == NULL || mhp == NULL || mhp->msg == NULL)
6776 panic("key_flush: NULL pointer is passed.\n");
6777
6778 /* map satype to proto */
6779 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6780 ipseclog((LOG_DEBUG, "key_flush: invalid satype is passed.\n"));
6781 return key_senderror(so, m, EINVAL);
6782 }
6783
6784 /* no SATYPE specified, i.e. flushing all SA. */
6785 for (sah = LIST_FIRST(&sahtree);
6786 sah != NULL;
6787 sah = nextsah) {
6788 nextsah = LIST_NEXT(sah, chain);
6789
6790 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6791 && proto != sah->saidx.proto)
6792 continue;
6793
6794 for (stateidx = 0;
6795 stateidx < _ARRAYLEN(saorder_state_alive);
6796 stateidx++) {
6797 state = saorder_state_any[stateidx];
6798 for (sav = LIST_FIRST(&sah->savtree[state]);
6799 sav != NULL;
6800 sav = nextsav) {
6801
6802 nextsav = LIST_NEXT(sav, chain);
6803
6804 key_sa_chgstate(sav, SADB_SASTATE_DEAD);
6805 key_freesav(sav);
6806 }
6807 }
6808
6809 sah->state = SADB_SASTATE_DEAD;
6810 }
6811
6812 if (m->m_len < sizeof(struct sadb_msg) ||
6813 sizeof(struct sadb_msg) > m->m_len + M_TRAILINGSPACE(m)) {
6814 ipseclog((LOG_DEBUG, "key_flush: No more memory.\n"));
6815 return key_senderror(so, m, ENOBUFS);
6816 }
6817
6818 if (m->m_next)
6819 m_freem(m->m_next);
6820 m->m_next = NULL;
6821 m->m_pkthdr.len = m->m_len = sizeof(struct sadb_msg);
6822 newmsg = mtod(m, struct sadb_msg *);
6823 newmsg->sadb_msg_errno = 0;
6824 newmsg->sadb_msg_len = PFKEY_UNIT64(m->m_pkthdr.len);
6825
6826 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6827 }
6828
6829 /*
6830 * SADB_DUMP processing
6831 * dump all entries including status of DEAD in SAD.
6832 * receive
6833 * <base>
6834 * from the ikmpd, and dump all secasvar leaves
6835 * and send,
6836 * <base> .....
6837 * to the ikmpd.
6838 *
6839 * m will always be freed.
6840 */
6841 static int
6842 key_dump(so, m, mhp)
6843 struct socket *so;
6844 struct mbuf *m;
6845 const struct sadb_msghdr *mhp;
6846 {
6847 struct secashead *sah;
6848 struct secasvar *sav;
6849 u_int16_t proto;
6850 u_int stateidx;
6851 u_int8_t satype;
6852 u_int8_t state;
6853 int cnt;
6854 struct sadb_msg *newmsg;
6855 struct mbuf *n;
6856
6857 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
6858
6859 /* sanity check */
6860 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6861 panic("key_dump: NULL pointer is passed.\n");
6862
6863 /* map satype to proto */
6864 if ((proto = key_satype2proto(mhp->msg->sadb_msg_satype)) == 0) {
6865 ipseclog((LOG_DEBUG, "key_dump: invalid satype is passed.\n"));
6866 return key_senderror(so, m, EINVAL);
6867 }
6868
6869 /* count sav entries to be sent to the userland. */
6870 cnt = 0;
6871 LIST_FOREACH(sah, &sahtree, chain) {
6872 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6873 && proto != sah->saidx.proto)
6874 continue;
6875
6876 for (stateidx = 0;
6877 stateidx < _ARRAYLEN(saorder_state_any);
6878 stateidx++) {
6879 state = saorder_state_any[stateidx];
6880 LIST_FOREACH(sav, &sah->savtree[state], chain) {
6881 cnt++;
6882 }
6883 }
6884 }
6885
6886 if (cnt == 0)
6887 return key_senderror(so, m, ENOENT);
6888
6889 /* send this to the userland, one at a time. */
6890 newmsg = NULL;
6891 LIST_FOREACH(sah, &sahtree, chain) {
6892 if (mhp->msg->sadb_msg_satype != SADB_SATYPE_UNSPEC
6893 && proto != sah->saidx.proto)
6894 continue;
6895
6896 /* map proto to satype */
6897 if ((satype = key_proto2satype(sah->saidx.proto)) == 0) {
6898 ipseclog((LOG_DEBUG, "key_dump: there was invalid proto in SAD.\n"));
6899 return key_senderror(so, m, EINVAL);
6900 }
6901
6902 for (stateidx = 0;
6903 stateidx < _ARRAYLEN(saorder_state_any);
6904 stateidx++) {
6905 state = saorder_state_any[stateidx];
6906 LIST_FOREACH(sav, &sah->savtree[state], chain) {
6907 n = key_setdumpsa(sav, SADB_DUMP, satype,
6908 --cnt, mhp->msg->sadb_msg_pid);
6909 if (!n)
6910 return key_senderror(so, m, ENOBUFS);
6911
6912 key_sendup_mbuf(so, n, KEY_SENDUP_ONE);
6913 }
6914 }
6915 }
6916
6917 m_freem(m);
6918 return 0;
6919 }
6920
6921 /*
6922 * SADB_X_PROMISC processing
6923 *
6924 * m will always be freed.
6925 */
6926 static int
6927 key_promisc(so, m, mhp)
6928 struct socket *so;
6929 struct mbuf *m;
6930 const struct sadb_msghdr *mhp;
6931 {
6932 int olen;
6933
6934 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
6935
6936 /* sanity check */
6937 if (so == NULL || m == NULL || mhp == NULL || mhp->msg == NULL)
6938 panic("key_promisc: NULL pointer is passed.\n");
6939
6940 olen = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
6941
6942 if (olen < sizeof(struct sadb_msg)) {
6943 #if 1
6944 return key_senderror(so, m, EINVAL);
6945 #else
6946 m_freem(m);
6947 return 0;
6948 #endif
6949 } else if (olen == sizeof(struct sadb_msg)) {
6950 /* enable/disable promisc mode */
6951 struct keycb *kp;
6952
6953 socket_lock(so, 1);
6954 if ((kp = (struct keycb *)sotorawcb(so)) == NULL)
6955 return key_senderror(so, m, EINVAL);
6956 mhp->msg->sadb_msg_errno = 0;
6957 switch (mhp->msg->sadb_msg_satype) {
6958 case 0:
6959 case 1:
6960 kp->kp_promisc = mhp->msg->sadb_msg_satype;
6961 break;
6962 default:
6963 socket_unlock(so, 1);
6964 return key_senderror(so, m, EINVAL);
6965 }
6966 socket_unlock(so, 1);
6967
6968 /* send the original message back to everyone */
6969 mhp->msg->sadb_msg_errno = 0;
6970 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6971 } else {
6972 /* send packet as is */
6973
6974 m_adj(m, PFKEY_ALIGN8(sizeof(struct sadb_msg)));
6975
6976 /* TODO: if sadb_msg_seq is specified, send to specific pid */
6977 return key_sendup_mbuf(so, m, KEY_SENDUP_ALL);
6978 }
6979 }
6980
6981 static int (*key_typesw[])(struct socket *, struct mbuf *,
6982 const struct sadb_msghdr *) = {
6983 NULL, /* SADB_RESERVED */
6984 key_getspi, /* SADB_GETSPI */
6985 key_update, /* SADB_UPDATE */
6986 key_add, /* SADB_ADD */
6987 key_delete, /* SADB_DELETE */
6988 key_get, /* SADB_GET */
6989 key_acquire2, /* SADB_ACQUIRE */
6990 key_register, /* SADB_REGISTER */
6991 NULL, /* SADB_EXPIRE */
6992 key_flush, /* SADB_FLUSH */
6993 key_dump, /* SADB_DUMP */
6994 key_promisc, /* SADB_X_PROMISC */
6995 NULL, /* SADB_X_PCHANGE */
6996 key_spdadd, /* SADB_X_SPDUPDATE */
6997 key_spdadd, /* SADB_X_SPDADD */
6998 key_spddelete, /* SADB_X_SPDDELETE */
6999 key_spdget, /* SADB_X_SPDGET */
7000 NULL, /* SADB_X_SPDACQUIRE */
7001 key_spddump, /* SADB_X_SPDDUMP */
7002 key_spdflush, /* SADB_X_SPDFLUSH */
7003 key_spdadd, /* SADB_X_SPDSETIDX */
7004 NULL, /* SADB_X_SPDEXPIRE */
7005 key_spddelete2, /* SADB_X_SPDDELETE2 */
7006 };
7007
7008 /*
7009 * parse sadb_msg buffer to process PFKEYv2,
7010 * and create a data to response if needed.
7011 * I think to be dealed with mbuf directly.
7012 * IN:
7013 * msgp : pointer to pointer to a received buffer pulluped.
7014 * This is rewrited to response.
7015 * so : pointer to socket.
7016 * OUT:
7017 * length for buffer to send to user process.
7018 */
7019 int
7020 key_parse(m, so)
7021 struct mbuf *m;
7022 struct socket *so;
7023 {
7024 struct sadb_msg *msg;
7025 struct sadb_msghdr mh;
7026 u_int orglen;
7027 int error;
7028 int target;
7029
7030 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
7031
7032 /* sanity check */
7033 if (m == NULL || so == NULL)
7034 panic("key_parse: NULL pointer is passed.\n");
7035
7036 #if 0 /*kdebug_sadb assumes msg in linear buffer*/
7037 KEYDEBUG(KEYDEBUG_KEY_DUMP,
7038 ipseclog((LOG_DEBUG, "key_parse: passed sadb_msg\n"));
7039 kdebug_sadb(msg));
7040 #endif
7041
7042 if (m->m_len < sizeof(struct sadb_msg)) {
7043 m = m_pullup(m, sizeof(struct sadb_msg));
7044 if (!m)
7045 return ENOBUFS;
7046 }
7047 msg = mtod(m, struct sadb_msg *);
7048 orglen = PFKEY_UNUNIT64(msg->sadb_msg_len);
7049 target = KEY_SENDUP_ONE;
7050
7051 if ((m->m_flags & M_PKTHDR) == 0 ||
7052 m->m_pkthdr.len != m->m_pkthdr.len) {
7053 ipseclog((LOG_DEBUG, "key_parse: invalid message length.\n"));
7054 pfkeystat.out_invlen++;
7055 error = EINVAL;
7056 goto senderror;
7057 }
7058
7059 if (msg->sadb_msg_version != PF_KEY_V2) {
7060 ipseclog((LOG_DEBUG,
7061 "key_parse: PF_KEY version %u is mismatched.\n",
7062 msg->sadb_msg_version));
7063 pfkeystat.out_invver++;
7064 error = EINVAL;
7065 goto senderror;
7066 }
7067
7068 if (msg->sadb_msg_type > SADB_MAX) {
7069 ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
7070 msg->sadb_msg_type));
7071 pfkeystat.out_invmsgtype++;
7072 error = EINVAL;
7073 goto senderror;
7074 }
7075
7076 /* for old-fashioned code - should be nuked */
7077 if (m->m_pkthdr.len > MCLBYTES) {
7078 m_freem(m);
7079 return ENOBUFS;
7080 }
7081 if (m->m_next) {
7082 struct mbuf *n;
7083
7084 MGETHDR(n, M_DONTWAIT, MT_DATA);
7085 if (n && m->m_pkthdr.len > MHLEN) {
7086 MCLGET(n, M_DONTWAIT);
7087 if ((n->m_flags & M_EXT) == 0) {
7088 m_free(n);
7089 n = NULL;
7090 }
7091 }
7092 if (!n) {
7093 m_freem(m);
7094 return ENOBUFS;
7095 }
7096 m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
7097 n->m_pkthdr.len = n->m_len = m->m_pkthdr.len;
7098 n->m_next = NULL;
7099 m_freem(m);
7100 m = n;
7101 }
7102
7103 /* align the mbuf chain so that extensions are in contiguous region. */
7104 error = key_align(m, &mh);
7105 if (error)
7106 return error;
7107
7108 if (m->m_next) { /*XXX*/
7109 m_freem(m);
7110 return ENOBUFS;
7111 }
7112
7113 msg = mh.msg;
7114
7115 /* check SA type */
7116 switch (msg->sadb_msg_satype) {
7117 case SADB_SATYPE_UNSPEC:
7118 switch (msg->sadb_msg_type) {
7119 case SADB_GETSPI:
7120 case SADB_UPDATE:
7121 case SADB_ADD:
7122 case SADB_DELETE:
7123 case SADB_GET:
7124 case SADB_ACQUIRE:
7125 case SADB_EXPIRE:
7126 ipseclog((LOG_DEBUG, "key_parse: must specify satype "
7127 "when msg type=%u.\n", msg->sadb_msg_type));
7128 pfkeystat.out_invsatype++;
7129 error = EINVAL;
7130 goto senderror;
7131 }
7132 break;
7133 case SADB_SATYPE_AH:
7134 case SADB_SATYPE_ESP:
7135 case SADB_X_SATYPE_IPCOMP:
7136 switch (msg->sadb_msg_type) {
7137 case SADB_X_SPDADD:
7138 case SADB_X_SPDDELETE:
7139 case SADB_X_SPDGET:
7140 case SADB_X_SPDDUMP:
7141 case SADB_X_SPDFLUSH:
7142 case SADB_X_SPDSETIDX:
7143 case SADB_X_SPDUPDATE:
7144 case SADB_X_SPDDELETE2:
7145 ipseclog((LOG_DEBUG, "key_parse: illegal satype=%u\n",
7146 msg->sadb_msg_type));
7147 pfkeystat.out_invsatype++;
7148 error = EINVAL;
7149 goto senderror;
7150 }
7151 break;
7152 case SADB_SATYPE_RSVP:
7153 case SADB_SATYPE_OSPFV2:
7154 case SADB_SATYPE_RIPV2:
7155 case SADB_SATYPE_MIP:
7156 ipseclog((LOG_DEBUG, "key_parse: type %u isn't supported.\n",
7157 msg->sadb_msg_satype));
7158 pfkeystat.out_invsatype++;
7159 error = EOPNOTSUPP;
7160 goto senderror;
7161 case 1: /* XXX: What does it do? */
7162 if (msg->sadb_msg_type == SADB_X_PROMISC)
7163 break;
7164 /*FALLTHROUGH*/
7165 default:
7166 ipseclog((LOG_DEBUG, "key_parse: invalid type %u is passed.\n",
7167 msg->sadb_msg_satype));
7168 pfkeystat.out_invsatype++;
7169 error = EINVAL;
7170 goto senderror;
7171 }
7172
7173 /* check field of upper layer protocol and address family */
7174 if (mh.ext[SADB_EXT_ADDRESS_SRC] != NULL
7175 && mh.ext[SADB_EXT_ADDRESS_DST] != NULL) {
7176 struct sadb_address *src0, *dst0;
7177 u_int plen;
7178
7179 src0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_SRC]);
7180 dst0 = (struct sadb_address *)(mh.ext[SADB_EXT_ADDRESS_DST]);
7181
7182 /* check upper layer protocol */
7183 if (src0->sadb_address_proto != dst0->sadb_address_proto) {
7184 ipseclog((LOG_DEBUG, "key_parse: upper layer protocol mismatched.\n"));
7185 pfkeystat.out_invaddr++;
7186 error = EINVAL;
7187 goto senderror;
7188 }
7189
7190 /* check family */
7191 if (PFKEY_ADDR_SADDR(src0)->sa_family !=
7192 PFKEY_ADDR_SADDR(dst0)->sa_family) {
7193 ipseclog((LOG_DEBUG, "key_parse: address family mismatched.\n"));
7194 pfkeystat.out_invaddr++;
7195 error = EINVAL;
7196 goto senderror;
7197 }
7198 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7199 PFKEY_ADDR_SADDR(dst0)->sa_len) {
7200 ipseclog((LOG_DEBUG,
7201 "key_parse: address struct size mismatched.\n"));
7202 pfkeystat.out_invaddr++;
7203 error = EINVAL;
7204 goto senderror;
7205 }
7206
7207 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7208 case AF_INET:
7209 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7210 sizeof(struct sockaddr_in)) {
7211 pfkeystat.out_invaddr++;
7212 error = EINVAL;
7213 goto senderror;
7214 }
7215 break;
7216 case AF_INET6:
7217 if (PFKEY_ADDR_SADDR(src0)->sa_len !=
7218 sizeof(struct sockaddr_in6)) {
7219 pfkeystat.out_invaddr++;
7220 error = EINVAL;
7221 goto senderror;
7222 }
7223 break;
7224 default:
7225 ipseclog((LOG_DEBUG,
7226 "key_parse: unsupported address family.\n"));
7227 pfkeystat.out_invaddr++;
7228 error = EAFNOSUPPORT;
7229 goto senderror;
7230 }
7231
7232 switch (PFKEY_ADDR_SADDR(src0)->sa_family) {
7233 case AF_INET:
7234 plen = sizeof(struct in_addr) << 3;
7235 break;
7236 case AF_INET6:
7237 plen = sizeof(struct in6_addr) << 3;
7238 break;
7239 default:
7240 plen = 0; /*fool gcc*/
7241 break;
7242 }
7243
7244 /* check max prefix length */
7245 if (src0->sadb_address_prefixlen > plen ||
7246 dst0->sadb_address_prefixlen > plen) {
7247 ipseclog((LOG_DEBUG,
7248 "key_parse: illegal prefixlen.\n"));
7249 pfkeystat.out_invaddr++;
7250 error = EINVAL;
7251 goto senderror;
7252 }
7253
7254 /*
7255 * prefixlen == 0 is valid because there can be a case when
7256 * all addresses are matched.
7257 */
7258 }
7259
7260 if (msg->sadb_msg_type >= sizeof(key_typesw)/sizeof(key_typesw[0]) ||
7261 key_typesw[msg->sadb_msg_type] == NULL) {
7262 pfkeystat.out_invmsgtype++;
7263 error = EINVAL;
7264 goto senderror;
7265 }
7266
7267 return (*key_typesw[msg->sadb_msg_type])(so, m, &mh);
7268
7269 senderror:
7270 msg->sadb_msg_errno = error;
7271 return key_sendup_mbuf(so, m, target);
7272 }
7273
7274 static int
7275 key_senderror(so, m, code)
7276 struct socket *so;
7277 struct mbuf *m;
7278 int code;
7279 {
7280 struct sadb_msg *msg;
7281
7282 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
7283
7284 if (m->m_len < sizeof(struct sadb_msg))
7285 panic("invalid mbuf passed to key_senderror");
7286
7287 msg = mtod(m, struct sadb_msg *);
7288 msg->sadb_msg_errno = code;
7289 return key_sendup_mbuf(so, m, KEY_SENDUP_ONE);
7290 }
7291
7292 /*
7293 * set the pointer to each header into message buffer.
7294 * m will be freed on error.
7295 * XXX larger-than-MCLBYTES extension?
7296 */
7297 static int
7298 key_align(m, mhp)
7299 struct mbuf *m;
7300 struct sadb_msghdr *mhp;
7301 {
7302 struct mbuf *n;
7303 struct sadb_ext *ext;
7304 size_t off, end;
7305 int extlen;
7306 int toff;
7307
7308 /* sanity check */
7309 if (m == NULL || mhp == NULL)
7310 panic("key_align: NULL pointer is passed.\n");
7311 if (m->m_len < sizeof(struct sadb_msg))
7312 panic("invalid mbuf passed to key_align");
7313
7314 /* initialize */
7315 bzero(mhp, sizeof(*mhp));
7316
7317 mhp->msg = mtod(m, struct sadb_msg *);
7318 mhp->ext[0] = (struct sadb_ext *)mhp->msg; /*XXX backward compat */
7319
7320 end = PFKEY_UNUNIT64(mhp->msg->sadb_msg_len);
7321 extlen = end; /*just in case extlen is not updated*/
7322 for (off = sizeof(struct sadb_msg); off < end; off += extlen) {
7323 n = m_pulldown(m, off, sizeof(struct sadb_ext), &toff);
7324 if (!n) {
7325 /* m is already freed */
7326 return ENOBUFS;
7327 }
7328 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7329
7330 /* set pointer */
7331 switch (ext->sadb_ext_type) {
7332 case SADB_EXT_SA:
7333 case SADB_EXT_ADDRESS_SRC:
7334 case SADB_EXT_ADDRESS_DST:
7335 case SADB_EXT_ADDRESS_PROXY:
7336 case SADB_EXT_LIFETIME_CURRENT:
7337 case SADB_EXT_LIFETIME_HARD:
7338 case SADB_EXT_LIFETIME_SOFT:
7339 case SADB_EXT_KEY_AUTH:
7340 case SADB_EXT_KEY_ENCRYPT:
7341 case SADB_EXT_IDENTITY_SRC:
7342 case SADB_EXT_IDENTITY_DST:
7343 case SADB_EXT_SENSITIVITY:
7344 case SADB_EXT_PROPOSAL:
7345 case SADB_EXT_SUPPORTED_AUTH:
7346 case SADB_EXT_SUPPORTED_ENCRYPT:
7347 case SADB_EXT_SPIRANGE:
7348 case SADB_X_EXT_POLICY:
7349 case SADB_X_EXT_SA2:
7350 /* duplicate check */
7351 /*
7352 * XXX Are there duplication payloads of either
7353 * KEY_AUTH or KEY_ENCRYPT ?
7354 */
7355 if (mhp->ext[ext->sadb_ext_type] != NULL) {
7356 ipseclog((LOG_DEBUG,
7357 "key_align: duplicate ext_type %u "
7358 "is passed.\n", ext->sadb_ext_type));
7359 m_freem(m);
7360 pfkeystat.out_dupext++;
7361 return EINVAL;
7362 }
7363 break;
7364 default:
7365 ipseclog((LOG_DEBUG,
7366 "key_align: invalid ext_type %u is passed.\n",
7367 ext->sadb_ext_type));
7368 m_freem(m);
7369 pfkeystat.out_invexttype++;
7370 return EINVAL;
7371 }
7372
7373 extlen = PFKEY_UNUNIT64(ext->sadb_ext_len);
7374
7375 if (key_validate_ext(ext, extlen)) {
7376 m_freem(m);
7377 pfkeystat.out_invlen++;
7378 return EINVAL;
7379 }
7380
7381 n = m_pulldown(m, off, extlen, &toff);
7382 if (!n) {
7383 /* m is already freed */
7384 return ENOBUFS;
7385 }
7386 ext = (struct sadb_ext *)(mtod(n, caddr_t) + toff);
7387
7388 mhp->ext[ext->sadb_ext_type] = ext;
7389 mhp->extoff[ext->sadb_ext_type] = off;
7390 mhp->extlen[ext->sadb_ext_type] = extlen;
7391 }
7392
7393 if (off != end) {
7394 m_freem(m);
7395 pfkeystat.out_invlen++;
7396 return EINVAL;
7397 }
7398
7399 return 0;
7400 }
7401
7402 static int
7403 key_validate_ext(ext, len)
7404 const struct sadb_ext *ext;
7405 int len;
7406 {
7407 struct sockaddr *sa;
7408 enum { NONE, ADDR } checktype = NONE;
7409 int baselen;
7410 const int sal = offsetof(struct sockaddr, sa_len) + sizeof(sa->sa_len);
7411
7412 if (len != PFKEY_UNUNIT64(ext->sadb_ext_len))
7413 return EINVAL;
7414
7415 /* if it does not match minimum/maximum length, bail */
7416 if (ext->sadb_ext_type >= sizeof(minsize) / sizeof(minsize[0]) ||
7417 ext->sadb_ext_type >= sizeof(maxsize) / sizeof(maxsize[0]))
7418 return EINVAL;
7419 if (!minsize[ext->sadb_ext_type] || len < minsize[ext->sadb_ext_type])
7420 return EINVAL;
7421 if (maxsize[ext->sadb_ext_type] && len > maxsize[ext->sadb_ext_type])
7422 return EINVAL;
7423
7424 /* more checks based on sadb_ext_type XXX need more */
7425 switch (ext->sadb_ext_type) {
7426 case SADB_EXT_ADDRESS_SRC:
7427 case SADB_EXT_ADDRESS_DST:
7428 case SADB_EXT_ADDRESS_PROXY:
7429 baselen = PFKEY_ALIGN8(sizeof(struct sadb_address));
7430 checktype = ADDR;
7431 break;
7432 case SADB_EXT_IDENTITY_SRC:
7433 case SADB_EXT_IDENTITY_DST:
7434 if (((struct sadb_ident *)ext)->sadb_ident_type ==
7435 SADB_X_IDENTTYPE_ADDR) {
7436 baselen = PFKEY_ALIGN8(sizeof(struct sadb_ident));
7437 checktype = ADDR;
7438 } else
7439 checktype = NONE;
7440 break;
7441 default:
7442 checktype = NONE;
7443 break;
7444 }
7445
7446 switch (checktype) {
7447 case NONE:
7448 break;
7449 case ADDR:
7450 sa = (struct sockaddr *)((caddr_t)ext + baselen);
7451 if (len < baselen + sal)
7452 return EINVAL;
7453 if (baselen + PFKEY_ALIGN8(sa->sa_len) != len)
7454 return EINVAL;
7455 break;
7456 }
7457
7458 return 0;
7459 }
7460
7461 void
7462 key_domain_init()
7463 {
7464 int i;
7465
7466 bzero((caddr_t)&key_cb, sizeof(key_cb));
7467
7468 for (i = 0; i < IPSEC_DIR_MAX; i++) {
7469 LIST_INIT(&sptree[i]);
7470 }
7471
7472 LIST_INIT(&sahtree);
7473
7474 for (i = 0; i <= SADB_SATYPE_MAX; i++) {
7475 LIST_INIT(&regtree[i]);
7476 }
7477
7478 #ifndef IPSEC_NONBLOCK_ACQUIRE
7479 LIST_INIT(&acqtree);
7480 #endif
7481 LIST_INIT(&spacqtree);
7482
7483 /* system default */
7484 #if INET
7485 ip4_def_policy.policy = IPSEC_POLICY_NONE;
7486 ip4_def_policy.refcnt++; /*never reclaim this*/
7487 #endif
7488 #if INET6
7489 ip6_def_policy.policy = IPSEC_POLICY_NONE;
7490 ip6_def_policy.refcnt++; /*never reclaim this*/
7491 #endif
7492
7493 #ifndef IPSEC_DEBUG2
7494 timeout((void *)key_timehandler, (void *)0, hz);
7495 #endif /*IPSEC_DEBUG2*/
7496
7497 /* initialize key statistics */
7498 keystat.getspi_count = 1;
7499
7500 #ifndef __APPLE__
7501 printf("IPsec: Initialized Security Association Processing.\n");
7502 #endif
7503
7504 return;
7505 }
7506
7507 /*
7508 * XXX: maybe This function is called after INBOUND IPsec processing.
7509 *
7510 * Special check for tunnel-mode packets.
7511 * We must make some checks for consistency between inner and outer IP header.
7512 *
7513 * xxx more checks to be provided
7514 */
7515 int
7516 key_checktunnelsanity(sav, family, src, dst)
7517 struct secasvar *sav;
7518 u_int family;
7519 caddr_t src;
7520 caddr_t dst;
7521 {
7522 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
7523
7524 /* sanity check */
7525 if (sav->sah == NULL)
7526 panic("sav->sah == NULL at key_checktunnelsanity");
7527
7528 /* XXX: check inner IP header */
7529
7530 return 1;
7531 }
7532
7533 #if 0
7534 #define hostnamelen strlen(hostname)
7535
7536 /*
7537 * Get FQDN for the host.
7538 * If the administrator configured hostname (by hostname(1)) without
7539 * domain name, returns nothing.
7540 */
7541 static const char *
7542 key_getfqdn()
7543 {
7544 int i;
7545 int hasdot;
7546 static char fqdn[MAXHOSTNAMELEN + 1];
7547
7548 if (!hostnamelen)
7549 return NULL;
7550
7551 /* check if it comes with domain name. */
7552 hasdot = 0;
7553 for (i = 0; i < hostnamelen; i++) {
7554 if (hostname[i] == '.')
7555 hasdot++;
7556 }
7557 if (!hasdot)
7558 return NULL;
7559
7560 /* NOTE: hostname may not be NUL-terminated. */
7561 bzero(fqdn, sizeof(fqdn));
7562 bcopy(hostname, fqdn, hostnamelen);
7563 fqdn[hostnamelen] = '\0';
7564 return fqdn;
7565 }
7566
7567 /*
7568 * get username@FQDN for the host/user.
7569 */
7570 static const char *
7571 key_getuserfqdn()
7572 {
7573 const char *host;
7574 static char userfqdn[MAXHOSTNAMELEN + MAXLOGNAME + 2];
7575 struct proc *p = curproc;
7576 char *q;
7577
7578 if (!p || !p->p_pgrp || !p->p_pgrp->pg_session)
7579 return NULL;
7580 if (!(host = key_getfqdn()))
7581 return NULL;
7582
7583 /* NOTE: s_login may not be-NUL terminated. */
7584 bzero(userfqdn, sizeof(userfqdn));
7585 bcopy(p->p_pgrp->pg_session->s_login, userfqdn, MAXLOGNAME);
7586 userfqdn[MAXLOGNAME] = '\0'; /* safeguard */
7587 q = userfqdn + strlen(userfqdn);
7588 *q++ = '@';
7589 bcopy(host, q, strlen(host));
7590 q += strlen(host);
7591 *q++ = '\0';
7592
7593 return userfqdn;
7594 }
7595 #endif
7596
7597 /* record data transfer on SA, and update timestamps */
7598 void
7599 key_sa_recordxfer(sav, m)
7600 struct secasvar *sav;
7601 struct mbuf *m;
7602 {
7603 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
7604
7605 if (!sav)
7606 panic("key_sa_recordxfer called with sav == NULL");
7607 if (!m)
7608 panic("key_sa_recordxfer called with m == NULL");
7609 if (!sav->lft_c)
7610 return;
7611
7612 /*
7613 * XXX Currently, there is a difference of bytes size
7614 * between inbound and outbound processing.
7615 */
7616 sav->lft_c->sadb_lifetime_bytes += m->m_pkthdr.len;
7617 /* to check bytes lifetime is done in key_timehandler(). */
7618
7619 /*
7620 * We use the number of packets as the unit of
7621 * sadb_lifetime_allocations. We increment the variable
7622 * whenever {esp,ah}_{in,out}put is called.
7623 */
7624 sav->lft_c->sadb_lifetime_allocations++;
7625 /* XXX check for expires? */
7626
7627 /*
7628 * NOTE: We record CURRENT sadb_lifetime_usetime by using wall clock,
7629 * in seconds. HARD and SOFT lifetime are measured by the time
7630 * difference (again in seconds) from sadb_lifetime_usetime.
7631 *
7632 * usetime
7633 * v expire expire
7634 * -----+-----+--------+---> t
7635 * <--------------> HARD
7636 * <-----> SOFT
7637 */
7638 {
7639 struct timeval tv;
7640 microtime(&tv);
7641 sav->lft_c->sadb_lifetime_usetime = tv.tv_sec;
7642 /* XXX check for expires? */
7643 }
7644
7645 return;
7646 }
7647
7648 /* dumb version */
7649 void
7650 key_sa_routechange(dst)
7651 struct sockaddr *dst;
7652 {
7653 struct secashead *sah;
7654 struct route *ro;
7655
7656 lck_mtx_lock(sadb_mutex);
7657 LIST_FOREACH(sah, &sahtree, chain) {
7658 ro = &sah->sa_route;
7659 if (ro->ro_rt && dst->sa_len == ro->ro_dst.sa_len
7660 && bcmp(dst, &ro->ro_dst, dst->sa_len) == 0) {
7661 rtfree(ro->ro_rt);
7662 ro->ro_rt = (struct rtentry *)NULL;
7663 }
7664 }
7665 lck_mtx_unlock(sadb_mutex);
7666
7667 return;
7668 }
7669
7670 static void
7671 key_sa_chgstate(sav, state)
7672 struct secasvar *sav;
7673 u_int8_t state;
7674 {
7675 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
7676
7677 if (sav == NULL)
7678 panic("key_sa_chgstate called with sav == NULL");
7679
7680 if (sav->state == state)
7681 return;
7682
7683 if (__LIST_CHAINED(sav))
7684 LIST_REMOVE(sav, chain);
7685
7686 sav->state = state;
7687 LIST_INSERT_HEAD(&sav->sah->savtree[state], sav, chain);
7688 }
7689
7690 void
7691 key_sa_stir_iv(sav)
7692 struct secasvar *sav;
7693 {
7694
7695 lck_mtx_assert(sadb_mutex, LCK_MTX_ASSERT_OWNED);
7696
7697 if (!sav->iv)
7698 panic("key_sa_stir_iv called with sav == NULL");
7699 key_randomfill(sav->iv, sav->ivlen);
7700 }
7701
7702 /* XXX too much? */
7703 static struct mbuf *
7704 key_alloc_mbuf(l)
7705 int l;
7706 {
7707 struct mbuf *m = NULL, *n;
7708 int len, t;
7709
7710 len = l;
7711 while (len > 0) {
7712 MGET(n, M_DONTWAIT, MT_DATA);
7713 if (n && len > MLEN)
7714 MCLGET(n, M_DONTWAIT);
7715 if (!n) {
7716 m_freem(m);
7717 return NULL;
7718 }
7719
7720 n->m_next = NULL;
7721 n->m_len = 0;
7722 n->m_len = M_TRAILINGSPACE(n);
7723 /* use the bottom of mbuf, hoping we can prepend afterwards */
7724 if (n->m_len > len) {
7725 t = (n->m_len - len) & ~(sizeof(long) - 1);
7726 n->m_data += t;
7727 n->m_len = len;
7728 }
7729
7730 len -= n->m_len;
7731
7732 if (m)
7733 m_cat(m, n);
7734 else
7735 m = n;
7736 }
7737
7738 return m;
7739 }