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