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