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