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->walk.dead || !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 if (policy->walk.dead)
1262 dir = xfrm_policy_id2dir(policy->index);
1263 if (dir >= XFRM_POLICY_MAX)
1266 if ((dir & XFRM_POLICY_MASK) == XFRM_POLICY_OUT) {
1267 if (policy->family == AF_INET) {
1275 if (policy->family == AF_INET) {
1284 if (policy->selector.prefixlen_d < dbits ||
1285 policy->selector.prefixlen_s < sbits)
1288 bin = xfrm_policy_inexact_alloc_bin(policy, dir);
1292 if (!xfrm_policy_inexact_alloc_chain(bin, policy, dir))
1296 /* reset the bydst and inexact table in all directions */
1297 for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
1298 struct hlist_node *n;
1300 hlist_for_each_entry_safe(policy, n,
1301 &net->xfrm.policy_inexact[dir],
1302 bydst_inexact_list) {
1303 hlist_del_rcu(&policy->bydst);
1304 hlist_del_init(&policy->bydst_inexact_list);
1307 hmask = net->xfrm.policy_bydst[dir].hmask;
1308 odst = net->xfrm.policy_bydst[dir].table;
1309 for (i = hmask; i >= 0; i--) {
1310 hlist_for_each_entry_safe(policy, n, odst + i, bydst)
1311 hlist_del_rcu(&policy->bydst);
1313 if ((dir & XFRM_POLICY_MASK) == XFRM_POLICY_OUT) {
1314 /* dir out => dst = remote, src = local */
1315 net->xfrm.policy_bydst[dir].dbits4 = rbits4;
1316 net->xfrm.policy_bydst[dir].sbits4 = lbits4;
1317 net->xfrm.policy_bydst[dir].dbits6 = rbits6;
1318 net->xfrm.policy_bydst[dir].sbits6 = lbits6;
1320 /* dir in/fwd => dst = local, src = remote */
1321 net->xfrm.policy_bydst[dir].dbits4 = lbits4;
1322 net->xfrm.policy_bydst[dir].sbits4 = rbits4;
1323 net->xfrm.policy_bydst[dir].dbits6 = lbits6;
1324 net->xfrm.policy_bydst[dir].sbits6 = rbits6;
1328 /* re-insert all policies by order of creation */
1329 list_for_each_entry_reverse(policy, &net->xfrm.policy_all, walk.all) {
1330 if (policy->walk.dead)
1332 dir = xfrm_policy_id2dir(policy->index);
1333 if (dir >= XFRM_POLICY_MAX) {
1334 /* skip socket policies */
1338 chain = policy_hash_bysel(net, &policy->selector,
1339 policy->family, dir);
1342 void *p = xfrm_policy_inexact_insert(policy, dir, 0);
1344 WARN_ONCE(IS_ERR(p), "reinsert: %ld\n", PTR_ERR(p));
1348 hlist_for_each_entry(pol, chain, bydst) {
1349 if (policy->priority >= pol->priority)
1350 newpos = &pol->bydst;
1354 if (newpos && policy->xdo.type != XFRM_DEV_OFFLOAD_PACKET)
1355 hlist_add_behind_rcu(&policy->bydst, newpos);
1357 hlist_add_head_rcu(&policy->bydst, chain);
1361 __xfrm_policy_inexact_flush(net);
1362 write_seqcount_end(&net->xfrm.xfrm_policy_hash_generation);
1363 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1365 mutex_unlock(&hash_resize_mutex);
1368 void xfrm_policy_hash_rebuild(struct net *net)
1370 schedule_work(&net->xfrm.policy_hthresh.work);
1372 EXPORT_SYMBOL(xfrm_policy_hash_rebuild);
1374 /* Generate new index... KAME seems to generate them ordered by cost
1375 * of an absolute inpredictability of ordering of rules. This will not pass. */
1376 static u32 xfrm_gen_index(struct net *net, int dir, u32 index)
1379 struct hlist_head *list;
1380 struct xfrm_policy *p;
1385 idx = (net->xfrm.idx_generator | dir);
1386 net->xfrm.idx_generator += 8;
1394 list = net->xfrm.policy_byidx + idx_hash(net, idx);
1396 hlist_for_each_entry(p, list, byidx) {
1397 if (p->index == idx) {
1407 static inline int selector_cmp(struct xfrm_selector *s1, struct xfrm_selector *s2)
1409 u32 *p1 = (u32 *) s1;
1410 u32 *p2 = (u32 *) s2;
1411 int len = sizeof(struct xfrm_selector) / sizeof(u32);
1414 for (i = 0; i < len; i++) {
1422 static void xfrm_policy_requeue(struct xfrm_policy *old,
1423 struct xfrm_policy *new)
1425 struct xfrm_policy_queue *pq = &old->polq;
1426 struct sk_buff_head list;
1428 if (skb_queue_empty(&pq->hold_queue))
1431 __skb_queue_head_init(&list);
1433 spin_lock_bh(&pq->hold_queue.lock);
1434 skb_queue_splice_init(&pq->hold_queue, &list);
1435 if (del_timer(&pq->hold_timer))
1437 spin_unlock_bh(&pq->hold_queue.lock);
1441 spin_lock_bh(&pq->hold_queue.lock);
1442 skb_queue_splice(&list, &pq->hold_queue);
1443 pq->timeout = XFRM_QUEUE_TMO_MIN;
1444 if (!mod_timer(&pq->hold_timer, jiffies))
1446 spin_unlock_bh(&pq->hold_queue.lock);
1449 static inline bool xfrm_policy_mark_match(const struct xfrm_mark *mark,
1450 struct xfrm_policy *pol)
1452 return mark->v == pol->mark.v && mark->m == pol->mark.m;
1455 static u32 xfrm_pol_bin_key(const void *data, u32 len, u32 seed)
1457 const struct xfrm_pol_inexact_key *k = data;
1458 u32 a = k->type << 24 | k->dir << 16 | k->family;
1460 return jhash_3words(a, k->if_id, net_hash_mix(read_pnet(&k->net)),
1464 static u32 xfrm_pol_bin_obj(const void *data, u32 len, u32 seed)
1466 const struct xfrm_pol_inexact_bin *b = data;
1468 return xfrm_pol_bin_key(&b->k, 0, seed);
1471 static int xfrm_pol_bin_cmp(struct rhashtable_compare_arg *arg,
1474 const struct xfrm_pol_inexact_key *key = arg->key;
1475 const struct xfrm_pol_inexact_bin *b = ptr;
1478 if (!net_eq(read_pnet(&b->k.net), read_pnet(&key->net)))
1481 ret = b->k.dir ^ key->dir;
1485 ret = b->k.type ^ key->type;
1489 ret = b->k.family ^ key->family;
1493 return b->k.if_id ^ key->if_id;
1496 static const struct rhashtable_params xfrm_pol_inexact_params = {
1497 .head_offset = offsetof(struct xfrm_pol_inexact_bin, head),
1498 .hashfn = xfrm_pol_bin_key,
1499 .obj_hashfn = xfrm_pol_bin_obj,
1500 .obj_cmpfn = xfrm_pol_bin_cmp,
1501 .automatic_shrinking = true,
1504 static void xfrm_policy_insert_inexact_list(struct hlist_head *chain,
1505 struct xfrm_policy *policy)
1507 struct xfrm_policy *pol, *delpol = NULL;
1508 struct hlist_node *newpos = NULL;
1511 hlist_for_each_entry(pol, chain, bydst_inexact_list) {
1512 if (pol->type == policy->type &&
1513 pol->if_id == policy->if_id &&
1514 !selector_cmp(&pol->selector, &policy->selector) &&
1515 xfrm_policy_mark_match(&policy->mark, pol) &&
1516 xfrm_sec_ctx_match(pol->security, policy->security) &&
1519 if (policy->priority > pol->priority)
1521 } else if (policy->priority >= pol->priority) {
1522 newpos = &pol->bydst_inexact_list;
1529 if (newpos && policy->xdo.type != XFRM_DEV_OFFLOAD_PACKET)
1530 hlist_add_behind_rcu(&policy->bydst_inexact_list, newpos);
1532 hlist_add_head_rcu(&policy->bydst_inexact_list, chain);
1534 hlist_for_each_entry(pol, chain, bydst_inexact_list) {
1540 static struct xfrm_policy *xfrm_policy_insert_list(struct hlist_head *chain,
1541 struct xfrm_policy *policy,
1544 struct xfrm_policy *pol, *newpos = NULL, *delpol = NULL;
1546 hlist_for_each_entry(pol, chain, bydst) {
1547 if (pol->type == policy->type &&
1548 pol->if_id == policy->if_id &&
1549 !selector_cmp(&pol->selector, &policy->selector) &&
1550 xfrm_policy_mark_match(&policy->mark, pol) &&
1551 xfrm_sec_ctx_match(pol->security, policy->security) &&
1554 return ERR_PTR(-EEXIST);
1556 if (policy->priority > pol->priority)
1558 } else if (policy->priority >= pol->priority) {
1566 if (newpos && policy->xdo.type != XFRM_DEV_OFFLOAD_PACKET)
1567 hlist_add_behind_rcu(&policy->bydst, &newpos->bydst);
1569 /* Packet offload policies enter to the head
1570 * to speed-up lookups.
1572 hlist_add_head_rcu(&policy->bydst, chain);
1577 int xfrm_policy_insert(int dir, struct xfrm_policy *policy, int excl)
1579 struct net *net = xp_net(policy);
1580 struct xfrm_policy *delpol;
1581 struct hlist_head *chain;
1583 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1584 chain = policy_hash_bysel(net, &policy->selector, policy->family, dir);
1586 delpol = xfrm_policy_insert_list(chain, policy, excl);
1588 delpol = xfrm_policy_inexact_insert(policy, dir, excl);
1590 if (IS_ERR(delpol)) {
1591 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1592 return PTR_ERR(delpol);
1595 __xfrm_policy_link(policy, dir);
1597 /* After previous checking, family can either be AF_INET or AF_INET6 */
1598 if (policy->family == AF_INET)
1599 rt_genid_bump_ipv4(net);
1601 rt_genid_bump_ipv6(net);
1604 xfrm_policy_requeue(delpol, policy);
1605 __xfrm_policy_unlink(delpol, dir);
1607 policy->index = delpol ? delpol->index : xfrm_gen_index(net, dir, policy->index);
1608 hlist_add_head(&policy->byidx, net->xfrm.policy_byidx+idx_hash(net, policy->index));
1609 policy->curlft.add_time = ktime_get_real_seconds();
1610 policy->curlft.use_time = 0;
1611 if (!mod_timer(&policy->timer, jiffies + HZ))
1612 xfrm_pol_hold(policy);
1613 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1616 xfrm_policy_kill(delpol);
1617 else if (xfrm_bydst_should_resize(net, dir, NULL))
1618 schedule_work(&net->xfrm.policy_hash_work);
1622 EXPORT_SYMBOL(xfrm_policy_insert);
1624 static struct xfrm_policy *
1625 __xfrm_policy_bysel_ctx(struct hlist_head *chain, const struct xfrm_mark *mark,
1626 u32 if_id, u8 type, int dir, struct xfrm_selector *sel,
1627 struct xfrm_sec_ctx *ctx)
1629 struct xfrm_policy *pol;
1634 hlist_for_each_entry(pol, chain, bydst) {
1635 if (pol->type == type &&
1636 pol->if_id == if_id &&
1637 xfrm_policy_mark_match(mark, pol) &&
1638 !selector_cmp(sel, &pol->selector) &&
1639 xfrm_sec_ctx_match(ctx, pol->security))
1646 struct xfrm_policy *
1647 xfrm_policy_bysel_ctx(struct net *net, const struct xfrm_mark *mark, u32 if_id,
1648 u8 type, int dir, struct xfrm_selector *sel,
1649 struct xfrm_sec_ctx *ctx, int delete, int *err)
1651 struct xfrm_pol_inexact_bin *bin = NULL;
1652 struct xfrm_policy *pol, *ret = NULL;
1653 struct hlist_head *chain;
1656 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1657 chain = policy_hash_bysel(net, sel, sel->family, dir);
1659 struct xfrm_pol_inexact_candidates cand;
1662 bin = xfrm_policy_inexact_lookup(net, type,
1663 sel->family, dir, if_id);
1665 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1669 if (!xfrm_policy_find_inexact_candidates(&cand, bin,
1672 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1677 for (i = 0; i < ARRAY_SIZE(cand.res); i++) {
1678 struct xfrm_policy *tmp;
1680 tmp = __xfrm_policy_bysel_ctx(cand.res[i], mark,
1686 if (!pol || tmp->pos < pol->pos)
1690 pol = __xfrm_policy_bysel_ctx(chain, mark, if_id, type, dir,
1697 *err = security_xfrm_policy_delete(pol->security);
1699 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1702 __xfrm_policy_unlink(pol, dir);
1706 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1709 xfrm_policy_kill(ret);
1711 xfrm_policy_inexact_prune_bin(bin);
1714 EXPORT_SYMBOL(xfrm_policy_bysel_ctx);
1716 struct xfrm_policy *
1717 xfrm_policy_byid(struct net *net, const struct xfrm_mark *mark, u32 if_id,
1718 u8 type, int dir, u32 id, int delete, int *err)
1720 struct xfrm_policy *pol, *ret;
1721 struct hlist_head *chain;
1724 if (xfrm_policy_id2dir(id) != dir)
1728 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1729 chain = net->xfrm.policy_byidx + idx_hash(net, id);
1731 hlist_for_each_entry(pol, chain, byidx) {
1732 if (pol->type == type && pol->index == id &&
1733 pol->if_id == if_id && xfrm_policy_mark_match(mark, pol)) {
1736 *err = security_xfrm_policy_delete(
1739 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1742 __xfrm_policy_unlink(pol, dir);
1748 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1751 xfrm_policy_kill(ret);
1754 EXPORT_SYMBOL(xfrm_policy_byid);
1756 #ifdef CONFIG_SECURITY_NETWORK_XFRM
1758 xfrm_policy_flush_secctx_check(struct net *net, u8 type, bool task_valid)
1760 struct xfrm_policy *pol;
1763 list_for_each_entry(pol, &net->xfrm.policy_all, walk.all) {
1764 if (pol->walk.dead ||
1765 xfrm_policy_id2dir(pol->index) >= XFRM_POLICY_MAX ||
1769 err = security_xfrm_policy_delete(pol->security);
1771 xfrm_audit_policy_delete(pol, 0, task_valid);
1778 static inline int xfrm_dev_policy_flush_secctx_check(struct net *net,
1779 struct net_device *dev,
1782 struct xfrm_policy *pol;
1785 list_for_each_entry(pol, &net->xfrm.policy_all, walk.all) {
1786 if (pol->walk.dead ||
1787 xfrm_policy_id2dir(pol->index) >= XFRM_POLICY_MAX ||
1788 pol->xdo.dev != dev)
1791 err = security_xfrm_policy_delete(pol->security);
1793 xfrm_audit_policy_delete(pol, 0, task_valid);
1801 xfrm_policy_flush_secctx_check(struct net *net, u8 type, bool task_valid)
1806 static inline int xfrm_dev_policy_flush_secctx_check(struct net *net,
1807 struct net_device *dev,
1814 int xfrm_policy_flush(struct net *net, u8 type, bool task_valid)
1816 int dir, err = 0, cnt = 0;
1817 struct xfrm_policy *pol;
1819 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1821 err = xfrm_policy_flush_secctx_check(net, type, task_valid);
1826 list_for_each_entry(pol, &net->xfrm.policy_all, walk.all) {
1830 dir = xfrm_policy_id2dir(pol->index);
1831 if (dir >= XFRM_POLICY_MAX ||
1835 __xfrm_policy_unlink(pol, dir);
1836 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1837 xfrm_dev_policy_delete(pol);
1839 xfrm_audit_policy_delete(pol, 1, task_valid);
1840 xfrm_policy_kill(pol);
1841 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1845 __xfrm_policy_inexact_flush(net);
1849 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1852 EXPORT_SYMBOL(xfrm_policy_flush);
1854 int xfrm_dev_policy_flush(struct net *net, struct net_device *dev,
1857 int dir, err = 0, cnt = 0;
1858 struct xfrm_policy *pol;
1860 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1862 err = xfrm_dev_policy_flush_secctx_check(net, dev, task_valid);
1867 list_for_each_entry(pol, &net->xfrm.policy_all, walk.all) {
1871 dir = xfrm_policy_id2dir(pol->index);
1872 if (dir >= XFRM_POLICY_MAX ||
1873 pol->xdo.dev != dev)
1876 __xfrm_policy_unlink(pol, dir);
1877 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1878 xfrm_dev_policy_delete(pol);
1880 xfrm_audit_policy_delete(pol, 1, task_valid);
1881 xfrm_policy_kill(pol);
1882 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1886 __xfrm_policy_inexact_flush(net);
1890 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1893 EXPORT_SYMBOL(xfrm_dev_policy_flush);
1895 int xfrm_policy_walk(struct net *net, struct xfrm_policy_walk *walk,
1896 int (*func)(struct xfrm_policy *, int, int, void*),
1899 struct xfrm_policy *pol;
1900 struct xfrm_policy_walk_entry *x;
1903 if (walk->type >= XFRM_POLICY_TYPE_MAX &&
1904 walk->type != XFRM_POLICY_TYPE_ANY)
1907 if (list_empty(&walk->walk.all) && walk->seq != 0)
1910 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1911 if (list_empty(&walk->walk.all))
1912 x = list_first_entry(&net->xfrm.policy_all, struct xfrm_policy_walk_entry, all);
1914 x = list_first_entry(&walk->walk.all,
1915 struct xfrm_policy_walk_entry, all);
1917 list_for_each_entry_from(x, &net->xfrm.policy_all, all) {
1920 pol = container_of(x, struct xfrm_policy, walk);
1921 if (walk->type != XFRM_POLICY_TYPE_ANY &&
1922 walk->type != pol->type)
1924 error = func(pol, xfrm_policy_id2dir(pol->index),
1927 list_move_tail(&walk->walk.all, &x->all);
1932 if (walk->seq == 0) {
1936 list_del_init(&walk->walk.all);
1938 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1941 EXPORT_SYMBOL(xfrm_policy_walk);
1943 void xfrm_policy_walk_init(struct xfrm_policy_walk *walk, u8 type)
1945 INIT_LIST_HEAD(&walk->walk.all);
1946 walk->walk.dead = 1;
1950 EXPORT_SYMBOL(xfrm_policy_walk_init);
1952 void xfrm_policy_walk_done(struct xfrm_policy_walk *walk, struct net *net)
1954 if (list_empty(&walk->walk.all))
1957 spin_lock_bh(&net->xfrm.xfrm_policy_lock); /*FIXME where is net? */
1958 list_del(&walk->walk.all);
1959 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1961 EXPORT_SYMBOL(xfrm_policy_walk_done);
1964 * Find policy to apply to this flow.
1966 * Returns 0 if policy found, else an -errno.
1968 static int xfrm_policy_match(const struct xfrm_policy *pol,
1969 const struct flowi *fl,
1970 u8 type, u16 family, u32 if_id)
1972 const struct xfrm_selector *sel = &pol->selector;
1976 if (pol->family != family ||
1977 pol->if_id != if_id ||
1978 (fl->flowi_mark & pol->mark.m) != pol->mark.v ||
1982 match = xfrm_selector_match(sel, fl, family);
1984 ret = security_xfrm_policy_lookup(pol->security, fl->flowi_secid);
1988 static struct xfrm_pol_inexact_node *
1989 xfrm_policy_lookup_inexact_addr(const struct rb_root *r,
1990 seqcount_spinlock_t *count,
1991 const xfrm_address_t *addr, u16 family)
1993 const struct rb_node *parent;
1997 seq = read_seqcount_begin(count);
1999 parent = rcu_dereference_raw(r->rb_node);
2001 struct xfrm_pol_inexact_node *node;
2004 node = rb_entry(parent, struct xfrm_pol_inexact_node, node);
2006 delta = xfrm_policy_addr_delta(addr, &node->addr,
2007 node->prefixlen, family);
2009 parent = rcu_dereference_raw(parent->rb_left);
2011 } else if (delta > 0) {
2012 parent = rcu_dereference_raw(parent->rb_right);
2019 if (read_seqcount_retry(count, seq))
2026 xfrm_policy_find_inexact_candidates(struct xfrm_pol_inexact_candidates *cand,
2027 struct xfrm_pol_inexact_bin *b,
2028 const xfrm_address_t *saddr,
2029 const xfrm_address_t *daddr)
2031 struct xfrm_pol_inexact_node *n;
2037 family = b->k.family;
2038 memset(cand, 0, sizeof(*cand));
2039 cand->res[XFRM_POL_CAND_ANY] = &b->hhead;
2041 n = xfrm_policy_lookup_inexact_addr(&b->root_d, &b->count, daddr,
2044 cand->res[XFRM_POL_CAND_DADDR] = &n->hhead;
2045 n = xfrm_policy_lookup_inexact_addr(&n->root, &b->count, saddr,
2048 cand->res[XFRM_POL_CAND_BOTH] = &n->hhead;
2051 n = xfrm_policy_lookup_inexact_addr(&b->root_s, &b->count, saddr,
2054 cand->res[XFRM_POL_CAND_SADDR] = &n->hhead;
2059 static struct xfrm_pol_inexact_bin *
2060 xfrm_policy_inexact_lookup_rcu(struct net *net, u8 type, u16 family,
2063 struct xfrm_pol_inexact_key k = {
2070 write_pnet(&k.net, net);
2072 return rhashtable_lookup(&xfrm_policy_inexact_table, &k,
2073 xfrm_pol_inexact_params);
2076 static struct xfrm_pol_inexact_bin *
2077 xfrm_policy_inexact_lookup(struct net *net, u8 type, u16 family,
2080 struct xfrm_pol_inexact_bin *bin;
2082 lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
2085 bin = xfrm_policy_inexact_lookup_rcu(net, type, family, dir, if_id);
2091 static struct xfrm_policy *
2092 __xfrm_policy_eval_candidates(struct hlist_head *chain,
2093 struct xfrm_policy *prefer,
2094 const struct flowi *fl,
2095 u8 type, u16 family, u32 if_id)
2097 u32 priority = prefer ? prefer->priority : ~0u;
2098 struct xfrm_policy *pol;
2103 hlist_for_each_entry_rcu(pol, chain, bydst) {
2106 if (pol->priority > priority)
2109 err = xfrm_policy_match(pol, fl, type, family, if_id);
2112 return ERR_PTR(err);
2118 /* matches. Is it older than *prefer? */
2119 if (pol->priority == priority &&
2120 prefer->pos < pol->pos)
2130 static struct xfrm_policy *
2131 xfrm_policy_eval_candidates(struct xfrm_pol_inexact_candidates *cand,
2132 struct xfrm_policy *prefer,
2133 const struct flowi *fl,
2134 u8 type, u16 family, u32 if_id)
2136 struct xfrm_policy *tmp;
2139 for (i = 0; i < ARRAY_SIZE(cand->res); i++) {
2140 tmp = __xfrm_policy_eval_candidates(cand->res[i],
2142 fl, type, family, if_id);
2154 static struct xfrm_policy *xfrm_policy_lookup_bytype(struct net *net, u8 type,
2155 const struct flowi *fl,
2159 struct xfrm_pol_inexact_candidates cand;
2160 const xfrm_address_t *daddr, *saddr;
2161 struct xfrm_pol_inexact_bin *bin;
2162 struct xfrm_policy *pol, *ret;
2163 struct hlist_head *chain;
2164 unsigned int sequence;
2167 daddr = xfrm_flowi_daddr(fl, family);
2168 saddr = xfrm_flowi_saddr(fl, family);
2169 if (unlikely(!daddr || !saddr))
2175 sequence = read_seqcount_begin(&net->xfrm.xfrm_policy_hash_generation);
2176 chain = policy_hash_direct(net, daddr, saddr, family, dir);
2177 } while (read_seqcount_retry(&net->xfrm.xfrm_policy_hash_generation, sequence));
2180 hlist_for_each_entry_rcu(pol, chain, bydst) {
2181 err = xfrm_policy_match(pol, fl, type, family, if_id);
2194 if (ret && ret->xdo.type == XFRM_DEV_OFFLOAD_PACKET)
2197 bin = xfrm_policy_inexact_lookup_rcu(net, type, family, dir, if_id);
2198 if (!bin || !xfrm_policy_find_inexact_candidates(&cand, bin, saddr,
2202 pol = xfrm_policy_eval_candidates(&cand, ret, fl, type,
2211 if (read_seqcount_retry(&net->xfrm.xfrm_policy_hash_generation, sequence))
2214 if (ret && !xfrm_pol_hold_rcu(ret))
2222 static struct xfrm_policy *xfrm_policy_lookup(struct net *net,
2223 const struct flowi *fl,
2224 u16 family, u8 dir, u32 if_id)
2226 #ifdef CONFIG_XFRM_SUB_POLICY
2227 struct xfrm_policy *pol;
2229 pol = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_SUB, fl, family,
2234 return xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN, fl, family,
2238 static struct xfrm_policy *xfrm_sk_policy_lookup(const struct sock *sk, int dir,
2239 const struct flowi *fl,
2240 u16 family, u32 if_id)
2242 struct xfrm_policy *pol;
2246 pol = rcu_dereference(sk->sk_policy[dir]);
2251 if (pol->family != family) {
2256 match = xfrm_selector_match(&pol->selector, fl, family);
2258 if ((READ_ONCE(sk->sk_mark) & pol->mark.m) != pol->mark.v ||
2259 pol->if_id != if_id) {
2263 err = security_xfrm_policy_lookup(pol->security,
2266 if (!xfrm_pol_hold_rcu(pol))
2268 } else if (err == -ESRCH) {
2281 static void __xfrm_policy_link(struct xfrm_policy *pol, int dir)
2283 struct net *net = xp_net(pol);
2285 list_add(&pol->walk.all, &net->xfrm.policy_all);
2286 net->xfrm.policy_count[dir]++;
2290 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
2293 struct net *net = xp_net(pol);
2295 if (list_empty(&pol->walk.all))
2298 /* Socket policies are not hashed. */
2299 if (!hlist_unhashed(&pol->bydst)) {
2300 hlist_del_rcu(&pol->bydst);
2301 hlist_del_init(&pol->bydst_inexact_list);
2302 hlist_del(&pol->byidx);
2305 list_del_init(&pol->walk.all);
2306 net->xfrm.policy_count[dir]--;
2311 static void xfrm_sk_policy_link(struct xfrm_policy *pol, int dir)
2313 __xfrm_policy_link(pol, XFRM_POLICY_MAX + dir);
2316 static void xfrm_sk_policy_unlink(struct xfrm_policy *pol, int dir)
2318 __xfrm_policy_unlink(pol, XFRM_POLICY_MAX + dir);
2321 int xfrm_policy_delete(struct xfrm_policy *pol, int dir)
2323 struct net *net = xp_net(pol);
2325 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
2326 pol = __xfrm_policy_unlink(pol, dir);
2327 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
2329 xfrm_dev_policy_delete(pol);
2330 xfrm_policy_kill(pol);
2335 EXPORT_SYMBOL(xfrm_policy_delete);
2337 int xfrm_sk_policy_insert(struct sock *sk, int dir, struct xfrm_policy *pol)
2339 struct net *net = sock_net(sk);
2340 struct xfrm_policy *old_pol;
2342 #ifdef CONFIG_XFRM_SUB_POLICY
2343 if (pol && pol->type != XFRM_POLICY_TYPE_MAIN)
2347 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
2348 old_pol = rcu_dereference_protected(sk->sk_policy[dir],
2349 lockdep_is_held(&net->xfrm.xfrm_policy_lock));
2351 pol->curlft.add_time = ktime_get_real_seconds();
2352 pol->index = xfrm_gen_index(net, XFRM_POLICY_MAX+dir, 0);
2353 xfrm_sk_policy_link(pol, dir);
2355 rcu_assign_pointer(sk->sk_policy[dir], pol);
2358 xfrm_policy_requeue(old_pol, pol);
2360 /* Unlinking succeeds always. This is the only function
2361 * allowed to delete or replace socket policy.
2363 xfrm_sk_policy_unlink(old_pol, dir);
2365 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
2368 xfrm_policy_kill(old_pol);
2373 static struct xfrm_policy *clone_policy(const struct xfrm_policy *old, int dir)
2375 struct xfrm_policy *newp = xfrm_policy_alloc(xp_net(old), GFP_ATOMIC);
2376 struct net *net = xp_net(old);
2379 newp->selector = old->selector;
2380 if (security_xfrm_policy_clone(old->security,
2383 return NULL; /* ENOMEM */
2385 newp->lft = old->lft;
2386 newp->curlft = old->curlft;
2387 newp->mark = old->mark;
2388 newp->if_id = old->if_id;
2389 newp->action = old->action;
2390 newp->flags = old->flags;
2391 newp->xfrm_nr = old->xfrm_nr;
2392 newp->index = old->index;
2393 newp->type = old->type;
2394 newp->family = old->family;
2395 memcpy(newp->xfrm_vec, old->xfrm_vec,
2396 newp->xfrm_nr*sizeof(struct xfrm_tmpl));
2397 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
2398 xfrm_sk_policy_link(newp, dir);
2399 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
2405 int __xfrm_sk_clone_policy(struct sock *sk, const struct sock *osk)
2407 const struct xfrm_policy *p;
2408 struct xfrm_policy *np;
2412 for (i = 0; i < 2; i++) {
2413 p = rcu_dereference(osk->sk_policy[i]);
2415 np = clone_policy(p, i);
2416 if (unlikely(!np)) {
2420 rcu_assign_pointer(sk->sk_policy[i], np);
2428 xfrm_get_saddr(struct net *net, int oif, xfrm_address_t *local,
2429 xfrm_address_t *remote, unsigned short family, u32 mark)
2432 const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
2434 if (unlikely(afinfo == NULL))
2436 err = afinfo->get_saddr(net, oif, local, remote, mark);
2441 /* Resolve list of templates for the flow, given policy. */
2444 xfrm_tmpl_resolve_one(struct xfrm_policy *policy, const struct flowi *fl,
2445 struct xfrm_state **xfrm, unsigned short family)
2447 struct net *net = xp_net(policy);
2450 xfrm_address_t *daddr = xfrm_flowi_daddr(fl, family);
2451 xfrm_address_t *saddr = xfrm_flowi_saddr(fl, family);
2454 for (nx = 0, i = 0; i < policy->xfrm_nr; i++) {
2455 struct xfrm_state *x;
2456 xfrm_address_t *remote = daddr;
2457 xfrm_address_t *local = saddr;
2458 struct xfrm_tmpl *tmpl = &policy->xfrm_vec[i];
2460 if (tmpl->mode == XFRM_MODE_TUNNEL ||
2461 tmpl->mode == XFRM_MODE_BEET) {
2462 remote = &tmpl->id.daddr;
2463 local = &tmpl->saddr;
2464 if (xfrm_addr_any(local, tmpl->encap_family)) {
2465 error = xfrm_get_saddr(net, fl->flowi_oif,
2467 tmpl->encap_family, 0);
2474 x = xfrm_state_find(remote, local, fl, tmpl, policy, &error,
2475 family, policy->if_id);
2477 if (x && x->km.state == XFRM_STATE_VALID) {
2484 error = (x->km.state == XFRM_STATE_ERROR ?
2487 } else if (error == -ESRCH) {
2491 if (!tmpl->optional)
2497 for (nx--; nx >= 0; nx--)
2498 xfrm_state_put(xfrm[nx]);
2503 xfrm_tmpl_resolve(struct xfrm_policy **pols, int npols, const struct flowi *fl,
2504 struct xfrm_state **xfrm, unsigned short family)
2506 struct xfrm_state *tp[XFRM_MAX_DEPTH];
2507 struct xfrm_state **tpp = (npols > 1) ? tp : xfrm;
2513 for (i = 0; i < npols; i++) {
2514 if (cnx + pols[i]->xfrm_nr >= XFRM_MAX_DEPTH) {
2519 ret = xfrm_tmpl_resolve_one(pols[i], fl, &tpp[cnx], family);
2527 /* found states are sorted for outbound processing */
2529 xfrm_state_sort(xfrm, tpp, cnx, family);
2534 for (cnx--; cnx >= 0; cnx--)
2535 xfrm_state_put(tpp[cnx]);
2540 static int xfrm_get_tos(const struct flowi *fl, int family)
2542 if (family == AF_INET)
2543 return IPTOS_RT_MASK & fl->u.ip4.flowi4_tos;
2548 static inline struct xfrm_dst *xfrm_alloc_dst(struct net *net, int family)
2550 const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
2551 struct dst_ops *dst_ops;
2552 struct xfrm_dst *xdst;
2555 return ERR_PTR(-EINVAL);
2559 dst_ops = &net->xfrm.xfrm4_dst_ops;
2561 #if IS_ENABLED(CONFIG_IPV6)
2563 dst_ops = &net->xfrm.xfrm6_dst_ops;
2569 xdst = dst_alloc(dst_ops, NULL, 1, DST_OBSOLETE_NONE, 0);
2572 memset_after(xdst, 0, u.dst);
2574 xdst = ERR_PTR(-ENOBUFS);
2581 static void xfrm_init_path(struct xfrm_dst *path, struct dst_entry *dst,
2584 if (dst->ops->family == AF_INET6) {
2585 struct rt6_info *rt = (struct rt6_info *)dst;
2586 path->path_cookie = rt6_get_cookie(rt);
2587 path->u.rt6.rt6i_nfheader_len = nfheader_len;
2591 static inline int xfrm_fill_dst(struct xfrm_dst *xdst, struct net_device *dev,
2592 const struct flowi *fl)
2594 const struct xfrm_policy_afinfo *afinfo =
2595 xfrm_policy_get_afinfo(xdst->u.dst.ops->family);
2601 err = afinfo->fill_dst(xdst, dev, fl);
2609 /* Allocate chain of dst_entry's, attach known xfrm's, calculate
2610 * all the metrics... Shortly, bundle a bundle.
2613 static struct dst_entry *xfrm_bundle_create(struct xfrm_policy *policy,
2614 struct xfrm_state **xfrm,
2615 struct xfrm_dst **bundle,
2617 const struct flowi *fl,
2618 struct dst_entry *dst)
2620 const struct xfrm_state_afinfo *afinfo;
2621 const struct xfrm_mode *inner_mode;
2622 struct net *net = xp_net(policy);
2623 unsigned long now = jiffies;
2624 struct net_device *dev;
2625 struct xfrm_dst *xdst_prev = NULL;
2626 struct xfrm_dst *xdst0 = NULL;
2630 int nfheader_len = 0;
2631 int trailer_len = 0;
2633 int family = policy->selector.family;
2634 xfrm_address_t saddr, daddr;
2636 xfrm_flowi_addr_get(fl, &saddr, &daddr, family);
2638 tos = xfrm_get_tos(fl, family);
2642 for (; i < nx; i++) {
2643 struct xfrm_dst *xdst = xfrm_alloc_dst(net, family);
2644 struct dst_entry *dst1 = &xdst->u.dst;
2646 err = PTR_ERR(xdst);
2656 /* Ref count is taken during xfrm_alloc_dst()
2657 * No need to do dst_clone() on dst1
2659 xfrm_dst_set_child(xdst_prev, &xdst->u.dst);
2661 if (xfrm[i]->sel.family == AF_UNSPEC) {
2662 inner_mode = xfrm_ip2inner_mode(xfrm[i],
2663 xfrm_af2proto(family));
2665 err = -EAFNOSUPPORT;
2670 inner_mode = &xfrm[i]->inner_mode;
2673 dst_copy_metrics(dst1, dst);
2675 if (xfrm[i]->props.mode != XFRM_MODE_TRANSPORT) {
2679 if (xfrm[i]->props.smark.v || xfrm[i]->props.smark.m)
2680 mark = xfrm_smark_get(fl->flowi_mark, xfrm[i]);
2682 family = xfrm[i]->props.family;
2683 oif = fl->flowi_oif ? : fl->flowi_l3mdev;
2684 dst = xfrm_dst_lookup(xfrm[i], tos, oif,
2685 &saddr, &daddr, family, mark);
2692 dst1->xfrm = xfrm[i];
2693 xdst->xfrm_genid = xfrm[i]->genid;
2695 dst1->obsolete = DST_OBSOLETE_FORCE_CHK;
2696 dst1->lastuse = now;
2698 dst1->input = dst_discard;
2701 afinfo = xfrm_state_afinfo_get_rcu(inner_mode->family);
2703 dst1->output = afinfo->output;
2705 dst1->output = dst_discard_out;
2710 header_len += xfrm[i]->props.header_len;
2711 if (xfrm[i]->type->flags & XFRM_TYPE_NON_FRAGMENT)
2712 nfheader_len += xfrm[i]->props.header_len;
2713 trailer_len += xfrm[i]->props.trailer_len;
2716 xfrm_dst_set_child(xdst_prev, dst);
2724 xfrm_init_path(xdst0, dst, nfheader_len);
2725 xfrm_init_pmtu(bundle, nx);
2727 for (xdst_prev = xdst0; xdst_prev != (struct xfrm_dst *)dst;
2728 xdst_prev = (struct xfrm_dst *) xfrm_dst_child(&xdst_prev->u.dst)) {
2729 err = xfrm_fill_dst(xdst_prev, dev, fl);
2733 xdst_prev->u.dst.header_len = header_len;
2734 xdst_prev->u.dst.trailer_len = trailer_len;
2735 header_len -= xdst_prev->u.dst.xfrm->props.header_len;
2736 trailer_len -= xdst_prev->u.dst.xfrm->props.trailer_len;
2739 return &xdst0->u.dst;
2743 xfrm_state_put(xfrm[i]);
2746 dst_release_immediate(&xdst0->u.dst);
2748 return ERR_PTR(err);
2751 static int xfrm_expand_policies(const struct flowi *fl, u16 family,
2752 struct xfrm_policy **pols,
2753 int *num_pols, int *num_xfrms)
2757 if (*num_pols == 0 || !pols[0]) {
2762 if (IS_ERR(pols[0])) {
2764 return PTR_ERR(pols[0]);
2767 *num_xfrms = pols[0]->xfrm_nr;
2769 #ifdef CONFIG_XFRM_SUB_POLICY
2770 if (pols[0]->action == XFRM_POLICY_ALLOW &&
2771 pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
2772 pols[1] = xfrm_policy_lookup_bytype(xp_net(pols[0]),
2773 XFRM_POLICY_TYPE_MAIN,
2778 if (IS_ERR(pols[1])) {
2779 xfrm_pols_put(pols, *num_pols);
2781 return PTR_ERR(pols[1]);
2784 (*num_xfrms) += pols[1]->xfrm_nr;
2788 for (i = 0; i < *num_pols; i++) {
2789 if (pols[i]->action != XFRM_POLICY_ALLOW) {
2799 static struct xfrm_dst *
2800 xfrm_resolve_and_create_bundle(struct xfrm_policy **pols, int num_pols,
2801 const struct flowi *fl, u16 family,
2802 struct dst_entry *dst_orig)
2804 struct net *net = xp_net(pols[0]);
2805 struct xfrm_state *xfrm[XFRM_MAX_DEPTH];
2806 struct xfrm_dst *bundle[XFRM_MAX_DEPTH];
2807 struct xfrm_dst *xdst;
2808 struct dst_entry *dst;
2811 /* Try to instantiate a bundle */
2812 err = xfrm_tmpl_resolve(pols, num_pols, fl, xfrm, family);
2818 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
2819 return ERR_PTR(err);
2822 dst = xfrm_bundle_create(pols[0], xfrm, bundle, err, fl, dst_orig);
2824 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTBUNDLEGENERROR);
2825 return ERR_CAST(dst);
2828 xdst = (struct xfrm_dst *)dst;
2829 xdst->num_xfrms = err;
2830 xdst->num_pols = num_pols;
2831 memcpy(xdst->pols, pols, sizeof(struct xfrm_policy *) * num_pols);
2832 xdst->policy_genid = atomic_read(&pols[0]->genid);
2837 static void xfrm_policy_queue_process(struct timer_list *t)
2839 struct sk_buff *skb;
2841 struct dst_entry *dst;
2842 struct xfrm_policy *pol = from_timer(pol, t, polq.hold_timer);
2843 struct net *net = xp_net(pol);
2844 struct xfrm_policy_queue *pq = &pol->polq;
2846 struct sk_buff_head list;
2849 spin_lock(&pq->hold_queue.lock);
2850 skb = skb_peek(&pq->hold_queue);
2852 spin_unlock(&pq->hold_queue.lock);
2858 /* Fixup the mark to support VTI. */
2859 skb_mark = skb->mark;
2860 skb->mark = pol->mark.v;
2861 xfrm_decode_session(skb, &fl, dst->ops->family);
2862 skb->mark = skb_mark;
2863 spin_unlock(&pq->hold_queue.lock);
2865 dst_hold(xfrm_dst_path(dst));
2866 dst = xfrm_lookup(net, xfrm_dst_path(dst), &fl, sk, XFRM_LOOKUP_QUEUE);
2870 if (dst->flags & DST_XFRM_QUEUE) {
2873 if (pq->timeout >= XFRM_QUEUE_TMO_MAX)
2876 pq->timeout = pq->timeout << 1;
2877 if (!mod_timer(&pq->hold_timer, jiffies + pq->timeout))
2884 __skb_queue_head_init(&list);
2886 spin_lock(&pq->hold_queue.lock);
2888 skb_queue_splice_init(&pq->hold_queue, &list);
2889 spin_unlock(&pq->hold_queue.lock);
2891 while (!skb_queue_empty(&list)) {
2892 skb = __skb_dequeue(&list);
2894 /* Fixup the mark to support VTI. */
2895 skb_mark = skb->mark;
2896 skb->mark = pol->mark.v;
2897 xfrm_decode_session(skb, &fl, skb_dst(skb)->ops->family);
2898 skb->mark = skb_mark;
2900 dst_hold(xfrm_dst_path(skb_dst(skb)));
2901 dst = xfrm_lookup(net, xfrm_dst_path(skb_dst(skb)), &fl, skb->sk, 0);
2909 skb_dst_set(skb, dst);
2911 dst_output(net, skb->sk, skb);
2920 skb_queue_purge(&pq->hold_queue);
2924 static int xdst_queue_output(struct net *net, struct sock *sk, struct sk_buff *skb)
2926 unsigned long sched_next;
2927 struct dst_entry *dst = skb_dst(skb);
2928 struct xfrm_dst *xdst = (struct xfrm_dst *) dst;
2929 struct xfrm_policy *pol = xdst->pols[0];
2930 struct xfrm_policy_queue *pq = &pol->polq;
2932 if (unlikely(skb_fclone_busy(sk, skb))) {
2937 if (pq->hold_queue.qlen > XFRM_MAX_QUEUE_LEN) {
2944 spin_lock_bh(&pq->hold_queue.lock);
2947 pq->timeout = XFRM_QUEUE_TMO_MIN;
2949 sched_next = jiffies + pq->timeout;
2951 if (del_timer(&pq->hold_timer)) {
2952 if (time_before(pq->hold_timer.expires, sched_next))
2953 sched_next = pq->hold_timer.expires;
2957 __skb_queue_tail(&pq->hold_queue, skb);
2958 if (!mod_timer(&pq->hold_timer, sched_next))
2961 spin_unlock_bh(&pq->hold_queue.lock);
2966 static struct xfrm_dst *xfrm_create_dummy_bundle(struct net *net,
2967 struct xfrm_flo *xflo,
2968 const struct flowi *fl,
2973 struct net_device *dev;
2974 struct dst_entry *dst;
2975 struct dst_entry *dst1;
2976 struct xfrm_dst *xdst;
2978 xdst = xfrm_alloc_dst(net, family);
2982 if (!(xflo->flags & XFRM_LOOKUP_QUEUE) ||
2983 net->xfrm.sysctl_larval_drop ||
2987 dst = xflo->dst_orig;
2988 dst1 = &xdst->u.dst;
2992 dst_copy_metrics(dst1, dst);
2994 dst1->obsolete = DST_OBSOLETE_FORCE_CHK;
2995 dst1->flags |= DST_XFRM_QUEUE;
2996 dst1->lastuse = jiffies;
2998 dst1->input = dst_discard;
2999 dst1->output = xdst_queue_output;
3002 xfrm_dst_set_child(xdst, dst);
3005 xfrm_init_path((struct xfrm_dst *)dst1, dst, 0);
3012 err = xfrm_fill_dst(xdst, dev, fl);
3021 xdst = ERR_PTR(err);
3025 static struct xfrm_dst *xfrm_bundle_lookup(struct net *net,
3026 const struct flowi *fl,
3028 struct xfrm_flo *xflo, u32 if_id)
3030 struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
3031 int num_pols = 0, num_xfrms = 0, err;
3032 struct xfrm_dst *xdst;
3034 /* Resolve policies to use if we couldn't get them from
3035 * previous cache entry */
3037 pols[0] = xfrm_policy_lookup(net, fl, family, dir, if_id);
3038 err = xfrm_expand_policies(fl, family, pols,
3039 &num_pols, &num_xfrms);
3045 goto make_dummy_bundle;
3047 xdst = xfrm_resolve_and_create_bundle(pols, num_pols, fl, family,
3050 err = PTR_ERR(xdst);
3051 if (err == -EREMOTE) {
3052 xfrm_pols_put(pols, num_pols);
3058 goto make_dummy_bundle;
3059 } else if (xdst == NULL) {
3061 goto make_dummy_bundle;
3067 /* We found policies, but there's no bundles to instantiate:
3068 * either because the policy blocks, has no transformations or
3069 * we could not build template (no xfrm_states).*/
3070 xdst = xfrm_create_dummy_bundle(net, xflo, fl, num_xfrms, family);
3072 xfrm_pols_put(pols, num_pols);
3073 return ERR_CAST(xdst);
3075 xdst->num_pols = num_pols;
3076 xdst->num_xfrms = num_xfrms;
3077 memcpy(xdst->pols, pols, sizeof(struct xfrm_policy *) * num_pols);
3082 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
3084 xfrm_pols_put(pols, num_pols);
3085 return ERR_PTR(err);
3088 static struct dst_entry *make_blackhole(struct net *net, u16 family,
3089 struct dst_entry *dst_orig)
3091 const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
3092 struct dst_entry *ret;
3095 dst_release(dst_orig);
3096 return ERR_PTR(-EINVAL);
3098 ret = afinfo->blackhole_route(net, dst_orig);
3105 /* Finds/creates a bundle for given flow and if_id
3107 * At the moment we eat a raw IP route. Mostly to speed up lookups
3108 * on interfaces with disabled IPsec.
3110 * xfrm_lookup uses an if_id of 0 by default, and is provided for
3113 struct dst_entry *xfrm_lookup_with_ifid(struct net *net,
3114 struct dst_entry *dst_orig,
3115 const struct flowi *fl,
3116 const struct sock *sk,
3117 int flags, u32 if_id)
3119 struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
3120 struct xfrm_dst *xdst;
3121 struct dst_entry *dst, *route;
3122 u16 family = dst_orig->ops->family;
3123 u8 dir = XFRM_POLICY_OUT;
3124 int i, err, num_pols, num_xfrms = 0, drop_pols = 0;
3130 sk = sk_const_to_full_sk(sk);
3131 if (sk && sk->sk_policy[XFRM_POLICY_OUT]) {
3133 pols[0] = xfrm_sk_policy_lookup(sk, XFRM_POLICY_OUT, fl, family,
3135 err = xfrm_expand_policies(fl, family, pols,
3136 &num_pols, &num_xfrms);
3141 if (num_xfrms <= 0) {
3142 drop_pols = num_pols;
3146 xdst = xfrm_resolve_and_create_bundle(
3151 xfrm_pols_put(pols, num_pols);
3152 err = PTR_ERR(xdst);
3153 if (err == -EREMOTE)
3157 } else if (xdst == NULL) {
3159 drop_pols = num_pols;
3163 route = xdst->route;
3168 struct xfrm_flo xflo;
3170 xflo.dst_orig = dst_orig;
3173 /* To accelerate a bit... */
3174 if (!if_id && ((dst_orig->flags & DST_NOXFRM) ||
3175 !net->xfrm.policy_count[XFRM_POLICY_OUT]))
3178 xdst = xfrm_bundle_lookup(net, fl, family, dir, &xflo, if_id);
3182 err = PTR_ERR(xdst);
3186 num_pols = xdst->num_pols;
3187 num_xfrms = xdst->num_xfrms;
3188 memcpy(pols, xdst->pols, sizeof(struct xfrm_policy *) * num_pols);
3189 route = xdst->route;
3193 if (route == NULL && num_xfrms > 0) {
3194 /* The only case when xfrm_bundle_lookup() returns a
3195 * bundle with null route, is when the template could
3196 * not be resolved. It means policies are there, but
3197 * bundle could not be created, since we don't yet
3198 * have the xfrm_state's. We need to wait for KM to
3199 * negotiate new SA's or bail out with error.*/
3200 if (net->xfrm.sysctl_larval_drop) {
3201 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
3208 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
3216 if ((flags & XFRM_LOOKUP_ICMP) &&
3217 !(pols[0]->flags & XFRM_POLICY_ICMP)) {
3222 for (i = 0; i < num_pols; i++)
3223 WRITE_ONCE(pols[i]->curlft.use_time, ktime_get_real_seconds());
3225 if (num_xfrms < 0) {
3226 /* Prohibit the flow */
3227 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLBLOCK);
3230 } else if (num_xfrms > 0) {
3231 /* Flow transformed */
3232 dst_release(dst_orig);
3234 /* Flow passes untransformed */
3239 xfrm_pols_put(pols, drop_pols);
3240 if (dst && dst->xfrm &&
3241 dst->xfrm->props.mode == XFRM_MODE_TUNNEL)
3242 dst->flags |= DST_XFRM_TUNNEL;
3246 if ((!dst_orig->dev || !(dst_orig->dev->flags & IFF_LOOPBACK)) &&
3247 net->xfrm.policy_default[dir] == XFRM_USERPOLICY_BLOCK) {
3251 if (!(flags & XFRM_LOOKUP_ICMP)) {
3259 if (!(flags & XFRM_LOOKUP_KEEP_DST_REF))
3260 dst_release(dst_orig);
3261 xfrm_pols_put(pols, drop_pols);
3262 return ERR_PTR(err);
3264 EXPORT_SYMBOL(xfrm_lookup_with_ifid);
3266 /* Main function: finds/creates a bundle for given flow.
3268 * At the moment we eat a raw IP route. Mostly to speed up lookups
3269 * on interfaces with disabled IPsec.
3271 struct dst_entry *xfrm_lookup(struct net *net, struct dst_entry *dst_orig,
3272 const struct flowi *fl, const struct sock *sk,
3275 return xfrm_lookup_with_ifid(net, dst_orig, fl, sk, flags, 0);
3277 EXPORT_SYMBOL(xfrm_lookup);
3279 /* Callers of xfrm_lookup_route() must ensure a call to dst_output().
3280 * Otherwise we may send out blackholed packets.
3282 struct dst_entry *xfrm_lookup_route(struct net *net, struct dst_entry *dst_orig,
3283 const struct flowi *fl,
3284 const struct sock *sk, int flags)
3286 struct dst_entry *dst = xfrm_lookup(net, dst_orig, fl, sk,
3287 flags | XFRM_LOOKUP_QUEUE |
3288 XFRM_LOOKUP_KEEP_DST_REF);
3290 if (PTR_ERR(dst) == -EREMOTE)
3291 return make_blackhole(net, dst_orig->ops->family, dst_orig);
3294 dst_release(dst_orig);
3298 EXPORT_SYMBOL(xfrm_lookup_route);
3301 xfrm_secpath_reject(int idx, struct sk_buff *skb, const struct flowi *fl)
3303 struct sec_path *sp = skb_sec_path(skb);
3304 struct xfrm_state *x;
3306 if (!sp || idx < 0 || idx >= sp->len)
3309 if (!x->type->reject)
3311 return x->type->reject(x, skb, fl);
3314 /* When skb is transformed back to its "native" form, we have to
3315 * check policy restrictions. At the moment we make this in maximally
3316 * stupid way. Shame on me. :-) Of course, connected sockets must
3317 * have policy cached at them.
3321 xfrm_state_ok(const struct xfrm_tmpl *tmpl, const struct xfrm_state *x,
3322 unsigned short family, u32 if_id)
3324 if (xfrm_state_kern(x))
3325 return tmpl->optional && !xfrm_state_addr_cmp(tmpl, x, tmpl->encap_family);
3326 return x->id.proto == tmpl->id.proto &&
3327 (x->id.spi == tmpl->id.spi || !tmpl->id.spi) &&
3328 (x->props.reqid == tmpl->reqid || !tmpl->reqid) &&
3329 x->props.mode == tmpl->mode &&
3330 (tmpl->allalgs || (tmpl->aalgos & (1<<x->props.aalgo)) ||
3331 !(xfrm_id_proto_match(tmpl->id.proto, IPSEC_PROTO_ANY))) &&
3332 !(x->props.mode != XFRM_MODE_TRANSPORT &&
3333 xfrm_state_addr_cmp(tmpl, x, family)) &&
3334 (if_id == 0 || if_id == x->if_id);
3338 * 0 or more than 0 is returned when validation is succeeded (either bypass
3339 * because of optional transport mode, or next index of the matched secpath
3340 * state with the template.
3341 * -1 is returned when no matching template is found.
3342 * Otherwise "-2 - errored_index" is returned.
3345 xfrm_policy_ok(const struct xfrm_tmpl *tmpl, const struct sec_path *sp, int start,
3346 unsigned short family, u32 if_id)
3350 if (tmpl->optional) {
3351 if (tmpl->mode == XFRM_MODE_TRANSPORT)
3355 for (; idx < sp->len; idx++) {
3356 if (xfrm_state_ok(tmpl, sp->xvec[idx], family, if_id))
3358 if (sp->xvec[idx]->props.mode != XFRM_MODE_TRANSPORT) {
3359 if (idx < sp->verified_cnt) {
3360 /* Secpath entry previously verified, consider optional and
3361 * continue searching
3375 decode_session4(struct sk_buff *skb, struct flowi *fl, bool reverse)
3377 const struct iphdr *iph = ip_hdr(skb);
3379 u8 *xprth = skb_network_header(skb) + ihl * 4;
3380 struct flowi4 *fl4 = &fl->u.ip4;
3383 if (skb_dst(skb) && skb_dst(skb)->dev)
3384 oif = skb_dst(skb)->dev->ifindex;
3386 memset(fl4, 0, sizeof(struct flowi4));
3387 fl4->flowi4_mark = skb->mark;
3388 fl4->flowi4_oif = reverse ? skb->skb_iif : oif;
3390 fl4->flowi4_proto = iph->protocol;
3391 fl4->daddr = reverse ? iph->saddr : iph->daddr;
3392 fl4->saddr = reverse ? iph->daddr : iph->saddr;
3393 fl4->flowi4_tos = iph->tos & ~INET_ECN_MASK;
3395 if (!ip_is_fragment(iph)) {
3396 switch (iph->protocol) {
3398 case IPPROTO_UDPLITE:
3402 if (xprth + 4 < skb->data ||
3403 pskb_may_pull(skb, xprth + 4 - skb->data)) {
3406 xprth = skb_network_header(skb) + ihl * 4;
3407 ports = (__be16 *)xprth;
3409 fl4->fl4_sport = ports[!!reverse];
3410 fl4->fl4_dport = ports[!reverse];
3414 if (xprth + 2 < skb->data ||
3415 pskb_may_pull(skb, xprth + 2 - skb->data)) {
3418 xprth = skb_network_header(skb) + ihl * 4;
3421 fl4->fl4_icmp_type = icmp[0];
3422 fl4->fl4_icmp_code = icmp[1];
3426 if (xprth + 12 < skb->data ||
3427 pskb_may_pull(skb, xprth + 12 - skb->data)) {
3431 xprth = skb_network_header(skb) + ihl * 4;
3432 greflags = (__be16 *)xprth;
3433 gre_hdr = (__be32 *)xprth;
3435 if (greflags[0] & GRE_KEY) {
3436 if (greflags[0] & GRE_CSUM)
3438 fl4->fl4_gre_key = gre_hdr[1];
3448 #if IS_ENABLED(CONFIG_IPV6)
3450 decode_session6(struct sk_buff *skb, struct flowi *fl, bool reverse)
3452 struct flowi6 *fl6 = &fl->u.ip6;
3454 const struct ipv6hdr *hdr = ipv6_hdr(skb);
3455 u32 offset = sizeof(*hdr);
3456 struct ipv6_opt_hdr *exthdr;
3457 const unsigned char *nh = skb_network_header(skb);
3458 u16 nhoff = IP6CB(skb)->nhoff;
3463 nhoff = offsetof(struct ipv6hdr, nexthdr);
3465 nexthdr = nh[nhoff];
3467 if (skb_dst(skb) && skb_dst(skb)->dev)
3468 oif = skb_dst(skb)->dev->ifindex;
3470 memset(fl6, 0, sizeof(struct flowi6));
3471 fl6->flowi6_mark = skb->mark;
3472 fl6->flowi6_oif = reverse ? skb->skb_iif : oif;
3474 fl6->daddr = reverse ? hdr->saddr : hdr->daddr;
3475 fl6->saddr = reverse ? hdr->daddr : hdr->saddr;
3477 while (nh + offset + sizeof(*exthdr) < skb->data ||
3478 pskb_may_pull(skb, nh + offset + sizeof(*exthdr) - skb->data)) {
3479 nh = skb_network_header(skb);
3480 exthdr = (struct ipv6_opt_hdr *)(nh + offset);
3483 case NEXTHDR_FRAGMENT:
3486 case NEXTHDR_ROUTING:
3489 offset += ipv6_optlen(exthdr);
3490 nexthdr = exthdr->nexthdr;
3493 case IPPROTO_UDPLITE:
3497 if (!onlyproto && (nh + offset + 4 < skb->data ||
3498 pskb_may_pull(skb, nh + offset + 4 - skb->data))) {
3501 nh = skb_network_header(skb);
3502 ports = (__be16 *)(nh + offset);
3503 fl6->fl6_sport = ports[!!reverse];
3504 fl6->fl6_dport = ports[!reverse];
3506 fl6->flowi6_proto = nexthdr;
3508 case IPPROTO_ICMPV6:
3509 if (!onlyproto && (nh + offset + 2 < skb->data ||
3510 pskb_may_pull(skb, nh + offset + 2 - skb->data))) {
3513 nh = skb_network_header(skb);
3514 icmp = (u8 *)(nh + offset);
3515 fl6->fl6_icmp_type = icmp[0];
3516 fl6->fl6_icmp_code = icmp[1];
3518 fl6->flowi6_proto = nexthdr;
3522 (nh + offset + 12 < skb->data ||
3523 pskb_may_pull(skb, nh + offset + 12 - skb->data))) {
3524 struct gre_base_hdr *gre_hdr;
3527 nh = skb_network_header(skb);
3528 gre_hdr = (struct gre_base_hdr *)(nh + offset);
3529 gre_key = (__be32 *)(gre_hdr + 1);
3531 if (gre_hdr->flags & GRE_KEY) {
3532 if (gre_hdr->flags & GRE_CSUM)
3534 fl6->fl6_gre_key = *gre_key;
3537 fl6->flowi6_proto = nexthdr;
3540 #if IS_ENABLED(CONFIG_IPV6_MIP6)
3542 offset += ipv6_optlen(exthdr);
3543 if (!onlyproto && (nh + offset + 3 < skb->data ||
3544 pskb_may_pull(skb, nh + offset + 3 - skb->data))) {
3547 nh = skb_network_header(skb);
3548 mh = (struct ip6_mh *)(nh + offset);
3549 fl6->fl6_mh_type = mh->ip6mh_type;
3551 fl6->flowi6_proto = nexthdr;
3555 fl6->flowi6_proto = nexthdr;
3562 int __xfrm_decode_session(struct sk_buff *skb, struct flowi *fl,
3563 unsigned int family, int reverse)
3567 decode_session4(skb, fl, reverse);
3569 #if IS_ENABLED(CONFIG_IPV6)
3571 decode_session6(skb, fl, reverse);
3575 return -EAFNOSUPPORT;
3578 return security_xfrm_decode_session(skb, &fl->flowi_secid);
3580 EXPORT_SYMBOL(__xfrm_decode_session);
3582 static inline int secpath_has_nontransport(const struct sec_path *sp, int k, int *idxp)
3584 for (; k < sp->len; k++) {
3585 if (sp->xvec[k]->props.mode != XFRM_MODE_TRANSPORT) {
3594 int __xfrm_policy_check(struct sock *sk, int dir, struct sk_buff *skb,
3595 unsigned short family)
3597 struct net *net = dev_net(skb->dev);
3598 struct xfrm_policy *pol;
3599 struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
3606 const struct xfrm_if_cb *ifcb;
3607 struct sec_path *sp;
3611 ifcb = xfrm_if_get_cb();
3614 struct xfrm_if_decode_session_result r;
3616 if (ifcb->decode_session(skb, family, &r)) {
3623 reverse = dir & ~XFRM_POLICY_MASK;
3624 dir &= XFRM_POLICY_MASK;
3626 if (__xfrm_decode_session(skb, &fl, family, reverse) < 0) {
3627 XFRM_INC_STATS(net, LINUX_MIB_XFRMINHDRERROR);
3631 nf_nat_decode_session(skb, &fl, family);
3633 /* First, check used SA against their selectors. */
3634 sp = skb_sec_path(skb);
3638 for (i = sp->len - 1; i >= 0; i--) {
3639 struct xfrm_state *x = sp->xvec[i];
3640 if (!xfrm_selector_match(&x->sel, &fl, family)) {
3641 XFRM_INC_STATS(net, LINUX_MIB_XFRMINSTATEMISMATCH);
3648 sk = sk_to_full_sk(sk);
3649 if (sk && sk->sk_policy[dir]) {
3650 pol = xfrm_sk_policy_lookup(sk, dir, &fl, family, if_id);
3652 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
3658 pol = xfrm_policy_lookup(net, &fl, family, dir, if_id);
3661 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
3666 if (net->xfrm.policy_default[dir] == XFRM_USERPOLICY_BLOCK) {
3667 XFRM_INC_STATS(net, LINUX_MIB_XFRMINNOPOLS);
3671 if (sp && secpath_has_nontransport(sp, 0, &xerr_idx)) {
3672 xfrm_secpath_reject(xerr_idx, skb, &fl);
3673 XFRM_INC_STATS(net, LINUX_MIB_XFRMINNOPOLS);
3679 /* This lockless write can happen from different cpus. */
3680 WRITE_ONCE(pol->curlft.use_time, ktime_get_real_seconds());
3684 #ifdef CONFIG_XFRM_SUB_POLICY
3685 if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
3686 pols[1] = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN,
3688 XFRM_POLICY_IN, if_id);
3690 if (IS_ERR(pols[1])) {
3691 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
3692 xfrm_pol_put(pols[0]);
3695 /* This write can happen from different cpus. */
3696 WRITE_ONCE(pols[1]->curlft.use_time,
3697 ktime_get_real_seconds());
3703 if (pol->action == XFRM_POLICY_ALLOW) {
3704 static struct sec_path dummy;
3705 struct xfrm_tmpl *tp[XFRM_MAX_DEPTH];
3706 struct xfrm_tmpl *stp[XFRM_MAX_DEPTH];
3707 struct xfrm_tmpl **tpp = tp;
3711 sp = skb_sec_path(skb);
3715 for (pi = 0; pi < npols; pi++) {
3716 if (pols[pi] != pol &&
3717 pols[pi]->action != XFRM_POLICY_ALLOW) {
3718 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
3721 if (ti + pols[pi]->xfrm_nr >= XFRM_MAX_DEPTH) {
3722 XFRM_INC_STATS(net, LINUX_MIB_XFRMINBUFFERERROR);
3725 for (i = 0; i < pols[pi]->xfrm_nr; i++)
3726 tpp[ti++] = &pols[pi]->xfrm_vec[i];
3731 xfrm_tmpl_sort(stp, tpp, xfrm_nr, family);
3735 /* For each tunnel xfrm, find the first matching tmpl.
3736 * For each tmpl before that, find corresponding xfrm.
3737 * Order is _important_. Later we will implement
3738 * some barriers, but at the moment barriers
3739 * are implied between each two transformations.
3740 * Upon success, marks secpath entries as having been
3741 * verified to allow them to be skipped in future policy
3742 * checks (e.g. nested tunnels).
3744 for (i = xfrm_nr-1, k = 0; i >= 0; i--) {
3745 k = xfrm_policy_ok(tpp[i], sp, k, family, if_id);
3748 /* "-2 - errored_index" returned */
3750 XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
3755 if (secpath_has_nontransport(sp, k, &xerr_idx)) {
3756 XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
3760 xfrm_pols_put(pols, npols);
3761 sp->verified_cnt = k;
3765 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
3768 xfrm_secpath_reject(xerr_idx, skb, &fl);
3770 xfrm_pols_put(pols, npols);
3773 EXPORT_SYMBOL(__xfrm_policy_check);
3775 int __xfrm_route_forward(struct sk_buff *skb, unsigned short family)
3777 struct net *net = dev_net(skb->dev);
3779 struct dst_entry *dst;
3782 if (xfrm_decode_session(skb, &fl, family) < 0) {
3783 XFRM_INC_STATS(net, LINUX_MIB_XFRMFWDHDRERROR);
3788 if (!skb_dst(skb)) {
3789 XFRM_INC_STATS(net, LINUX_MIB_XFRMFWDHDRERROR);
3793 dst = xfrm_lookup(net, skb_dst(skb), &fl, NULL, XFRM_LOOKUP_QUEUE);
3798 skb_dst_set(skb, dst);
3801 EXPORT_SYMBOL(__xfrm_route_forward);
3803 /* Optimize later using cookies and generation ids. */
3805 static struct dst_entry *xfrm_dst_check(struct dst_entry *dst, u32 cookie)
3807 /* Code (such as __xfrm4_bundle_create()) sets dst->obsolete
3808 * to DST_OBSOLETE_FORCE_CHK to force all XFRM destinations to
3809 * get validated by dst_ops->check on every use. We do this
3810 * because when a normal route referenced by an XFRM dst is
3811 * obsoleted we do not go looking around for all parent
3812 * referencing XFRM dsts so that we can invalidate them. It
3813 * is just too much work. Instead we make the checks here on
3814 * every use. For example:
3816 * XFRM dst A --> IPv4 dst X
3818 * X is the "xdst->route" of A (X is also the "dst->path" of A
3819 * in this example). If X is marked obsolete, "A" will not
3820 * notice. That's what we are validating here via the
3821 * stale_bundle() check.
3823 * When a dst is removed from the fib tree, DST_OBSOLETE_DEAD will
3825 * This will force stale_bundle() to fail on any xdst bundle with
3826 * this dst linked in it.
3828 if (dst->obsolete < 0 && !stale_bundle(dst))
3834 static int stale_bundle(struct dst_entry *dst)
3836 return !xfrm_bundle_ok((struct xfrm_dst *)dst);
3839 void xfrm_dst_ifdown(struct dst_entry *dst, struct net_device *dev)
3841 while ((dst = xfrm_dst_child(dst)) && dst->xfrm && dst->dev == dev) {
3842 dst->dev = blackhole_netdev;
3847 EXPORT_SYMBOL(xfrm_dst_ifdown);
3849 static void xfrm_link_failure(struct sk_buff *skb)
3851 /* Impossible. Such dst must be popped before reaches point of failure. */
3854 static struct dst_entry *xfrm_negative_advice(struct dst_entry *dst)
3857 if (dst->obsolete) {
3865 static void xfrm_init_pmtu(struct xfrm_dst **bundle, int nr)
3868 struct xfrm_dst *xdst = bundle[nr];
3869 u32 pmtu, route_mtu_cached;
3870 struct dst_entry *dst;
3873 pmtu = dst_mtu(xfrm_dst_child(dst));
3874 xdst->child_mtu_cached = pmtu;
3876 pmtu = xfrm_state_mtu(dst->xfrm, pmtu);
3878 route_mtu_cached = dst_mtu(xdst->route);
3879 xdst->route_mtu_cached = route_mtu_cached;
3881 if (pmtu > route_mtu_cached)
3882 pmtu = route_mtu_cached;
3884 dst_metric_set(dst, RTAX_MTU, pmtu);
3888 /* Check that the bundle accepts the flow and its components are
3892 static int xfrm_bundle_ok(struct xfrm_dst *first)
3894 struct xfrm_dst *bundle[XFRM_MAX_DEPTH];
3895 struct dst_entry *dst = &first->u.dst;
3896 struct xfrm_dst *xdst;
3900 if (!dst_check(xfrm_dst_path(dst), ((struct xfrm_dst *)dst)->path_cookie) ||
3901 (dst->dev && !netif_running(dst->dev)))
3904 if (dst->flags & DST_XFRM_QUEUE)
3907 start_from = nr = 0;
3909 struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
3911 if (dst->xfrm->km.state != XFRM_STATE_VALID)
3913 if (xdst->xfrm_genid != dst->xfrm->genid)
3915 if (xdst->num_pols > 0 &&
3916 xdst->policy_genid != atomic_read(&xdst->pols[0]->genid))
3919 bundle[nr++] = xdst;
3921 mtu = dst_mtu(xfrm_dst_child(dst));
3922 if (xdst->child_mtu_cached != mtu) {
3924 xdst->child_mtu_cached = mtu;
3927 if (!dst_check(xdst->route, xdst->route_cookie))
3929 mtu = dst_mtu(xdst->route);
3930 if (xdst->route_mtu_cached != mtu) {
3932 xdst->route_mtu_cached = mtu;
3935 dst = xfrm_dst_child(dst);
3936 } while (dst->xfrm);
3938 if (likely(!start_from))
3941 xdst = bundle[start_from - 1];
3942 mtu = xdst->child_mtu_cached;
3943 while (start_from--) {
3946 mtu = xfrm_state_mtu(dst->xfrm, mtu);
3947 if (mtu > xdst->route_mtu_cached)
3948 mtu = xdst->route_mtu_cached;
3949 dst_metric_set(dst, RTAX_MTU, mtu);
3953 xdst = bundle[start_from - 1];
3954 xdst->child_mtu_cached = mtu;
3960 static unsigned int xfrm_default_advmss(const struct dst_entry *dst)
3962 return dst_metric_advmss(xfrm_dst_path(dst));
3965 static unsigned int xfrm_mtu(const struct dst_entry *dst)
3967 unsigned int mtu = dst_metric_raw(dst, RTAX_MTU);
3969 return mtu ? : dst_mtu(xfrm_dst_path(dst));
3972 static const void *xfrm_get_dst_nexthop(const struct dst_entry *dst,
3976 const struct xfrm_state *xfrm = dst->xfrm;
3978 dst = xfrm_dst_child(dst);
3980 if (xfrm->props.mode == XFRM_MODE_TRANSPORT)
3982 if (xfrm->type->flags & XFRM_TYPE_REMOTE_COADDR)
3983 daddr = xfrm->coaddr;
3984 else if (!(xfrm->type->flags & XFRM_TYPE_LOCAL_COADDR))
3985 daddr = &xfrm->id.daddr;
3990 static struct neighbour *xfrm_neigh_lookup(const struct dst_entry *dst,
3991 struct sk_buff *skb,
3994 const struct dst_entry *path = xfrm_dst_path(dst);
3997 daddr = xfrm_get_dst_nexthop(dst, daddr);
3998 return path->ops->neigh_lookup(path, skb, daddr);
4001 static void xfrm_confirm_neigh(const struct dst_entry *dst, const void *daddr)
4003 const struct dst_entry *path = xfrm_dst_path(dst);
4005 daddr = xfrm_get_dst_nexthop(dst, daddr);
4006 path->ops->confirm_neigh(path, daddr);
4009 int xfrm_policy_register_afinfo(const struct xfrm_policy_afinfo *afinfo, int family)
4013 if (WARN_ON(family >= ARRAY_SIZE(xfrm_policy_afinfo)))
4014 return -EAFNOSUPPORT;
4016 spin_lock(&xfrm_policy_afinfo_lock);
4017 if (unlikely(xfrm_policy_afinfo[family] != NULL))
4020 struct dst_ops *dst_ops = afinfo->dst_ops;
4021 if (likely(dst_ops->kmem_cachep == NULL))
4022 dst_ops->kmem_cachep = xfrm_dst_cache;
4023 if (likely(dst_ops->check == NULL))
4024 dst_ops->check = xfrm_dst_check;
4025 if (likely(dst_ops->default_advmss == NULL))
4026 dst_ops->default_advmss = xfrm_default_advmss;
4027 if (likely(dst_ops->mtu == NULL))
4028 dst_ops->mtu = xfrm_mtu;
4029 if (likely(dst_ops->negative_advice == NULL))
4030 dst_ops->negative_advice = xfrm_negative_advice;
4031 if (likely(dst_ops->link_failure == NULL))
4032 dst_ops->link_failure = xfrm_link_failure;
4033 if (likely(dst_ops->neigh_lookup == NULL))
4034 dst_ops->neigh_lookup = xfrm_neigh_lookup;
4035 if (likely(!dst_ops->confirm_neigh))
4036 dst_ops->confirm_neigh = xfrm_confirm_neigh;
4037 rcu_assign_pointer(xfrm_policy_afinfo[family], afinfo);
4039 spin_unlock(&xfrm_policy_afinfo_lock);
4043 EXPORT_SYMBOL(xfrm_policy_register_afinfo);
4045 void xfrm_policy_unregister_afinfo(const struct xfrm_policy_afinfo *afinfo)
4047 struct dst_ops *dst_ops = afinfo->dst_ops;
4050 for (i = 0; i < ARRAY_SIZE(xfrm_policy_afinfo); i++) {
4051 if (xfrm_policy_afinfo[i] != afinfo)
4053 RCU_INIT_POINTER(xfrm_policy_afinfo[i], NULL);
4059 dst_ops->kmem_cachep = NULL;
4060 dst_ops->check = NULL;
4061 dst_ops->negative_advice = NULL;
4062 dst_ops->link_failure = NULL;
4064 EXPORT_SYMBOL(xfrm_policy_unregister_afinfo);
4066 void xfrm_if_register_cb(const struct xfrm_if_cb *ifcb)
4068 spin_lock(&xfrm_if_cb_lock);
4069 rcu_assign_pointer(xfrm_if_cb, ifcb);
4070 spin_unlock(&xfrm_if_cb_lock);
4072 EXPORT_SYMBOL(xfrm_if_register_cb);
4074 void xfrm_if_unregister_cb(void)
4076 RCU_INIT_POINTER(xfrm_if_cb, NULL);
4079 EXPORT_SYMBOL(xfrm_if_unregister_cb);
4081 #ifdef CONFIG_XFRM_STATISTICS
4082 static int __net_init xfrm_statistics_init(struct net *net)
4085 net->mib.xfrm_statistics = alloc_percpu(struct linux_xfrm_mib);
4086 if (!net->mib.xfrm_statistics)
4088 rv = xfrm_proc_init(net);
4090 free_percpu(net->mib.xfrm_statistics);
4094 static void xfrm_statistics_fini(struct net *net)
4096 xfrm_proc_fini(net);
4097 free_percpu(net->mib.xfrm_statistics);
4100 static int __net_init xfrm_statistics_init(struct net *net)
4105 static void xfrm_statistics_fini(struct net *net)
4110 static int __net_init xfrm_policy_init(struct net *net)
4112 unsigned int hmask, sz;
4115 if (net_eq(net, &init_net)) {
4116 xfrm_dst_cache = kmem_cache_create("xfrm_dst_cache",
4117 sizeof(struct xfrm_dst),
4118 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4120 err = rhashtable_init(&xfrm_policy_inexact_table,
4121 &xfrm_pol_inexact_params);
4126 sz = (hmask+1) * sizeof(struct hlist_head);
4128 net->xfrm.policy_byidx = xfrm_hash_alloc(sz);
4129 if (!net->xfrm.policy_byidx)
4131 net->xfrm.policy_idx_hmask = hmask;
4133 for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
4134 struct xfrm_policy_hash *htab;
4136 net->xfrm.policy_count[dir] = 0;
4137 net->xfrm.policy_count[XFRM_POLICY_MAX + dir] = 0;
4138 INIT_HLIST_HEAD(&net->xfrm.policy_inexact[dir]);
4140 htab = &net->xfrm.policy_bydst[dir];
4141 htab->table = xfrm_hash_alloc(sz);
4144 htab->hmask = hmask;
4150 net->xfrm.policy_hthresh.lbits4 = 32;
4151 net->xfrm.policy_hthresh.rbits4 = 32;
4152 net->xfrm.policy_hthresh.lbits6 = 128;
4153 net->xfrm.policy_hthresh.rbits6 = 128;
4155 seqlock_init(&net->xfrm.policy_hthresh.lock);
4157 INIT_LIST_HEAD(&net->xfrm.policy_all);
4158 INIT_LIST_HEAD(&net->xfrm.inexact_bins);
4159 INIT_WORK(&net->xfrm.policy_hash_work, xfrm_hash_resize);
4160 INIT_WORK(&net->xfrm.policy_hthresh.work, xfrm_hash_rebuild);
4164 for (dir--; dir >= 0; dir--) {
4165 struct xfrm_policy_hash *htab;
4167 htab = &net->xfrm.policy_bydst[dir];
4168 xfrm_hash_free(htab->table, sz);
4170 xfrm_hash_free(net->xfrm.policy_byidx, sz);
4175 static void xfrm_policy_fini(struct net *net)
4177 struct xfrm_pol_inexact_bin *b, *t;
4181 flush_work(&net->xfrm.policy_hash_work);
4182 #ifdef CONFIG_XFRM_SUB_POLICY
4183 xfrm_policy_flush(net, XFRM_POLICY_TYPE_SUB, false);
4185 xfrm_policy_flush(net, XFRM_POLICY_TYPE_MAIN, false);
4187 WARN_ON(!list_empty(&net->xfrm.policy_all));
4189 for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
4190 struct xfrm_policy_hash *htab;
4192 WARN_ON(!hlist_empty(&net->xfrm.policy_inexact[dir]));
4194 htab = &net->xfrm.policy_bydst[dir];
4195 sz = (htab->hmask + 1) * sizeof(struct hlist_head);
4196 WARN_ON(!hlist_empty(htab->table));
4197 xfrm_hash_free(htab->table, sz);
4200 sz = (net->xfrm.policy_idx_hmask + 1) * sizeof(struct hlist_head);
4201 WARN_ON(!hlist_empty(net->xfrm.policy_byidx));
4202 xfrm_hash_free(net->xfrm.policy_byidx, sz);
4204 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
4205 list_for_each_entry_safe(b, t, &net->xfrm.inexact_bins, inexact_bins)
4206 __xfrm_policy_inexact_prune_bin(b, true);
4207 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
4210 static int __net_init xfrm_net_init(struct net *net)
4214 /* Initialize the per-net locks here */
4215 spin_lock_init(&net->xfrm.xfrm_state_lock);
4216 spin_lock_init(&net->xfrm.xfrm_policy_lock);
4217 seqcount_spinlock_init(&net->xfrm.xfrm_policy_hash_generation, &net->xfrm.xfrm_policy_lock);
4218 mutex_init(&net->xfrm.xfrm_cfg_mutex);
4219 net->xfrm.policy_default[XFRM_POLICY_IN] = XFRM_USERPOLICY_ACCEPT;
4220 net->xfrm.policy_default[XFRM_POLICY_FWD] = XFRM_USERPOLICY_ACCEPT;
4221 net->xfrm.policy_default[XFRM_POLICY_OUT] = XFRM_USERPOLICY_ACCEPT;
4223 rv = xfrm_statistics_init(net);
4225 goto out_statistics;
4226 rv = xfrm_state_init(net);
4229 rv = xfrm_policy_init(net);
4232 rv = xfrm_sysctl_init(net);
4239 xfrm_policy_fini(net);
4241 xfrm_state_fini(net);
4243 xfrm_statistics_fini(net);
4248 static void __net_exit xfrm_net_exit(struct net *net)
4250 xfrm_sysctl_fini(net);
4251 xfrm_policy_fini(net);
4252 xfrm_state_fini(net);
4253 xfrm_statistics_fini(net);
4256 static struct pernet_operations __net_initdata xfrm_net_ops = {
4257 .init = xfrm_net_init,
4258 .exit = xfrm_net_exit,
4261 void __init xfrm_init(void)
4263 register_pernet_subsys(&xfrm_net_ops);
4267 #ifdef CONFIG_XFRM_ESPINTCP
4272 #ifdef CONFIG_AUDITSYSCALL
4273 static void xfrm_audit_common_policyinfo(struct xfrm_policy *xp,
4274 struct audit_buffer *audit_buf)
4276 struct xfrm_sec_ctx *ctx = xp->security;
4277 struct xfrm_selector *sel = &xp->selector;
4280 audit_log_format(audit_buf, " sec_alg=%u sec_doi=%u sec_obj=%s",
4281 ctx->ctx_alg, ctx->ctx_doi, ctx->ctx_str);
4283 switch (sel->family) {
4285 audit_log_format(audit_buf, " src=%pI4", &sel->saddr.a4);
4286 if (sel->prefixlen_s != 32)
4287 audit_log_format(audit_buf, " src_prefixlen=%d",
4289 audit_log_format(audit_buf, " dst=%pI4", &sel->daddr.a4);
4290 if (sel->prefixlen_d != 32)
4291 audit_log_format(audit_buf, " dst_prefixlen=%d",
4295 audit_log_format(audit_buf, " src=%pI6", sel->saddr.a6);
4296 if (sel->prefixlen_s != 128)
4297 audit_log_format(audit_buf, " src_prefixlen=%d",
4299 audit_log_format(audit_buf, " dst=%pI6", sel->daddr.a6);
4300 if (sel->prefixlen_d != 128)
4301 audit_log_format(audit_buf, " dst_prefixlen=%d",
4307 void xfrm_audit_policy_add(struct xfrm_policy *xp, int result, bool task_valid)
4309 struct audit_buffer *audit_buf;
4311 audit_buf = xfrm_audit_start("SPD-add");
4312 if (audit_buf == NULL)
4314 xfrm_audit_helper_usrinfo(task_valid, audit_buf);
4315 audit_log_format(audit_buf, " res=%u", result);
4316 xfrm_audit_common_policyinfo(xp, audit_buf);
4317 audit_log_end(audit_buf);
4319 EXPORT_SYMBOL_GPL(xfrm_audit_policy_add);
4321 void xfrm_audit_policy_delete(struct xfrm_policy *xp, int result,
4324 struct audit_buffer *audit_buf;
4326 audit_buf = xfrm_audit_start("SPD-delete");
4327 if (audit_buf == NULL)
4329 xfrm_audit_helper_usrinfo(task_valid, audit_buf);
4330 audit_log_format(audit_buf, " res=%u", result);
4331 xfrm_audit_common_policyinfo(xp, audit_buf);
4332 audit_log_end(audit_buf);
4334 EXPORT_SYMBOL_GPL(xfrm_audit_policy_delete);
4337 #ifdef CONFIG_XFRM_MIGRATE
4338 static bool xfrm_migrate_selector_match(const struct xfrm_selector *sel_cmp,
4339 const struct xfrm_selector *sel_tgt)
4341 if (sel_cmp->proto == IPSEC_ULPROTO_ANY) {
4342 if (sel_tgt->family == sel_cmp->family &&
4343 xfrm_addr_equal(&sel_tgt->daddr, &sel_cmp->daddr,
4345 xfrm_addr_equal(&sel_tgt->saddr, &sel_cmp->saddr,
4347 sel_tgt->prefixlen_d == sel_cmp->prefixlen_d &&
4348 sel_tgt->prefixlen_s == sel_cmp->prefixlen_s) {
4352 if (memcmp(sel_tgt, sel_cmp, sizeof(*sel_tgt)) == 0) {
4359 static struct xfrm_policy *xfrm_migrate_policy_find(const struct xfrm_selector *sel,
4360 u8 dir, u8 type, struct net *net, u32 if_id)
4362 struct xfrm_policy *pol, *ret = NULL;
4363 struct hlist_head *chain;
4366 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
4367 chain = policy_hash_direct(net, &sel->daddr, &sel->saddr, sel->family, dir);
4368 hlist_for_each_entry(pol, chain, bydst) {
4369 if ((if_id == 0 || pol->if_id == if_id) &&
4370 xfrm_migrate_selector_match(sel, &pol->selector) &&
4371 pol->type == type) {
4373 priority = ret->priority;
4377 chain = &net->xfrm.policy_inexact[dir];
4378 hlist_for_each_entry(pol, chain, bydst_inexact_list) {
4379 if ((pol->priority >= priority) && ret)
4382 if ((if_id == 0 || pol->if_id == if_id) &&
4383 xfrm_migrate_selector_match(sel, &pol->selector) &&
4384 pol->type == type) {
4392 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
4397 static int migrate_tmpl_match(const struct xfrm_migrate *m, const struct xfrm_tmpl *t)
4401 if (t->mode == m->mode && t->id.proto == m->proto &&
4402 (m->reqid == 0 || t->reqid == m->reqid)) {
4404 case XFRM_MODE_TUNNEL:
4405 case XFRM_MODE_BEET:
4406 if (xfrm_addr_equal(&t->id.daddr, &m->old_daddr,
4408 xfrm_addr_equal(&t->saddr, &m->old_saddr,
4413 case XFRM_MODE_TRANSPORT:
4414 /* in case of transport mode, template does not store
4415 any IP addresses, hence we just compare mode and
4426 /* update endpoint address(es) of template(s) */
4427 static int xfrm_policy_migrate(struct xfrm_policy *pol,
4428 struct xfrm_migrate *m, int num_migrate,
4429 struct netlink_ext_ack *extack)
4431 struct xfrm_migrate *mp;
4434 write_lock_bh(&pol->lock);
4435 if (unlikely(pol->walk.dead)) {
4436 /* target policy has been deleted */
4437 NL_SET_ERR_MSG(extack, "Target policy not found");
4438 write_unlock_bh(&pol->lock);
4442 for (i = 0; i < pol->xfrm_nr; i++) {
4443 for (j = 0, mp = m; j < num_migrate; j++, mp++) {
4444 if (!migrate_tmpl_match(mp, &pol->xfrm_vec[i]))
4447 if (pol->xfrm_vec[i].mode != XFRM_MODE_TUNNEL &&
4448 pol->xfrm_vec[i].mode != XFRM_MODE_BEET)
4450 /* update endpoints */
4451 memcpy(&pol->xfrm_vec[i].id.daddr, &mp->new_daddr,
4452 sizeof(pol->xfrm_vec[i].id.daddr));
4453 memcpy(&pol->xfrm_vec[i].saddr, &mp->new_saddr,
4454 sizeof(pol->xfrm_vec[i].saddr));
4455 pol->xfrm_vec[i].encap_family = mp->new_family;
4457 atomic_inc(&pol->genid);
4461 write_unlock_bh(&pol->lock);
4469 static int xfrm_migrate_check(const struct xfrm_migrate *m, int num_migrate,
4470 struct netlink_ext_ack *extack)
4474 if (num_migrate < 1 || num_migrate > XFRM_MAX_DEPTH) {
4475 NL_SET_ERR_MSG(extack, "Invalid number of SAs to migrate, must be 0 < num <= XFRM_MAX_DEPTH (6)");
4479 for (i = 0; i < num_migrate; i++) {
4480 if (xfrm_addr_any(&m[i].new_daddr, m[i].new_family) ||
4481 xfrm_addr_any(&m[i].new_saddr, m[i].new_family)) {
4482 NL_SET_ERR_MSG(extack, "Addresses in the MIGRATE attribute's list cannot be null");
4486 /* check if there is any duplicated entry */
4487 for (j = i + 1; j < num_migrate; j++) {
4488 if (!memcmp(&m[i].old_daddr, &m[j].old_daddr,
4489 sizeof(m[i].old_daddr)) &&
4490 !memcmp(&m[i].old_saddr, &m[j].old_saddr,
4491 sizeof(m[i].old_saddr)) &&
4492 m[i].proto == m[j].proto &&
4493 m[i].mode == m[j].mode &&
4494 m[i].reqid == m[j].reqid &&
4495 m[i].old_family == m[j].old_family) {
4496 NL_SET_ERR_MSG(extack, "Entries in the MIGRATE attribute's list must be unique");
4505 int xfrm_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
4506 struct xfrm_migrate *m, int num_migrate,
4507 struct xfrm_kmaddress *k, struct net *net,
4508 struct xfrm_encap_tmpl *encap, u32 if_id,
4509 struct netlink_ext_ack *extack)
4511 int i, err, nx_cur = 0, nx_new = 0;
4512 struct xfrm_policy *pol = NULL;
4513 struct xfrm_state *x, *xc;
4514 struct xfrm_state *x_cur[XFRM_MAX_DEPTH];
4515 struct xfrm_state *x_new[XFRM_MAX_DEPTH];
4516 struct xfrm_migrate *mp;
4518 /* Stage 0 - sanity checks */
4519 err = xfrm_migrate_check(m, num_migrate, extack);
4523 if (dir >= XFRM_POLICY_MAX) {
4524 NL_SET_ERR_MSG(extack, "Invalid policy direction");
4529 /* Stage 1 - find policy */
4530 pol = xfrm_migrate_policy_find(sel, dir, type, net, if_id);
4532 NL_SET_ERR_MSG(extack, "Target policy not found");
4537 /* Stage 2 - find and update state(s) */
4538 for (i = 0, mp = m; i < num_migrate; i++, mp++) {
4539 if ((x = xfrm_migrate_state_find(mp, net, if_id))) {
4542 xc = xfrm_state_migrate(x, mp, encap);
4553 /* Stage 3 - update policy */
4554 err = xfrm_policy_migrate(pol, m, num_migrate, extack);
4558 /* Stage 4 - delete old state(s) */
4560 xfrm_states_put(x_cur, nx_cur);
4561 xfrm_states_delete(x_cur, nx_cur);
4564 /* Stage 5 - announce */
4565 km_migrate(sel, dir, type, m, num_migrate, k, encap);
4577 xfrm_states_put(x_cur, nx_cur);
4579 xfrm_states_delete(x_new, nx_new);
4583 EXPORT_SYMBOL(xfrm_migrate);