1 // SPDX-License-Identifier: GPL-2.0-only
7 * Kazunori MIYAZAWA @USAGI
8 * Kunihiro Ishiguro <kunihiro@ipinfusion.com>
10 * Kazunori MIYAZAWA @USAGI
12 * Split up af-specific portion
13 * Derek Atkins <derek@ihtfp.com> Add the post_input processor
17 #include <linux/err.h>
18 #include <linux/slab.h>
19 #include <linux/kmod.h>
20 #include <linux/list.h>
21 #include <linux/spinlock.h>
22 #include <linux/workqueue.h>
23 #include <linux/notifier.h>
24 #include <linux/netdevice.h>
25 #include <linux/netfilter.h>
26 #include <linux/module.h>
27 #include <linux/cache.h>
28 #include <linux/cpu.h>
29 #include <linux/audit.h>
30 #include <linux/rhashtable.h>
31 #include <linux/if_tunnel.h>
34 #include <net/inet_ecn.h>
38 #if IS_ENABLED(CONFIG_IPV6_MIP6)
41 #ifdef CONFIG_XFRM_STATISTICS
44 #ifdef CONFIG_XFRM_ESPINTCP
45 #include <net/espintcp.h>
48 #include "xfrm_hash.h"
50 #define XFRM_QUEUE_TMO_MIN ((unsigned)(HZ/10))
51 #define XFRM_QUEUE_TMO_MAX ((unsigned)(60*HZ))
52 #define XFRM_MAX_QUEUE_LEN 100
55 struct dst_entry *dst_orig;
59 /* prefixes smaller than this are stored in lists, not trees. */
60 #define INEXACT_PREFIXLEN_IPV4 16
61 #define INEXACT_PREFIXLEN_IPV6 48
63 struct xfrm_pol_inexact_node {
73 /* the policies matching this node, can be empty list */
74 struct hlist_head hhead;
77 /* xfrm inexact policy search tree:
78 * xfrm_pol_inexact_bin = hash(dir,type,family,if_id);
80 * +---- root_d: sorted by daddr:prefix
82 * | xfrm_pol_inexact_node
84 * | +- root: sorted by saddr/prefix
86 * | | xfrm_pol_inexact_node
90 * | | + hhead: saddr:daddr policies
92 * | +- coarse policies and all any:daddr policies
94 * +---- root_s: sorted by saddr:prefix
96 * | xfrm_pol_inexact_node
100 * | + hhead: saddr:any policies
102 * +---- coarse policies and all any:any policies
104 * Lookups return four candidate lists:
105 * 1. any:any list from top-level xfrm_pol_inexact_bin
106 * 2. any:daddr list from daddr tree
107 * 3. saddr:daddr list from 2nd level daddr tree
108 * 4. saddr:any list from saddr tree
110 * This result set then needs to be searched for the policy with
111 * the lowest priority. If two results have same prio, youngest one wins.
114 struct xfrm_pol_inexact_key {
121 struct xfrm_pol_inexact_bin {
122 struct xfrm_pol_inexact_key k;
123 struct rhash_head head;
124 /* list containing '*:*' policies */
125 struct hlist_head hhead;
127 seqcount_spinlock_t count;
128 /* tree sorted by daddr/prefix */
129 struct rb_root root_d;
131 /* tree sorted by saddr/prefix */
132 struct rb_root root_s;
134 /* slow path below */
135 struct list_head inexact_bins;
139 enum xfrm_pol_inexact_candidate_type {
148 struct xfrm_pol_inexact_candidates {
149 struct hlist_head *res[XFRM_POL_CAND_MAX];
152 static DEFINE_SPINLOCK(xfrm_if_cb_lock);
153 static struct xfrm_if_cb const __rcu *xfrm_if_cb __read_mostly;
155 static DEFINE_SPINLOCK(xfrm_policy_afinfo_lock);
156 static struct xfrm_policy_afinfo const __rcu *xfrm_policy_afinfo[AF_INET6 + 1]
159 static struct kmem_cache *xfrm_dst_cache __ro_after_init;
161 static struct rhashtable xfrm_policy_inexact_table;
162 static const struct rhashtable_params xfrm_pol_inexact_params;
164 static void xfrm_init_pmtu(struct xfrm_dst **bundle, int nr);
165 static int stale_bundle(struct dst_entry *dst);
166 static int xfrm_bundle_ok(struct xfrm_dst *xdst);
167 static void xfrm_policy_queue_process(struct timer_list *t);
169 static void __xfrm_policy_link(struct xfrm_policy *pol, int dir);
170 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
173 static struct xfrm_pol_inexact_bin *
174 xfrm_policy_inexact_lookup(struct net *net, u8 type, u16 family, u8 dir,
177 static struct xfrm_pol_inexact_bin *
178 xfrm_policy_inexact_lookup_rcu(struct net *net,
179 u8 type, u16 family, u8 dir, u32 if_id);
180 static struct xfrm_policy *
181 xfrm_policy_insert_list(struct hlist_head *chain, struct xfrm_policy *policy,
183 static void xfrm_policy_insert_inexact_list(struct hlist_head *chain,
184 struct xfrm_policy *policy);
187 xfrm_policy_find_inexact_candidates(struct xfrm_pol_inexact_candidates *cand,
188 struct xfrm_pol_inexact_bin *b,
189 const xfrm_address_t *saddr,
190 const xfrm_address_t *daddr);
192 static inline bool xfrm_pol_hold_rcu(struct xfrm_policy *policy)
194 return refcount_inc_not_zero(&policy->refcnt);
198 __xfrm4_selector_match(const struct xfrm_selector *sel, const struct flowi *fl)
200 const struct flowi4 *fl4 = &fl->u.ip4;
202 return addr4_match(fl4->daddr, sel->daddr.a4, sel->prefixlen_d) &&
203 addr4_match(fl4->saddr, sel->saddr.a4, sel->prefixlen_s) &&
204 !((xfrm_flowi_dport(fl, &fl4->uli) ^ sel->dport) & sel->dport_mask) &&
205 !((xfrm_flowi_sport(fl, &fl4->uli) ^ sel->sport) & sel->sport_mask) &&
206 (fl4->flowi4_proto == sel->proto || !sel->proto) &&
207 (fl4->flowi4_oif == sel->ifindex || !sel->ifindex);
211 __xfrm6_selector_match(const struct xfrm_selector *sel, const struct flowi *fl)
213 const struct flowi6 *fl6 = &fl->u.ip6;
215 return addr_match(&fl6->daddr, &sel->daddr, sel->prefixlen_d) &&
216 addr_match(&fl6->saddr, &sel->saddr, sel->prefixlen_s) &&
217 !((xfrm_flowi_dport(fl, &fl6->uli) ^ sel->dport) & sel->dport_mask) &&
218 !((xfrm_flowi_sport(fl, &fl6->uli) ^ sel->sport) & sel->sport_mask) &&
219 (fl6->flowi6_proto == sel->proto || !sel->proto) &&
220 (fl6->flowi6_oif == sel->ifindex || !sel->ifindex);
223 bool xfrm_selector_match(const struct xfrm_selector *sel, const struct flowi *fl,
224 unsigned short family)
228 return __xfrm4_selector_match(sel, fl);
230 return __xfrm6_selector_match(sel, fl);
235 static const struct xfrm_policy_afinfo *xfrm_policy_get_afinfo(unsigned short family)
237 const struct xfrm_policy_afinfo *afinfo;
239 if (unlikely(family >= ARRAY_SIZE(xfrm_policy_afinfo)))
242 afinfo = rcu_dereference(xfrm_policy_afinfo[family]);
243 if (unlikely(!afinfo))
248 /* Called with rcu_read_lock(). */
249 static const struct xfrm_if_cb *xfrm_if_get_cb(void)
251 return rcu_dereference(xfrm_if_cb);
254 struct dst_entry *__xfrm_dst_lookup(struct net *net, int tos, int oif,
255 const xfrm_address_t *saddr,
256 const xfrm_address_t *daddr,
257 int family, u32 mark)
259 const struct xfrm_policy_afinfo *afinfo;
260 struct dst_entry *dst;
262 afinfo = xfrm_policy_get_afinfo(family);
263 if (unlikely(afinfo == NULL))
264 return ERR_PTR(-EAFNOSUPPORT);
266 dst = afinfo->dst_lookup(net, tos, oif, saddr, daddr, mark);
272 EXPORT_SYMBOL(__xfrm_dst_lookup);
274 static inline struct dst_entry *xfrm_dst_lookup(struct xfrm_state *x,
276 xfrm_address_t *prev_saddr,
277 xfrm_address_t *prev_daddr,
278 int family, u32 mark)
280 struct net *net = xs_net(x);
281 xfrm_address_t *saddr = &x->props.saddr;
282 xfrm_address_t *daddr = &x->id.daddr;
283 struct dst_entry *dst;
285 if (x->type->flags & XFRM_TYPE_LOCAL_COADDR) {
289 if (x->type->flags & XFRM_TYPE_REMOTE_COADDR) {
294 dst = __xfrm_dst_lookup(net, tos, oif, saddr, daddr, family, mark);
297 if (prev_saddr != saddr)
298 memcpy(prev_saddr, saddr, sizeof(*prev_saddr));
299 if (prev_daddr != daddr)
300 memcpy(prev_daddr, daddr, sizeof(*prev_daddr));
306 static inline unsigned long make_jiffies(long secs)
308 if (secs >= (MAX_SCHEDULE_TIMEOUT-1)/HZ)
309 return MAX_SCHEDULE_TIMEOUT-1;
314 static void xfrm_policy_timer(struct timer_list *t)
316 struct xfrm_policy *xp = from_timer(xp, t, timer);
317 time64_t now = ktime_get_real_seconds();
318 time64_t next = TIME64_MAX;
322 read_lock(&xp->lock);
324 if (unlikely(xp->walk.dead))
327 dir = xfrm_policy_id2dir(xp->index);
329 if (xp->lft.hard_add_expires_seconds) {
330 time64_t tmo = xp->lft.hard_add_expires_seconds +
331 xp->curlft.add_time - now;
337 if (xp->lft.hard_use_expires_seconds) {
338 time64_t tmo = xp->lft.hard_use_expires_seconds +
339 (READ_ONCE(xp->curlft.use_time) ? : xp->curlft.add_time) - now;
345 if (xp->lft.soft_add_expires_seconds) {
346 time64_t tmo = xp->lft.soft_add_expires_seconds +
347 xp->curlft.add_time - now;
350 tmo = XFRM_KM_TIMEOUT;
355 if (xp->lft.soft_use_expires_seconds) {
356 time64_t tmo = xp->lft.soft_use_expires_seconds +
357 (READ_ONCE(xp->curlft.use_time) ? : xp->curlft.add_time) - now;
360 tmo = XFRM_KM_TIMEOUT;
367 km_policy_expired(xp, dir, 0, 0);
368 if (next != TIME64_MAX &&
369 !mod_timer(&xp->timer, jiffies + make_jiffies(next)))
373 read_unlock(&xp->lock);
378 read_unlock(&xp->lock);
379 if (!xfrm_policy_delete(xp, dir))
380 km_policy_expired(xp, dir, 1, 0);
384 /* Allocate xfrm_policy. Not used here, it is supposed to be used by pfkeyv2
388 struct xfrm_policy *xfrm_policy_alloc(struct net *net, gfp_t gfp)
390 struct xfrm_policy *policy;
392 policy = kzalloc(sizeof(struct xfrm_policy), gfp);
395 write_pnet(&policy->xp_net, net);
396 INIT_LIST_HEAD(&policy->walk.all);
397 INIT_HLIST_NODE(&policy->bydst_inexact_list);
398 INIT_HLIST_NODE(&policy->bydst);
399 INIT_HLIST_NODE(&policy->byidx);
400 rwlock_init(&policy->lock);
401 refcount_set(&policy->refcnt, 1);
402 skb_queue_head_init(&policy->polq.hold_queue);
403 timer_setup(&policy->timer, xfrm_policy_timer, 0);
404 timer_setup(&policy->polq.hold_timer,
405 xfrm_policy_queue_process, 0);
409 EXPORT_SYMBOL(xfrm_policy_alloc);
411 static void xfrm_policy_destroy_rcu(struct rcu_head *head)
413 struct xfrm_policy *policy = container_of(head, struct xfrm_policy, rcu);
415 security_xfrm_policy_free(policy->security);
419 /* Destroy xfrm_policy: descendant resources must be released to this moment. */
421 void xfrm_policy_destroy(struct xfrm_policy *policy)
423 BUG_ON(!policy->walk.dead);
425 if (del_timer(&policy->timer) || del_timer(&policy->polq.hold_timer))
428 xfrm_dev_policy_free(policy);
429 call_rcu(&policy->rcu, xfrm_policy_destroy_rcu);
431 EXPORT_SYMBOL(xfrm_policy_destroy);
433 /* Rule must be locked. Release descendant resources, announce
434 * entry dead. The rule must be unlinked from lists to the moment.
437 static void xfrm_policy_kill(struct xfrm_policy *policy)
439 write_lock_bh(&policy->lock);
440 policy->walk.dead = 1;
441 write_unlock_bh(&policy->lock);
443 atomic_inc(&policy->genid);
445 if (del_timer(&policy->polq.hold_timer))
446 xfrm_pol_put(policy);
447 skb_queue_purge(&policy->polq.hold_queue);
449 if (del_timer(&policy->timer))
450 xfrm_pol_put(policy);
452 xfrm_pol_put(policy);
455 static unsigned int xfrm_policy_hashmax __read_mostly = 1 * 1024 * 1024;
457 static inline unsigned int idx_hash(struct net *net, u32 index)
459 return __idx_hash(index, net->xfrm.policy_idx_hmask);
462 /* calculate policy hash thresholds */
463 static void __get_hash_thresh(struct net *net,
464 unsigned short family, int dir,
465 u8 *dbits, u8 *sbits)
469 *dbits = net->xfrm.policy_bydst[dir].dbits4;
470 *sbits = net->xfrm.policy_bydst[dir].sbits4;
474 *dbits = net->xfrm.policy_bydst[dir].dbits6;
475 *sbits = net->xfrm.policy_bydst[dir].sbits6;
484 static struct hlist_head *policy_hash_bysel(struct net *net,
485 const struct xfrm_selector *sel,
486 unsigned short family, int dir)
488 unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
493 __get_hash_thresh(net, family, dir, &dbits, &sbits);
494 hash = __sel_hash(sel, family, hmask, dbits, sbits);
496 if (hash == hmask + 1)
499 return rcu_dereference_check(net->xfrm.policy_bydst[dir].table,
500 lockdep_is_held(&net->xfrm.xfrm_policy_lock)) + hash;
503 static struct hlist_head *policy_hash_direct(struct net *net,
504 const xfrm_address_t *daddr,
505 const xfrm_address_t *saddr,
506 unsigned short family, int dir)
508 unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
513 __get_hash_thresh(net, family, dir, &dbits, &sbits);
514 hash = __addr_hash(daddr, saddr, family, hmask, dbits, sbits);
516 return rcu_dereference_check(net->xfrm.policy_bydst[dir].table,
517 lockdep_is_held(&net->xfrm.xfrm_policy_lock)) + hash;
520 static void xfrm_dst_hash_transfer(struct net *net,
521 struct hlist_head *list,
522 struct hlist_head *ndsttable,
523 unsigned int nhashmask,
526 struct hlist_node *tmp, *entry0 = NULL;
527 struct xfrm_policy *pol;
533 hlist_for_each_entry_safe(pol, tmp, list, bydst) {
536 __get_hash_thresh(net, pol->family, dir, &dbits, &sbits);
537 h = __addr_hash(&pol->selector.daddr, &pol->selector.saddr,
538 pol->family, nhashmask, dbits, sbits);
539 if (!entry0 || pol->xdo.type == XFRM_DEV_OFFLOAD_PACKET) {
540 hlist_del_rcu(&pol->bydst);
541 hlist_add_head_rcu(&pol->bydst, ndsttable + h);
546 hlist_del_rcu(&pol->bydst);
547 hlist_add_behind_rcu(&pol->bydst, entry0);
549 entry0 = &pol->bydst;
551 if (!hlist_empty(list)) {
557 static void xfrm_idx_hash_transfer(struct hlist_head *list,
558 struct hlist_head *nidxtable,
559 unsigned int nhashmask)
561 struct hlist_node *tmp;
562 struct xfrm_policy *pol;
564 hlist_for_each_entry_safe(pol, tmp, list, byidx) {
567 h = __idx_hash(pol->index, nhashmask);
568 hlist_add_head(&pol->byidx, nidxtable+h);
572 static unsigned long xfrm_new_hash_mask(unsigned int old_hmask)
574 return ((old_hmask + 1) << 1) - 1;
577 static void xfrm_bydst_resize(struct net *net, int dir)
579 unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
580 unsigned int nhashmask = xfrm_new_hash_mask(hmask);
581 unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
582 struct hlist_head *ndst = xfrm_hash_alloc(nsize);
583 struct hlist_head *odst;
589 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
590 write_seqcount_begin(&net->xfrm.xfrm_policy_hash_generation);
592 odst = rcu_dereference_protected(net->xfrm.policy_bydst[dir].table,
593 lockdep_is_held(&net->xfrm.xfrm_policy_lock));
595 for (i = hmask; i >= 0; i--)
596 xfrm_dst_hash_transfer(net, odst + i, ndst, nhashmask, dir);
598 rcu_assign_pointer(net->xfrm.policy_bydst[dir].table, ndst);
599 net->xfrm.policy_bydst[dir].hmask = nhashmask;
601 write_seqcount_end(&net->xfrm.xfrm_policy_hash_generation);
602 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
606 xfrm_hash_free(odst, (hmask + 1) * sizeof(struct hlist_head));
609 static void xfrm_byidx_resize(struct net *net)
611 unsigned int hmask = net->xfrm.policy_idx_hmask;
612 unsigned int nhashmask = xfrm_new_hash_mask(hmask);
613 unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
614 struct hlist_head *oidx = net->xfrm.policy_byidx;
615 struct hlist_head *nidx = xfrm_hash_alloc(nsize);
621 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
623 for (i = hmask; i >= 0; i--)
624 xfrm_idx_hash_transfer(oidx + i, nidx, nhashmask);
626 net->xfrm.policy_byidx = nidx;
627 net->xfrm.policy_idx_hmask = nhashmask;
629 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
631 xfrm_hash_free(oidx, (hmask + 1) * sizeof(struct hlist_head));
634 static inline int xfrm_bydst_should_resize(struct net *net, int dir, int *total)
636 unsigned int cnt = net->xfrm.policy_count[dir];
637 unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
642 if ((hmask + 1) < xfrm_policy_hashmax &&
649 static inline int xfrm_byidx_should_resize(struct net *net, int total)
651 unsigned int hmask = net->xfrm.policy_idx_hmask;
653 if ((hmask + 1) < xfrm_policy_hashmax &&
660 void xfrm_spd_getinfo(struct net *net, struct xfrmk_spdinfo *si)
662 si->incnt = net->xfrm.policy_count[XFRM_POLICY_IN];
663 si->outcnt = net->xfrm.policy_count[XFRM_POLICY_OUT];
664 si->fwdcnt = net->xfrm.policy_count[XFRM_POLICY_FWD];
665 si->inscnt = net->xfrm.policy_count[XFRM_POLICY_IN+XFRM_POLICY_MAX];
666 si->outscnt = net->xfrm.policy_count[XFRM_POLICY_OUT+XFRM_POLICY_MAX];
667 si->fwdscnt = net->xfrm.policy_count[XFRM_POLICY_FWD+XFRM_POLICY_MAX];
668 si->spdhcnt = net->xfrm.policy_idx_hmask;
669 si->spdhmcnt = xfrm_policy_hashmax;
671 EXPORT_SYMBOL(xfrm_spd_getinfo);
673 static DEFINE_MUTEX(hash_resize_mutex);
674 static void xfrm_hash_resize(struct work_struct *work)
676 struct net *net = container_of(work, struct net, xfrm.policy_hash_work);
679 mutex_lock(&hash_resize_mutex);
682 for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
683 if (xfrm_bydst_should_resize(net, dir, &total))
684 xfrm_bydst_resize(net, dir);
686 if (xfrm_byidx_should_resize(net, total))
687 xfrm_byidx_resize(net);
689 mutex_unlock(&hash_resize_mutex);
692 /* Make sure *pol can be inserted into fastbin.
693 * Useful to check that later insert requests will be successful
694 * (provided xfrm_policy_lock is held throughout).
696 static struct xfrm_pol_inexact_bin *
697 xfrm_policy_inexact_alloc_bin(const struct xfrm_policy *pol, u8 dir)
699 struct xfrm_pol_inexact_bin *bin, *prev;
700 struct xfrm_pol_inexact_key k = {
701 .family = pol->family,
706 struct net *net = xp_net(pol);
708 lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
710 write_pnet(&k.net, net);
711 bin = rhashtable_lookup_fast(&xfrm_policy_inexact_table, &k,
712 xfrm_pol_inexact_params);
716 bin = kzalloc(sizeof(*bin), GFP_ATOMIC);
721 INIT_HLIST_HEAD(&bin->hhead);
722 bin->root_d = RB_ROOT;
723 bin->root_s = RB_ROOT;
724 seqcount_spinlock_init(&bin->count, &net->xfrm.xfrm_policy_lock);
726 prev = rhashtable_lookup_get_insert_key(&xfrm_policy_inexact_table,
728 xfrm_pol_inexact_params);
730 list_add(&bin->inexact_bins, &net->xfrm.inexact_bins);
736 return IS_ERR(prev) ? NULL : prev;
739 static bool xfrm_pol_inexact_addr_use_any_list(const xfrm_address_t *addr,
740 int family, u8 prefixlen)
742 if (xfrm_addr_any(addr, family))
745 if (family == AF_INET6 && prefixlen < INEXACT_PREFIXLEN_IPV6)
748 if (family == AF_INET && prefixlen < INEXACT_PREFIXLEN_IPV4)
755 xfrm_policy_inexact_insert_use_any_list(const struct xfrm_policy *policy)
757 const xfrm_address_t *addr;
758 bool saddr_any, daddr_any;
761 addr = &policy->selector.saddr;
762 prefixlen = policy->selector.prefixlen_s;
764 saddr_any = xfrm_pol_inexact_addr_use_any_list(addr,
767 addr = &policy->selector.daddr;
768 prefixlen = policy->selector.prefixlen_d;
769 daddr_any = xfrm_pol_inexact_addr_use_any_list(addr,
772 return saddr_any && daddr_any;
775 static void xfrm_pol_inexact_node_init(struct xfrm_pol_inexact_node *node,
776 const xfrm_address_t *addr, u8 prefixlen)
779 node->prefixlen = prefixlen;
782 static struct xfrm_pol_inexact_node *
783 xfrm_pol_inexact_node_alloc(const xfrm_address_t *addr, u8 prefixlen)
785 struct xfrm_pol_inexact_node *node;
787 node = kzalloc(sizeof(*node), GFP_ATOMIC);
789 xfrm_pol_inexact_node_init(node, addr, prefixlen);
794 static int xfrm_policy_addr_delta(const xfrm_address_t *a,
795 const xfrm_address_t *b,
796 u8 prefixlen, u16 family)
799 unsigned int pdw, pbi;
806 mask = ~0U << (32 - prefixlen);
807 ma = ntohl(a->a4) & mask;
808 mb = ntohl(b->a4) & mask;
815 pdw = prefixlen >> 5;
816 pbi = prefixlen & 0x1f;
819 delta = memcmp(a->a6, b->a6, pdw << 2);
824 mask = ~0U << (32 - pbi);
825 ma = ntohl(a->a6[pdw]) & mask;
826 mb = ntohl(b->a6[pdw]) & mask;
840 static void xfrm_policy_inexact_list_reinsert(struct net *net,
841 struct xfrm_pol_inexact_node *n,
844 unsigned int matched_s, matched_d;
845 struct xfrm_policy *policy, *p;
850 list_for_each_entry_reverse(policy, &net->xfrm.policy_all, walk.all) {
851 struct hlist_node *newpos = NULL;
852 bool matches_s, matches_d;
854 if (!policy->bydst_reinsert)
857 WARN_ON_ONCE(policy->family != family);
859 policy->bydst_reinsert = false;
860 hlist_for_each_entry(p, &n->hhead, bydst) {
861 if (policy->priority > p->priority)
863 else if (policy->priority == p->priority &&
864 policy->pos > p->pos)
870 if (newpos && policy->xdo.type != XFRM_DEV_OFFLOAD_PACKET)
871 hlist_add_behind_rcu(&policy->bydst, newpos);
873 hlist_add_head_rcu(&policy->bydst, &n->hhead);
875 /* paranoia checks follow.
876 * Check that the reinserted policy matches at least
877 * saddr or daddr for current node prefix.
879 * Matching both is fine, matching saddr in one policy
880 * (but not daddr) and then matching only daddr in another
883 matches_s = xfrm_policy_addr_delta(&policy->selector.saddr,
887 matches_d = xfrm_policy_addr_delta(&policy->selector.daddr,
891 if (matches_s && matches_d)
894 WARN_ON_ONCE(!matches_s && !matches_d);
899 WARN_ON_ONCE(matched_s && matched_d);
903 static void xfrm_policy_inexact_node_reinsert(struct net *net,
904 struct xfrm_pol_inexact_node *n,
908 struct xfrm_pol_inexact_node *node;
909 struct rb_node **p, *parent;
911 /* we should not have another subtree here */
912 WARN_ON_ONCE(!RB_EMPTY_ROOT(&n->root));
921 node = rb_entry(*p, struct xfrm_pol_inexact_node, node);
923 prefixlen = min(node->prefixlen, n->prefixlen);
925 delta = xfrm_policy_addr_delta(&n->addr, &node->addr,
928 p = &parent->rb_left;
929 } else if (delta > 0) {
930 p = &parent->rb_right;
932 bool same_prefixlen = node->prefixlen == n->prefixlen;
933 struct xfrm_policy *tmp;
935 hlist_for_each_entry(tmp, &n->hhead, bydst) {
936 tmp->bydst_reinsert = true;
937 hlist_del_rcu(&tmp->bydst);
940 node->prefixlen = prefixlen;
942 xfrm_policy_inexact_list_reinsert(net, node, family);
944 if (same_prefixlen) {
956 rb_link_node_rcu(&n->node, parent, p);
957 rb_insert_color(&n->node, new);
960 /* merge nodes v and n */
961 static void xfrm_policy_inexact_node_merge(struct net *net,
962 struct xfrm_pol_inexact_node *v,
963 struct xfrm_pol_inexact_node *n,
966 struct xfrm_pol_inexact_node *node;
967 struct xfrm_policy *tmp;
968 struct rb_node *rnode;
970 /* To-be-merged node v has a subtree.
972 * Dismantle it and insert its nodes to n->root.
974 while ((rnode = rb_first(&v->root)) != NULL) {
975 node = rb_entry(rnode, struct xfrm_pol_inexact_node, node);
976 rb_erase(&node->node, &v->root);
977 xfrm_policy_inexact_node_reinsert(net, node, &n->root,
981 hlist_for_each_entry(tmp, &v->hhead, bydst) {
982 tmp->bydst_reinsert = true;
983 hlist_del_rcu(&tmp->bydst);
986 xfrm_policy_inexact_list_reinsert(net, n, family);
989 static struct xfrm_pol_inexact_node *
990 xfrm_policy_inexact_insert_node(struct net *net,
991 struct rb_root *root,
992 xfrm_address_t *addr,
993 u16 family, u8 prefixlen, u8 dir)
995 struct xfrm_pol_inexact_node *cached = NULL;
996 struct rb_node **p, *parent = NULL;
997 struct xfrm_pol_inexact_node *node;
1004 node = rb_entry(*p, struct xfrm_pol_inexact_node, node);
1006 delta = xfrm_policy_addr_delta(addr, &node->addr,
1009 if (delta == 0 && prefixlen >= node->prefixlen) {
1010 WARN_ON_ONCE(cached); /* ipsec policies got lost */
1015 p = &parent->rb_left;
1017 p = &parent->rb_right;
1019 if (prefixlen < node->prefixlen) {
1020 delta = xfrm_policy_addr_delta(addr, &node->addr,
1026 /* This node is a subnet of the new prefix. It needs
1027 * to be removed and re-inserted with the smaller
1028 * prefix and all nodes that are now also covered
1029 * by the reduced prefixlen.
1031 rb_erase(&node->node, root);
1034 xfrm_pol_inexact_node_init(node, addr,
1038 /* This node also falls within the new
1039 * prefixlen. Merge the to-be-reinserted
1040 * node and this one.
1042 xfrm_policy_inexact_node_merge(net, node,
1044 kfree_rcu(node, rcu);
1055 node = xfrm_pol_inexact_node_alloc(addr, prefixlen);
1060 rb_link_node_rcu(&node->node, parent, p);
1061 rb_insert_color(&node->node, root);
1066 static void xfrm_policy_inexact_gc_tree(struct rb_root *r, bool rm)
1068 struct xfrm_pol_inexact_node *node;
1069 struct rb_node *rn = rb_first(r);
1072 node = rb_entry(rn, struct xfrm_pol_inexact_node, node);
1074 xfrm_policy_inexact_gc_tree(&node->root, rm);
1077 if (!hlist_empty(&node->hhead) || !RB_EMPTY_ROOT(&node->root)) {
1082 rb_erase(&node->node, r);
1083 kfree_rcu(node, rcu);
1087 static void __xfrm_policy_inexact_prune_bin(struct xfrm_pol_inexact_bin *b, bool net_exit)
1089 write_seqcount_begin(&b->count);
1090 xfrm_policy_inexact_gc_tree(&b->root_d, net_exit);
1091 xfrm_policy_inexact_gc_tree(&b->root_s, net_exit);
1092 write_seqcount_end(&b->count);
1094 if (!RB_EMPTY_ROOT(&b->root_d) || !RB_EMPTY_ROOT(&b->root_s) ||
1095 !hlist_empty(&b->hhead)) {
1096 WARN_ON_ONCE(net_exit);
1100 if (rhashtable_remove_fast(&xfrm_policy_inexact_table, &b->head,
1101 xfrm_pol_inexact_params) == 0) {
1102 list_del(&b->inexact_bins);
1107 static void xfrm_policy_inexact_prune_bin(struct xfrm_pol_inexact_bin *b)
1109 struct net *net = read_pnet(&b->k.net);
1111 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1112 __xfrm_policy_inexact_prune_bin(b, false);
1113 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1116 static void __xfrm_policy_inexact_flush(struct net *net)
1118 struct xfrm_pol_inexact_bin *bin, *t;
1120 lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
1122 list_for_each_entry_safe(bin, t, &net->xfrm.inexact_bins, inexact_bins)
1123 __xfrm_policy_inexact_prune_bin(bin, false);
1126 static struct hlist_head *
1127 xfrm_policy_inexact_alloc_chain(struct xfrm_pol_inexact_bin *bin,
1128 struct xfrm_policy *policy, u8 dir)
1130 struct xfrm_pol_inexact_node *n;
1133 net = xp_net(policy);
1134 lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
1136 if (xfrm_policy_inexact_insert_use_any_list(policy))
1139 if (xfrm_pol_inexact_addr_use_any_list(&policy->selector.daddr,
1141 policy->selector.prefixlen_d)) {
1142 write_seqcount_begin(&bin->count);
1143 n = xfrm_policy_inexact_insert_node(net,
1145 &policy->selector.saddr,
1147 policy->selector.prefixlen_s,
1149 write_seqcount_end(&bin->count);
1156 /* daddr is fixed */
1157 write_seqcount_begin(&bin->count);
1158 n = xfrm_policy_inexact_insert_node(net,
1160 &policy->selector.daddr,
1162 policy->selector.prefixlen_d, dir);
1163 write_seqcount_end(&bin->count);
1167 /* saddr is wildcard */
1168 if (xfrm_pol_inexact_addr_use_any_list(&policy->selector.saddr,
1170 policy->selector.prefixlen_s))
1173 write_seqcount_begin(&bin->count);
1174 n = xfrm_policy_inexact_insert_node(net,
1176 &policy->selector.saddr,
1178 policy->selector.prefixlen_s, dir);
1179 write_seqcount_end(&bin->count);
1186 static struct xfrm_policy *
1187 xfrm_policy_inexact_insert(struct xfrm_policy *policy, u8 dir, int excl)
1189 struct xfrm_pol_inexact_bin *bin;
1190 struct xfrm_policy *delpol;
1191 struct hlist_head *chain;
1194 bin = xfrm_policy_inexact_alloc_bin(policy, dir);
1196 return ERR_PTR(-ENOMEM);
1198 net = xp_net(policy);
1199 lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
1201 chain = xfrm_policy_inexact_alloc_chain(bin, policy, dir);
1203 __xfrm_policy_inexact_prune_bin(bin, false);
1204 return ERR_PTR(-ENOMEM);
1207 delpol = xfrm_policy_insert_list(chain, policy, excl);
1208 if (delpol && excl) {
1209 __xfrm_policy_inexact_prune_bin(bin, false);
1210 return ERR_PTR(-EEXIST);
1213 chain = &net->xfrm.policy_inexact[dir];
1214 xfrm_policy_insert_inexact_list(chain, policy);
1217 __xfrm_policy_inexact_prune_bin(bin, false);
1222 static void xfrm_hash_rebuild(struct work_struct *work)
1224 struct net *net = container_of(work, struct net,
1225 xfrm.policy_hthresh.work);
1227 struct xfrm_policy *pol;
1228 struct xfrm_policy *policy;
1229 struct hlist_head *chain;
1230 struct hlist_head *odst;
1231 struct hlist_node *newpos;
1235 u8 lbits4, rbits4, lbits6, rbits6;
1237 mutex_lock(&hash_resize_mutex);
1239 /* read selector prefixlen thresholds */
1241 seq = read_seqbegin(&net->xfrm.policy_hthresh.lock);
1243 lbits4 = net->xfrm.policy_hthresh.lbits4;
1244 rbits4 = net->xfrm.policy_hthresh.rbits4;
1245 lbits6 = net->xfrm.policy_hthresh.lbits6;
1246 rbits6 = net->xfrm.policy_hthresh.rbits6;
1247 } while (read_seqretry(&net->xfrm.policy_hthresh.lock, seq));
1249 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1250 write_seqcount_begin(&net->xfrm.xfrm_policy_hash_generation);
1252 /* make sure that we can insert the indirect policies again before
1253 * we start with destructive action.
1255 list_for_each_entry(policy, &net->xfrm.policy_all, walk.all) {
1256 struct xfrm_pol_inexact_bin *bin;
1259 dir = xfrm_policy_id2dir(policy->index);
1260 if (policy->walk.dead || dir >= XFRM_POLICY_MAX)
1263 if ((dir & XFRM_POLICY_MASK) == XFRM_POLICY_OUT) {
1264 if (policy->family == AF_INET) {
1272 if (policy->family == AF_INET) {
1281 if (policy->selector.prefixlen_d < dbits ||
1282 policy->selector.prefixlen_s < sbits)
1285 bin = xfrm_policy_inexact_alloc_bin(policy, dir);
1289 if (!xfrm_policy_inexact_alloc_chain(bin, policy, dir))
1293 /* reset the bydst and inexact table in all directions */
1294 for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
1295 struct hlist_node *n;
1297 hlist_for_each_entry_safe(policy, n,
1298 &net->xfrm.policy_inexact[dir],
1299 bydst_inexact_list) {
1300 hlist_del_rcu(&policy->bydst);
1301 hlist_del_init(&policy->bydst_inexact_list);
1304 hmask = net->xfrm.policy_bydst[dir].hmask;
1305 odst = net->xfrm.policy_bydst[dir].table;
1306 for (i = hmask; i >= 0; i--) {
1307 hlist_for_each_entry_safe(policy, n, odst + i, bydst)
1308 hlist_del_rcu(&policy->bydst);
1310 if ((dir & XFRM_POLICY_MASK) == XFRM_POLICY_OUT) {
1311 /* dir out => dst = remote, src = local */
1312 net->xfrm.policy_bydst[dir].dbits4 = rbits4;
1313 net->xfrm.policy_bydst[dir].sbits4 = lbits4;
1314 net->xfrm.policy_bydst[dir].dbits6 = rbits6;
1315 net->xfrm.policy_bydst[dir].sbits6 = lbits6;
1317 /* dir in/fwd => dst = local, src = remote */
1318 net->xfrm.policy_bydst[dir].dbits4 = lbits4;
1319 net->xfrm.policy_bydst[dir].sbits4 = rbits4;
1320 net->xfrm.policy_bydst[dir].dbits6 = lbits6;
1321 net->xfrm.policy_bydst[dir].sbits6 = rbits6;
1325 /* re-insert all policies by order of creation */
1326 list_for_each_entry_reverse(policy, &net->xfrm.policy_all, walk.all) {
1327 if (policy->walk.dead)
1329 dir = xfrm_policy_id2dir(policy->index);
1330 if (dir >= XFRM_POLICY_MAX) {
1331 /* skip socket policies */
1335 chain = policy_hash_bysel(net, &policy->selector,
1336 policy->family, dir);
1339 void *p = xfrm_policy_inexact_insert(policy, dir, 0);
1341 WARN_ONCE(IS_ERR(p), "reinsert: %ld\n", PTR_ERR(p));
1345 hlist_for_each_entry(pol, chain, bydst) {
1346 if (policy->priority >= pol->priority)
1347 newpos = &pol->bydst;
1351 if (newpos && policy->xdo.type != XFRM_DEV_OFFLOAD_PACKET)
1352 hlist_add_behind_rcu(&policy->bydst, newpos);
1354 hlist_add_head_rcu(&policy->bydst, chain);
1358 __xfrm_policy_inexact_flush(net);
1359 write_seqcount_end(&net->xfrm.xfrm_policy_hash_generation);
1360 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1362 mutex_unlock(&hash_resize_mutex);
1365 void xfrm_policy_hash_rebuild(struct net *net)
1367 schedule_work(&net->xfrm.policy_hthresh.work);
1369 EXPORT_SYMBOL(xfrm_policy_hash_rebuild);
1371 /* Generate new index... KAME seems to generate them ordered by cost
1372 * of an absolute inpredictability of ordering of rules. This will not pass. */
1373 static u32 xfrm_gen_index(struct net *net, int dir, u32 index)
1375 static u32 idx_generator;
1378 struct hlist_head *list;
1379 struct xfrm_policy *p;
1384 idx = (idx_generator | dir);
1393 list = net->xfrm.policy_byidx + idx_hash(net, idx);
1395 hlist_for_each_entry(p, list, byidx) {
1396 if (p->index == idx) {
1406 static inline int selector_cmp(struct xfrm_selector *s1, struct xfrm_selector *s2)
1408 u32 *p1 = (u32 *) s1;
1409 u32 *p2 = (u32 *) s2;
1410 int len = sizeof(struct xfrm_selector) / sizeof(u32);
1413 for (i = 0; i < len; i++) {
1421 static void xfrm_policy_requeue(struct xfrm_policy *old,
1422 struct xfrm_policy *new)
1424 struct xfrm_policy_queue *pq = &old->polq;
1425 struct sk_buff_head list;
1427 if (skb_queue_empty(&pq->hold_queue))
1430 __skb_queue_head_init(&list);
1432 spin_lock_bh(&pq->hold_queue.lock);
1433 skb_queue_splice_init(&pq->hold_queue, &list);
1434 if (del_timer(&pq->hold_timer))
1436 spin_unlock_bh(&pq->hold_queue.lock);
1440 spin_lock_bh(&pq->hold_queue.lock);
1441 skb_queue_splice(&list, &pq->hold_queue);
1442 pq->timeout = XFRM_QUEUE_TMO_MIN;
1443 if (!mod_timer(&pq->hold_timer, jiffies))
1445 spin_unlock_bh(&pq->hold_queue.lock);
1448 static inline bool xfrm_policy_mark_match(const struct xfrm_mark *mark,
1449 struct xfrm_policy *pol)
1451 return mark->v == pol->mark.v && mark->m == pol->mark.m;
1454 static u32 xfrm_pol_bin_key(const void *data, u32 len, u32 seed)
1456 const struct xfrm_pol_inexact_key *k = data;
1457 u32 a = k->type << 24 | k->dir << 16 | k->family;
1459 return jhash_3words(a, k->if_id, net_hash_mix(read_pnet(&k->net)),
1463 static u32 xfrm_pol_bin_obj(const void *data, u32 len, u32 seed)
1465 const struct xfrm_pol_inexact_bin *b = data;
1467 return xfrm_pol_bin_key(&b->k, 0, seed);
1470 static int xfrm_pol_bin_cmp(struct rhashtable_compare_arg *arg,
1473 const struct xfrm_pol_inexact_key *key = arg->key;
1474 const struct xfrm_pol_inexact_bin *b = ptr;
1477 if (!net_eq(read_pnet(&b->k.net), read_pnet(&key->net)))
1480 ret = b->k.dir ^ key->dir;
1484 ret = b->k.type ^ key->type;
1488 ret = b->k.family ^ key->family;
1492 return b->k.if_id ^ key->if_id;
1495 static const struct rhashtable_params xfrm_pol_inexact_params = {
1496 .head_offset = offsetof(struct xfrm_pol_inexact_bin, head),
1497 .hashfn = xfrm_pol_bin_key,
1498 .obj_hashfn = xfrm_pol_bin_obj,
1499 .obj_cmpfn = xfrm_pol_bin_cmp,
1500 .automatic_shrinking = true,
1503 static void xfrm_policy_insert_inexact_list(struct hlist_head *chain,
1504 struct xfrm_policy *policy)
1506 struct xfrm_policy *pol, *delpol = NULL;
1507 struct hlist_node *newpos = NULL;
1510 hlist_for_each_entry(pol, chain, bydst_inexact_list) {
1511 if (pol->type == policy->type &&
1512 pol->if_id == policy->if_id &&
1513 !selector_cmp(&pol->selector, &policy->selector) &&
1514 xfrm_policy_mark_match(&policy->mark, pol) &&
1515 xfrm_sec_ctx_match(pol->security, policy->security) &&
1518 if (policy->priority > pol->priority)
1520 } else if (policy->priority >= pol->priority) {
1521 newpos = &pol->bydst_inexact_list;
1528 if (newpos && policy->xdo.type != XFRM_DEV_OFFLOAD_PACKET)
1529 hlist_add_behind_rcu(&policy->bydst_inexact_list, newpos);
1531 hlist_add_head_rcu(&policy->bydst_inexact_list, chain);
1533 hlist_for_each_entry(pol, chain, bydst_inexact_list) {
1539 static struct xfrm_policy *xfrm_policy_insert_list(struct hlist_head *chain,
1540 struct xfrm_policy *policy,
1543 struct xfrm_policy *pol, *newpos = NULL, *delpol = NULL;
1545 hlist_for_each_entry(pol, chain, bydst) {
1546 if (pol->type == policy->type &&
1547 pol->if_id == policy->if_id &&
1548 !selector_cmp(&pol->selector, &policy->selector) &&
1549 xfrm_policy_mark_match(&policy->mark, pol) &&
1550 xfrm_sec_ctx_match(pol->security, policy->security) &&
1553 return ERR_PTR(-EEXIST);
1555 if (policy->priority > pol->priority)
1557 } else if (policy->priority >= pol->priority) {
1565 if (newpos && policy->xdo.type != XFRM_DEV_OFFLOAD_PACKET)
1566 hlist_add_behind_rcu(&policy->bydst, &newpos->bydst);
1568 /* Packet offload policies enter to the head
1569 * to speed-up lookups.
1571 hlist_add_head_rcu(&policy->bydst, chain);
1576 int xfrm_policy_insert(int dir, struct xfrm_policy *policy, int excl)
1578 struct net *net = xp_net(policy);
1579 struct xfrm_policy *delpol;
1580 struct hlist_head *chain;
1582 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1583 chain = policy_hash_bysel(net, &policy->selector, policy->family, dir);
1585 delpol = xfrm_policy_insert_list(chain, policy, excl);
1587 delpol = xfrm_policy_inexact_insert(policy, dir, excl);
1589 if (IS_ERR(delpol)) {
1590 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1591 return PTR_ERR(delpol);
1594 __xfrm_policy_link(policy, dir);
1596 /* After previous checking, family can either be AF_INET or AF_INET6 */
1597 if (policy->family == AF_INET)
1598 rt_genid_bump_ipv4(net);
1600 rt_genid_bump_ipv6(net);
1603 xfrm_policy_requeue(delpol, policy);
1604 __xfrm_policy_unlink(delpol, dir);
1606 policy->index = delpol ? delpol->index : xfrm_gen_index(net, dir, policy->index);
1607 hlist_add_head(&policy->byidx, net->xfrm.policy_byidx+idx_hash(net, policy->index));
1608 policy->curlft.add_time = ktime_get_real_seconds();
1609 policy->curlft.use_time = 0;
1610 if (!mod_timer(&policy->timer, jiffies + HZ))
1611 xfrm_pol_hold(policy);
1612 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1615 xfrm_policy_kill(delpol);
1616 else if (xfrm_bydst_should_resize(net, dir, NULL))
1617 schedule_work(&net->xfrm.policy_hash_work);
1621 EXPORT_SYMBOL(xfrm_policy_insert);
1623 static struct xfrm_policy *
1624 __xfrm_policy_bysel_ctx(struct hlist_head *chain, const struct xfrm_mark *mark,
1625 u32 if_id, u8 type, int dir, struct xfrm_selector *sel,
1626 struct xfrm_sec_ctx *ctx)
1628 struct xfrm_policy *pol;
1633 hlist_for_each_entry(pol, chain, bydst) {
1634 if (pol->type == type &&
1635 pol->if_id == if_id &&
1636 xfrm_policy_mark_match(mark, pol) &&
1637 !selector_cmp(sel, &pol->selector) &&
1638 xfrm_sec_ctx_match(ctx, pol->security))
1645 struct xfrm_policy *
1646 xfrm_policy_bysel_ctx(struct net *net, const struct xfrm_mark *mark, u32 if_id,
1647 u8 type, int dir, struct xfrm_selector *sel,
1648 struct xfrm_sec_ctx *ctx, int delete, int *err)
1650 struct xfrm_pol_inexact_bin *bin = NULL;
1651 struct xfrm_policy *pol, *ret = NULL;
1652 struct hlist_head *chain;
1655 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1656 chain = policy_hash_bysel(net, sel, sel->family, dir);
1658 struct xfrm_pol_inexact_candidates cand;
1661 bin = xfrm_policy_inexact_lookup(net, type,
1662 sel->family, dir, if_id);
1664 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1668 if (!xfrm_policy_find_inexact_candidates(&cand, bin,
1671 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1676 for (i = 0; i < ARRAY_SIZE(cand.res); i++) {
1677 struct xfrm_policy *tmp;
1679 tmp = __xfrm_policy_bysel_ctx(cand.res[i], mark,
1685 if (!pol || tmp->pos < pol->pos)
1689 pol = __xfrm_policy_bysel_ctx(chain, mark, if_id, type, dir,
1696 *err = security_xfrm_policy_delete(pol->security);
1698 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1701 __xfrm_policy_unlink(pol, dir);
1705 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1708 xfrm_policy_kill(ret);
1710 xfrm_policy_inexact_prune_bin(bin);
1713 EXPORT_SYMBOL(xfrm_policy_bysel_ctx);
1715 struct xfrm_policy *
1716 xfrm_policy_byid(struct net *net, const struct xfrm_mark *mark, u32 if_id,
1717 u8 type, int dir, u32 id, int delete, int *err)
1719 struct xfrm_policy *pol, *ret;
1720 struct hlist_head *chain;
1723 if (xfrm_policy_id2dir(id) != dir)
1727 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1728 chain = net->xfrm.policy_byidx + idx_hash(net, id);
1730 hlist_for_each_entry(pol, chain, byidx) {
1731 if (pol->type == type && pol->index == id &&
1732 pol->if_id == if_id && xfrm_policy_mark_match(mark, pol)) {
1735 *err = security_xfrm_policy_delete(
1738 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1741 __xfrm_policy_unlink(pol, dir);
1747 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1750 xfrm_policy_kill(ret);
1753 EXPORT_SYMBOL(xfrm_policy_byid);
1755 #ifdef CONFIG_SECURITY_NETWORK_XFRM
1757 xfrm_policy_flush_secctx_check(struct net *net, u8 type, bool task_valid)
1759 struct xfrm_policy *pol;
1762 list_for_each_entry(pol, &net->xfrm.policy_all, walk.all) {
1763 if (pol->walk.dead ||
1764 xfrm_policy_id2dir(pol->index) >= XFRM_POLICY_MAX ||
1768 err = security_xfrm_policy_delete(pol->security);
1770 xfrm_audit_policy_delete(pol, 0, task_valid);
1777 static inline int xfrm_dev_policy_flush_secctx_check(struct net *net,
1778 struct net_device *dev,
1781 struct xfrm_policy *pol;
1784 list_for_each_entry(pol, &net->xfrm.policy_all, walk.all) {
1785 if (pol->walk.dead ||
1786 xfrm_policy_id2dir(pol->index) >= XFRM_POLICY_MAX ||
1787 pol->xdo.dev != dev)
1790 err = security_xfrm_policy_delete(pol->security);
1792 xfrm_audit_policy_delete(pol, 0, task_valid);
1800 xfrm_policy_flush_secctx_check(struct net *net, u8 type, bool task_valid)
1805 static inline int xfrm_dev_policy_flush_secctx_check(struct net *net,
1806 struct net_device *dev,
1813 int xfrm_policy_flush(struct net *net, u8 type, bool task_valid)
1815 int dir, err = 0, cnt = 0;
1816 struct xfrm_policy *pol;
1818 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1820 err = xfrm_policy_flush_secctx_check(net, type, task_valid);
1825 list_for_each_entry(pol, &net->xfrm.policy_all, walk.all) {
1826 dir = xfrm_policy_id2dir(pol->index);
1827 if (pol->walk.dead ||
1828 dir >= XFRM_POLICY_MAX ||
1832 __xfrm_policy_unlink(pol, dir);
1833 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1835 xfrm_audit_policy_delete(pol, 1, task_valid);
1836 xfrm_policy_kill(pol);
1837 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1841 __xfrm_policy_inexact_flush(net);
1845 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1848 EXPORT_SYMBOL(xfrm_policy_flush);
1850 int xfrm_dev_policy_flush(struct net *net, struct net_device *dev,
1853 int dir, err = 0, cnt = 0;
1854 struct xfrm_policy *pol;
1856 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1858 err = xfrm_dev_policy_flush_secctx_check(net, dev, task_valid);
1863 list_for_each_entry(pol, &net->xfrm.policy_all, walk.all) {
1864 dir = xfrm_policy_id2dir(pol->index);
1865 if (pol->walk.dead ||
1866 dir >= XFRM_POLICY_MAX ||
1867 pol->xdo.dev != dev)
1870 __xfrm_policy_unlink(pol, dir);
1871 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1873 xfrm_audit_policy_delete(pol, 1, task_valid);
1874 xfrm_policy_kill(pol);
1875 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1879 __xfrm_policy_inexact_flush(net);
1883 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1886 EXPORT_SYMBOL(xfrm_dev_policy_flush);
1888 int xfrm_policy_walk(struct net *net, struct xfrm_policy_walk *walk,
1889 int (*func)(struct xfrm_policy *, int, int, void*),
1892 struct xfrm_policy *pol;
1893 struct xfrm_policy_walk_entry *x;
1896 if (walk->type >= XFRM_POLICY_TYPE_MAX &&
1897 walk->type != XFRM_POLICY_TYPE_ANY)
1900 if (list_empty(&walk->walk.all) && walk->seq != 0)
1903 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1904 if (list_empty(&walk->walk.all))
1905 x = list_first_entry(&net->xfrm.policy_all, struct xfrm_policy_walk_entry, all);
1907 x = list_first_entry(&walk->walk.all,
1908 struct xfrm_policy_walk_entry, all);
1910 list_for_each_entry_from(x, &net->xfrm.policy_all, all) {
1913 pol = container_of(x, struct xfrm_policy, walk);
1914 if (walk->type != XFRM_POLICY_TYPE_ANY &&
1915 walk->type != pol->type)
1917 error = func(pol, xfrm_policy_id2dir(pol->index),
1920 list_move_tail(&walk->walk.all, &x->all);
1925 if (walk->seq == 0) {
1929 list_del_init(&walk->walk.all);
1931 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1934 EXPORT_SYMBOL(xfrm_policy_walk);
1936 void xfrm_policy_walk_init(struct xfrm_policy_walk *walk, u8 type)
1938 INIT_LIST_HEAD(&walk->walk.all);
1939 walk->walk.dead = 1;
1943 EXPORT_SYMBOL(xfrm_policy_walk_init);
1945 void xfrm_policy_walk_done(struct xfrm_policy_walk *walk, struct net *net)
1947 if (list_empty(&walk->walk.all))
1950 spin_lock_bh(&net->xfrm.xfrm_policy_lock); /*FIXME where is net? */
1951 list_del(&walk->walk.all);
1952 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1954 EXPORT_SYMBOL(xfrm_policy_walk_done);
1957 * Find policy to apply to this flow.
1959 * Returns 0 if policy found, else an -errno.
1961 static int xfrm_policy_match(const struct xfrm_policy *pol,
1962 const struct flowi *fl,
1963 u8 type, u16 family, u32 if_id)
1965 const struct xfrm_selector *sel = &pol->selector;
1969 if (pol->family != family ||
1970 pol->if_id != if_id ||
1971 (fl->flowi_mark & pol->mark.m) != pol->mark.v ||
1975 match = xfrm_selector_match(sel, fl, family);
1977 ret = security_xfrm_policy_lookup(pol->security, fl->flowi_secid);
1981 static struct xfrm_pol_inexact_node *
1982 xfrm_policy_lookup_inexact_addr(const struct rb_root *r,
1983 seqcount_spinlock_t *count,
1984 const xfrm_address_t *addr, u16 family)
1986 const struct rb_node *parent;
1990 seq = read_seqcount_begin(count);
1992 parent = rcu_dereference_raw(r->rb_node);
1994 struct xfrm_pol_inexact_node *node;
1997 node = rb_entry(parent, struct xfrm_pol_inexact_node, node);
1999 delta = xfrm_policy_addr_delta(addr, &node->addr,
2000 node->prefixlen, family);
2002 parent = rcu_dereference_raw(parent->rb_left);
2004 } else if (delta > 0) {
2005 parent = rcu_dereference_raw(parent->rb_right);
2012 if (read_seqcount_retry(count, seq))
2019 xfrm_policy_find_inexact_candidates(struct xfrm_pol_inexact_candidates *cand,
2020 struct xfrm_pol_inexact_bin *b,
2021 const xfrm_address_t *saddr,
2022 const xfrm_address_t *daddr)
2024 struct xfrm_pol_inexact_node *n;
2030 family = b->k.family;
2031 memset(cand, 0, sizeof(*cand));
2032 cand->res[XFRM_POL_CAND_ANY] = &b->hhead;
2034 n = xfrm_policy_lookup_inexact_addr(&b->root_d, &b->count, daddr,
2037 cand->res[XFRM_POL_CAND_DADDR] = &n->hhead;
2038 n = xfrm_policy_lookup_inexact_addr(&n->root, &b->count, saddr,
2041 cand->res[XFRM_POL_CAND_BOTH] = &n->hhead;
2044 n = xfrm_policy_lookup_inexact_addr(&b->root_s, &b->count, saddr,
2047 cand->res[XFRM_POL_CAND_SADDR] = &n->hhead;
2052 static struct xfrm_pol_inexact_bin *
2053 xfrm_policy_inexact_lookup_rcu(struct net *net, u8 type, u16 family,
2056 struct xfrm_pol_inexact_key k = {
2063 write_pnet(&k.net, net);
2065 return rhashtable_lookup(&xfrm_policy_inexact_table, &k,
2066 xfrm_pol_inexact_params);
2069 static struct xfrm_pol_inexact_bin *
2070 xfrm_policy_inexact_lookup(struct net *net, u8 type, u16 family,
2073 struct xfrm_pol_inexact_bin *bin;
2075 lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
2078 bin = xfrm_policy_inexact_lookup_rcu(net, type, family, dir, if_id);
2084 static struct xfrm_policy *
2085 __xfrm_policy_eval_candidates(struct hlist_head *chain,
2086 struct xfrm_policy *prefer,
2087 const struct flowi *fl,
2088 u8 type, u16 family, u32 if_id)
2090 u32 priority = prefer ? prefer->priority : ~0u;
2091 struct xfrm_policy *pol;
2096 hlist_for_each_entry_rcu(pol, chain, bydst) {
2099 if (pol->priority > priority)
2102 err = xfrm_policy_match(pol, fl, type, family, if_id);
2105 return ERR_PTR(err);
2111 /* matches. Is it older than *prefer? */
2112 if (pol->priority == priority &&
2113 prefer->pos < pol->pos)
2123 static struct xfrm_policy *
2124 xfrm_policy_eval_candidates(struct xfrm_pol_inexact_candidates *cand,
2125 struct xfrm_policy *prefer,
2126 const struct flowi *fl,
2127 u8 type, u16 family, u32 if_id)
2129 struct xfrm_policy *tmp;
2132 for (i = 0; i < ARRAY_SIZE(cand->res); i++) {
2133 tmp = __xfrm_policy_eval_candidates(cand->res[i],
2135 fl, type, family, if_id);
2147 static struct xfrm_policy *xfrm_policy_lookup_bytype(struct net *net, u8 type,
2148 const struct flowi *fl,
2152 struct xfrm_pol_inexact_candidates cand;
2153 const xfrm_address_t *daddr, *saddr;
2154 struct xfrm_pol_inexact_bin *bin;
2155 struct xfrm_policy *pol, *ret;
2156 struct hlist_head *chain;
2157 unsigned int sequence;
2160 daddr = xfrm_flowi_daddr(fl, family);
2161 saddr = xfrm_flowi_saddr(fl, family);
2162 if (unlikely(!daddr || !saddr))
2168 sequence = read_seqcount_begin(&net->xfrm.xfrm_policy_hash_generation);
2169 chain = policy_hash_direct(net, daddr, saddr, family, dir);
2170 } while (read_seqcount_retry(&net->xfrm.xfrm_policy_hash_generation, sequence));
2173 hlist_for_each_entry_rcu(pol, chain, bydst) {
2174 err = xfrm_policy_match(pol, fl, type, family, if_id);
2187 if (ret && ret->xdo.type == XFRM_DEV_OFFLOAD_PACKET)
2190 bin = xfrm_policy_inexact_lookup_rcu(net, type, family, dir, if_id);
2191 if (!bin || !xfrm_policy_find_inexact_candidates(&cand, bin, saddr,
2195 pol = xfrm_policy_eval_candidates(&cand, ret, fl, type,
2204 if (read_seqcount_retry(&net->xfrm.xfrm_policy_hash_generation, sequence))
2207 if (ret && !xfrm_pol_hold_rcu(ret))
2215 static struct xfrm_policy *xfrm_policy_lookup(struct net *net,
2216 const struct flowi *fl,
2217 u16 family, u8 dir, u32 if_id)
2219 #ifdef CONFIG_XFRM_SUB_POLICY
2220 struct xfrm_policy *pol;
2222 pol = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_SUB, fl, family,
2227 return xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN, fl, family,
2231 static struct xfrm_policy *xfrm_sk_policy_lookup(const struct sock *sk, int dir,
2232 const struct flowi *fl,
2233 u16 family, u32 if_id)
2235 struct xfrm_policy *pol;
2239 pol = rcu_dereference(sk->sk_policy[dir]);
2244 if (pol->family != family) {
2249 match = xfrm_selector_match(&pol->selector, fl, family);
2251 if ((sk->sk_mark & pol->mark.m) != pol->mark.v ||
2252 pol->if_id != if_id) {
2256 err = security_xfrm_policy_lookup(pol->security,
2259 if (!xfrm_pol_hold_rcu(pol))
2261 } else if (err == -ESRCH) {
2274 static void __xfrm_policy_link(struct xfrm_policy *pol, int dir)
2276 struct net *net = xp_net(pol);
2278 list_add(&pol->walk.all, &net->xfrm.policy_all);
2279 net->xfrm.policy_count[dir]++;
2283 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
2286 struct net *net = xp_net(pol);
2288 if (list_empty(&pol->walk.all))
2291 /* Socket policies are not hashed. */
2292 if (!hlist_unhashed(&pol->bydst)) {
2293 hlist_del_rcu(&pol->bydst);
2294 hlist_del_init(&pol->bydst_inexact_list);
2295 hlist_del(&pol->byidx);
2298 list_del_init(&pol->walk.all);
2299 net->xfrm.policy_count[dir]--;
2304 static void xfrm_sk_policy_link(struct xfrm_policy *pol, int dir)
2306 __xfrm_policy_link(pol, XFRM_POLICY_MAX + dir);
2309 static void xfrm_sk_policy_unlink(struct xfrm_policy *pol, int dir)
2311 __xfrm_policy_unlink(pol, XFRM_POLICY_MAX + dir);
2314 int xfrm_policy_delete(struct xfrm_policy *pol, int dir)
2316 struct net *net = xp_net(pol);
2318 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
2319 pol = __xfrm_policy_unlink(pol, dir);
2320 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
2322 xfrm_dev_policy_delete(pol);
2323 xfrm_policy_kill(pol);
2328 EXPORT_SYMBOL(xfrm_policy_delete);
2330 int xfrm_sk_policy_insert(struct sock *sk, int dir, struct xfrm_policy *pol)
2332 struct net *net = sock_net(sk);
2333 struct xfrm_policy *old_pol;
2335 #ifdef CONFIG_XFRM_SUB_POLICY
2336 if (pol && pol->type != XFRM_POLICY_TYPE_MAIN)
2340 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
2341 old_pol = rcu_dereference_protected(sk->sk_policy[dir],
2342 lockdep_is_held(&net->xfrm.xfrm_policy_lock));
2344 pol->curlft.add_time = ktime_get_real_seconds();
2345 pol->index = xfrm_gen_index(net, XFRM_POLICY_MAX+dir, 0);
2346 xfrm_sk_policy_link(pol, dir);
2348 rcu_assign_pointer(sk->sk_policy[dir], pol);
2351 xfrm_policy_requeue(old_pol, pol);
2353 /* Unlinking succeeds always. This is the only function
2354 * allowed to delete or replace socket policy.
2356 xfrm_sk_policy_unlink(old_pol, dir);
2358 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
2361 xfrm_policy_kill(old_pol);
2366 static struct xfrm_policy *clone_policy(const struct xfrm_policy *old, int dir)
2368 struct xfrm_policy *newp = xfrm_policy_alloc(xp_net(old), GFP_ATOMIC);
2369 struct net *net = xp_net(old);
2372 newp->selector = old->selector;
2373 if (security_xfrm_policy_clone(old->security,
2376 return NULL; /* ENOMEM */
2378 newp->lft = old->lft;
2379 newp->curlft = old->curlft;
2380 newp->mark = old->mark;
2381 newp->if_id = old->if_id;
2382 newp->action = old->action;
2383 newp->flags = old->flags;
2384 newp->xfrm_nr = old->xfrm_nr;
2385 newp->index = old->index;
2386 newp->type = old->type;
2387 newp->family = old->family;
2388 memcpy(newp->xfrm_vec, old->xfrm_vec,
2389 newp->xfrm_nr*sizeof(struct xfrm_tmpl));
2390 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
2391 xfrm_sk_policy_link(newp, dir);
2392 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
2398 int __xfrm_sk_clone_policy(struct sock *sk, const struct sock *osk)
2400 const struct xfrm_policy *p;
2401 struct xfrm_policy *np;
2405 for (i = 0; i < 2; i++) {
2406 p = rcu_dereference(osk->sk_policy[i]);
2408 np = clone_policy(p, i);
2409 if (unlikely(!np)) {
2413 rcu_assign_pointer(sk->sk_policy[i], np);
2421 xfrm_get_saddr(struct net *net, int oif, xfrm_address_t *local,
2422 xfrm_address_t *remote, unsigned short family, u32 mark)
2425 const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
2427 if (unlikely(afinfo == NULL))
2429 err = afinfo->get_saddr(net, oif, local, remote, mark);
2434 /* Resolve list of templates for the flow, given policy. */
2437 xfrm_tmpl_resolve_one(struct xfrm_policy *policy, const struct flowi *fl,
2438 struct xfrm_state **xfrm, unsigned short family)
2440 struct net *net = xp_net(policy);
2443 xfrm_address_t *daddr = xfrm_flowi_daddr(fl, family);
2444 xfrm_address_t *saddr = xfrm_flowi_saddr(fl, family);
2447 for (nx = 0, i = 0; i < policy->xfrm_nr; i++) {
2448 struct xfrm_state *x;
2449 xfrm_address_t *remote = daddr;
2450 xfrm_address_t *local = saddr;
2451 struct xfrm_tmpl *tmpl = &policy->xfrm_vec[i];
2453 if (tmpl->mode == XFRM_MODE_TUNNEL ||
2454 tmpl->mode == XFRM_MODE_BEET) {
2455 remote = &tmpl->id.daddr;
2456 local = &tmpl->saddr;
2457 if (xfrm_addr_any(local, tmpl->encap_family)) {
2458 error = xfrm_get_saddr(net, fl->flowi_oif,
2460 tmpl->encap_family, 0);
2467 x = xfrm_state_find(remote, local, fl, tmpl, policy, &error,
2468 family, policy->if_id);
2470 if (x && x->km.state == XFRM_STATE_VALID) {
2477 error = (x->km.state == XFRM_STATE_ERROR ?
2480 } else if (error == -ESRCH) {
2484 if (!tmpl->optional)
2490 for (nx--; nx >= 0; nx--)
2491 xfrm_state_put(xfrm[nx]);
2496 xfrm_tmpl_resolve(struct xfrm_policy **pols, int npols, const struct flowi *fl,
2497 struct xfrm_state **xfrm, unsigned short family)
2499 struct xfrm_state *tp[XFRM_MAX_DEPTH];
2500 struct xfrm_state **tpp = (npols > 1) ? tp : xfrm;
2506 for (i = 0; i < npols; i++) {
2507 if (cnx + pols[i]->xfrm_nr >= XFRM_MAX_DEPTH) {
2512 ret = xfrm_tmpl_resolve_one(pols[i], fl, &tpp[cnx], family);
2520 /* found states are sorted for outbound processing */
2522 xfrm_state_sort(xfrm, tpp, cnx, family);
2527 for (cnx--; cnx >= 0; cnx--)
2528 xfrm_state_put(tpp[cnx]);
2533 static int xfrm_get_tos(const struct flowi *fl, int family)
2535 if (family == AF_INET)
2536 return IPTOS_RT_MASK & fl->u.ip4.flowi4_tos;
2541 static inline struct xfrm_dst *xfrm_alloc_dst(struct net *net, int family)
2543 const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
2544 struct dst_ops *dst_ops;
2545 struct xfrm_dst *xdst;
2548 return ERR_PTR(-EINVAL);
2552 dst_ops = &net->xfrm.xfrm4_dst_ops;
2554 #if IS_ENABLED(CONFIG_IPV6)
2556 dst_ops = &net->xfrm.xfrm6_dst_ops;
2562 xdst = dst_alloc(dst_ops, NULL, 1, DST_OBSOLETE_NONE, 0);
2565 memset_after(xdst, 0, u.dst);
2567 xdst = ERR_PTR(-ENOBUFS);
2574 static void xfrm_init_path(struct xfrm_dst *path, struct dst_entry *dst,
2577 if (dst->ops->family == AF_INET6) {
2578 struct rt6_info *rt = (struct rt6_info *)dst;
2579 path->path_cookie = rt6_get_cookie(rt);
2580 path->u.rt6.rt6i_nfheader_len = nfheader_len;
2584 static inline int xfrm_fill_dst(struct xfrm_dst *xdst, struct net_device *dev,
2585 const struct flowi *fl)
2587 const struct xfrm_policy_afinfo *afinfo =
2588 xfrm_policy_get_afinfo(xdst->u.dst.ops->family);
2594 err = afinfo->fill_dst(xdst, dev, fl);
2602 /* Allocate chain of dst_entry's, attach known xfrm's, calculate
2603 * all the metrics... Shortly, bundle a bundle.
2606 static struct dst_entry *xfrm_bundle_create(struct xfrm_policy *policy,
2607 struct xfrm_state **xfrm,
2608 struct xfrm_dst **bundle,
2610 const struct flowi *fl,
2611 struct dst_entry *dst)
2613 const struct xfrm_state_afinfo *afinfo;
2614 const struct xfrm_mode *inner_mode;
2615 struct net *net = xp_net(policy);
2616 unsigned long now = jiffies;
2617 struct net_device *dev;
2618 struct xfrm_dst *xdst_prev = NULL;
2619 struct xfrm_dst *xdst0 = NULL;
2623 int nfheader_len = 0;
2624 int trailer_len = 0;
2626 int family = policy->selector.family;
2627 xfrm_address_t saddr, daddr;
2629 xfrm_flowi_addr_get(fl, &saddr, &daddr, family);
2631 tos = xfrm_get_tos(fl, family);
2635 for (; i < nx; i++) {
2636 struct xfrm_dst *xdst = xfrm_alloc_dst(net, family);
2637 struct dst_entry *dst1 = &xdst->u.dst;
2639 err = PTR_ERR(xdst);
2649 /* Ref count is taken during xfrm_alloc_dst()
2650 * No need to do dst_clone() on dst1
2652 xfrm_dst_set_child(xdst_prev, &xdst->u.dst);
2654 if (xfrm[i]->sel.family == AF_UNSPEC) {
2655 inner_mode = xfrm_ip2inner_mode(xfrm[i],
2656 xfrm_af2proto(family));
2658 err = -EAFNOSUPPORT;
2663 inner_mode = &xfrm[i]->inner_mode;
2666 dst_copy_metrics(dst1, dst);
2668 if (xfrm[i]->props.mode != XFRM_MODE_TRANSPORT) {
2672 if (xfrm[i]->props.smark.v || xfrm[i]->props.smark.m)
2673 mark = xfrm_smark_get(fl->flowi_mark, xfrm[i]);
2675 family = xfrm[i]->props.family;
2676 oif = fl->flowi_oif ? : fl->flowi_l3mdev;
2677 dst = xfrm_dst_lookup(xfrm[i], tos, oif,
2678 &saddr, &daddr, family, mark);
2685 dst1->xfrm = xfrm[i];
2686 xdst->xfrm_genid = xfrm[i]->genid;
2688 dst1->obsolete = DST_OBSOLETE_FORCE_CHK;
2689 dst1->lastuse = now;
2691 dst1->input = dst_discard;
2694 afinfo = xfrm_state_afinfo_get_rcu(inner_mode->family);
2696 dst1->output = afinfo->output;
2698 dst1->output = dst_discard_out;
2703 header_len += xfrm[i]->props.header_len;
2704 if (xfrm[i]->type->flags & XFRM_TYPE_NON_FRAGMENT)
2705 nfheader_len += xfrm[i]->props.header_len;
2706 trailer_len += xfrm[i]->props.trailer_len;
2709 xfrm_dst_set_child(xdst_prev, dst);
2717 xfrm_init_path(xdst0, dst, nfheader_len);
2718 xfrm_init_pmtu(bundle, nx);
2720 for (xdst_prev = xdst0; xdst_prev != (struct xfrm_dst *)dst;
2721 xdst_prev = (struct xfrm_dst *) xfrm_dst_child(&xdst_prev->u.dst)) {
2722 err = xfrm_fill_dst(xdst_prev, dev, fl);
2726 xdst_prev->u.dst.header_len = header_len;
2727 xdst_prev->u.dst.trailer_len = trailer_len;
2728 header_len -= xdst_prev->u.dst.xfrm->props.header_len;
2729 trailer_len -= xdst_prev->u.dst.xfrm->props.trailer_len;
2732 return &xdst0->u.dst;
2736 xfrm_state_put(xfrm[i]);
2739 dst_release_immediate(&xdst0->u.dst);
2741 return ERR_PTR(err);
2744 static int xfrm_expand_policies(const struct flowi *fl, u16 family,
2745 struct xfrm_policy **pols,
2746 int *num_pols, int *num_xfrms)
2750 if (*num_pols == 0 || !pols[0]) {
2755 if (IS_ERR(pols[0])) {
2757 return PTR_ERR(pols[0]);
2760 *num_xfrms = pols[0]->xfrm_nr;
2762 #ifdef CONFIG_XFRM_SUB_POLICY
2763 if (pols[0]->action == XFRM_POLICY_ALLOW &&
2764 pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
2765 pols[1] = xfrm_policy_lookup_bytype(xp_net(pols[0]),
2766 XFRM_POLICY_TYPE_MAIN,
2771 if (IS_ERR(pols[1])) {
2772 xfrm_pols_put(pols, *num_pols);
2774 return PTR_ERR(pols[1]);
2777 (*num_xfrms) += pols[1]->xfrm_nr;
2781 for (i = 0; i < *num_pols; i++) {
2782 if (pols[i]->action != XFRM_POLICY_ALLOW) {
2792 static struct xfrm_dst *
2793 xfrm_resolve_and_create_bundle(struct xfrm_policy **pols, int num_pols,
2794 const struct flowi *fl, u16 family,
2795 struct dst_entry *dst_orig)
2797 struct net *net = xp_net(pols[0]);
2798 struct xfrm_state *xfrm[XFRM_MAX_DEPTH];
2799 struct xfrm_dst *bundle[XFRM_MAX_DEPTH];
2800 struct xfrm_dst *xdst;
2801 struct dst_entry *dst;
2804 /* Try to instantiate a bundle */
2805 err = xfrm_tmpl_resolve(pols, num_pols, fl, xfrm, family);
2811 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
2812 return ERR_PTR(err);
2815 dst = xfrm_bundle_create(pols[0], xfrm, bundle, err, fl, dst_orig);
2817 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTBUNDLEGENERROR);
2818 return ERR_CAST(dst);
2821 xdst = (struct xfrm_dst *)dst;
2822 xdst->num_xfrms = err;
2823 xdst->num_pols = num_pols;
2824 memcpy(xdst->pols, pols, sizeof(struct xfrm_policy *) * num_pols);
2825 xdst->policy_genid = atomic_read(&pols[0]->genid);
2830 static void xfrm_policy_queue_process(struct timer_list *t)
2832 struct sk_buff *skb;
2834 struct dst_entry *dst;
2835 struct xfrm_policy *pol = from_timer(pol, t, polq.hold_timer);
2836 struct net *net = xp_net(pol);
2837 struct xfrm_policy_queue *pq = &pol->polq;
2839 struct sk_buff_head list;
2842 spin_lock(&pq->hold_queue.lock);
2843 skb = skb_peek(&pq->hold_queue);
2845 spin_unlock(&pq->hold_queue.lock);
2851 /* Fixup the mark to support VTI. */
2852 skb_mark = skb->mark;
2853 skb->mark = pol->mark.v;
2854 xfrm_decode_session(skb, &fl, dst->ops->family);
2855 skb->mark = skb_mark;
2856 spin_unlock(&pq->hold_queue.lock);
2858 dst_hold(xfrm_dst_path(dst));
2859 dst = xfrm_lookup(net, xfrm_dst_path(dst), &fl, sk, XFRM_LOOKUP_QUEUE);
2863 if (dst->flags & DST_XFRM_QUEUE) {
2866 if (pq->timeout >= XFRM_QUEUE_TMO_MAX)
2869 pq->timeout = pq->timeout << 1;
2870 if (!mod_timer(&pq->hold_timer, jiffies + pq->timeout))
2877 __skb_queue_head_init(&list);
2879 spin_lock(&pq->hold_queue.lock);
2881 skb_queue_splice_init(&pq->hold_queue, &list);
2882 spin_unlock(&pq->hold_queue.lock);
2884 while (!skb_queue_empty(&list)) {
2885 skb = __skb_dequeue(&list);
2887 /* Fixup the mark to support VTI. */
2888 skb_mark = skb->mark;
2889 skb->mark = pol->mark.v;
2890 xfrm_decode_session(skb, &fl, skb_dst(skb)->ops->family);
2891 skb->mark = skb_mark;
2893 dst_hold(xfrm_dst_path(skb_dst(skb)));
2894 dst = xfrm_lookup(net, xfrm_dst_path(skb_dst(skb)), &fl, skb->sk, 0);
2902 skb_dst_set(skb, dst);
2904 dst_output(net, skb->sk, skb);
2913 skb_queue_purge(&pq->hold_queue);
2917 static int xdst_queue_output(struct net *net, struct sock *sk, struct sk_buff *skb)
2919 unsigned long sched_next;
2920 struct dst_entry *dst = skb_dst(skb);
2921 struct xfrm_dst *xdst = (struct xfrm_dst *) dst;
2922 struct xfrm_policy *pol = xdst->pols[0];
2923 struct xfrm_policy_queue *pq = &pol->polq;
2925 if (unlikely(skb_fclone_busy(sk, skb))) {
2930 if (pq->hold_queue.qlen > XFRM_MAX_QUEUE_LEN) {
2937 spin_lock_bh(&pq->hold_queue.lock);
2940 pq->timeout = XFRM_QUEUE_TMO_MIN;
2942 sched_next = jiffies + pq->timeout;
2944 if (del_timer(&pq->hold_timer)) {
2945 if (time_before(pq->hold_timer.expires, sched_next))
2946 sched_next = pq->hold_timer.expires;
2950 __skb_queue_tail(&pq->hold_queue, skb);
2951 if (!mod_timer(&pq->hold_timer, sched_next))
2954 spin_unlock_bh(&pq->hold_queue.lock);
2959 static struct xfrm_dst *xfrm_create_dummy_bundle(struct net *net,
2960 struct xfrm_flo *xflo,
2961 const struct flowi *fl,
2966 struct net_device *dev;
2967 struct dst_entry *dst;
2968 struct dst_entry *dst1;
2969 struct xfrm_dst *xdst;
2971 xdst = xfrm_alloc_dst(net, family);
2975 if (!(xflo->flags & XFRM_LOOKUP_QUEUE) ||
2976 net->xfrm.sysctl_larval_drop ||
2980 dst = xflo->dst_orig;
2981 dst1 = &xdst->u.dst;
2985 dst_copy_metrics(dst1, dst);
2987 dst1->obsolete = DST_OBSOLETE_FORCE_CHK;
2988 dst1->flags |= DST_XFRM_QUEUE;
2989 dst1->lastuse = jiffies;
2991 dst1->input = dst_discard;
2992 dst1->output = xdst_queue_output;
2995 xfrm_dst_set_child(xdst, dst);
2998 xfrm_init_path((struct xfrm_dst *)dst1, dst, 0);
3005 err = xfrm_fill_dst(xdst, dev, fl);
3014 xdst = ERR_PTR(err);
3018 static struct xfrm_dst *xfrm_bundle_lookup(struct net *net,
3019 const struct flowi *fl,
3021 struct xfrm_flo *xflo, u32 if_id)
3023 struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
3024 int num_pols = 0, num_xfrms = 0, err;
3025 struct xfrm_dst *xdst;
3027 /* Resolve policies to use if we couldn't get them from
3028 * previous cache entry */
3030 pols[0] = xfrm_policy_lookup(net, fl, family, dir, if_id);
3031 err = xfrm_expand_policies(fl, family, pols,
3032 &num_pols, &num_xfrms);
3038 goto make_dummy_bundle;
3040 xdst = xfrm_resolve_and_create_bundle(pols, num_pols, fl, family,
3043 err = PTR_ERR(xdst);
3044 if (err == -EREMOTE) {
3045 xfrm_pols_put(pols, num_pols);
3051 goto make_dummy_bundle;
3052 } else if (xdst == NULL) {
3054 goto make_dummy_bundle;
3060 /* We found policies, but there's no bundles to instantiate:
3061 * either because the policy blocks, has no transformations or
3062 * we could not build template (no xfrm_states).*/
3063 xdst = xfrm_create_dummy_bundle(net, xflo, fl, num_xfrms, family);
3065 xfrm_pols_put(pols, num_pols);
3066 return ERR_CAST(xdst);
3068 xdst->num_pols = num_pols;
3069 xdst->num_xfrms = num_xfrms;
3070 memcpy(xdst->pols, pols, sizeof(struct xfrm_policy *) * num_pols);
3075 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
3077 xfrm_pols_put(pols, num_pols);
3078 return ERR_PTR(err);
3081 static struct dst_entry *make_blackhole(struct net *net, u16 family,
3082 struct dst_entry *dst_orig)
3084 const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
3085 struct dst_entry *ret;
3088 dst_release(dst_orig);
3089 return ERR_PTR(-EINVAL);
3091 ret = afinfo->blackhole_route(net, dst_orig);
3098 /* Finds/creates a bundle for given flow and if_id
3100 * At the moment we eat a raw IP route. Mostly to speed up lookups
3101 * on interfaces with disabled IPsec.
3103 * xfrm_lookup uses an if_id of 0 by default, and is provided for
3106 struct dst_entry *xfrm_lookup_with_ifid(struct net *net,
3107 struct dst_entry *dst_orig,
3108 const struct flowi *fl,
3109 const struct sock *sk,
3110 int flags, u32 if_id)
3112 struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
3113 struct xfrm_dst *xdst;
3114 struct dst_entry *dst, *route;
3115 u16 family = dst_orig->ops->family;
3116 u8 dir = XFRM_POLICY_OUT;
3117 int i, err, num_pols, num_xfrms = 0, drop_pols = 0;
3123 sk = sk_const_to_full_sk(sk);
3124 if (sk && sk->sk_policy[XFRM_POLICY_OUT]) {
3126 pols[0] = xfrm_sk_policy_lookup(sk, XFRM_POLICY_OUT, fl, family,
3128 err = xfrm_expand_policies(fl, family, pols,
3129 &num_pols, &num_xfrms);
3134 if (num_xfrms <= 0) {
3135 drop_pols = num_pols;
3139 xdst = xfrm_resolve_and_create_bundle(
3144 xfrm_pols_put(pols, num_pols);
3145 err = PTR_ERR(xdst);
3146 if (err == -EREMOTE)
3150 } else if (xdst == NULL) {
3152 drop_pols = num_pols;
3156 route = xdst->route;
3161 struct xfrm_flo xflo;
3163 xflo.dst_orig = dst_orig;
3166 /* To accelerate a bit... */
3167 if (!if_id && ((dst_orig->flags & DST_NOXFRM) ||
3168 !net->xfrm.policy_count[XFRM_POLICY_OUT]))
3171 xdst = xfrm_bundle_lookup(net, fl, family, dir, &xflo, if_id);
3175 err = PTR_ERR(xdst);
3179 num_pols = xdst->num_pols;
3180 num_xfrms = xdst->num_xfrms;
3181 memcpy(pols, xdst->pols, sizeof(struct xfrm_policy *) * num_pols);
3182 route = xdst->route;
3186 if (route == NULL && num_xfrms > 0) {
3187 /* The only case when xfrm_bundle_lookup() returns a
3188 * bundle with null route, is when the template could
3189 * not be resolved. It means policies are there, but
3190 * bundle could not be created, since we don't yet
3191 * have the xfrm_state's. We need to wait for KM to
3192 * negotiate new SA's or bail out with error.*/
3193 if (net->xfrm.sysctl_larval_drop) {
3194 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
3201 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
3209 if ((flags & XFRM_LOOKUP_ICMP) &&
3210 !(pols[0]->flags & XFRM_POLICY_ICMP)) {
3215 for (i = 0; i < num_pols; i++)
3216 pols[i]->curlft.use_time = ktime_get_real_seconds();
3218 if (num_xfrms < 0) {
3219 /* Prohibit the flow */
3220 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLBLOCK);
3223 } else if (num_xfrms > 0) {
3224 /* Flow transformed */
3225 dst_release(dst_orig);
3227 /* Flow passes untransformed */
3232 xfrm_pols_put(pols, drop_pols);
3233 if (dst && dst->xfrm &&
3234 dst->xfrm->props.mode == XFRM_MODE_TUNNEL)
3235 dst->flags |= DST_XFRM_TUNNEL;
3239 if ((!dst_orig->dev || !(dst_orig->dev->flags & IFF_LOOPBACK)) &&
3240 net->xfrm.policy_default[dir] == XFRM_USERPOLICY_BLOCK) {
3244 if (!(flags & XFRM_LOOKUP_ICMP)) {
3252 if (!(flags & XFRM_LOOKUP_KEEP_DST_REF))
3253 dst_release(dst_orig);
3254 xfrm_pols_put(pols, drop_pols);
3255 return ERR_PTR(err);
3257 EXPORT_SYMBOL(xfrm_lookup_with_ifid);
3259 /* Main function: finds/creates a bundle for given flow.
3261 * At the moment we eat a raw IP route. Mostly to speed up lookups
3262 * on interfaces with disabled IPsec.
3264 struct dst_entry *xfrm_lookup(struct net *net, struct dst_entry *dst_orig,
3265 const struct flowi *fl, const struct sock *sk,
3268 return xfrm_lookup_with_ifid(net, dst_orig, fl, sk, flags, 0);
3270 EXPORT_SYMBOL(xfrm_lookup);
3272 /* Callers of xfrm_lookup_route() must ensure a call to dst_output().
3273 * Otherwise we may send out blackholed packets.
3275 struct dst_entry *xfrm_lookup_route(struct net *net, struct dst_entry *dst_orig,
3276 const struct flowi *fl,
3277 const struct sock *sk, int flags)
3279 struct dst_entry *dst = xfrm_lookup(net, dst_orig, fl, sk,
3280 flags | XFRM_LOOKUP_QUEUE |
3281 XFRM_LOOKUP_KEEP_DST_REF);
3283 if (PTR_ERR(dst) == -EREMOTE)
3284 return make_blackhole(net, dst_orig->ops->family, dst_orig);
3287 dst_release(dst_orig);
3291 EXPORT_SYMBOL(xfrm_lookup_route);
3294 xfrm_secpath_reject(int idx, struct sk_buff *skb, const struct flowi *fl)
3296 struct sec_path *sp = skb_sec_path(skb);
3297 struct xfrm_state *x;
3299 if (!sp || idx < 0 || idx >= sp->len)
3302 if (!x->type->reject)
3304 return x->type->reject(x, skb, fl);
3307 /* When skb is transformed back to its "native" form, we have to
3308 * check policy restrictions. At the moment we make this in maximally
3309 * stupid way. Shame on me. :-) Of course, connected sockets must
3310 * have policy cached at them.
3314 xfrm_state_ok(const struct xfrm_tmpl *tmpl, const struct xfrm_state *x,
3315 unsigned short family, u32 if_id)
3317 if (xfrm_state_kern(x))
3318 return tmpl->optional && !xfrm_state_addr_cmp(tmpl, x, tmpl->encap_family);
3319 return x->id.proto == tmpl->id.proto &&
3320 (x->id.spi == tmpl->id.spi || !tmpl->id.spi) &&
3321 (x->props.reqid == tmpl->reqid || !tmpl->reqid) &&
3322 x->props.mode == tmpl->mode &&
3323 (tmpl->allalgs || (tmpl->aalgos & (1<<x->props.aalgo)) ||
3324 !(xfrm_id_proto_match(tmpl->id.proto, IPSEC_PROTO_ANY))) &&
3325 !(x->props.mode != XFRM_MODE_TRANSPORT &&
3326 xfrm_state_addr_cmp(tmpl, x, family)) &&
3327 (if_id == 0 || if_id == x->if_id);
3331 * 0 or more than 0 is returned when validation is succeeded (either bypass
3332 * because of optional transport mode, or next index of the matched secpath
3333 * state with the template.
3334 * -1 is returned when no matching template is found.
3335 * Otherwise "-2 - errored_index" is returned.
3338 xfrm_policy_ok(const struct xfrm_tmpl *tmpl, const struct sec_path *sp, int start,
3339 unsigned short family, u32 if_id)
3343 if (tmpl->optional) {
3344 if (tmpl->mode == XFRM_MODE_TRANSPORT)
3348 for (; idx < sp->len; idx++) {
3349 if (xfrm_state_ok(tmpl, sp->xvec[idx], family, if_id))
3351 if (sp->xvec[idx]->props.mode != XFRM_MODE_TRANSPORT) {
3361 decode_session4(struct sk_buff *skb, struct flowi *fl, bool reverse)
3363 const struct iphdr *iph = ip_hdr(skb);
3365 u8 *xprth = skb_network_header(skb) + ihl * 4;
3366 struct flowi4 *fl4 = &fl->u.ip4;
3369 if (skb_dst(skb) && skb_dst(skb)->dev)
3370 oif = skb_dst(skb)->dev->ifindex;
3372 memset(fl4, 0, sizeof(struct flowi4));
3373 fl4->flowi4_mark = skb->mark;
3374 fl4->flowi4_oif = reverse ? skb->skb_iif : oif;
3376 fl4->flowi4_proto = iph->protocol;
3377 fl4->daddr = reverse ? iph->saddr : iph->daddr;
3378 fl4->saddr = reverse ? iph->daddr : iph->saddr;
3379 fl4->flowi4_tos = iph->tos & ~INET_ECN_MASK;
3381 if (!ip_is_fragment(iph)) {
3382 switch (iph->protocol) {
3384 case IPPROTO_UDPLITE:
3388 if (xprth + 4 < skb->data ||
3389 pskb_may_pull(skb, xprth + 4 - skb->data)) {
3392 xprth = skb_network_header(skb) + ihl * 4;
3393 ports = (__be16 *)xprth;
3395 fl4->fl4_sport = ports[!!reverse];
3396 fl4->fl4_dport = ports[!reverse];
3400 if (xprth + 2 < skb->data ||
3401 pskb_may_pull(skb, xprth + 2 - skb->data)) {
3404 xprth = skb_network_header(skb) + ihl * 4;
3407 fl4->fl4_icmp_type = icmp[0];
3408 fl4->fl4_icmp_code = icmp[1];
3412 if (xprth + 12 < skb->data ||
3413 pskb_may_pull(skb, xprth + 12 - skb->data)) {
3417 xprth = skb_network_header(skb) + ihl * 4;
3418 greflags = (__be16 *)xprth;
3419 gre_hdr = (__be32 *)xprth;
3421 if (greflags[0] & GRE_KEY) {
3422 if (greflags[0] & GRE_CSUM)
3424 fl4->fl4_gre_key = gre_hdr[1];
3434 #if IS_ENABLED(CONFIG_IPV6)
3436 decode_session6(struct sk_buff *skb, struct flowi *fl, bool reverse)
3438 struct flowi6 *fl6 = &fl->u.ip6;
3440 const struct ipv6hdr *hdr = ipv6_hdr(skb);
3441 u32 offset = sizeof(*hdr);
3442 struct ipv6_opt_hdr *exthdr;
3443 const unsigned char *nh = skb_network_header(skb);
3444 u16 nhoff = IP6CB(skb)->nhoff;
3449 nhoff = offsetof(struct ipv6hdr, nexthdr);
3451 nexthdr = nh[nhoff];
3453 if (skb_dst(skb) && skb_dst(skb)->dev)
3454 oif = skb_dst(skb)->dev->ifindex;
3456 memset(fl6, 0, sizeof(struct flowi6));
3457 fl6->flowi6_mark = skb->mark;
3458 fl6->flowi6_oif = reverse ? skb->skb_iif : oif;
3460 fl6->daddr = reverse ? hdr->saddr : hdr->daddr;
3461 fl6->saddr = reverse ? hdr->daddr : hdr->saddr;
3463 while (nh + offset + sizeof(*exthdr) < skb->data ||
3464 pskb_may_pull(skb, nh + offset + sizeof(*exthdr) - skb->data)) {
3465 nh = skb_network_header(skb);
3466 exthdr = (struct ipv6_opt_hdr *)(nh + offset);
3469 case NEXTHDR_FRAGMENT:
3472 case NEXTHDR_ROUTING:
3475 offset += ipv6_optlen(exthdr);
3476 nexthdr = exthdr->nexthdr;
3479 case IPPROTO_UDPLITE:
3483 if (!onlyproto && (nh + offset + 4 < skb->data ||
3484 pskb_may_pull(skb, nh + offset + 4 - skb->data))) {
3487 nh = skb_network_header(skb);
3488 ports = (__be16 *)(nh + offset);
3489 fl6->fl6_sport = ports[!!reverse];
3490 fl6->fl6_dport = ports[!reverse];
3492 fl6->flowi6_proto = nexthdr;
3494 case IPPROTO_ICMPV6:
3495 if (!onlyproto && (nh + offset + 2 < skb->data ||
3496 pskb_may_pull(skb, nh + offset + 2 - skb->data))) {
3499 nh = skb_network_header(skb);
3500 icmp = (u8 *)(nh + offset);
3501 fl6->fl6_icmp_type = icmp[0];
3502 fl6->fl6_icmp_code = icmp[1];
3504 fl6->flowi6_proto = nexthdr;
3508 (nh + offset + 12 < skb->data ||
3509 pskb_may_pull(skb, nh + offset + 12 - skb->data))) {
3510 struct gre_base_hdr *gre_hdr;
3513 nh = skb_network_header(skb);
3514 gre_hdr = (struct gre_base_hdr *)(nh + offset);
3515 gre_key = (__be32 *)(gre_hdr + 1);
3517 if (gre_hdr->flags & GRE_KEY) {
3518 if (gre_hdr->flags & GRE_CSUM)
3520 fl6->fl6_gre_key = *gre_key;
3523 fl6->flowi6_proto = nexthdr;
3526 #if IS_ENABLED(CONFIG_IPV6_MIP6)
3528 offset += ipv6_optlen(exthdr);
3529 if (!onlyproto && (nh + offset + 3 < skb->data ||
3530 pskb_may_pull(skb, nh + offset + 3 - skb->data))) {
3533 nh = skb_network_header(skb);
3534 mh = (struct ip6_mh *)(nh + offset);
3535 fl6->fl6_mh_type = mh->ip6mh_type;
3537 fl6->flowi6_proto = nexthdr;
3541 fl6->flowi6_proto = nexthdr;
3548 int __xfrm_decode_session(struct sk_buff *skb, struct flowi *fl,
3549 unsigned int family, int reverse)
3553 decode_session4(skb, fl, reverse);
3555 #if IS_ENABLED(CONFIG_IPV6)
3557 decode_session6(skb, fl, reverse);
3561 return -EAFNOSUPPORT;
3564 return security_xfrm_decode_session(skb, &fl->flowi_secid);
3566 EXPORT_SYMBOL(__xfrm_decode_session);
3568 static inline int secpath_has_nontransport(const struct sec_path *sp, int k, int *idxp)
3570 for (; k < sp->len; k++) {
3571 if (sp->xvec[k]->props.mode != XFRM_MODE_TRANSPORT) {
3580 int __xfrm_policy_check(struct sock *sk, int dir, struct sk_buff *skb,
3581 unsigned short family)
3583 struct net *net = dev_net(skb->dev);
3584 struct xfrm_policy *pol;
3585 struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
3592 const struct xfrm_if_cb *ifcb;
3593 struct sec_path *sp;
3597 ifcb = xfrm_if_get_cb();
3600 struct xfrm_if_decode_session_result r;
3602 if (ifcb->decode_session(skb, family, &r)) {
3609 reverse = dir & ~XFRM_POLICY_MASK;
3610 dir &= XFRM_POLICY_MASK;
3612 if (__xfrm_decode_session(skb, &fl, family, reverse) < 0) {
3613 XFRM_INC_STATS(net, LINUX_MIB_XFRMINHDRERROR);
3617 nf_nat_decode_session(skb, &fl, family);
3619 /* First, check used SA against their selectors. */
3620 sp = skb_sec_path(skb);
3624 for (i = sp->len - 1; i >= 0; i--) {
3625 struct xfrm_state *x = sp->xvec[i];
3626 if (!xfrm_selector_match(&x->sel, &fl, family)) {
3627 XFRM_INC_STATS(net, LINUX_MIB_XFRMINSTATEMISMATCH);
3634 sk = sk_to_full_sk(sk);
3635 if (sk && sk->sk_policy[dir]) {
3636 pol = xfrm_sk_policy_lookup(sk, dir, &fl, family, if_id);
3638 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
3644 pol = xfrm_policy_lookup(net, &fl, family, dir, if_id);
3647 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
3652 if (net->xfrm.policy_default[dir] == XFRM_USERPOLICY_BLOCK) {
3653 XFRM_INC_STATS(net, LINUX_MIB_XFRMINNOPOLS);
3657 if (sp && secpath_has_nontransport(sp, 0, &xerr_idx)) {
3658 xfrm_secpath_reject(xerr_idx, skb, &fl);
3659 XFRM_INC_STATS(net, LINUX_MIB_XFRMINNOPOLS);
3665 /* This lockless write can happen from different cpus. */
3666 WRITE_ONCE(pol->curlft.use_time, ktime_get_real_seconds());
3670 #ifdef CONFIG_XFRM_SUB_POLICY
3671 if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
3672 pols[1] = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN,
3674 XFRM_POLICY_IN, if_id);
3676 if (IS_ERR(pols[1])) {
3677 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
3678 xfrm_pol_put(pols[0]);
3681 /* This write can happen from different cpus. */
3682 WRITE_ONCE(pols[1]->curlft.use_time,
3683 ktime_get_real_seconds());
3689 if (pol->action == XFRM_POLICY_ALLOW) {
3690 static struct sec_path dummy;
3691 struct xfrm_tmpl *tp[XFRM_MAX_DEPTH];
3692 struct xfrm_tmpl *stp[XFRM_MAX_DEPTH];
3693 struct xfrm_tmpl **tpp = tp;
3697 sp = skb_sec_path(skb);
3701 for (pi = 0; pi < npols; pi++) {
3702 if (pols[pi] != pol &&
3703 pols[pi]->action != XFRM_POLICY_ALLOW) {
3704 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
3707 if (ti + pols[pi]->xfrm_nr >= XFRM_MAX_DEPTH) {
3708 XFRM_INC_STATS(net, LINUX_MIB_XFRMINBUFFERERROR);
3711 for (i = 0; i < pols[pi]->xfrm_nr; i++)
3712 tpp[ti++] = &pols[pi]->xfrm_vec[i];
3717 xfrm_tmpl_sort(stp, tpp, xfrm_nr, family);
3721 /* For each tunnel xfrm, find the first matching tmpl.
3722 * For each tmpl before that, find corresponding xfrm.
3723 * Order is _important_. Later we will implement
3724 * some barriers, but at the moment barriers
3725 * are implied between each two transformations.
3727 for (i = xfrm_nr-1, k = 0; i >= 0; i--) {
3728 k = xfrm_policy_ok(tpp[i], sp, k, family, if_id);
3731 /* "-2 - errored_index" returned */
3733 XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
3738 if (secpath_has_nontransport(sp, k, &xerr_idx)) {
3739 XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
3743 xfrm_pols_put(pols, npols);
3746 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
3749 xfrm_secpath_reject(xerr_idx, skb, &fl);
3751 xfrm_pols_put(pols, npols);
3754 EXPORT_SYMBOL(__xfrm_policy_check);
3756 int __xfrm_route_forward(struct sk_buff *skb, unsigned short family)
3758 struct net *net = dev_net(skb->dev);
3760 struct dst_entry *dst;
3763 if (xfrm_decode_session(skb, &fl, family) < 0) {
3764 XFRM_INC_STATS(net, LINUX_MIB_XFRMFWDHDRERROR);
3769 if (!skb_dst(skb)) {
3770 XFRM_INC_STATS(net, LINUX_MIB_XFRMFWDHDRERROR);
3774 dst = xfrm_lookup(net, skb_dst(skb), &fl, NULL, XFRM_LOOKUP_QUEUE);
3779 skb_dst_set(skb, dst);
3782 EXPORT_SYMBOL(__xfrm_route_forward);
3784 /* Optimize later using cookies and generation ids. */
3786 static struct dst_entry *xfrm_dst_check(struct dst_entry *dst, u32 cookie)
3788 /* Code (such as __xfrm4_bundle_create()) sets dst->obsolete
3789 * to DST_OBSOLETE_FORCE_CHK to force all XFRM destinations to
3790 * get validated by dst_ops->check on every use. We do this
3791 * because when a normal route referenced by an XFRM dst is
3792 * obsoleted we do not go looking around for all parent
3793 * referencing XFRM dsts so that we can invalidate them. It
3794 * is just too much work. Instead we make the checks here on
3795 * every use. For example:
3797 * XFRM dst A --> IPv4 dst X
3799 * X is the "xdst->route" of A (X is also the "dst->path" of A
3800 * in this example). If X is marked obsolete, "A" will not
3801 * notice. That's what we are validating here via the
3802 * stale_bundle() check.
3804 * When a dst is removed from the fib tree, DST_OBSOLETE_DEAD will
3806 * This will force stale_bundle() to fail on any xdst bundle with
3807 * this dst linked in it.
3809 if (dst->obsolete < 0 && !stale_bundle(dst))
3815 static int stale_bundle(struct dst_entry *dst)
3817 return !xfrm_bundle_ok((struct xfrm_dst *)dst);
3820 void xfrm_dst_ifdown(struct dst_entry *dst, struct net_device *dev)
3822 while ((dst = xfrm_dst_child(dst)) && dst->xfrm && dst->dev == dev) {
3823 dst->dev = blackhole_netdev;
3828 EXPORT_SYMBOL(xfrm_dst_ifdown);
3830 static void xfrm_link_failure(struct sk_buff *skb)
3832 /* Impossible. Such dst must be popped before reaches point of failure. */
3835 static struct dst_entry *xfrm_negative_advice(struct dst_entry *dst)
3838 if (dst->obsolete) {
3846 static void xfrm_init_pmtu(struct xfrm_dst **bundle, int nr)
3849 struct xfrm_dst *xdst = bundle[nr];
3850 u32 pmtu, route_mtu_cached;
3851 struct dst_entry *dst;
3854 pmtu = dst_mtu(xfrm_dst_child(dst));
3855 xdst->child_mtu_cached = pmtu;
3857 pmtu = xfrm_state_mtu(dst->xfrm, pmtu);
3859 route_mtu_cached = dst_mtu(xdst->route);
3860 xdst->route_mtu_cached = route_mtu_cached;
3862 if (pmtu > route_mtu_cached)
3863 pmtu = route_mtu_cached;
3865 dst_metric_set(dst, RTAX_MTU, pmtu);
3869 /* Check that the bundle accepts the flow and its components are
3873 static int xfrm_bundle_ok(struct xfrm_dst *first)
3875 struct xfrm_dst *bundle[XFRM_MAX_DEPTH];
3876 struct dst_entry *dst = &first->u.dst;
3877 struct xfrm_dst *xdst;
3881 if (!dst_check(xfrm_dst_path(dst), ((struct xfrm_dst *)dst)->path_cookie) ||
3882 (dst->dev && !netif_running(dst->dev)))
3885 if (dst->flags & DST_XFRM_QUEUE)
3888 start_from = nr = 0;
3890 struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
3892 if (dst->xfrm->km.state != XFRM_STATE_VALID)
3894 if (xdst->xfrm_genid != dst->xfrm->genid)
3896 if (xdst->num_pols > 0 &&
3897 xdst->policy_genid != atomic_read(&xdst->pols[0]->genid))
3900 bundle[nr++] = xdst;
3902 mtu = dst_mtu(xfrm_dst_child(dst));
3903 if (xdst->child_mtu_cached != mtu) {
3905 xdst->child_mtu_cached = mtu;
3908 if (!dst_check(xdst->route, xdst->route_cookie))
3910 mtu = dst_mtu(xdst->route);
3911 if (xdst->route_mtu_cached != mtu) {
3913 xdst->route_mtu_cached = mtu;
3916 dst = xfrm_dst_child(dst);
3917 } while (dst->xfrm);
3919 if (likely(!start_from))
3922 xdst = bundle[start_from - 1];
3923 mtu = xdst->child_mtu_cached;
3924 while (start_from--) {
3927 mtu = xfrm_state_mtu(dst->xfrm, mtu);
3928 if (mtu > xdst->route_mtu_cached)
3929 mtu = xdst->route_mtu_cached;
3930 dst_metric_set(dst, RTAX_MTU, mtu);
3934 xdst = bundle[start_from - 1];
3935 xdst->child_mtu_cached = mtu;
3941 static unsigned int xfrm_default_advmss(const struct dst_entry *dst)
3943 return dst_metric_advmss(xfrm_dst_path(dst));
3946 static unsigned int xfrm_mtu(const struct dst_entry *dst)
3948 unsigned int mtu = dst_metric_raw(dst, RTAX_MTU);
3950 return mtu ? : dst_mtu(xfrm_dst_path(dst));
3953 static const void *xfrm_get_dst_nexthop(const struct dst_entry *dst,
3957 const struct xfrm_state *xfrm = dst->xfrm;
3959 dst = xfrm_dst_child(dst);
3961 if (xfrm->props.mode == XFRM_MODE_TRANSPORT)
3963 if (xfrm->type->flags & XFRM_TYPE_REMOTE_COADDR)
3964 daddr = xfrm->coaddr;
3965 else if (!(xfrm->type->flags & XFRM_TYPE_LOCAL_COADDR))
3966 daddr = &xfrm->id.daddr;
3971 static struct neighbour *xfrm_neigh_lookup(const struct dst_entry *dst,
3972 struct sk_buff *skb,
3975 const struct dst_entry *path = xfrm_dst_path(dst);
3978 daddr = xfrm_get_dst_nexthop(dst, daddr);
3979 return path->ops->neigh_lookup(path, skb, daddr);
3982 static void xfrm_confirm_neigh(const struct dst_entry *dst, const void *daddr)
3984 const struct dst_entry *path = xfrm_dst_path(dst);
3986 daddr = xfrm_get_dst_nexthop(dst, daddr);
3987 path->ops->confirm_neigh(path, daddr);
3990 int xfrm_policy_register_afinfo(const struct xfrm_policy_afinfo *afinfo, int family)
3994 if (WARN_ON(family >= ARRAY_SIZE(xfrm_policy_afinfo)))
3995 return -EAFNOSUPPORT;
3997 spin_lock(&xfrm_policy_afinfo_lock);
3998 if (unlikely(xfrm_policy_afinfo[family] != NULL))
4001 struct dst_ops *dst_ops = afinfo->dst_ops;
4002 if (likely(dst_ops->kmem_cachep == NULL))
4003 dst_ops->kmem_cachep = xfrm_dst_cache;
4004 if (likely(dst_ops->check == NULL))
4005 dst_ops->check = xfrm_dst_check;
4006 if (likely(dst_ops->default_advmss == NULL))
4007 dst_ops->default_advmss = xfrm_default_advmss;
4008 if (likely(dst_ops->mtu == NULL))
4009 dst_ops->mtu = xfrm_mtu;
4010 if (likely(dst_ops->negative_advice == NULL))
4011 dst_ops->negative_advice = xfrm_negative_advice;
4012 if (likely(dst_ops->link_failure == NULL))
4013 dst_ops->link_failure = xfrm_link_failure;
4014 if (likely(dst_ops->neigh_lookup == NULL))
4015 dst_ops->neigh_lookup = xfrm_neigh_lookup;
4016 if (likely(!dst_ops->confirm_neigh))
4017 dst_ops->confirm_neigh = xfrm_confirm_neigh;
4018 rcu_assign_pointer(xfrm_policy_afinfo[family], afinfo);
4020 spin_unlock(&xfrm_policy_afinfo_lock);
4024 EXPORT_SYMBOL(xfrm_policy_register_afinfo);
4026 void xfrm_policy_unregister_afinfo(const struct xfrm_policy_afinfo *afinfo)
4028 struct dst_ops *dst_ops = afinfo->dst_ops;
4031 for (i = 0; i < ARRAY_SIZE(xfrm_policy_afinfo); i++) {
4032 if (xfrm_policy_afinfo[i] != afinfo)
4034 RCU_INIT_POINTER(xfrm_policy_afinfo[i], NULL);
4040 dst_ops->kmem_cachep = NULL;
4041 dst_ops->check = NULL;
4042 dst_ops->negative_advice = NULL;
4043 dst_ops->link_failure = NULL;
4045 EXPORT_SYMBOL(xfrm_policy_unregister_afinfo);
4047 void xfrm_if_register_cb(const struct xfrm_if_cb *ifcb)
4049 spin_lock(&xfrm_if_cb_lock);
4050 rcu_assign_pointer(xfrm_if_cb, ifcb);
4051 spin_unlock(&xfrm_if_cb_lock);
4053 EXPORT_SYMBOL(xfrm_if_register_cb);
4055 void xfrm_if_unregister_cb(void)
4057 RCU_INIT_POINTER(xfrm_if_cb, NULL);
4060 EXPORT_SYMBOL(xfrm_if_unregister_cb);
4062 #ifdef CONFIG_XFRM_STATISTICS
4063 static int __net_init xfrm_statistics_init(struct net *net)
4066 net->mib.xfrm_statistics = alloc_percpu(struct linux_xfrm_mib);
4067 if (!net->mib.xfrm_statistics)
4069 rv = xfrm_proc_init(net);
4071 free_percpu(net->mib.xfrm_statistics);
4075 static void xfrm_statistics_fini(struct net *net)
4077 xfrm_proc_fini(net);
4078 free_percpu(net->mib.xfrm_statistics);
4081 static int __net_init xfrm_statistics_init(struct net *net)
4086 static void xfrm_statistics_fini(struct net *net)
4091 static int __net_init xfrm_policy_init(struct net *net)
4093 unsigned int hmask, sz;
4096 if (net_eq(net, &init_net)) {
4097 xfrm_dst_cache = kmem_cache_create("xfrm_dst_cache",
4098 sizeof(struct xfrm_dst),
4099 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4101 err = rhashtable_init(&xfrm_policy_inexact_table,
4102 &xfrm_pol_inexact_params);
4107 sz = (hmask+1) * sizeof(struct hlist_head);
4109 net->xfrm.policy_byidx = xfrm_hash_alloc(sz);
4110 if (!net->xfrm.policy_byidx)
4112 net->xfrm.policy_idx_hmask = hmask;
4114 for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
4115 struct xfrm_policy_hash *htab;
4117 net->xfrm.policy_count[dir] = 0;
4118 net->xfrm.policy_count[XFRM_POLICY_MAX + dir] = 0;
4119 INIT_HLIST_HEAD(&net->xfrm.policy_inexact[dir]);
4121 htab = &net->xfrm.policy_bydst[dir];
4122 htab->table = xfrm_hash_alloc(sz);
4125 htab->hmask = hmask;
4131 net->xfrm.policy_hthresh.lbits4 = 32;
4132 net->xfrm.policy_hthresh.rbits4 = 32;
4133 net->xfrm.policy_hthresh.lbits6 = 128;
4134 net->xfrm.policy_hthresh.rbits6 = 128;
4136 seqlock_init(&net->xfrm.policy_hthresh.lock);
4138 INIT_LIST_HEAD(&net->xfrm.policy_all);
4139 INIT_LIST_HEAD(&net->xfrm.inexact_bins);
4140 INIT_WORK(&net->xfrm.policy_hash_work, xfrm_hash_resize);
4141 INIT_WORK(&net->xfrm.policy_hthresh.work, xfrm_hash_rebuild);
4145 for (dir--; dir >= 0; dir--) {
4146 struct xfrm_policy_hash *htab;
4148 htab = &net->xfrm.policy_bydst[dir];
4149 xfrm_hash_free(htab->table, sz);
4151 xfrm_hash_free(net->xfrm.policy_byidx, sz);
4156 static void xfrm_policy_fini(struct net *net)
4158 struct xfrm_pol_inexact_bin *b, *t;
4162 flush_work(&net->xfrm.policy_hash_work);
4163 #ifdef CONFIG_XFRM_SUB_POLICY
4164 xfrm_policy_flush(net, XFRM_POLICY_TYPE_SUB, false);
4166 xfrm_policy_flush(net, XFRM_POLICY_TYPE_MAIN, false);
4168 WARN_ON(!list_empty(&net->xfrm.policy_all));
4170 for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
4171 struct xfrm_policy_hash *htab;
4173 WARN_ON(!hlist_empty(&net->xfrm.policy_inexact[dir]));
4175 htab = &net->xfrm.policy_bydst[dir];
4176 sz = (htab->hmask + 1) * sizeof(struct hlist_head);
4177 WARN_ON(!hlist_empty(htab->table));
4178 xfrm_hash_free(htab->table, sz);
4181 sz = (net->xfrm.policy_idx_hmask + 1) * sizeof(struct hlist_head);
4182 WARN_ON(!hlist_empty(net->xfrm.policy_byidx));
4183 xfrm_hash_free(net->xfrm.policy_byidx, sz);
4185 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
4186 list_for_each_entry_safe(b, t, &net->xfrm.inexact_bins, inexact_bins)
4187 __xfrm_policy_inexact_prune_bin(b, true);
4188 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
4191 static int __net_init xfrm_net_init(struct net *net)
4195 /* Initialize the per-net locks here */
4196 spin_lock_init(&net->xfrm.xfrm_state_lock);
4197 spin_lock_init(&net->xfrm.xfrm_policy_lock);
4198 seqcount_spinlock_init(&net->xfrm.xfrm_policy_hash_generation, &net->xfrm.xfrm_policy_lock);
4199 mutex_init(&net->xfrm.xfrm_cfg_mutex);
4200 net->xfrm.policy_default[XFRM_POLICY_IN] = XFRM_USERPOLICY_ACCEPT;
4201 net->xfrm.policy_default[XFRM_POLICY_FWD] = XFRM_USERPOLICY_ACCEPT;
4202 net->xfrm.policy_default[XFRM_POLICY_OUT] = XFRM_USERPOLICY_ACCEPT;
4204 rv = xfrm_statistics_init(net);
4206 goto out_statistics;
4207 rv = xfrm_state_init(net);
4210 rv = xfrm_policy_init(net);
4213 rv = xfrm_sysctl_init(net);
4220 xfrm_policy_fini(net);
4222 xfrm_state_fini(net);
4224 xfrm_statistics_fini(net);
4229 static void __net_exit xfrm_net_exit(struct net *net)
4231 xfrm_sysctl_fini(net);
4232 xfrm_policy_fini(net);
4233 xfrm_state_fini(net);
4234 xfrm_statistics_fini(net);
4237 static struct pernet_operations __net_initdata xfrm_net_ops = {
4238 .init = xfrm_net_init,
4239 .exit = xfrm_net_exit,
4242 void __init xfrm_init(void)
4244 register_pernet_subsys(&xfrm_net_ops);
4248 #ifdef CONFIG_XFRM_ESPINTCP
4253 #ifdef CONFIG_AUDITSYSCALL
4254 static void xfrm_audit_common_policyinfo(struct xfrm_policy *xp,
4255 struct audit_buffer *audit_buf)
4257 struct xfrm_sec_ctx *ctx = xp->security;
4258 struct xfrm_selector *sel = &xp->selector;
4261 audit_log_format(audit_buf, " sec_alg=%u sec_doi=%u sec_obj=%s",
4262 ctx->ctx_alg, ctx->ctx_doi, ctx->ctx_str);
4264 switch (sel->family) {
4266 audit_log_format(audit_buf, " src=%pI4", &sel->saddr.a4);
4267 if (sel->prefixlen_s != 32)
4268 audit_log_format(audit_buf, " src_prefixlen=%d",
4270 audit_log_format(audit_buf, " dst=%pI4", &sel->daddr.a4);
4271 if (sel->prefixlen_d != 32)
4272 audit_log_format(audit_buf, " dst_prefixlen=%d",
4276 audit_log_format(audit_buf, " src=%pI6", sel->saddr.a6);
4277 if (sel->prefixlen_s != 128)
4278 audit_log_format(audit_buf, " src_prefixlen=%d",
4280 audit_log_format(audit_buf, " dst=%pI6", sel->daddr.a6);
4281 if (sel->prefixlen_d != 128)
4282 audit_log_format(audit_buf, " dst_prefixlen=%d",
4288 void xfrm_audit_policy_add(struct xfrm_policy *xp, int result, bool task_valid)
4290 struct audit_buffer *audit_buf;
4292 audit_buf = xfrm_audit_start("SPD-add");
4293 if (audit_buf == NULL)
4295 xfrm_audit_helper_usrinfo(task_valid, audit_buf);
4296 audit_log_format(audit_buf, " res=%u", result);
4297 xfrm_audit_common_policyinfo(xp, audit_buf);
4298 audit_log_end(audit_buf);
4300 EXPORT_SYMBOL_GPL(xfrm_audit_policy_add);
4302 void xfrm_audit_policy_delete(struct xfrm_policy *xp, int result,
4305 struct audit_buffer *audit_buf;
4307 audit_buf = xfrm_audit_start("SPD-delete");
4308 if (audit_buf == NULL)
4310 xfrm_audit_helper_usrinfo(task_valid, audit_buf);
4311 audit_log_format(audit_buf, " res=%u", result);
4312 xfrm_audit_common_policyinfo(xp, audit_buf);
4313 audit_log_end(audit_buf);
4315 EXPORT_SYMBOL_GPL(xfrm_audit_policy_delete);
4318 #ifdef CONFIG_XFRM_MIGRATE
4319 static bool xfrm_migrate_selector_match(const struct xfrm_selector *sel_cmp,
4320 const struct xfrm_selector *sel_tgt)
4322 if (sel_cmp->proto == IPSEC_ULPROTO_ANY) {
4323 if (sel_tgt->family == sel_cmp->family &&
4324 xfrm_addr_equal(&sel_tgt->daddr, &sel_cmp->daddr,
4326 xfrm_addr_equal(&sel_tgt->saddr, &sel_cmp->saddr,
4328 sel_tgt->prefixlen_d == sel_cmp->prefixlen_d &&
4329 sel_tgt->prefixlen_s == sel_cmp->prefixlen_s) {
4333 if (memcmp(sel_tgt, sel_cmp, sizeof(*sel_tgt)) == 0) {
4340 static struct xfrm_policy *xfrm_migrate_policy_find(const struct xfrm_selector *sel,
4341 u8 dir, u8 type, struct net *net, u32 if_id)
4343 struct xfrm_policy *pol, *ret = NULL;
4344 struct hlist_head *chain;
4347 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
4348 chain = policy_hash_direct(net, &sel->daddr, &sel->saddr, sel->family, dir);
4349 hlist_for_each_entry(pol, chain, bydst) {
4350 if ((if_id == 0 || pol->if_id == if_id) &&
4351 xfrm_migrate_selector_match(sel, &pol->selector) &&
4352 pol->type == type) {
4354 priority = ret->priority;
4358 chain = &net->xfrm.policy_inexact[dir];
4359 hlist_for_each_entry(pol, chain, bydst_inexact_list) {
4360 if ((pol->priority >= priority) && ret)
4363 if ((if_id == 0 || pol->if_id == if_id) &&
4364 xfrm_migrate_selector_match(sel, &pol->selector) &&
4365 pol->type == type) {
4373 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
4378 static int migrate_tmpl_match(const struct xfrm_migrate *m, const struct xfrm_tmpl *t)
4382 if (t->mode == m->mode && t->id.proto == m->proto &&
4383 (m->reqid == 0 || t->reqid == m->reqid)) {
4385 case XFRM_MODE_TUNNEL:
4386 case XFRM_MODE_BEET:
4387 if (xfrm_addr_equal(&t->id.daddr, &m->old_daddr,
4389 xfrm_addr_equal(&t->saddr, &m->old_saddr,
4394 case XFRM_MODE_TRANSPORT:
4395 /* in case of transport mode, template does not store
4396 any IP addresses, hence we just compare mode and
4407 /* update endpoint address(es) of template(s) */
4408 static int xfrm_policy_migrate(struct xfrm_policy *pol,
4409 struct xfrm_migrate *m, int num_migrate,
4410 struct netlink_ext_ack *extack)
4412 struct xfrm_migrate *mp;
4415 write_lock_bh(&pol->lock);
4416 if (unlikely(pol->walk.dead)) {
4417 /* target policy has been deleted */
4418 NL_SET_ERR_MSG(extack, "Target policy not found");
4419 write_unlock_bh(&pol->lock);
4423 for (i = 0; i < pol->xfrm_nr; i++) {
4424 for (j = 0, mp = m; j < num_migrate; j++, mp++) {
4425 if (!migrate_tmpl_match(mp, &pol->xfrm_vec[i]))
4428 if (pol->xfrm_vec[i].mode != XFRM_MODE_TUNNEL &&
4429 pol->xfrm_vec[i].mode != XFRM_MODE_BEET)
4431 /* update endpoints */
4432 memcpy(&pol->xfrm_vec[i].id.daddr, &mp->new_daddr,
4433 sizeof(pol->xfrm_vec[i].id.daddr));
4434 memcpy(&pol->xfrm_vec[i].saddr, &mp->new_saddr,
4435 sizeof(pol->xfrm_vec[i].saddr));
4436 pol->xfrm_vec[i].encap_family = mp->new_family;
4438 atomic_inc(&pol->genid);
4442 write_unlock_bh(&pol->lock);
4450 static int xfrm_migrate_check(const struct xfrm_migrate *m, int num_migrate,
4451 struct netlink_ext_ack *extack)
4455 if (num_migrate < 1 || num_migrate > XFRM_MAX_DEPTH) {
4456 NL_SET_ERR_MSG(extack, "Invalid number of SAs to migrate, must be 0 < num <= XFRM_MAX_DEPTH (6)");
4460 for (i = 0; i < num_migrate; i++) {
4461 if (xfrm_addr_any(&m[i].new_daddr, m[i].new_family) ||
4462 xfrm_addr_any(&m[i].new_saddr, m[i].new_family)) {
4463 NL_SET_ERR_MSG(extack, "Addresses in the MIGRATE attribute's list cannot be null");
4467 /* check if there is any duplicated entry */
4468 for (j = i + 1; j < num_migrate; j++) {
4469 if (!memcmp(&m[i].old_daddr, &m[j].old_daddr,
4470 sizeof(m[i].old_daddr)) &&
4471 !memcmp(&m[i].old_saddr, &m[j].old_saddr,
4472 sizeof(m[i].old_saddr)) &&
4473 m[i].proto == m[j].proto &&
4474 m[i].mode == m[j].mode &&
4475 m[i].reqid == m[j].reqid &&
4476 m[i].old_family == m[j].old_family) {
4477 NL_SET_ERR_MSG(extack, "Entries in the MIGRATE attribute's list must be unique");
4486 int xfrm_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
4487 struct xfrm_migrate *m, int num_migrate,
4488 struct xfrm_kmaddress *k, struct net *net,
4489 struct xfrm_encap_tmpl *encap, u32 if_id,
4490 struct netlink_ext_ack *extack)
4492 int i, err, nx_cur = 0, nx_new = 0;
4493 struct xfrm_policy *pol = NULL;
4494 struct xfrm_state *x, *xc;
4495 struct xfrm_state *x_cur[XFRM_MAX_DEPTH];
4496 struct xfrm_state *x_new[XFRM_MAX_DEPTH];
4497 struct xfrm_migrate *mp;
4499 /* Stage 0 - sanity checks */
4500 err = xfrm_migrate_check(m, num_migrate, extack);
4504 if (dir >= XFRM_POLICY_MAX) {
4505 NL_SET_ERR_MSG(extack, "Invalid policy direction");
4510 /* Stage 1 - find policy */
4511 pol = xfrm_migrate_policy_find(sel, dir, type, net, if_id);
4513 NL_SET_ERR_MSG(extack, "Target policy not found");
4518 /* Stage 2 - find and update state(s) */
4519 for (i = 0, mp = m; i < num_migrate; i++, mp++) {
4520 if ((x = xfrm_migrate_state_find(mp, net, if_id))) {
4523 xc = xfrm_state_migrate(x, mp, encap);
4534 /* Stage 3 - update policy */
4535 err = xfrm_policy_migrate(pol, m, num_migrate, extack);
4539 /* Stage 4 - delete old state(s) */
4541 xfrm_states_put(x_cur, nx_cur);
4542 xfrm_states_delete(x_cur, nx_cur);
4545 /* Stage 5 - announce */
4546 km_migrate(sel, dir, type, m, num_migrate, k, encap);
4558 xfrm_states_put(x_cur, nx_cur);
4560 xfrm_states_delete(x_new, nx_new);
4564 EXPORT_SYMBOL(xfrm_migrate);