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