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