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