1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * xfrm_policy.c
4 *
5 * Changes:
6 * Mitsuru KANDA @USAGI
7 * Kazunori MIYAZAWA @USAGI
8 * Kunihiro Ishiguro <kunihiro@ipinfusion.com>
9 * IPv6 support
10 * Kazunori MIYAZAWA @USAGI
11 * YOSHIFUJI Hideaki
12 * Split up af-specific portion
13 * Derek Atkins <derek@ihtfp.com> Add the post_input processor
14 *
15 */
16
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>
32 #include <net/dst.h>
33 #include <net/flow.h>
34 #include <net/inet_ecn.h>
35 #include <net/xfrm.h>
36 #include <net/ip.h>
37 #include <net/gre.h>
38 #if IS_ENABLED(CONFIG_IPV6_MIP6)
39 #include <net/mip6.h>
40 #endif
41 #ifdef CONFIG_XFRM_STATISTICS
42 #include <net/snmp.h>
43 #endif
44 #ifdef CONFIG_XFRM_ESPINTCP
45 #include <net/espintcp.h>
46 #endif
47
48 #include "xfrm_hash.h"
49
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
53
54 struct xfrm_flo {
55 struct dst_entry *dst_orig;
56 u8 flags;
57 };
58
59 /* prefixes smaller than this are stored in lists, not trees. */
60 #define INEXACT_PREFIXLEN_IPV4 16
61 #define INEXACT_PREFIXLEN_IPV6 48
62
63 struct xfrm_pol_inexact_node {
64 struct rb_node node;
65 union {
66 xfrm_address_t addr;
67 struct rcu_head rcu;
68 };
69 u8 prefixlen;
70
71 struct rb_root root;
72
73 /* the policies matching this node, can be empty list */
74 struct hlist_head hhead;
75 };
76
77 /* xfrm inexact policy search tree:
78 * xfrm_pol_inexact_bin = hash(dir,type,family,if_id);
79 * |
80 * +---- root_d: sorted by daddr:prefix
81 * | |
82 * | xfrm_pol_inexact_node
83 * | |
84 * | +- root: sorted by saddr/prefix
85 * | | |
86 * | | xfrm_pol_inexact_node
87 * | | |
88 * | | + root: unused
89 * | | |
90 * | | + hhead: saddr:daddr policies
91 * | |
92 * | +- coarse policies and all any:daddr policies
93 * |
94 * +---- root_s: sorted by saddr:prefix
95 * | |
96 * | xfrm_pol_inexact_node
97 * | |
98 * | + root: unused
99 * | |
100 * | + hhead: saddr:any policies
101 * |
102 * +---- coarse policies and all any:any policies
103 *
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
109 *
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.
112 */
113
114 struct xfrm_pol_inexact_key {
115 possible_net_t net;
116 u32 if_id;
117 u16 family;
118 u8 dir, type;
119 };
120
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;
126
127 seqcount_spinlock_t count;
128 /* tree sorted by daddr/prefix */
129 struct rb_root root_d;
130
131 /* tree sorted by saddr/prefix */
132 struct rb_root root_s;
133
134 /* slow path below */
135 struct list_head inexact_bins;
136 struct rcu_head rcu;
137 };
138
139 enum xfrm_pol_inexact_candidate_type {
140 XFRM_POL_CAND_BOTH,
141 XFRM_POL_CAND_SADDR,
142 XFRM_POL_CAND_DADDR,
143 XFRM_POL_CAND_ANY,
144
145 XFRM_POL_CAND_MAX,
146 };
147
148 struct xfrm_pol_inexact_candidates {
149 struct hlist_head *res[XFRM_POL_CAND_MAX];
150 };
151
152 static DEFINE_SPINLOCK(xfrm_if_cb_lock);
153 static struct xfrm_if_cb const __rcu *xfrm_if_cb __read_mostly;
154
155 static DEFINE_SPINLOCK(xfrm_policy_afinfo_lock);
156 static struct xfrm_policy_afinfo const __rcu *xfrm_policy_afinfo[AF_INET6 + 1]
157 __read_mostly;
158
159 static struct kmem_cache *xfrm_dst_cache __ro_after_init;
160
161 static struct rhashtable xfrm_policy_inexact_table;
162 static const struct rhashtable_params xfrm_pol_inexact_params;
163
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);
168
169 static void __xfrm_policy_link(struct xfrm_policy *pol, int dir);
170 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
171 int dir);
172
173 static struct xfrm_pol_inexact_bin *
174 xfrm_policy_inexact_lookup(struct net *net, u8 type, u16 family, u8 dir,
175 u32 if_id);
176
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,
182 bool excl);
183 static void xfrm_policy_insert_inexact_list(struct hlist_head *chain,
184 struct xfrm_policy *policy);
185
186 static bool
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);
191
xfrm_pol_hold_rcu(struct xfrm_policy * policy)192 static inline bool xfrm_pol_hold_rcu(struct xfrm_policy *policy)
193 {
194 return refcount_inc_not_zero(&policy->refcnt);
195 }
196
197 static inline bool
__xfrm4_selector_match(const struct xfrm_selector * sel,const struct flowi * fl)198 __xfrm4_selector_match(const struct xfrm_selector *sel, const struct flowi *fl)
199 {
200 const struct flowi4 *fl4 = &fl->u.ip4;
201
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);
208 }
209
210 static inline bool
__xfrm6_selector_match(const struct xfrm_selector * sel,const struct flowi * fl)211 __xfrm6_selector_match(const struct xfrm_selector *sel, const struct flowi *fl)
212 {
213 const struct flowi6 *fl6 = &fl->u.ip6;
214
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);
221 }
222
xfrm_selector_match(const struct xfrm_selector * sel,const struct flowi * fl,unsigned short family)223 bool xfrm_selector_match(const struct xfrm_selector *sel, const struct flowi *fl,
224 unsigned short family)
225 {
226 switch (family) {
227 case AF_INET:
228 return __xfrm4_selector_match(sel, fl);
229 case AF_INET6:
230 return __xfrm6_selector_match(sel, fl);
231 }
232 return false;
233 }
234
xfrm_policy_get_afinfo(unsigned short family)235 static const struct xfrm_policy_afinfo *xfrm_policy_get_afinfo(unsigned short family)
236 {
237 const struct xfrm_policy_afinfo *afinfo;
238
239 if (unlikely(family >= ARRAY_SIZE(xfrm_policy_afinfo)))
240 return NULL;
241 rcu_read_lock();
242 afinfo = rcu_dereference(xfrm_policy_afinfo[family]);
243 if (unlikely(!afinfo))
244 rcu_read_unlock();
245 return afinfo;
246 }
247
248 /* Called with rcu_read_lock(). */
xfrm_if_get_cb(void)249 static const struct xfrm_if_cb *xfrm_if_get_cb(void)
250 {
251 return rcu_dereference(xfrm_if_cb);
252 }
253
__xfrm_dst_lookup(struct net * net,int tos,int oif,const xfrm_address_t * saddr,const xfrm_address_t * daddr,int family,u32 mark)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)
258 {
259 const struct xfrm_policy_afinfo *afinfo;
260 struct dst_entry *dst;
261
262 afinfo = xfrm_policy_get_afinfo(family);
263 if (unlikely(afinfo == NULL))
264 return ERR_PTR(-EAFNOSUPPORT);
265
266 dst = afinfo->dst_lookup(net, tos, oif, saddr, daddr, mark);
267
268 rcu_read_unlock();
269
270 return dst;
271 }
272 EXPORT_SYMBOL(__xfrm_dst_lookup);
273
xfrm_dst_lookup(struct xfrm_state * x,int tos,int oif,xfrm_address_t * prev_saddr,xfrm_address_t * prev_daddr,int family,u32 mark)274 static inline struct dst_entry *xfrm_dst_lookup(struct xfrm_state *x,
275 int tos, int oif,
276 xfrm_address_t *prev_saddr,
277 xfrm_address_t *prev_daddr,
278 int family, u32 mark)
279 {
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;
284
285 if (x->type->flags & XFRM_TYPE_LOCAL_COADDR) {
286 saddr = x->coaddr;
287 daddr = prev_daddr;
288 }
289 if (x->type->flags & XFRM_TYPE_REMOTE_COADDR) {
290 saddr = prev_saddr;
291 daddr = x->coaddr;
292 }
293
294 dst = __xfrm_dst_lookup(net, tos, oif, saddr, daddr, family, mark);
295
296 if (!IS_ERR(dst)) {
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));
301 }
302
303 return dst;
304 }
305
make_jiffies(long secs)306 static inline unsigned long make_jiffies(long secs)
307 {
308 if (secs >= (MAX_SCHEDULE_TIMEOUT-1)/HZ)
309 return MAX_SCHEDULE_TIMEOUT-1;
310 else
311 return secs*HZ;
312 }
313
xfrm_policy_timer(struct timer_list * t)314 static void xfrm_policy_timer(struct timer_list *t)
315 {
316 struct xfrm_policy *xp = from_timer(xp, t, timer);
317 time64_t now = ktime_get_real_seconds();
318 time64_t next = TIME64_MAX;
319 int warn = 0;
320 int dir;
321
322 read_lock(&xp->lock);
323
324 if (unlikely(xp->walk.dead))
325 goto out;
326
327 dir = xfrm_policy_id2dir(xp->index);
328
329 if (xp->lft.hard_add_expires_seconds) {
330 time64_t tmo = xp->lft.hard_add_expires_seconds +
331 xp->curlft.add_time - now;
332 if (tmo <= 0)
333 goto expired;
334 if (tmo < next)
335 next = tmo;
336 }
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;
340 if (tmo <= 0)
341 goto expired;
342 if (tmo < next)
343 next = tmo;
344 }
345 if (xp->lft.soft_add_expires_seconds) {
346 time64_t tmo = xp->lft.soft_add_expires_seconds +
347 xp->curlft.add_time - now;
348 if (tmo <= 0) {
349 warn = 1;
350 tmo = XFRM_KM_TIMEOUT;
351 }
352 if (tmo < next)
353 next = tmo;
354 }
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;
358 if (tmo <= 0) {
359 warn = 1;
360 tmo = XFRM_KM_TIMEOUT;
361 }
362 if (tmo < next)
363 next = tmo;
364 }
365
366 if (warn)
367 km_policy_expired(xp, dir, 0, 0);
368 if (next != TIME64_MAX &&
369 !mod_timer(&xp->timer, jiffies + make_jiffies(next)))
370 xfrm_pol_hold(xp);
371
372 out:
373 read_unlock(&xp->lock);
374 xfrm_pol_put(xp);
375 return;
376
377 expired:
378 read_unlock(&xp->lock);
379 if (!xfrm_policy_delete(xp, dir))
380 km_policy_expired(xp, dir, 1, 0);
381 xfrm_pol_put(xp);
382 }
383
384 /* Allocate xfrm_policy. Not used here, it is supposed to be used by pfkeyv2
385 * SPD calls.
386 */
387
xfrm_policy_alloc(struct net * net,gfp_t gfp)388 struct xfrm_policy *xfrm_policy_alloc(struct net *net, gfp_t gfp)
389 {
390 struct xfrm_policy *policy;
391
392 policy = kzalloc(sizeof(struct xfrm_policy), gfp);
393
394 if (policy) {
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);
406 }
407 return policy;
408 }
409 EXPORT_SYMBOL(xfrm_policy_alloc);
410
xfrm_policy_destroy_rcu(struct rcu_head * head)411 static void xfrm_policy_destroy_rcu(struct rcu_head *head)
412 {
413 struct xfrm_policy *policy = container_of(head, struct xfrm_policy, rcu);
414
415 security_xfrm_policy_free(policy->security);
416 kfree(policy);
417 }
418
419 /* Destroy xfrm_policy: descendant resources must be released to this moment. */
420
xfrm_policy_destroy(struct xfrm_policy * policy)421 void xfrm_policy_destroy(struct xfrm_policy *policy)
422 {
423 BUG_ON(!policy->walk.dead);
424
425 if (del_timer(&policy->timer) || del_timer(&policy->polq.hold_timer))
426 BUG();
427
428 call_rcu(&policy->rcu, xfrm_policy_destroy_rcu);
429 }
430 EXPORT_SYMBOL(xfrm_policy_destroy);
431
432 /* Rule must be locked. Release descendant resources, announce
433 * entry dead. The rule must be unlinked from lists to the moment.
434 */
435
xfrm_policy_kill(struct xfrm_policy * policy)436 static void xfrm_policy_kill(struct xfrm_policy *policy)
437 {
438 write_lock_bh(&policy->lock);
439 policy->walk.dead = 1;
440 write_unlock_bh(&policy->lock);
441
442 atomic_inc(&policy->genid);
443
444 if (del_timer(&policy->polq.hold_timer))
445 xfrm_pol_put(policy);
446 skb_queue_purge(&policy->polq.hold_queue);
447
448 if (del_timer(&policy->timer))
449 xfrm_pol_put(policy);
450
451 xfrm_pol_put(policy);
452 }
453
454 static unsigned int xfrm_policy_hashmax __read_mostly = 1 * 1024 * 1024;
455
idx_hash(struct net * net,u32 index)456 static inline unsigned int idx_hash(struct net *net, u32 index)
457 {
458 return __idx_hash(index, net->xfrm.policy_idx_hmask);
459 }
460
461 /* calculate policy hash thresholds */
__get_hash_thresh(struct net * net,unsigned short family,int dir,u8 * dbits,u8 * sbits)462 static void __get_hash_thresh(struct net *net,
463 unsigned short family, int dir,
464 u8 *dbits, u8 *sbits)
465 {
466 switch (family) {
467 case AF_INET:
468 *dbits = net->xfrm.policy_bydst[dir].dbits4;
469 *sbits = net->xfrm.policy_bydst[dir].sbits4;
470 break;
471
472 case AF_INET6:
473 *dbits = net->xfrm.policy_bydst[dir].dbits6;
474 *sbits = net->xfrm.policy_bydst[dir].sbits6;
475 break;
476
477 default:
478 *dbits = 0;
479 *sbits = 0;
480 }
481 }
482
policy_hash_bysel(struct net * net,const struct xfrm_selector * sel,unsigned short family,int dir)483 static struct hlist_head *policy_hash_bysel(struct net *net,
484 const struct xfrm_selector *sel,
485 unsigned short family, int dir)
486 {
487 unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
488 unsigned int hash;
489 u8 dbits;
490 u8 sbits;
491
492 __get_hash_thresh(net, family, dir, &dbits, &sbits);
493 hash = __sel_hash(sel, family, hmask, dbits, sbits);
494
495 if (hash == hmask + 1)
496 return NULL;
497
498 return rcu_dereference_check(net->xfrm.policy_bydst[dir].table,
499 lockdep_is_held(&net->xfrm.xfrm_policy_lock)) + hash;
500 }
501
policy_hash_direct(struct net * net,const xfrm_address_t * daddr,const xfrm_address_t * saddr,unsigned short family,int dir)502 static struct hlist_head *policy_hash_direct(struct net *net,
503 const xfrm_address_t *daddr,
504 const xfrm_address_t *saddr,
505 unsigned short family, int dir)
506 {
507 unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
508 unsigned int hash;
509 u8 dbits;
510 u8 sbits;
511
512 __get_hash_thresh(net, family, dir, &dbits, &sbits);
513 hash = __addr_hash(daddr, saddr, family, hmask, dbits, sbits);
514
515 return rcu_dereference_check(net->xfrm.policy_bydst[dir].table,
516 lockdep_is_held(&net->xfrm.xfrm_policy_lock)) + hash;
517 }
518
xfrm_dst_hash_transfer(struct net * net,struct hlist_head * list,struct hlist_head * ndsttable,unsigned int nhashmask,int dir)519 static void xfrm_dst_hash_transfer(struct net *net,
520 struct hlist_head *list,
521 struct hlist_head *ndsttable,
522 unsigned int nhashmask,
523 int dir)
524 {
525 struct hlist_node *tmp, *entry0 = NULL;
526 struct xfrm_policy *pol;
527 unsigned int h0 = 0;
528 u8 dbits;
529 u8 sbits;
530
531 redo:
532 hlist_for_each_entry_safe(pol, tmp, list, bydst) {
533 unsigned int h;
534
535 __get_hash_thresh(net, pol->family, dir, &dbits, &sbits);
536 h = __addr_hash(&pol->selector.daddr, &pol->selector.saddr,
537 pol->family, nhashmask, dbits, sbits);
538 if (!entry0) {
539 hlist_del_rcu(&pol->bydst);
540 hlist_add_head_rcu(&pol->bydst, ndsttable + h);
541 h0 = h;
542 } else {
543 if (h != h0)
544 continue;
545 hlist_del_rcu(&pol->bydst);
546 hlist_add_behind_rcu(&pol->bydst, entry0);
547 }
548 entry0 = &pol->bydst;
549 }
550 if (!hlist_empty(list)) {
551 entry0 = NULL;
552 goto redo;
553 }
554 }
555
xfrm_idx_hash_transfer(struct hlist_head * list,struct hlist_head * nidxtable,unsigned int nhashmask)556 static void xfrm_idx_hash_transfer(struct hlist_head *list,
557 struct hlist_head *nidxtable,
558 unsigned int nhashmask)
559 {
560 struct hlist_node *tmp;
561 struct xfrm_policy *pol;
562
563 hlist_for_each_entry_safe(pol, tmp, list, byidx) {
564 unsigned int h;
565
566 h = __idx_hash(pol->index, nhashmask);
567 hlist_add_head(&pol->byidx, nidxtable+h);
568 }
569 }
570
xfrm_new_hash_mask(unsigned int old_hmask)571 static unsigned long xfrm_new_hash_mask(unsigned int old_hmask)
572 {
573 return ((old_hmask + 1) << 1) - 1;
574 }
575
xfrm_bydst_resize(struct net * net,int dir)576 static void xfrm_bydst_resize(struct net *net, int dir)
577 {
578 unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
579 unsigned int nhashmask = xfrm_new_hash_mask(hmask);
580 unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
581 struct hlist_head *ndst = xfrm_hash_alloc(nsize);
582 struct hlist_head *odst;
583 int i;
584
585 if (!ndst)
586 return;
587
588 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
589 write_seqcount_begin(&net->xfrm.xfrm_policy_hash_generation);
590
591 odst = rcu_dereference_protected(net->xfrm.policy_bydst[dir].table,
592 lockdep_is_held(&net->xfrm.xfrm_policy_lock));
593
594 for (i = hmask; i >= 0; i--)
595 xfrm_dst_hash_transfer(net, odst + i, ndst, nhashmask, dir);
596
597 rcu_assign_pointer(net->xfrm.policy_bydst[dir].table, ndst);
598 net->xfrm.policy_bydst[dir].hmask = nhashmask;
599
600 write_seqcount_end(&net->xfrm.xfrm_policy_hash_generation);
601 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
602
603 synchronize_rcu();
604
605 xfrm_hash_free(odst, (hmask + 1) * sizeof(struct hlist_head));
606 }
607
xfrm_byidx_resize(struct net * net,int total)608 static void xfrm_byidx_resize(struct net *net, int total)
609 {
610 unsigned int hmask = net->xfrm.policy_idx_hmask;
611 unsigned int nhashmask = xfrm_new_hash_mask(hmask);
612 unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
613 struct hlist_head *oidx = net->xfrm.policy_byidx;
614 struct hlist_head *nidx = xfrm_hash_alloc(nsize);
615 int i;
616
617 if (!nidx)
618 return;
619
620 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
621
622 for (i = hmask; i >= 0; i--)
623 xfrm_idx_hash_transfer(oidx + i, nidx, nhashmask);
624
625 net->xfrm.policy_byidx = nidx;
626 net->xfrm.policy_idx_hmask = nhashmask;
627
628 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
629
630 xfrm_hash_free(oidx, (hmask + 1) * sizeof(struct hlist_head));
631 }
632
xfrm_bydst_should_resize(struct net * net,int dir,int * total)633 static inline int xfrm_bydst_should_resize(struct net *net, int dir, int *total)
634 {
635 unsigned int cnt = net->xfrm.policy_count[dir];
636 unsigned int hmask = net->xfrm.policy_bydst[dir].hmask;
637
638 if (total)
639 *total += cnt;
640
641 if ((hmask + 1) < xfrm_policy_hashmax &&
642 cnt > hmask)
643 return 1;
644
645 return 0;
646 }
647
xfrm_byidx_should_resize(struct net * net,int total)648 static inline int xfrm_byidx_should_resize(struct net *net, int total)
649 {
650 unsigned int hmask = net->xfrm.policy_idx_hmask;
651
652 if ((hmask + 1) < xfrm_policy_hashmax &&
653 total > hmask)
654 return 1;
655
656 return 0;
657 }
658
xfrm_spd_getinfo(struct net * net,struct xfrmk_spdinfo * si)659 void xfrm_spd_getinfo(struct net *net, struct xfrmk_spdinfo *si)
660 {
661 si->incnt = net->xfrm.policy_count[XFRM_POLICY_IN];
662 si->outcnt = net->xfrm.policy_count[XFRM_POLICY_OUT];
663 si->fwdcnt = net->xfrm.policy_count[XFRM_POLICY_FWD];
664 si->inscnt = net->xfrm.policy_count[XFRM_POLICY_IN+XFRM_POLICY_MAX];
665 si->outscnt = net->xfrm.policy_count[XFRM_POLICY_OUT+XFRM_POLICY_MAX];
666 si->fwdscnt = net->xfrm.policy_count[XFRM_POLICY_FWD+XFRM_POLICY_MAX];
667 si->spdhcnt = net->xfrm.policy_idx_hmask;
668 si->spdhmcnt = xfrm_policy_hashmax;
669 }
670 EXPORT_SYMBOL(xfrm_spd_getinfo);
671
672 static DEFINE_MUTEX(hash_resize_mutex);
xfrm_hash_resize(struct work_struct * work)673 static void xfrm_hash_resize(struct work_struct *work)
674 {
675 struct net *net = container_of(work, struct net, xfrm.policy_hash_work);
676 int dir, total;
677
678 mutex_lock(&hash_resize_mutex);
679
680 total = 0;
681 for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
682 if (xfrm_bydst_should_resize(net, dir, &total))
683 xfrm_bydst_resize(net, dir);
684 }
685 if (xfrm_byidx_should_resize(net, total))
686 xfrm_byidx_resize(net, total);
687
688 mutex_unlock(&hash_resize_mutex);
689 }
690
691 /* Make sure *pol can be inserted into fastbin.
692 * Useful to check that later insert requests will be successful
693 * (provided xfrm_policy_lock is held throughout).
694 */
695 static struct xfrm_pol_inexact_bin *
xfrm_policy_inexact_alloc_bin(const struct xfrm_policy * pol,u8 dir)696 xfrm_policy_inexact_alloc_bin(const struct xfrm_policy *pol, u8 dir)
697 {
698 struct xfrm_pol_inexact_bin *bin, *prev;
699 struct xfrm_pol_inexact_key k = {
700 .family = pol->family,
701 .type = pol->type,
702 .dir = dir,
703 .if_id = pol->if_id,
704 };
705 struct net *net = xp_net(pol);
706
707 lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
708
709 write_pnet(&k.net, net);
710 bin = rhashtable_lookup_fast(&xfrm_policy_inexact_table, &k,
711 xfrm_pol_inexact_params);
712 if (bin)
713 return bin;
714
715 bin = kzalloc(sizeof(*bin), GFP_ATOMIC);
716 if (!bin)
717 return NULL;
718
719 bin->k = k;
720 INIT_HLIST_HEAD(&bin->hhead);
721 bin->root_d = RB_ROOT;
722 bin->root_s = RB_ROOT;
723 seqcount_spinlock_init(&bin->count, &net->xfrm.xfrm_policy_lock);
724
725 prev = rhashtable_lookup_get_insert_key(&xfrm_policy_inexact_table,
726 &bin->k, &bin->head,
727 xfrm_pol_inexact_params);
728 if (!prev) {
729 list_add(&bin->inexact_bins, &net->xfrm.inexact_bins);
730 return bin;
731 }
732
733 kfree(bin);
734
735 return IS_ERR(prev) ? NULL : prev;
736 }
737
xfrm_pol_inexact_addr_use_any_list(const xfrm_address_t * addr,int family,u8 prefixlen)738 static bool xfrm_pol_inexact_addr_use_any_list(const xfrm_address_t *addr,
739 int family, u8 prefixlen)
740 {
741 if (xfrm_addr_any(addr, family))
742 return true;
743
744 if (family == AF_INET6 && prefixlen < INEXACT_PREFIXLEN_IPV6)
745 return true;
746
747 if (family == AF_INET && prefixlen < INEXACT_PREFIXLEN_IPV4)
748 return true;
749
750 return false;
751 }
752
753 static bool
xfrm_policy_inexact_insert_use_any_list(const struct xfrm_policy * policy)754 xfrm_policy_inexact_insert_use_any_list(const struct xfrm_policy *policy)
755 {
756 const xfrm_address_t *addr;
757 bool saddr_any, daddr_any;
758 u8 prefixlen;
759
760 addr = &policy->selector.saddr;
761 prefixlen = policy->selector.prefixlen_s;
762
763 saddr_any = xfrm_pol_inexact_addr_use_any_list(addr,
764 policy->family,
765 prefixlen);
766 addr = &policy->selector.daddr;
767 prefixlen = policy->selector.prefixlen_d;
768 daddr_any = xfrm_pol_inexact_addr_use_any_list(addr,
769 policy->family,
770 prefixlen);
771 return saddr_any && daddr_any;
772 }
773
xfrm_pol_inexact_node_init(struct xfrm_pol_inexact_node * node,const xfrm_address_t * addr,u8 prefixlen)774 static void xfrm_pol_inexact_node_init(struct xfrm_pol_inexact_node *node,
775 const xfrm_address_t *addr, u8 prefixlen)
776 {
777 node->addr = *addr;
778 node->prefixlen = prefixlen;
779 }
780
781 static struct xfrm_pol_inexact_node *
xfrm_pol_inexact_node_alloc(const xfrm_address_t * addr,u8 prefixlen)782 xfrm_pol_inexact_node_alloc(const xfrm_address_t *addr, u8 prefixlen)
783 {
784 struct xfrm_pol_inexact_node *node;
785
786 node = kzalloc(sizeof(*node), GFP_ATOMIC);
787 if (node)
788 xfrm_pol_inexact_node_init(node, addr, prefixlen);
789
790 return node;
791 }
792
xfrm_policy_addr_delta(const xfrm_address_t * a,const xfrm_address_t * b,u8 prefixlen,u16 family)793 static int xfrm_policy_addr_delta(const xfrm_address_t *a,
794 const xfrm_address_t *b,
795 u8 prefixlen, u16 family)
796 {
797 u32 ma, mb, mask;
798 unsigned int pdw, pbi;
799 int delta = 0;
800
801 switch (family) {
802 case AF_INET:
803 if (prefixlen == 0)
804 return 0;
805 mask = ~0U << (32 - prefixlen);
806 ma = ntohl(a->a4) & mask;
807 mb = ntohl(b->a4) & mask;
808 if (ma < mb)
809 delta = -1;
810 else if (ma > mb)
811 delta = 1;
812 break;
813 case AF_INET6:
814 pdw = prefixlen >> 5;
815 pbi = prefixlen & 0x1f;
816
817 if (pdw) {
818 delta = memcmp(a->a6, b->a6, pdw << 2);
819 if (delta)
820 return delta;
821 }
822 if (pbi) {
823 mask = ~0U << (32 - pbi);
824 ma = ntohl(a->a6[pdw]) & mask;
825 mb = ntohl(b->a6[pdw]) & mask;
826 if (ma < mb)
827 delta = -1;
828 else if (ma > mb)
829 delta = 1;
830 }
831 break;
832 default:
833 break;
834 }
835
836 return delta;
837 }
838
xfrm_policy_inexact_list_reinsert(struct net * net,struct xfrm_pol_inexact_node * n,u16 family)839 static void xfrm_policy_inexact_list_reinsert(struct net *net,
840 struct xfrm_pol_inexact_node *n,
841 u16 family)
842 {
843 unsigned int matched_s, matched_d;
844 struct xfrm_policy *policy, *p;
845
846 matched_s = 0;
847 matched_d = 0;
848
849 list_for_each_entry_reverse(policy, &net->xfrm.policy_all, walk.all) {
850 struct hlist_node *newpos = NULL;
851 bool matches_s, matches_d;
852
853 if (policy->walk.dead || !policy->bydst_reinsert)
854 continue;
855
856 WARN_ON_ONCE(policy->family != family);
857
858 policy->bydst_reinsert = false;
859 hlist_for_each_entry(p, &n->hhead, bydst) {
860 if (policy->priority > p->priority)
861 newpos = &p->bydst;
862 else if (policy->priority == p->priority &&
863 policy->pos > p->pos)
864 newpos = &p->bydst;
865 else
866 break;
867 }
868
869 if (newpos)
870 hlist_add_behind_rcu(&policy->bydst, newpos);
871 else
872 hlist_add_head_rcu(&policy->bydst, &n->hhead);
873
874 /* paranoia checks follow.
875 * Check that the reinserted policy matches at least
876 * saddr or daddr for current node prefix.
877 *
878 * Matching both is fine, matching saddr in one policy
879 * (but not daddr) and then matching only daddr in another
880 * is a bug.
881 */
882 matches_s = xfrm_policy_addr_delta(&policy->selector.saddr,
883 &n->addr,
884 n->prefixlen,
885 family) == 0;
886 matches_d = xfrm_policy_addr_delta(&policy->selector.daddr,
887 &n->addr,
888 n->prefixlen,
889 family) == 0;
890 if (matches_s && matches_d)
891 continue;
892
893 WARN_ON_ONCE(!matches_s && !matches_d);
894 if (matches_s)
895 matched_s++;
896 if (matches_d)
897 matched_d++;
898 WARN_ON_ONCE(matched_s && matched_d);
899 }
900 }
901
xfrm_policy_inexact_node_reinsert(struct net * net,struct xfrm_pol_inexact_node * n,struct rb_root * new,u16 family)902 static void xfrm_policy_inexact_node_reinsert(struct net *net,
903 struct xfrm_pol_inexact_node *n,
904 struct rb_root *new,
905 u16 family)
906 {
907 struct xfrm_pol_inexact_node *node;
908 struct rb_node **p, *parent;
909
910 /* we should not have another subtree here */
911 WARN_ON_ONCE(!RB_EMPTY_ROOT(&n->root));
912 restart:
913 parent = NULL;
914 p = &new->rb_node;
915 while (*p) {
916 u8 prefixlen;
917 int delta;
918
919 parent = *p;
920 node = rb_entry(*p, struct xfrm_pol_inexact_node, node);
921
922 prefixlen = min(node->prefixlen, n->prefixlen);
923
924 delta = xfrm_policy_addr_delta(&n->addr, &node->addr,
925 prefixlen, family);
926 if (delta < 0) {
927 p = &parent->rb_left;
928 } else if (delta > 0) {
929 p = &parent->rb_right;
930 } else {
931 bool same_prefixlen = node->prefixlen == n->prefixlen;
932 struct xfrm_policy *tmp;
933
934 hlist_for_each_entry(tmp, &n->hhead, bydst) {
935 tmp->bydst_reinsert = true;
936 hlist_del_rcu(&tmp->bydst);
937 }
938
939 node->prefixlen = prefixlen;
940
941 xfrm_policy_inexact_list_reinsert(net, node, family);
942
943 if (same_prefixlen) {
944 kfree_rcu(n, rcu);
945 return;
946 }
947
948 rb_erase(*p, new);
949 kfree_rcu(n, rcu);
950 n = node;
951 goto restart;
952 }
953 }
954
955 rb_link_node_rcu(&n->node, parent, p);
956 rb_insert_color(&n->node, new);
957 }
958
959 /* merge nodes v and n */
xfrm_policy_inexact_node_merge(struct net * net,struct xfrm_pol_inexact_node * v,struct xfrm_pol_inexact_node * n,u16 family)960 static void xfrm_policy_inexact_node_merge(struct net *net,
961 struct xfrm_pol_inexact_node *v,
962 struct xfrm_pol_inexact_node *n,
963 u16 family)
964 {
965 struct xfrm_pol_inexact_node *node;
966 struct xfrm_policy *tmp;
967 struct rb_node *rnode;
968
969 /* To-be-merged node v has a subtree.
970 *
971 * Dismantle it and insert its nodes to n->root.
972 */
973 while ((rnode = rb_first(&v->root)) != NULL) {
974 node = rb_entry(rnode, struct xfrm_pol_inexact_node, node);
975 rb_erase(&node->node, &v->root);
976 xfrm_policy_inexact_node_reinsert(net, node, &n->root,
977 family);
978 }
979
980 hlist_for_each_entry(tmp, &v->hhead, bydst) {
981 tmp->bydst_reinsert = true;
982 hlist_del_rcu(&tmp->bydst);
983 }
984
985 xfrm_policy_inexact_list_reinsert(net, n, family);
986 }
987
988 static struct xfrm_pol_inexact_node *
xfrm_policy_inexact_insert_node(struct net * net,struct rb_root * root,xfrm_address_t * addr,u16 family,u8 prefixlen,u8 dir)989 xfrm_policy_inexact_insert_node(struct net *net,
990 struct rb_root *root,
991 xfrm_address_t *addr,
992 u16 family, u8 prefixlen, u8 dir)
993 {
994 struct xfrm_pol_inexact_node *cached = NULL;
995 struct rb_node **p, *parent = NULL;
996 struct xfrm_pol_inexact_node *node;
997
998 p = &root->rb_node;
999 while (*p) {
1000 int delta;
1001
1002 parent = *p;
1003 node = rb_entry(*p, struct xfrm_pol_inexact_node, node);
1004
1005 delta = xfrm_policy_addr_delta(addr, &node->addr,
1006 node->prefixlen,
1007 family);
1008 if (delta == 0 && prefixlen >= node->prefixlen) {
1009 WARN_ON_ONCE(cached); /* ipsec policies got lost */
1010 return node;
1011 }
1012
1013 if (delta < 0)
1014 p = &parent->rb_left;
1015 else
1016 p = &parent->rb_right;
1017
1018 if (prefixlen < node->prefixlen) {
1019 delta = xfrm_policy_addr_delta(addr, &node->addr,
1020 prefixlen,
1021 family);
1022 if (delta)
1023 continue;
1024
1025 /* This node is a subnet of the new prefix. It needs
1026 * to be removed and re-inserted with the smaller
1027 * prefix and all nodes that are now also covered
1028 * by the reduced prefixlen.
1029 */
1030 rb_erase(&node->node, root);
1031
1032 if (!cached) {
1033 xfrm_pol_inexact_node_init(node, addr,
1034 prefixlen);
1035 cached = node;
1036 } else {
1037 /* This node also falls within the new
1038 * prefixlen. Merge the to-be-reinserted
1039 * node and this one.
1040 */
1041 xfrm_policy_inexact_node_merge(net, node,
1042 cached, family);
1043 kfree_rcu(node, rcu);
1044 }
1045
1046 /* restart */
1047 p = &root->rb_node;
1048 parent = NULL;
1049 }
1050 }
1051
1052 node = cached;
1053 if (!node) {
1054 node = xfrm_pol_inexact_node_alloc(addr, prefixlen);
1055 if (!node)
1056 return NULL;
1057 }
1058
1059 rb_link_node_rcu(&node->node, parent, p);
1060 rb_insert_color(&node->node, root);
1061
1062 return node;
1063 }
1064
xfrm_policy_inexact_gc_tree(struct rb_root * r,bool rm)1065 static void xfrm_policy_inexact_gc_tree(struct rb_root *r, bool rm)
1066 {
1067 struct xfrm_pol_inexact_node *node;
1068 struct rb_node *rn = rb_first(r);
1069
1070 while (rn) {
1071 node = rb_entry(rn, struct xfrm_pol_inexact_node, node);
1072
1073 xfrm_policy_inexact_gc_tree(&node->root, rm);
1074 rn = rb_next(rn);
1075
1076 if (!hlist_empty(&node->hhead) || !RB_EMPTY_ROOT(&node->root)) {
1077 WARN_ON_ONCE(rm);
1078 continue;
1079 }
1080
1081 rb_erase(&node->node, r);
1082 kfree_rcu(node, rcu);
1083 }
1084 }
1085
__xfrm_policy_inexact_prune_bin(struct xfrm_pol_inexact_bin * b,bool net_exit)1086 static void __xfrm_policy_inexact_prune_bin(struct xfrm_pol_inexact_bin *b, bool net_exit)
1087 {
1088 write_seqcount_begin(&b->count);
1089 xfrm_policy_inexact_gc_tree(&b->root_d, net_exit);
1090 xfrm_policy_inexact_gc_tree(&b->root_s, net_exit);
1091 write_seqcount_end(&b->count);
1092
1093 if (!RB_EMPTY_ROOT(&b->root_d) || !RB_EMPTY_ROOT(&b->root_s) ||
1094 !hlist_empty(&b->hhead)) {
1095 WARN_ON_ONCE(net_exit);
1096 return;
1097 }
1098
1099 if (rhashtable_remove_fast(&xfrm_policy_inexact_table, &b->head,
1100 xfrm_pol_inexact_params) == 0) {
1101 list_del(&b->inexact_bins);
1102 kfree_rcu(b, rcu);
1103 }
1104 }
1105
xfrm_policy_inexact_prune_bin(struct xfrm_pol_inexact_bin * b)1106 static void xfrm_policy_inexact_prune_bin(struct xfrm_pol_inexact_bin *b)
1107 {
1108 struct net *net = read_pnet(&b->k.net);
1109
1110 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1111 __xfrm_policy_inexact_prune_bin(b, false);
1112 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1113 }
1114
__xfrm_policy_inexact_flush(struct net * net)1115 static void __xfrm_policy_inexact_flush(struct net *net)
1116 {
1117 struct xfrm_pol_inexact_bin *bin, *t;
1118
1119 lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
1120
1121 list_for_each_entry_safe(bin, t, &net->xfrm.inexact_bins, inexact_bins)
1122 __xfrm_policy_inexact_prune_bin(bin, false);
1123 }
1124
1125 static struct hlist_head *
xfrm_policy_inexact_alloc_chain(struct xfrm_pol_inexact_bin * bin,struct xfrm_policy * policy,u8 dir)1126 xfrm_policy_inexact_alloc_chain(struct xfrm_pol_inexact_bin *bin,
1127 struct xfrm_policy *policy, u8 dir)
1128 {
1129 struct xfrm_pol_inexact_node *n;
1130 struct net *net;
1131
1132 net = xp_net(policy);
1133 lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
1134
1135 if (xfrm_policy_inexact_insert_use_any_list(policy))
1136 return &bin->hhead;
1137
1138 if (xfrm_pol_inexact_addr_use_any_list(&policy->selector.daddr,
1139 policy->family,
1140 policy->selector.prefixlen_d)) {
1141 write_seqcount_begin(&bin->count);
1142 n = xfrm_policy_inexact_insert_node(net,
1143 &bin->root_s,
1144 &policy->selector.saddr,
1145 policy->family,
1146 policy->selector.prefixlen_s,
1147 dir);
1148 write_seqcount_end(&bin->count);
1149 if (!n)
1150 return NULL;
1151
1152 return &n->hhead;
1153 }
1154
1155 /* daddr is fixed */
1156 write_seqcount_begin(&bin->count);
1157 n = xfrm_policy_inexact_insert_node(net,
1158 &bin->root_d,
1159 &policy->selector.daddr,
1160 policy->family,
1161 policy->selector.prefixlen_d, dir);
1162 write_seqcount_end(&bin->count);
1163 if (!n)
1164 return NULL;
1165
1166 /* saddr is wildcard */
1167 if (xfrm_pol_inexact_addr_use_any_list(&policy->selector.saddr,
1168 policy->family,
1169 policy->selector.prefixlen_s))
1170 return &n->hhead;
1171
1172 write_seqcount_begin(&bin->count);
1173 n = xfrm_policy_inexact_insert_node(net,
1174 &n->root,
1175 &policy->selector.saddr,
1176 policy->family,
1177 policy->selector.prefixlen_s, dir);
1178 write_seqcount_end(&bin->count);
1179 if (!n)
1180 return NULL;
1181
1182 return &n->hhead;
1183 }
1184
1185 static struct xfrm_policy *
xfrm_policy_inexact_insert(struct xfrm_policy * policy,u8 dir,int excl)1186 xfrm_policy_inexact_insert(struct xfrm_policy *policy, u8 dir, int excl)
1187 {
1188 struct xfrm_pol_inexact_bin *bin;
1189 struct xfrm_policy *delpol;
1190 struct hlist_head *chain;
1191 struct net *net;
1192
1193 bin = xfrm_policy_inexact_alloc_bin(policy, dir);
1194 if (!bin)
1195 return ERR_PTR(-ENOMEM);
1196
1197 net = xp_net(policy);
1198 lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
1199
1200 chain = xfrm_policy_inexact_alloc_chain(bin, policy, dir);
1201 if (!chain) {
1202 __xfrm_policy_inexact_prune_bin(bin, false);
1203 return ERR_PTR(-ENOMEM);
1204 }
1205
1206 delpol = xfrm_policy_insert_list(chain, policy, excl);
1207 if (delpol && excl) {
1208 __xfrm_policy_inexact_prune_bin(bin, false);
1209 return ERR_PTR(-EEXIST);
1210 }
1211
1212 chain = &net->xfrm.policy_inexact[dir];
1213 xfrm_policy_insert_inexact_list(chain, policy);
1214
1215 if (delpol)
1216 __xfrm_policy_inexact_prune_bin(bin, false);
1217
1218 return delpol;
1219 }
1220
xfrm_hash_rebuild(struct work_struct * work)1221 static void xfrm_hash_rebuild(struct work_struct *work)
1222 {
1223 struct net *net = container_of(work, struct net,
1224 xfrm.policy_hthresh.work);
1225 unsigned int hmask;
1226 struct xfrm_policy *pol;
1227 struct xfrm_policy *policy;
1228 struct hlist_head *chain;
1229 struct hlist_head *odst;
1230 struct hlist_node *newpos;
1231 int i;
1232 int dir;
1233 unsigned seq;
1234 u8 lbits4, rbits4, lbits6, rbits6;
1235
1236 mutex_lock(&hash_resize_mutex);
1237
1238 /* read selector prefixlen thresholds */
1239 do {
1240 seq = read_seqbegin(&net->xfrm.policy_hthresh.lock);
1241
1242 lbits4 = net->xfrm.policy_hthresh.lbits4;
1243 rbits4 = net->xfrm.policy_hthresh.rbits4;
1244 lbits6 = net->xfrm.policy_hthresh.lbits6;
1245 rbits6 = net->xfrm.policy_hthresh.rbits6;
1246 } while (read_seqretry(&net->xfrm.policy_hthresh.lock, seq));
1247
1248 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1249 write_seqcount_begin(&net->xfrm.xfrm_policy_hash_generation);
1250
1251 /* make sure that we can insert the indirect policies again before
1252 * we start with destructive action.
1253 */
1254 list_for_each_entry(policy, &net->xfrm.policy_all, walk.all) {
1255 struct xfrm_pol_inexact_bin *bin;
1256 u8 dbits, sbits;
1257
1258 if (policy->walk.dead)
1259 continue;
1260
1261 dir = xfrm_policy_id2dir(policy->index);
1262 if (dir >= XFRM_POLICY_MAX)
1263 continue;
1264
1265 if ((dir & XFRM_POLICY_MASK) == XFRM_POLICY_OUT) {
1266 if (policy->family == AF_INET) {
1267 dbits = rbits4;
1268 sbits = lbits4;
1269 } else {
1270 dbits = rbits6;
1271 sbits = lbits6;
1272 }
1273 } else {
1274 if (policy->family == AF_INET) {
1275 dbits = lbits4;
1276 sbits = rbits4;
1277 } else {
1278 dbits = lbits6;
1279 sbits = rbits6;
1280 }
1281 }
1282
1283 if (policy->selector.prefixlen_d < dbits ||
1284 policy->selector.prefixlen_s < sbits)
1285 continue;
1286
1287 bin = xfrm_policy_inexact_alloc_bin(policy, dir);
1288 if (!bin)
1289 goto out_unlock;
1290
1291 if (!xfrm_policy_inexact_alloc_chain(bin, policy, dir))
1292 goto out_unlock;
1293 }
1294
1295 /* reset the bydst and inexact table in all directions */
1296 for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
1297 struct hlist_node *n;
1298
1299 hlist_for_each_entry_safe(policy, n,
1300 &net->xfrm.policy_inexact[dir],
1301 bydst_inexact_list) {
1302 hlist_del_rcu(&policy->bydst);
1303 hlist_del_init(&policy->bydst_inexact_list);
1304 }
1305
1306 hmask = net->xfrm.policy_bydst[dir].hmask;
1307 odst = net->xfrm.policy_bydst[dir].table;
1308 for (i = hmask; i >= 0; i--) {
1309 hlist_for_each_entry_safe(policy, n, odst + i, bydst)
1310 hlist_del_rcu(&policy->bydst);
1311 }
1312 if ((dir & XFRM_POLICY_MASK) == XFRM_POLICY_OUT) {
1313 /* dir out => dst = remote, src = local */
1314 net->xfrm.policy_bydst[dir].dbits4 = rbits4;
1315 net->xfrm.policy_bydst[dir].sbits4 = lbits4;
1316 net->xfrm.policy_bydst[dir].dbits6 = rbits6;
1317 net->xfrm.policy_bydst[dir].sbits6 = lbits6;
1318 } else {
1319 /* dir in/fwd => dst = local, src = remote */
1320 net->xfrm.policy_bydst[dir].dbits4 = lbits4;
1321 net->xfrm.policy_bydst[dir].sbits4 = rbits4;
1322 net->xfrm.policy_bydst[dir].dbits6 = lbits6;
1323 net->xfrm.policy_bydst[dir].sbits6 = rbits6;
1324 }
1325 }
1326
1327 /* re-insert all policies by order of creation */
1328 list_for_each_entry_reverse(policy, &net->xfrm.policy_all, walk.all) {
1329 if (policy->walk.dead)
1330 continue;
1331 dir = xfrm_policy_id2dir(policy->index);
1332 if (dir >= XFRM_POLICY_MAX) {
1333 /* skip socket policies */
1334 continue;
1335 }
1336 newpos = NULL;
1337 chain = policy_hash_bysel(net, &policy->selector,
1338 policy->family, dir);
1339
1340 if (!chain) {
1341 void *p = xfrm_policy_inexact_insert(policy, dir, 0);
1342
1343 WARN_ONCE(IS_ERR(p), "reinsert: %ld\n", PTR_ERR(p));
1344 continue;
1345 }
1346
1347 hlist_for_each_entry(pol, chain, bydst) {
1348 if (policy->priority >= pol->priority)
1349 newpos = &pol->bydst;
1350 else
1351 break;
1352 }
1353 if (newpos)
1354 hlist_add_behind_rcu(&policy->bydst, newpos);
1355 else
1356 hlist_add_head_rcu(&policy->bydst, chain);
1357 }
1358
1359 out_unlock:
1360 __xfrm_policy_inexact_flush(net);
1361 write_seqcount_end(&net->xfrm.xfrm_policy_hash_generation);
1362 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1363
1364 mutex_unlock(&hash_resize_mutex);
1365 }
1366
xfrm_policy_hash_rebuild(struct net * net)1367 void xfrm_policy_hash_rebuild(struct net *net)
1368 {
1369 schedule_work(&net->xfrm.policy_hthresh.work);
1370 }
1371 EXPORT_SYMBOL(xfrm_policy_hash_rebuild);
1372
1373 /* Generate new index... KAME seems to generate them ordered by cost
1374 * of an absolute inpredictability of ordering of rules. This will not pass. */
xfrm_gen_index(struct net * net,int dir,u32 index)1375 static u32 xfrm_gen_index(struct net *net, int dir, u32 index)
1376 {
1377 static u32 idx_generator;
1378
1379 for (;;) {
1380 struct hlist_head *list;
1381 struct xfrm_policy *p;
1382 u32 idx;
1383 int found;
1384
1385 if (!index) {
1386 idx = (idx_generator | dir);
1387 idx_generator += 8;
1388 } else {
1389 idx = index;
1390 index = 0;
1391 }
1392
1393 if (idx == 0)
1394 idx = 8;
1395 list = net->xfrm.policy_byidx + idx_hash(net, idx);
1396 found = 0;
1397 hlist_for_each_entry(p, list, byidx) {
1398 if (p->index == idx) {
1399 found = 1;
1400 break;
1401 }
1402 }
1403 if (!found)
1404 return idx;
1405 }
1406 }
1407
selector_cmp(struct xfrm_selector * s1,struct xfrm_selector * s2)1408 static inline int selector_cmp(struct xfrm_selector *s1, struct xfrm_selector *s2)
1409 {
1410 u32 *p1 = (u32 *) s1;
1411 u32 *p2 = (u32 *) s2;
1412 int len = sizeof(struct xfrm_selector) / sizeof(u32);
1413 int i;
1414
1415 for (i = 0; i < len; i++) {
1416 if (p1[i] != p2[i])
1417 return 1;
1418 }
1419
1420 return 0;
1421 }
1422
xfrm_policy_requeue(struct xfrm_policy * old,struct xfrm_policy * new)1423 static void xfrm_policy_requeue(struct xfrm_policy *old,
1424 struct xfrm_policy *new)
1425 {
1426 struct xfrm_policy_queue *pq = &old->polq;
1427 struct sk_buff_head list;
1428
1429 if (skb_queue_empty(&pq->hold_queue))
1430 return;
1431
1432 __skb_queue_head_init(&list);
1433
1434 spin_lock_bh(&pq->hold_queue.lock);
1435 skb_queue_splice_init(&pq->hold_queue, &list);
1436 if (del_timer(&pq->hold_timer))
1437 xfrm_pol_put(old);
1438 spin_unlock_bh(&pq->hold_queue.lock);
1439
1440 pq = &new->polq;
1441
1442 spin_lock_bh(&pq->hold_queue.lock);
1443 skb_queue_splice(&list, &pq->hold_queue);
1444 pq->timeout = XFRM_QUEUE_TMO_MIN;
1445 if (!mod_timer(&pq->hold_timer, jiffies))
1446 xfrm_pol_hold(new);
1447 spin_unlock_bh(&pq->hold_queue.lock);
1448 }
1449
xfrm_policy_mark_match(const struct xfrm_mark * mark,struct xfrm_policy * pol)1450 static inline bool xfrm_policy_mark_match(const struct xfrm_mark *mark,
1451 struct xfrm_policy *pol)
1452 {
1453 return mark->v == pol->mark.v && mark->m == pol->mark.m;
1454 }
1455
xfrm_pol_bin_key(const void * data,u32 len,u32 seed)1456 static u32 xfrm_pol_bin_key(const void *data, u32 len, u32 seed)
1457 {
1458 const struct xfrm_pol_inexact_key *k = data;
1459 u32 a = k->type << 24 | k->dir << 16 | k->family;
1460
1461 return jhash_3words(a, k->if_id, net_hash_mix(read_pnet(&k->net)),
1462 seed);
1463 }
1464
xfrm_pol_bin_obj(const void * data,u32 len,u32 seed)1465 static u32 xfrm_pol_bin_obj(const void *data, u32 len, u32 seed)
1466 {
1467 const struct xfrm_pol_inexact_bin *b = data;
1468
1469 return xfrm_pol_bin_key(&b->k, 0, seed);
1470 }
1471
xfrm_pol_bin_cmp(struct rhashtable_compare_arg * arg,const void * ptr)1472 static int xfrm_pol_bin_cmp(struct rhashtable_compare_arg *arg,
1473 const void *ptr)
1474 {
1475 const struct xfrm_pol_inexact_key *key = arg->key;
1476 const struct xfrm_pol_inexact_bin *b = ptr;
1477 int ret;
1478
1479 if (!net_eq(read_pnet(&b->k.net), read_pnet(&key->net)))
1480 return -1;
1481
1482 ret = b->k.dir ^ key->dir;
1483 if (ret)
1484 return ret;
1485
1486 ret = b->k.type ^ key->type;
1487 if (ret)
1488 return ret;
1489
1490 ret = b->k.family ^ key->family;
1491 if (ret)
1492 return ret;
1493
1494 return b->k.if_id ^ key->if_id;
1495 }
1496
1497 static const struct rhashtable_params xfrm_pol_inexact_params = {
1498 .head_offset = offsetof(struct xfrm_pol_inexact_bin, head),
1499 .hashfn = xfrm_pol_bin_key,
1500 .obj_hashfn = xfrm_pol_bin_obj,
1501 .obj_cmpfn = xfrm_pol_bin_cmp,
1502 .automatic_shrinking = true,
1503 };
1504
xfrm_policy_insert_inexact_list(struct hlist_head * chain,struct xfrm_policy * policy)1505 static void xfrm_policy_insert_inexact_list(struct hlist_head *chain,
1506 struct xfrm_policy *policy)
1507 {
1508 struct xfrm_policy *pol, *delpol = NULL;
1509 struct hlist_node *newpos = NULL;
1510 int i = 0;
1511
1512 hlist_for_each_entry(pol, chain, bydst_inexact_list) {
1513 if (pol->type == policy->type &&
1514 pol->if_id == policy->if_id &&
1515 !selector_cmp(&pol->selector, &policy->selector) &&
1516 xfrm_policy_mark_match(&policy->mark, pol) &&
1517 xfrm_sec_ctx_match(pol->security, policy->security) &&
1518 !WARN_ON(delpol)) {
1519 delpol = pol;
1520 if (policy->priority > pol->priority)
1521 continue;
1522 } else if (policy->priority >= pol->priority) {
1523 newpos = &pol->bydst_inexact_list;
1524 continue;
1525 }
1526 if (delpol)
1527 break;
1528 }
1529
1530 if (newpos)
1531 hlist_add_behind_rcu(&policy->bydst_inexact_list, newpos);
1532 else
1533 hlist_add_head_rcu(&policy->bydst_inexact_list, chain);
1534
1535 hlist_for_each_entry(pol, chain, bydst_inexact_list) {
1536 pol->pos = i;
1537 i++;
1538 }
1539 }
1540
xfrm_policy_insert_list(struct hlist_head * chain,struct xfrm_policy * policy,bool excl)1541 static struct xfrm_policy *xfrm_policy_insert_list(struct hlist_head *chain,
1542 struct xfrm_policy *policy,
1543 bool excl)
1544 {
1545 struct xfrm_policy *pol, *newpos = NULL, *delpol = NULL;
1546
1547 hlist_for_each_entry(pol, chain, bydst) {
1548 if (pol->type == policy->type &&
1549 pol->if_id == policy->if_id &&
1550 !selector_cmp(&pol->selector, &policy->selector) &&
1551 xfrm_policy_mark_match(&policy->mark, pol) &&
1552 xfrm_sec_ctx_match(pol->security, policy->security) &&
1553 !WARN_ON(delpol)) {
1554 if (excl)
1555 return ERR_PTR(-EEXIST);
1556 delpol = pol;
1557 if (policy->priority > pol->priority)
1558 continue;
1559 } else if (policy->priority >= pol->priority) {
1560 newpos = pol;
1561 continue;
1562 }
1563 if (delpol)
1564 break;
1565 }
1566
1567 if (newpos)
1568 hlist_add_behind_rcu(&policy->bydst, &newpos->bydst);
1569 else
1570 hlist_add_head_rcu(&policy->bydst, chain);
1571
1572 return delpol;
1573 }
1574
xfrm_policy_insert(int dir,struct xfrm_policy * policy,int excl)1575 int xfrm_policy_insert(int dir, struct xfrm_policy *policy, int excl)
1576 {
1577 struct net *net = xp_net(policy);
1578 struct xfrm_policy *delpol;
1579 struct hlist_head *chain;
1580
1581 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1582 chain = policy_hash_bysel(net, &policy->selector, policy->family, dir);
1583 if (chain)
1584 delpol = xfrm_policy_insert_list(chain, policy, excl);
1585 else
1586 delpol = xfrm_policy_inexact_insert(policy, dir, excl);
1587
1588 if (IS_ERR(delpol)) {
1589 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1590 return PTR_ERR(delpol);
1591 }
1592
1593 __xfrm_policy_link(policy, dir);
1594
1595 /* After previous checking, family can either be AF_INET or AF_INET6 */
1596 if (policy->family == AF_INET)
1597 rt_genid_bump_ipv4(net);
1598 else
1599 rt_genid_bump_ipv6(net);
1600
1601 if (delpol) {
1602 xfrm_policy_requeue(delpol, policy);
1603 __xfrm_policy_unlink(delpol, dir);
1604 }
1605 policy->index = delpol ? delpol->index : xfrm_gen_index(net, dir, policy->index);
1606 hlist_add_head(&policy->byidx, net->xfrm.policy_byidx+idx_hash(net, policy->index));
1607 policy->curlft.add_time = ktime_get_real_seconds();
1608 policy->curlft.use_time = 0;
1609 if (!mod_timer(&policy->timer, jiffies + HZ))
1610 xfrm_pol_hold(policy);
1611 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1612
1613 if (delpol)
1614 xfrm_policy_kill(delpol);
1615 else if (xfrm_bydst_should_resize(net, dir, NULL))
1616 schedule_work(&net->xfrm.policy_hash_work);
1617
1618 return 0;
1619 }
1620 EXPORT_SYMBOL(xfrm_policy_insert);
1621
1622 static struct xfrm_policy *
__xfrm_policy_bysel_ctx(struct hlist_head * chain,const struct xfrm_mark * mark,u32 if_id,u8 type,int dir,struct xfrm_selector * sel,struct xfrm_sec_ctx * ctx)1623 __xfrm_policy_bysel_ctx(struct hlist_head *chain, const struct xfrm_mark *mark,
1624 u32 if_id, u8 type, int dir, struct xfrm_selector *sel,
1625 struct xfrm_sec_ctx *ctx)
1626 {
1627 struct xfrm_policy *pol;
1628
1629 if (!chain)
1630 return NULL;
1631
1632 hlist_for_each_entry(pol, chain, bydst) {
1633 if (pol->type == type &&
1634 pol->if_id == if_id &&
1635 xfrm_policy_mark_match(mark, pol) &&
1636 !selector_cmp(sel, &pol->selector) &&
1637 xfrm_sec_ctx_match(ctx, pol->security))
1638 return pol;
1639 }
1640
1641 return NULL;
1642 }
1643
1644 struct xfrm_policy *
xfrm_policy_bysel_ctx(struct net * net,const struct xfrm_mark * mark,u32 if_id,u8 type,int dir,struct xfrm_selector * sel,struct xfrm_sec_ctx * ctx,int delete,int * err)1645 xfrm_policy_bysel_ctx(struct net *net, const struct xfrm_mark *mark, u32 if_id,
1646 u8 type, int dir, struct xfrm_selector *sel,
1647 struct xfrm_sec_ctx *ctx, int delete, int *err)
1648 {
1649 struct xfrm_pol_inexact_bin *bin = NULL;
1650 struct xfrm_policy *pol, *ret = NULL;
1651 struct hlist_head *chain;
1652
1653 *err = 0;
1654 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1655 chain = policy_hash_bysel(net, sel, sel->family, dir);
1656 if (!chain) {
1657 struct xfrm_pol_inexact_candidates cand;
1658 int i;
1659
1660 bin = xfrm_policy_inexact_lookup(net, type,
1661 sel->family, dir, if_id);
1662 if (!bin) {
1663 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1664 return NULL;
1665 }
1666
1667 if (!xfrm_policy_find_inexact_candidates(&cand, bin,
1668 &sel->saddr,
1669 &sel->daddr)) {
1670 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1671 return NULL;
1672 }
1673
1674 pol = NULL;
1675 for (i = 0; i < ARRAY_SIZE(cand.res); i++) {
1676 struct xfrm_policy *tmp;
1677
1678 tmp = __xfrm_policy_bysel_ctx(cand.res[i], mark,
1679 if_id, type, dir,
1680 sel, ctx);
1681 if (!tmp)
1682 continue;
1683
1684 if (!pol || tmp->pos < pol->pos)
1685 pol = tmp;
1686 }
1687 } else {
1688 pol = __xfrm_policy_bysel_ctx(chain, mark, if_id, type, dir,
1689 sel, ctx);
1690 }
1691
1692 if (pol) {
1693 xfrm_pol_hold(pol);
1694 if (delete) {
1695 *err = security_xfrm_policy_delete(pol->security);
1696 if (*err) {
1697 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1698 return pol;
1699 }
1700 __xfrm_policy_unlink(pol, dir);
1701 }
1702 ret = pol;
1703 }
1704 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1705
1706 if (ret && delete)
1707 xfrm_policy_kill(ret);
1708 if (bin && delete)
1709 xfrm_policy_inexact_prune_bin(bin);
1710 return ret;
1711 }
1712 EXPORT_SYMBOL(xfrm_policy_bysel_ctx);
1713
1714 struct xfrm_policy *
xfrm_policy_byid(struct net * net,const struct xfrm_mark * mark,u32 if_id,u8 type,int dir,u32 id,int delete,int * err)1715 xfrm_policy_byid(struct net *net, const struct xfrm_mark *mark, u32 if_id,
1716 u8 type, int dir, u32 id, int delete, int *err)
1717 {
1718 struct xfrm_policy *pol, *ret;
1719 struct hlist_head *chain;
1720
1721 *err = -ENOENT;
1722 if (xfrm_policy_id2dir(id) != dir)
1723 return NULL;
1724
1725 *err = 0;
1726 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1727 chain = net->xfrm.policy_byidx + idx_hash(net, id);
1728 ret = NULL;
1729 hlist_for_each_entry(pol, chain, byidx) {
1730 if (pol->type == type && pol->index == id &&
1731 pol->if_id == if_id && xfrm_policy_mark_match(mark, pol)) {
1732 xfrm_pol_hold(pol);
1733 if (delete) {
1734 *err = security_xfrm_policy_delete(
1735 pol->security);
1736 if (*err) {
1737 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1738 return pol;
1739 }
1740 __xfrm_policy_unlink(pol, dir);
1741 }
1742 ret = pol;
1743 break;
1744 }
1745 }
1746 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1747
1748 if (ret && delete)
1749 xfrm_policy_kill(ret);
1750 return ret;
1751 }
1752 EXPORT_SYMBOL(xfrm_policy_byid);
1753
1754 #ifdef CONFIG_SECURITY_NETWORK_XFRM
1755 static inline int
xfrm_policy_flush_secctx_check(struct net * net,u8 type,bool task_valid)1756 xfrm_policy_flush_secctx_check(struct net *net, u8 type, bool task_valid)
1757 {
1758 struct xfrm_policy *pol;
1759 int err = 0;
1760
1761 list_for_each_entry(pol, &net->xfrm.policy_all, walk.all) {
1762 if (pol->walk.dead ||
1763 xfrm_policy_id2dir(pol->index) >= XFRM_POLICY_MAX ||
1764 pol->type != type)
1765 continue;
1766
1767 err = security_xfrm_policy_delete(pol->security);
1768 if (err) {
1769 xfrm_audit_policy_delete(pol, 0, task_valid);
1770 return err;
1771 }
1772 }
1773 return err;
1774 }
1775 #else
1776 static inline int
xfrm_policy_flush_secctx_check(struct net * net,u8 type,bool task_valid)1777 xfrm_policy_flush_secctx_check(struct net *net, u8 type, bool task_valid)
1778 {
1779 return 0;
1780 }
1781 #endif
1782
xfrm_policy_flush(struct net * net,u8 type,bool task_valid)1783 int xfrm_policy_flush(struct net *net, u8 type, bool task_valid)
1784 {
1785 int dir, err = 0, cnt = 0;
1786 struct xfrm_policy *pol;
1787
1788 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1789
1790 err = xfrm_policy_flush_secctx_check(net, type, task_valid);
1791 if (err)
1792 goto out;
1793
1794 again:
1795 list_for_each_entry(pol, &net->xfrm.policy_all, walk.all) {
1796 if (pol->walk.dead)
1797 continue;
1798
1799 dir = xfrm_policy_id2dir(pol->index);
1800 if (dir >= XFRM_POLICY_MAX ||
1801 pol->type != type)
1802 continue;
1803
1804 __xfrm_policy_unlink(pol, dir);
1805 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1806 cnt++;
1807 xfrm_audit_policy_delete(pol, 1, task_valid);
1808 xfrm_policy_kill(pol);
1809 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1810 goto again;
1811 }
1812 if (cnt)
1813 __xfrm_policy_inexact_flush(net);
1814 else
1815 err = -ESRCH;
1816 out:
1817 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1818 return err;
1819 }
1820 EXPORT_SYMBOL(xfrm_policy_flush);
1821
xfrm_policy_walk(struct net * net,struct xfrm_policy_walk * walk,int (* func)(struct xfrm_policy *,int,int,void *),void * data)1822 int xfrm_policy_walk(struct net *net, struct xfrm_policy_walk *walk,
1823 int (*func)(struct xfrm_policy *, int, int, void*),
1824 void *data)
1825 {
1826 struct xfrm_policy *pol;
1827 struct xfrm_policy_walk_entry *x;
1828 int error = 0;
1829
1830 if (walk->type >= XFRM_POLICY_TYPE_MAX &&
1831 walk->type != XFRM_POLICY_TYPE_ANY)
1832 return -EINVAL;
1833
1834 if (list_empty(&walk->walk.all) && walk->seq != 0)
1835 return 0;
1836
1837 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
1838 if (list_empty(&walk->walk.all))
1839 x = list_first_entry(&net->xfrm.policy_all, struct xfrm_policy_walk_entry, all);
1840 else
1841 x = list_first_entry(&walk->walk.all,
1842 struct xfrm_policy_walk_entry, all);
1843
1844 list_for_each_entry_from(x, &net->xfrm.policy_all, all) {
1845 if (x->dead)
1846 continue;
1847 pol = container_of(x, struct xfrm_policy, walk);
1848 if (walk->type != XFRM_POLICY_TYPE_ANY &&
1849 walk->type != pol->type)
1850 continue;
1851 error = func(pol, xfrm_policy_id2dir(pol->index),
1852 walk->seq, data);
1853 if (error) {
1854 list_move_tail(&walk->walk.all, &x->all);
1855 goto out;
1856 }
1857 walk->seq++;
1858 }
1859 if (walk->seq == 0) {
1860 error = -ENOENT;
1861 goto out;
1862 }
1863 list_del_init(&walk->walk.all);
1864 out:
1865 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1866 return error;
1867 }
1868 EXPORT_SYMBOL(xfrm_policy_walk);
1869
xfrm_policy_walk_init(struct xfrm_policy_walk * walk,u8 type)1870 void xfrm_policy_walk_init(struct xfrm_policy_walk *walk, u8 type)
1871 {
1872 INIT_LIST_HEAD(&walk->walk.all);
1873 walk->walk.dead = 1;
1874 walk->type = type;
1875 walk->seq = 0;
1876 }
1877 EXPORT_SYMBOL(xfrm_policy_walk_init);
1878
xfrm_policy_walk_done(struct xfrm_policy_walk * walk,struct net * net)1879 void xfrm_policy_walk_done(struct xfrm_policy_walk *walk, struct net *net)
1880 {
1881 if (list_empty(&walk->walk.all))
1882 return;
1883
1884 spin_lock_bh(&net->xfrm.xfrm_policy_lock); /*FIXME where is net? */
1885 list_del(&walk->walk.all);
1886 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
1887 }
1888 EXPORT_SYMBOL(xfrm_policy_walk_done);
1889
1890 /*
1891 * Find policy to apply to this flow.
1892 *
1893 * Returns 0 if policy found, else an -errno.
1894 */
xfrm_policy_match(const struct xfrm_policy * pol,const struct flowi * fl,u8 type,u16 family,u32 if_id)1895 static int xfrm_policy_match(const struct xfrm_policy *pol,
1896 const struct flowi *fl,
1897 u8 type, u16 family, u32 if_id)
1898 {
1899 const struct xfrm_selector *sel = &pol->selector;
1900 int ret = -ESRCH;
1901 bool match;
1902
1903 if (pol->family != family ||
1904 pol->if_id != if_id ||
1905 (fl->flowi_mark & pol->mark.m) != pol->mark.v ||
1906 pol->type != type)
1907 return ret;
1908
1909 match = xfrm_selector_match(sel, fl, family);
1910 if (match)
1911 ret = security_xfrm_policy_lookup(pol->security, fl->flowi_secid);
1912 return ret;
1913 }
1914
1915 static struct xfrm_pol_inexact_node *
xfrm_policy_lookup_inexact_addr(const struct rb_root * r,seqcount_spinlock_t * count,const xfrm_address_t * addr,u16 family)1916 xfrm_policy_lookup_inexact_addr(const struct rb_root *r,
1917 seqcount_spinlock_t *count,
1918 const xfrm_address_t *addr, u16 family)
1919 {
1920 const struct rb_node *parent;
1921 int seq;
1922
1923 again:
1924 seq = read_seqcount_begin(count);
1925
1926 parent = rcu_dereference_raw(r->rb_node);
1927 while (parent) {
1928 struct xfrm_pol_inexact_node *node;
1929 int delta;
1930
1931 node = rb_entry(parent, struct xfrm_pol_inexact_node, node);
1932
1933 delta = xfrm_policy_addr_delta(addr, &node->addr,
1934 node->prefixlen, family);
1935 if (delta < 0) {
1936 parent = rcu_dereference_raw(parent->rb_left);
1937 continue;
1938 } else if (delta > 0) {
1939 parent = rcu_dereference_raw(parent->rb_right);
1940 continue;
1941 }
1942
1943 return node;
1944 }
1945
1946 if (read_seqcount_retry(count, seq))
1947 goto again;
1948
1949 return NULL;
1950 }
1951
1952 static bool
xfrm_policy_find_inexact_candidates(struct xfrm_pol_inexact_candidates * cand,struct xfrm_pol_inexact_bin * b,const xfrm_address_t * saddr,const xfrm_address_t * daddr)1953 xfrm_policy_find_inexact_candidates(struct xfrm_pol_inexact_candidates *cand,
1954 struct xfrm_pol_inexact_bin *b,
1955 const xfrm_address_t *saddr,
1956 const xfrm_address_t *daddr)
1957 {
1958 struct xfrm_pol_inexact_node *n;
1959 u16 family;
1960
1961 if (!b)
1962 return false;
1963
1964 family = b->k.family;
1965 memset(cand, 0, sizeof(*cand));
1966 cand->res[XFRM_POL_CAND_ANY] = &b->hhead;
1967
1968 n = xfrm_policy_lookup_inexact_addr(&b->root_d, &b->count, daddr,
1969 family);
1970 if (n) {
1971 cand->res[XFRM_POL_CAND_DADDR] = &n->hhead;
1972 n = xfrm_policy_lookup_inexact_addr(&n->root, &b->count, saddr,
1973 family);
1974 if (n)
1975 cand->res[XFRM_POL_CAND_BOTH] = &n->hhead;
1976 }
1977
1978 n = xfrm_policy_lookup_inexact_addr(&b->root_s, &b->count, saddr,
1979 family);
1980 if (n)
1981 cand->res[XFRM_POL_CAND_SADDR] = &n->hhead;
1982
1983 return true;
1984 }
1985
1986 static struct xfrm_pol_inexact_bin *
xfrm_policy_inexact_lookup_rcu(struct net * net,u8 type,u16 family,u8 dir,u32 if_id)1987 xfrm_policy_inexact_lookup_rcu(struct net *net, u8 type, u16 family,
1988 u8 dir, u32 if_id)
1989 {
1990 struct xfrm_pol_inexact_key k = {
1991 .family = family,
1992 .type = type,
1993 .dir = dir,
1994 .if_id = if_id,
1995 };
1996
1997 write_pnet(&k.net, net);
1998
1999 return rhashtable_lookup(&xfrm_policy_inexact_table, &k,
2000 xfrm_pol_inexact_params);
2001 }
2002
2003 static struct xfrm_pol_inexact_bin *
xfrm_policy_inexact_lookup(struct net * net,u8 type,u16 family,u8 dir,u32 if_id)2004 xfrm_policy_inexact_lookup(struct net *net, u8 type, u16 family,
2005 u8 dir, u32 if_id)
2006 {
2007 struct xfrm_pol_inexact_bin *bin;
2008
2009 lockdep_assert_held(&net->xfrm.xfrm_policy_lock);
2010
2011 rcu_read_lock();
2012 bin = xfrm_policy_inexact_lookup_rcu(net, type, family, dir, if_id);
2013 rcu_read_unlock();
2014
2015 return bin;
2016 }
2017
2018 static struct xfrm_policy *
__xfrm_policy_eval_candidates(struct hlist_head * chain,struct xfrm_policy * prefer,const struct flowi * fl,u8 type,u16 family,u32 if_id)2019 __xfrm_policy_eval_candidates(struct hlist_head *chain,
2020 struct xfrm_policy *prefer,
2021 const struct flowi *fl,
2022 u8 type, u16 family, u32 if_id)
2023 {
2024 u32 priority = prefer ? prefer->priority : ~0u;
2025 struct xfrm_policy *pol;
2026
2027 if (!chain)
2028 return NULL;
2029
2030 hlist_for_each_entry_rcu(pol, chain, bydst) {
2031 int err;
2032
2033 if (pol->priority > priority)
2034 break;
2035
2036 err = xfrm_policy_match(pol, fl, type, family, if_id);
2037 if (err) {
2038 if (err != -ESRCH)
2039 return ERR_PTR(err);
2040
2041 continue;
2042 }
2043
2044 if (prefer) {
2045 /* matches. Is it older than *prefer? */
2046 if (pol->priority == priority &&
2047 prefer->pos < pol->pos)
2048 return prefer;
2049 }
2050
2051 return pol;
2052 }
2053
2054 return NULL;
2055 }
2056
2057 static struct xfrm_policy *
xfrm_policy_eval_candidates(struct xfrm_pol_inexact_candidates * cand,struct xfrm_policy * prefer,const struct flowi * fl,u8 type,u16 family,u32 if_id)2058 xfrm_policy_eval_candidates(struct xfrm_pol_inexact_candidates *cand,
2059 struct xfrm_policy *prefer,
2060 const struct flowi *fl,
2061 u8 type, u16 family, u32 if_id)
2062 {
2063 struct xfrm_policy *tmp;
2064 int i;
2065
2066 for (i = 0; i < ARRAY_SIZE(cand->res); i++) {
2067 tmp = __xfrm_policy_eval_candidates(cand->res[i],
2068 prefer,
2069 fl, type, family, if_id);
2070 if (!tmp)
2071 continue;
2072
2073 if (IS_ERR(tmp))
2074 return tmp;
2075 prefer = tmp;
2076 }
2077
2078 return prefer;
2079 }
2080
xfrm_policy_lookup_bytype(struct net * net,u8 type,const struct flowi * fl,u16 family,u8 dir,u32 if_id)2081 static struct xfrm_policy *xfrm_policy_lookup_bytype(struct net *net, u8 type,
2082 const struct flowi *fl,
2083 u16 family, u8 dir,
2084 u32 if_id)
2085 {
2086 struct xfrm_pol_inexact_candidates cand;
2087 const xfrm_address_t *daddr, *saddr;
2088 struct xfrm_pol_inexact_bin *bin;
2089 struct xfrm_policy *pol, *ret;
2090 struct hlist_head *chain;
2091 unsigned int sequence;
2092 int err;
2093
2094 daddr = xfrm_flowi_daddr(fl, family);
2095 saddr = xfrm_flowi_saddr(fl, family);
2096 if (unlikely(!daddr || !saddr))
2097 return NULL;
2098
2099 rcu_read_lock();
2100 retry:
2101 do {
2102 sequence = read_seqcount_begin(&net->xfrm.xfrm_policy_hash_generation);
2103 chain = policy_hash_direct(net, daddr, saddr, family, dir);
2104 } while (read_seqcount_retry(&net->xfrm.xfrm_policy_hash_generation, sequence));
2105
2106 ret = NULL;
2107 hlist_for_each_entry_rcu(pol, chain, bydst) {
2108 err = xfrm_policy_match(pol, fl, type, family, if_id);
2109 if (err) {
2110 if (err == -ESRCH)
2111 continue;
2112 else {
2113 ret = ERR_PTR(err);
2114 goto fail;
2115 }
2116 } else {
2117 ret = pol;
2118 break;
2119 }
2120 }
2121 bin = xfrm_policy_inexact_lookup_rcu(net, type, family, dir, if_id);
2122 if (!bin || !xfrm_policy_find_inexact_candidates(&cand, bin, saddr,
2123 daddr))
2124 goto skip_inexact;
2125
2126 pol = xfrm_policy_eval_candidates(&cand, ret, fl, type,
2127 family, if_id);
2128 if (pol) {
2129 ret = pol;
2130 if (IS_ERR(pol))
2131 goto fail;
2132 }
2133
2134 skip_inexact:
2135 if (read_seqcount_retry(&net->xfrm.xfrm_policy_hash_generation, sequence))
2136 goto retry;
2137
2138 if (ret && !xfrm_pol_hold_rcu(ret))
2139 goto retry;
2140 fail:
2141 rcu_read_unlock();
2142
2143 return ret;
2144 }
2145
xfrm_policy_lookup(struct net * net,const struct flowi * fl,u16 family,u8 dir,u32 if_id)2146 static struct xfrm_policy *xfrm_policy_lookup(struct net *net,
2147 const struct flowi *fl,
2148 u16 family, u8 dir, u32 if_id)
2149 {
2150 #ifdef CONFIG_XFRM_SUB_POLICY
2151 struct xfrm_policy *pol;
2152
2153 pol = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_SUB, fl, family,
2154 dir, if_id);
2155 if (pol != NULL)
2156 return pol;
2157 #endif
2158 return xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN, fl, family,
2159 dir, if_id);
2160 }
2161
xfrm_sk_policy_lookup(const struct sock * sk,int dir,const struct flowi * fl,u16 family,u32 if_id)2162 static struct xfrm_policy *xfrm_sk_policy_lookup(const struct sock *sk, int dir,
2163 const struct flowi *fl,
2164 u16 family, u32 if_id)
2165 {
2166 struct xfrm_policy *pol;
2167
2168 rcu_read_lock();
2169 again:
2170 pol = rcu_dereference(sk->sk_policy[dir]);
2171 if (pol != NULL) {
2172 bool match;
2173 int err = 0;
2174
2175 if (pol->family != family) {
2176 pol = NULL;
2177 goto out;
2178 }
2179
2180 match = xfrm_selector_match(&pol->selector, fl, family);
2181 if (match) {
2182 if ((READ_ONCE(sk->sk_mark) & pol->mark.m) != pol->mark.v ||
2183 pol->if_id != if_id) {
2184 pol = NULL;
2185 goto out;
2186 }
2187 err = security_xfrm_policy_lookup(pol->security,
2188 fl->flowi_secid);
2189 if (!err) {
2190 if (!xfrm_pol_hold_rcu(pol))
2191 goto again;
2192 } else if (err == -ESRCH) {
2193 pol = NULL;
2194 } else {
2195 pol = ERR_PTR(err);
2196 }
2197 } else
2198 pol = NULL;
2199 }
2200 out:
2201 rcu_read_unlock();
2202 return pol;
2203 }
2204
__xfrm_policy_link(struct xfrm_policy * pol,int dir)2205 static void __xfrm_policy_link(struct xfrm_policy *pol, int dir)
2206 {
2207 struct net *net = xp_net(pol);
2208
2209 list_add(&pol->walk.all, &net->xfrm.policy_all);
2210 net->xfrm.policy_count[dir]++;
2211 xfrm_pol_hold(pol);
2212 }
2213
__xfrm_policy_unlink(struct xfrm_policy * pol,int dir)2214 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
2215 int dir)
2216 {
2217 struct net *net = xp_net(pol);
2218
2219 if (list_empty(&pol->walk.all))
2220 return NULL;
2221
2222 /* Socket policies are not hashed. */
2223 if (!hlist_unhashed(&pol->bydst)) {
2224 hlist_del_rcu(&pol->bydst);
2225 hlist_del_init(&pol->bydst_inexact_list);
2226 hlist_del(&pol->byidx);
2227 }
2228
2229 list_del_init(&pol->walk.all);
2230 net->xfrm.policy_count[dir]--;
2231
2232 return pol;
2233 }
2234
xfrm_sk_policy_link(struct xfrm_policy * pol,int dir)2235 static void xfrm_sk_policy_link(struct xfrm_policy *pol, int dir)
2236 {
2237 __xfrm_policy_link(pol, XFRM_POLICY_MAX + dir);
2238 }
2239
xfrm_sk_policy_unlink(struct xfrm_policy * pol,int dir)2240 static void xfrm_sk_policy_unlink(struct xfrm_policy *pol, int dir)
2241 {
2242 __xfrm_policy_unlink(pol, XFRM_POLICY_MAX + dir);
2243 }
2244
xfrm_policy_delete(struct xfrm_policy * pol,int dir)2245 int xfrm_policy_delete(struct xfrm_policy *pol, int dir)
2246 {
2247 struct net *net = xp_net(pol);
2248
2249 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
2250 pol = __xfrm_policy_unlink(pol, dir);
2251 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
2252 if (pol) {
2253 xfrm_policy_kill(pol);
2254 return 0;
2255 }
2256 return -ENOENT;
2257 }
2258 EXPORT_SYMBOL(xfrm_policy_delete);
2259
xfrm_sk_policy_insert(struct sock * sk,int dir,struct xfrm_policy * pol)2260 int xfrm_sk_policy_insert(struct sock *sk, int dir, struct xfrm_policy *pol)
2261 {
2262 struct net *net = sock_net(sk);
2263 struct xfrm_policy *old_pol;
2264
2265 #ifdef CONFIG_XFRM_SUB_POLICY
2266 if (pol && pol->type != XFRM_POLICY_TYPE_MAIN)
2267 return -EINVAL;
2268 #endif
2269
2270 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
2271 old_pol = rcu_dereference_protected(sk->sk_policy[dir],
2272 lockdep_is_held(&net->xfrm.xfrm_policy_lock));
2273 if (pol) {
2274 pol->curlft.add_time = ktime_get_real_seconds();
2275 pol->index = xfrm_gen_index(net, XFRM_POLICY_MAX+dir, 0);
2276 xfrm_sk_policy_link(pol, dir);
2277 }
2278 rcu_assign_pointer(sk->sk_policy[dir], pol);
2279 if (old_pol) {
2280 if (pol)
2281 xfrm_policy_requeue(old_pol, pol);
2282
2283 /* Unlinking succeeds always. This is the only function
2284 * allowed to delete or replace socket policy.
2285 */
2286 xfrm_sk_policy_unlink(old_pol, dir);
2287 }
2288 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
2289
2290 if (old_pol) {
2291 xfrm_policy_kill(old_pol);
2292 }
2293 return 0;
2294 }
2295
clone_policy(const struct xfrm_policy * old,int dir)2296 static struct xfrm_policy *clone_policy(const struct xfrm_policy *old, int dir)
2297 {
2298 struct xfrm_policy *newp = xfrm_policy_alloc(xp_net(old), GFP_ATOMIC);
2299 struct net *net = xp_net(old);
2300
2301 if (newp) {
2302 newp->selector = old->selector;
2303 if (security_xfrm_policy_clone(old->security,
2304 &newp->security)) {
2305 kfree(newp);
2306 return NULL; /* ENOMEM */
2307 }
2308 newp->lft = old->lft;
2309 newp->curlft = old->curlft;
2310 newp->mark = old->mark;
2311 newp->if_id = old->if_id;
2312 newp->action = old->action;
2313 newp->flags = old->flags;
2314 newp->xfrm_nr = old->xfrm_nr;
2315 newp->index = old->index;
2316 newp->type = old->type;
2317 newp->family = old->family;
2318 memcpy(newp->xfrm_vec, old->xfrm_vec,
2319 newp->xfrm_nr*sizeof(struct xfrm_tmpl));
2320 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
2321 xfrm_sk_policy_link(newp, dir);
2322 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
2323 xfrm_pol_put(newp);
2324 }
2325 return newp;
2326 }
2327
__xfrm_sk_clone_policy(struct sock * sk,const struct sock * osk)2328 int __xfrm_sk_clone_policy(struct sock *sk, const struct sock *osk)
2329 {
2330 const struct xfrm_policy *p;
2331 struct xfrm_policy *np;
2332 int i, ret = 0;
2333
2334 rcu_read_lock();
2335 for (i = 0; i < 2; i++) {
2336 p = rcu_dereference(osk->sk_policy[i]);
2337 if (p) {
2338 np = clone_policy(p, i);
2339 if (unlikely(!np)) {
2340 ret = -ENOMEM;
2341 break;
2342 }
2343 rcu_assign_pointer(sk->sk_policy[i], np);
2344 }
2345 }
2346 rcu_read_unlock();
2347 return ret;
2348 }
2349
2350 static int
xfrm_get_saddr(struct net * net,int oif,xfrm_address_t * local,xfrm_address_t * remote,unsigned short family,u32 mark)2351 xfrm_get_saddr(struct net *net, int oif, xfrm_address_t *local,
2352 xfrm_address_t *remote, unsigned short family, u32 mark)
2353 {
2354 int err;
2355 const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
2356
2357 if (unlikely(afinfo == NULL))
2358 return -EINVAL;
2359 err = afinfo->get_saddr(net, oif, local, remote, mark);
2360 rcu_read_unlock();
2361 return err;
2362 }
2363
2364 /* Resolve list of templates for the flow, given policy. */
2365
2366 static int
xfrm_tmpl_resolve_one(struct xfrm_policy * policy,const struct flowi * fl,struct xfrm_state ** xfrm,unsigned short family)2367 xfrm_tmpl_resolve_one(struct xfrm_policy *policy, const struct flowi *fl,
2368 struct xfrm_state **xfrm, unsigned short family)
2369 {
2370 struct net *net = xp_net(policy);
2371 int nx;
2372 int i, error;
2373 xfrm_address_t *daddr = xfrm_flowi_daddr(fl, family);
2374 xfrm_address_t *saddr = xfrm_flowi_saddr(fl, family);
2375 xfrm_address_t tmp;
2376
2377 for (nx = 0, i = 0; i < policy->xfrm_nr; i++) {
2378 struct xfrm_state *x;
2379 xfrm_address_t *remote = daddr;
2380 xfrm_address_t *local = saddr;
2381 struct xfrm_tmpl *tmpl = &policy->xfrm_vec[i];
2382
2383 if (tmpl->mode == XFRM_MODE_TUNNEL ||
2384 tmpl->mode == XFRM_MODE_BEET) {
2385 remote = &tmpl->id.daddr;
2386 local = &tmpl->saddr;
2387 if (xfrm_addr_any(local, tmpl->encap_family)) {
2388 error = xfrm_get_saddr(net, fl->flowi_oif,
2389 &tmp, remote,
2390 tmpl->encap_family, 0);
2391 if (error)
2392 goto fail;
2393 local = &tmp;
2394 }
2395 }
2396
2397 x = xfrm_state_find(remote, local, fl, tmpl, policy, &error,
2398 family, policy->if_id);
2399
2400 if (x && x->km.state == XFRM_STATE_VALID) {
2401 xfrm[nx++] = x;
2402 daddr = remote;
2403 saddr = local;
2404 continue;
2405 }
2406 if (x) {
2407 error = (x->km.state == XFRM_STATE_ERROR ?
2408 -EINVAL : -EAGAIN);
2409 xfrm_state_put(x);
2410 } else if (error == -ESRCH) {
2411 error = -EAGAIN;
2412 }
2413
2414 if (!tmpl->optional)
2415 goto fail;
2416 }
2417 return nx;
2418
2419 fail:
2420 for (nx--; nx >= 0; nx--)
2421 xfrm_state_put(xfrm[nx]);
2422 return error;
2423 }
2424
2425 static int
xfrm_tmpl_resolve(struct xfrm_policy ** pols,int npols,const struct flowi * fl,struct xfrm_state ** xfrm,unsigned short family)2426 xfrm_tmpl_resolve(struct xfrm_policy **pols, int npols, const struct flowi *fl,
2427 struct xfrm_state **xfrm, unsigned short family)
2428 {
2429 struct xfrm_state *tp[XFRM_MAX_DEPTH];
2430 struct xfrm_state **tpp = (npols > 1) ? tp : xfrm;
2431 int cnx = 0;
2432 int error;
2433 int ret;
2434 int i;
2435
2436 for (i = 0; i < npols; i++) {
2437 if (cnx + pols[i]->xfrm_nr >= XFRM_MAX_DEPTH) {
2438 error = -ENOBUFS;
2439 goto fail;
2440 }
2441
2442 ret = xfrm_tmpl_resolve_one(pols[i], fl, &tpp[cnx], family);
2443 if (ret < 0) {
2444 error = ret;
2445 goto fail;
2446 } else
2447 cnx += ret;
2448 }
2449
2450 /* found states are sorted for outbound processing */
2451 if (npols > 1)
2452 xfrm_state_sort(xfrm, tpp, cnx, family);
2453
2454 return cnx;
2455
2456 fail:
2457 for (cnx--; cnx >= 0; cnx--)
2458 xfrm_state_put(tpp[cnx]);
2459 return error;
2460
2461 }
2462
xfrm_get_tos(const struct flowi * fl,int family)2463 static int xfrm_get_tos(const struct flowi *fl, int family)
2464 {
2465 if (family == AF_INET)
2466 return IPTOS_RT_MASK & fl->u.ip4.flowi4_tos;
2467
2468 return 0;
2469 }
2470
xfrm_alloc_dst(struct net * net,int family)2471 static inline struct xfrm_dst *xfrm_alloc_dst(struct net *net, int family)
2472 {
2473 const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
2474 struct dst_ops *dst_ops;
2475 struct xfrm_dst *xdst;
2476
2477 if (!afinfo)
2478 return ERR_PTR(-EINVAL);
2479
2480 switch (family) {
2481 case AF_INET:
2482 dst_ops = &net->xfrm.xfrm4_dst_ops;
2483 break;
2484 #if IS_ENABLED(CONFIG_IPV6)
2485 case AF_INET6:
2486 dst_ops = &net->xfrm.xfrm6_dst_ops;
2487 break;
2488 #endif
2489 default:
2490 BUG();
2491 }
2492 xdst = dst_alloc(dst_ops, NULL, 1, DST_OBSOLETE_NONE, 0);
2493
2494 if (likely(xdst)) {
2495 memset_after(xdst, 0, u.dst);
2496 } else
2497 xdst = ERR_PTR(-ENOBUFS);
2498
2499 rcu_read_unlock();
2500
2501 return xdst;
2502 }
2503
xfrm_init_path(struct xfrm_dst * path,struct dst_entry * dst,int nfheader_len)2504 static void xfrm_init_path(struct xfrm_dst *path, struct dst_entry *dst,
2505 int nfheader_len)
2506 {
2507 if (dst->ops->family == AF_INET6) {
2508 struct rt6_info *rt = (struct rt6_info *)dst;
2509 path->path_cookie = rt6_get_cookie(rt);
2510 path->u.rt6.rt6i_nfheader_len = nfheader_len;
2511 }
2512 }
2513
xfrm_fill_dst(struct xfrm_dst * xdst,struct net_device * dev,const struct flowi * fl)2514 static inline int xfrm_fill_dst(struct xfrm_dst *xdst, struct net_device *dev,
2515 const struct flowi *fl)
2516 {
2517 const struct xfrm_policy_afinfo *afinfo =
2518 xfrm_policy_get_afinfo(xdst->u.dst.ops->family);
2519 int err;
2520
2521 if (!afinfo)
2522 return -EINVAL;
2523
2524 err = afinfo->fill_dst(xdst, dev, fl);
2525
2526 rcu_read_unlock();
2527
2528 return err;
2529 }
2530
2531
2532 /* Allocate chain of dst_entry's, attach known xfrm's, calculate
2533 * all the metrics... Shortly, bundle a bundle.
2534 */
2535
xfrm_bundle_create(struct xfrm_policy * policy,struct xfrm_state ** xfrm,struct xfrm_dst ** bundle,int nx,const struct flowi * fl,struct dst_entry * dst)2536 static struct dst_entry *xfrm_bundle_create(struct xfrm_policy *policy,
2537 struct xfrm_state **xfrm,
2538 struct xfrm_dst **bundle,
2539 int nx,
2540 const struct flowi *fl,
2541 struct dst_entry *dst)
2542 {
2543 const struct xfrm_state_afinfo *afinfo;
2544 const struct xfrm_mode *inner_mode;
2545 struct net *net = xp_net(policy);
2546 unsigned long now = jiffies;
2547 struct net_device *dev;
2548 struct xfrm_dst *xdst_prev = NULL;
2549 struct xfrm_dst *xdst0 = NULL;
2550 int i = 0;
2551 int err;
2552 int header_len = 0;
2553 int nfheader_len = 0;
2554 int trailer_len = 0;
2555 int tos;
2556 int family = policy->selector.family;
2557 xfrm_address_t saddr, daddr;
2558
2559 xfrm_flowi_addr_get(fl, &saddr, &daddr, family);
2560
2561 tos = xfrm_get_tos(fl, family);
2562
2563 dst_hold(dst);
2564
2565 for (; i < nx; i++) {
2566 struct xfrm_dst *xdst = xfrm_alloc_dst(net, family);
2567 struct dst_entry *dst1 = &xdst->u.dst;
2568
2569 err = PTR_ERR(xdst);
2570 if (IS_ERR(xdst)) {
2571 dst_release(dst);
2572 goto put_states;
2573 }
2574
2575 bundle[i] = xdst;
2576 if (!xdst_prev)
2577 xdst0 = xdst;
2578 else
2579 /* Ref count is taken during xfrm_alloc_dst()
2580 * No need to do dst_clone() on dst1
2581 */
2582 xfrm_dst_set_child(xdst_prev, &xdst->u.dst);
2583
2584 if (xfrm[i]->sel.family == AF_UNSPEC) {
2585 inner_mode = xfrm_ip2inner_mode(xfrm[i],
2586 xfrm_af2proto(family));
2587 if (!inner_mode) {
2588 err = -EAFNOSUPPORT;
2589 dst_release(dst);
2590 goto put_states;
2591 }
2592 } else
2593 inner_mode = &xfrm[i]->inner_mode;
2594
2595 xdst->route = dst;
2596 dst_copy_metrics(dst1, dst);
2597
2598 if (xfrm[i]->props.mode != XFRM_MODE_TRANSPORT) {
2599 __u32 mark = 0;
2600 int oif;
2601
2602 if (xfrm[i]->props.smark.v || xfrm[i]->props.smark.m)
2603 mark = xfrm_smark_get(fl->flowi_mark, xfrm[i]);
2604
2605 family = xfrm[i]->props.family;
2606 oif = fl->flowi_oif ? : fl->flowi_l3mdev;
2607 dst = xfrm_dst_lookup(xfrm[i], tos, oif,
2608 &saddr, &daddr, family, mark);
2609 err = PTR_ERR(dst);
2610 if (IS_ERR(dst))
2611 goto put_states;
2612 } else
2613 dst_hold(dst);
2614
2615 dst1->xfrm = xfrm[i];
2616 xdst->xfrm_genid = xfrm[i]->genid;
2617
2618 dst1->obsolete = DST_OBSOLETE_FORCE_CHK;
2619 dst1->lastuse = now;
2620
2621 dst1->input = dst_discard;
2622
2623 rcu_read_lock();
2624 afinfo = xfrm_state_afinfo_get_rcu(inner_mode->family);
2625 if (likely(afinfo))
2626 dst1->output = afinfo->output;
2627 else
2628 dst1->output = dst_discard_out;
2629 rcu_read_unlock();
2630
2631 xdst_prev = xdst;
2632
2633 header_len += xfrm[i]->props.header_len;
2634 if (xfrm[i]->type->flags & XFRM_TYPE_NON_FRAGMENT)
2635 nfheader_len += xfrm[i]->props.header_len;
2636 trailer_len += xfrm[i]->props.trailer_len;
2637 }
2638
2639 xfrm_dst_set_child(xdst_prev, dst);
2640 xdst0->path = dst;
2641
2642 err = -ENODEV;
2643 dev = dst->dev;
2644 if (!dev)
2645 goto free_dst;
2646
2647 xfrm_init_path(xdst0, dst, nfheader_len);
2648 xfrm_init_pmtu(bundle, nx);
2649
2650 for (xdst_prev = xdst0; xdst_prev != (struct xfrm_dst *)dst;
2651 xdst_prev = (struct xfrm_dst *) xfrm_dst_child(&xdst_prev->u.dst)) {
2652 err = xfrm_fill_dst(xdst_prev, dev, fl);
2653 if (err)
2654 goto free_dst;
2655
2656 xdst_prev->u.dst.header_len = header_len;
2657 xdst_prev->u.dst.trailer_len = trailer_len;
2658 header_len -= xdst_prev->u.dst.xfrm->props.header_len;
2659 trailer_len -= xdst_prev->u.dst.xfrm->props.trailer_len;
2660 }
2661
2662 return &xdst0->u.dst;
2663
2664 put_states:
2665 for (; i < nx; i++)
2666 xfrm_state_put(xfrm[i]);
2667 free_dst:
2668 if (xdst0)
2669 dst_release_immediate(&xdst0->u.dst);
2670
2671 return ERR_PTR(err);
2672 }
2673
xfrm_expand_policies(const struct flowi * fl,u16 family,struct xfrm_policy ** pols,int * num_pols,int * num_xfrms)2674 static int xfrm_expand_policies(const struct flowi *fl, u16 family,
2675 struct xfrm_policy **pols,
2676 int *num_pols, int *num_xfrms)
2677 {
2678 int i;
2679
2680 if (*num_pols == 0 || !pols[0]) {
2681 *num_pols = 0;
2682 *num_xfrms = 0;
2683 return 0;
2684 }
2685 if (IS_ERR(pols[0])) {
2686 *num_pols = 0;
2687 return PTR_ERR(pols[0]);
2688 }
2689
2690 *num_xfrms = pols[0]->xfrm_nr;
2691
2692 #ifdef CONFIG_XFRM_SUB_POLICY
2693 if (pols[0]->action == XFRM_POLICY_ALLOW &&
2694 pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
2695 pols[1] = xfrm_policy_lookup_bytype(xp_net(pols[0]),
2696 XFRM_POLICY_TYPE_MAIN,
2697 fl, family,
2698 XFRM_POLICY_OUT,
2699 pols[0]->if_id);
2700 if (pols[1]) {
2701 if (IS_ERR(pols[1])) {
2702 xfrm_pols_put(pols, *num_pols);
2703 *num_pols = 0;
2704 return PTR_ERR(pols[1]);
2705 }
2706 (*num_pols)++;
2707 (*num_xfrms) += pols[1]->xfrm_nr;
2708 }
2709 }
2710 #endif
2711 for (i = 0; i < *num_pols; i++) {
2712 if (pols[i]->action != XFRM_POLICY_ALLOW) {
2713 *num_xfrms = -1;
2714 break;
2715 }
2716 }
2717
2718 return 0;
2719
2720 }
2721
2722 static struct xfrm_dst *
xfrm_resolve_and_create_bundle(struct xfrm_policy ** pols,int num_pols,const struct flowi * fl,u16 family,struct dst_entry * dst_orig)2723 xfrm_resolve_and_create_bundle(struct xfrm_policy **pols, int num_pols,
2724 const struct flowi *fl, u16 family,
2725 struct dst_entry *dst_orig)
2726 {
2727 struct net *net = xp_net(pols[0]);
2728 struct xfrm_state *xfrm[XFRM_MAX_DEPTH];
2729 struct xfrm_dst *bundle[XFRM_MAX_DEPTH];
2730 struct xfrm_dst *xdst;
2731 struct dst_entry *dst;
2732 int err;
2733
2734 /* Try to instantiate a bundle */
2735 err = xfrm_tmpl_resolve(pols, num_pols, fl, xfrm, family);
2736 if (err <= 0) {
2737 if (err == 0)
2738 return NULL;
2739
2740 if (err != -EAGAIN)
2741 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
2742 return ERR_PTR(err);
2743 }
2744
2745 dst = xfrm_bundle_create(pols[0], xfrm, bundle, err, fl, dst_orig);
2746 if (IS_ERR(dst)) {
2747 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTBUNDLEGENERROR);
2748 return ERR_CAST(dst);
2749 }
2750
2751 xdst = (struct xfrm_dst *)dst;
2752 xdst->num_xfrms = err;
2753 xdst->num_pols = num_pols;
2754 memcpy(xdst->pols, pols, sizeof(struct xfrm_policy *) * num_pols);
2755 xdst->policy_genid = atomic_read(&pols[0]->genid);
2756
2757 return xdst;
2758 }
2759
xfrm_policy_queue_process(struct timer_list * t)2760 static void xfrm_policy_queue_process(struct timer_list *t)
2761 {
2762 struct sk_buff *skb;
2763 struct sock *sk;
2764 struct dst_entry *dst;
2765 struct xfrm_policy *pol = from_timer(pol, t, polq.hold_timer);
2766 struct net *net = xp_net(pol);
2767 struct xfrm_policy_queue *pq = &pol->polq;
2768 struct flowi fl;
2769 struct sk_buff_head list;
2770 __u32 skb_mark;
2771
2772 spin_lock(&pq->hold_queue.lock);
2773 skb = skb_peek(&pq->hold_queue);
2774 if (!skb) {
2775 spin_unlock(&pq->hold_queue.lock);
2776 goto out;
2777 }
2778 dst = skb_dst(skb);
2779 sk = skb->sk;
2780
2781 /* Fixup the mark to support VTI. */
2782 skb_mark = skb->mark;
2783 skb->mark = pol->mark.v;
2784 xfrm_decode_session(skb, &fl, dst->ops->family);
2785 skb->mark = skb_mark;
2786 spin_unlock(&pq->hold_queue.lock);
2787
2788 dst_hold(xfrm_dst_path(dst));
2789 dst = xfrm_lookup(net, xfrm_dst_path(dst), &fl, sk, XFRM_LOOKUP_QUEUE);
2790 if (IS_ERR(dst))
2791 goto purge_queue;
2792
2793 if (dst->flags & DST_XFRM_QUEUE) {
2794 dst_release(dst);
2795
2796 if (pq->timeout >= XFRM_QUEUE_TMO_MAX)
2797 goto purge_queue;
2798
2799 pq->timeout = pq->timeout << 1;
2800 if (!mod_timer(&pq->hold_timer, jiffies + pq->timeout))
2801 xfrm_pol_hold(pol);
2802 goto out;
2803 }
2804
2805 dst_release(dst);
2806
2807 __skb_queue_head_init(&list);
2808
2809 spin_lock(&pq->hold_queue.lock);
2810 pq->timeout = 0;
2811 skb_queue_splice_init(&pq->hold_queue, &list);
2812 spin_unlock(&pq->hold_queue.lock);
2813
2814 while (!skb_queue_empty(&list)) {
2815 skb = __skb_dequeue(&list);
2816
2817 /* Fixup the mark to support VTI. */
2818 skb_mark = skb->mark;
2819 skb->mark = pol->mark.v;
2820 xfrm_decode_session(skb, &fl, skb_dst(skb)->ops->family);
2821 skb->mark = skb_mark;
2822
2823 dst_hold(xfrm_dst_path(skb_dst(skb)));
2824 dst = xfrm_lookup(net, xfrm_dst_path(skb_dst(skb)), &fl, skb->sk, 0);
2825 if (IS_ERR(dst)) {
2826 kfree_skb(skb);
2827 continue;
2828 }
2829
2830 nf_reset_ct(skb);
2831 skb_dst_drop(skb);
2832 skb_dst_set(skb, dst);
2833
2834 dst_output(net, skb->sk, skb);
2835 }
2836
2837 out:
2838 xfrm_pol_put(pol);
2839 return;
2840
2841 purge_queue:
2842 pq->timeout = 0;
2843 skb_queue_purge(&pq->hold_queue);
2844 xfrm_pol_put(pol);
2845 }
2846
xdst_queue_output(struct net * net,struct sock * sk,struct sk_buff * skb)2847 static int xdst_queue_output(struct net *net, struct sock *sk, struct sk_buff *skb)
2848 {
2849 unsigned long sched_next;
2850 struct dst_entry *dst = skb_dst(skb);
2851 struct xfrm_dst *xdst = (struct xfrm_dst *) dst;
2852 struct xfrm_policy *pol = xdst->pols[0];
2853 struct xfrm_policy_queue *pq = &pol->polq;
2854
2855 if (unlikely(skb_fclone_busy(sk, skb))) {
2856 kfree_skb(skb);
2857 return 0;
2858 }
2859
2860 if (pq->hold_queue.qlen > XFRM_MAX_QUEUE_LEN) {
2861 kfree_skb(skb);
2862 return -EAGAIN;
2863 }
2864
2865 skb_dst_force(skb);
2866
2867 spin_lock_bh(&pq->hold_queue.lock);
2868
2869 if (!pq->timeout)
2870 pq->timeout = XFRM_QUEUE_TMO_MIN;
2871
2872 sched_next = jiffies + pq->timeout;
2873
2874 if (del_timer(&pq->hold_timer)) {
2875 if (time_before(pq->hold_timer.expires, sched_next))
2876 sched_next = pq->hold_timer.expires;
2877 xfrm_pol_put(pol);
2878 }
2879
2880 __skb_queue_tail(&pq->hold_queue, skb);
2881 if (!mod_timer(&pq->hold_timer, sched_next))
2882 xfrm_pol_hold(pol);
2883
2884 spin_unlock_bh(&pq->hold_queue.lock);
2885
2886 return 0;
2887 }
2888
xfrm_create_dummy_bundle(struct net * net,struct xfrm_flo * xflo,const struct flowi * fl,int num_xfrms,u16 family)2889 static struct xfrm_dst *xfrm_create_dummy_bundle(struct net *net,
2890 struct xfrm_flo *xflo,
2891 const struct flowi *fl,
2892 int num_xfrms,
2893 u16 family)
2894 {
2895 int err;
2896 struct net_device *dev;
2897 struct dst_entry *dst;
2898 struct dst_entry *dst1;
2899 struct xfrm_dst *xdst;
2900
2901 xdst = xfrm_alloc_dst(net, family);
2902 if (IS_ERR(xdst))
2903 return xdst;
2904
2905 if (!(xflo->flags & XFRM_LOOKUP_QUEUE) ||
2906 net->xfrm.sysctl_larval_drop ||
2907 num_xfrms <= 0)
2908 return xdst;
2909
2910 dst = xflo->dst_orig;
2911 dst1 = &xdst->u.dst;
2912 dst_hold(dst);
2913 xdst->route = dst;
2914
2915 dst_copy_metrics(dst1, dst);
2916
2917 dst1->obsolete = DST_OBSOLETE_FORCE_CHK;
2918 dst1->flags |= DST_XFRM_QUEUE;
2919 dst1->lastuse = jiffies;
2920
2921 dst1->input = dst_discard;
2922 dst1->output = xdst_queue_output;
2923
2924 dst_hold(dst);
2925 xfrm_dst_set_child(xdst, dst);
2926 xdst->path = dst;
2927
2928 xfrm_init_path((struct xfrm_dst *)dst1, dst, 0);
2929
2930 err = -ENODEV;
2931 dev = dst->dev;
2932 if (!dev)
2933 goto free_dst;
2934
2935 err = xfrm_fill_dst(xdst, dev, fl);
2936 if (err)
2937 goto free_dst;
2938
2939 out:
2940 return xdst;
2941
2942 free_dst:
2943 dst_release(dst1);
2944 xdst = ERR_PTR(err);
2945 goto out;
2946 }
2947
xfrm_bundle_lookup(struct net * net,const struct flowi * fl,u16 family,u8 dir,struct xfrm_flo * xflo,u32 if_id)2948 static struct xfrm_dst *xfrm_bundle_lookup(struct net *net,
2949 const struct flowi *fl,
2950 u16 family, u8 dir,
2951 struct xfrm_flo *xflo, u32 if_id)
2952 {
2953 struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
2954 int num_pols = 0, num_xfrms = 0, err;
2955 struct xfrm_dst *xdst;
2956
2957 /* Resolve policies to use if we couldn't get them from
2958 * previous cache entry */
2959 num_pols = 1;
2960 pols[0] = xfrm_policy_lookup(net, fl, family, dir, if_id);
2961 err = xfrm_expand_policies(fl, family, pols,
2962 &num_pols, &num_xfrms);
2963 if (err < 0)
2964 goto inc_error;
2965 if (num_pols == 0)
2966 return NULL;
2967 if (num_xfrms <= 0)
2968 goto make_dummy_bundle;
2969
2970 xdst = xfrm_resolve_and_create_bundle(pols, num_pols, fl, family,
2971 xflo->dst_orig);
2972 if (IS_ERR(xdst)) {
2973 err = PTR_ERR(xdst);
2974 if (err == -EREMOTE) {
2975 xfrm_pols_put(pols, num_pols);
2976 return NULL;
2977 }
2978
2979 if (err != -EAGAIN)
2980 goto error;
2981 goto make_dummy_bundle;
2982 } else if (xdst == NULL) {
2983 num_xfrms = 0;
2984 goto make_dummy_bundle;
2985 }
2986
2987 return xdst;
2988
2989 make_dummy_bundle:
2990 /* We found policies, but there's no bundles to instantiate:
2991 * either because the policy blocks, has no transformations or
2992 * we could not build template (no xfrm_states).*/
2993 xdst = xfrm_create_dummy_bundle(net, xflo, fl, num_xfrms, family);
2994 if (IS_ERR(xdst)) {
2995 xfrm_pols_put(pols, num_pols);
2996 return ERR_CAST(xdst);
2997 }
2998 xdst->num_pols = num_pols;
2999 xdst->num_xfrms = num_xfrms;
3000 memcpy(xdst->pols, pols, sizeof(struct xfrm_policy *) * num_pols);
3001
3002 return xdst;
3003
3004 inc_error:
3005 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLERROR);
3006 error:
3007 xfrm_pols_put(pols, num_pols);
3008 return ERR_PTR(err);
3009 }
3010
make_blackhole(struct net * net,u16 family,struct dst_entry * dst_orig)3011 static struct dst_entry *make_blackhole(struct net *net, u16 family,
3012 struct dst_entry *dst_orig)
3013 {
3014 const struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
3015 struct dst_entry *ret;
3016
3017 if (!afinfo) {
3018 dst_release(dst_orig);
3019 return ERR_PTR(-EINVAL);
3020 } else {
3021 ret = afinfo->blackhole_route(net, dst_orig);
3022 }
3023 rcu_read_unlock();
3024
3025 return ret;
3026 }
3027
3028 /* Finds/creates a bundle for given flow and if_id
3029 *
3030 * At the moment we eat a raw IP route. Mostly to speed up lookups
3031 * on interfaces with disabled IPsec.
3032 *
3033 * xfrm_lookup uses an if_id of 0 by default, and is provided for
3034 * compatibility
3035 */
xfrm_lookup_with_ifid(struct net * net,struct dst_entry * dst_orig,const struct flowi * fl,const struct sock * sk,int flags,u32 if_id)3036 struct dst_entry *xfrm_lookup_with_ifid(struct net *net,
3037 struct dst_entry *dst_orig,
3038 const struct flowi *fl,
3039 const struct sock *sk,
3040 int flags, u32 if_id)
3041 {
3042 struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
3043 struct xfrm_dst *xdst;
3044 struct dst_entry *dst, *route;
3045 u16 family = dst_orig->ops->family;
3046 u8 dir = XFRM_POLICY_OUT;
3047 int i, err, num_pols, num_xfrms = 0, drop_pols = 0;
3048
3049 dst = NULL;
3050 xdst = NULL;
3051 route = NULL;
3052
3053 sk = sk_const_to_full_sk(sk);
3054 if (sk && sk->sk_policy[XFRM_POLICY_OUT]) {
3055 num_pols = 1;
3056 pols[0] = xfrm_sk_policy_lookup(sk, XFRM_POLICY_OUT, fl, family,
3057 if_id);
3058 err = xfrm_expand_policies(fl, family, pols,
3059 &num_pols, &num_xfrms);
3060 if (err < 0)
3061 goto dropdst;
3062
3063 if (num_pols) {
3064 if (num_xfrms <= 0) {
3065 drop_pols = num_pols;
3066 goto no_transform;
3067 }
3068
3069 xdst = xfrm_resolve_and_create_bundle(
3070 pols, num_pols, fl,
3071 family, dst_orig);
3072
3073 if (IS_ERR(xdst)) {
3074 xfrm_pols_put(pols, num_pols);
3075 err = PTR_ERR(xdst);
3076 if (err == -EREMOTE)
3077 goto nopol;
3078
3079 goto dropdst;
3080 } else if (xdst == NULL) {
3081 num_xfrms = 0;
3082 drop_pols = num_pols;
3083 goto no_transform;
3084 }
3085
3086 route = xdst->route;
3087 }
3088 }
3089
3090 if (xdst == NULL) {
3091 struct xfrm_flo xflo;
3092
3093 xflo.dst_orig = dst_orig;
3094 xflo.flags = flags;
3095
3096 /* To accelerate a bit... */
3097 if (!if_id && ((dst_orig->flags & DST_NOXFRM) ||
3098 !net->xfrm.policy_count[XFRM_POLICY_OUT]))
3099 goto nopol;
3100
3101 xdst = xfrm_bundle_lookup(net, fl, family, dir, &xflo, if_id);
3102 if (xdst == NULL)
3103 goto nopol;
3104 if (IS_ERR(xdst)) {
3105 err = PTR_ERR(xdst);
3106 goto dropdst;
3107 }
3108
3109 num_pols = xdst->num_pols;
3110 num_xfrms = xdst->num_xfrms;
3111 memcpy(pols, xdst->pols, sizeof(struct xfrm_policy *) * num_pols);
3112 route = xdst->route;
3113 }
3114
3115 dst = &xdst->u.dst;
3116 if (route == NULL && num_xfrms > 0) {
3117 /* The only case when xfrm_bundle_lookup() returns a
3118 * bundle with null route, is when the template could
3119 * not be resolved. It means policies are there, but
3120 * bundle could not be created, since we don't yet
3121 * have the xfrm_state's. We need to wait for KM to
3122 * negotiate new SA's or bail out with error.*/
3123 if (net->xfrm.sysctl_larval_drop) {
3124 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
3125 err = -EREMOTE;
3126 goto error;
3127 }
3128
3129 err = -EAGAIN;
3130
3131 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTNOSTATES);
3132 goto error;
3133 }
3134
3135 no_transform:
3136 if (num_pols == 0)
3137 goto nopol;
3138
3139 if ((flags & XFRM_LOOKUP_ICMP) &&
3140 !(pols[0]->flags & XFRM_POLICY_ICMP)) {
3141 err = -ENOENT;
3142 goto error;
3143 }
3144
3145 for (i = 0; i < num_pols; i++)
3146 WRITE_ONCE(pols[i]->curlft.use_time, ktime_get_real_seconds());
3147
3148 if (num_xfrms < 0) {
3149 /* Prohibit the flow */
3150 XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTPOLBLOCK);
3151 err = -EPERM;
3152 goto error;
3153 } else if (num_xfrms > 0) {
3154 /* Flow transformed */
3155 dst_release(dst_orig);
3156 } else {
3157 /* Flow passes untransformed */
3158 dst_release(dst);
3159 dst = dst_orig;
3160 }
3161 ok:
3162 xfrm_pols_put(pols, drop_pols);
3163 if (dst && dst->xfrm &&
3164 dst->xfrm->props.mode == XFRM_MODE_TUNNEL)
3165 dst->flags |= DST_XFRM_TUNNEL;
3166 return dst;
3167
3168 nopol:
3169 if ((!dst_orig->dev || !(dst_orig->dev->flags & IFF_LOOPBACK)) &&
3170 net->xfrm.policy_default[dir] == XFRM_USERPOLICY_BLOCK) {
3171 err = -EPERM;
3172 goto error;
3173 }
3174 if (!(flags & XFRM_LOOKUP_ICMP)) {
3175 dst = dst_orig;
3176 goto ok;
3177 }
3178 err = -ENOENT;
3179 error:
3180 dst_release(dst);
3181 dropdst:
3182 if (!(flags & XFRM_LOOKUP_KEEP_DST_REF))
3183 dst_release(dst_orig);
3184 xfrm_pols_put(pols, drop_pols);
3185 return ERR_PTR(err);
3186 }
3187 EXPORT_SYMBOL(xfrm_lookup_with_ifid);
3188
3189 /* Main function: finds/creates a bundle for given flow.
3190 *
3191 * At the moment we eat a raw IP route. Mostly to speed up lookups
3192 * on interfaces with disabled IPsec.
3193 */
xfrm_lookup(struct net * net,struct dst_entry * dst_orig,const struct flowi * fl,const struct sock * sk,int flags)3194 struct dst_entry *xfrm_lookup(struct net *net, struct dst_entry *dst_orig,
3195 const struct flowi *fl, const struct sock *sk,
3196 int flags)
3197 {
3198 return xfrm_lookup_with_ifid(net, dst_orig, fl, sk, flags, 0);
3199 }
3200 EXPORT_SYMBOL(xfrm_lookup);
3201
3202 /* Callers of xfrm_lookup_route() must ensure a call to dst_output().
3203 * Otherwise we may send out blackholed packets.
3204 */
xfrm_lookup_route(struct net * net,struct dst_entry * dst_orig,const struct flowi * fl,const struct sock * sk,int flags)3205 struct dst_entry *xfrm_lookup_route(struct net *net, struct dst_entry *dst_orig,
3206 const struct flowi *fl,
3207 const struct sock *sk, int flags)
3208 {
3209 struct dst_entry *dst = xfrm_lookup(net, dst_orig, fl, sk,
3210 flags | XFRM_LOOKUP_QUEUE |
3211 XFRM_LOOKUP_KEEP_DST_REF);
3212
3213 if (PTR_ERR(dst) == -EREMOTE)
3214 return make_blackhole(net, dst_orig->ops->family, dst_orig);
3215
3216 if (IS_ERR(dst))
3217 dst_release(dst_orig);
3218
3219 return dst;
3220 }
3221 EXPORT_SYMBOL(xfrm_lookup_route);
3222
3223 static inline int
xfrm_secpath_reject(int idx,struct sk_buff * skb,const struct flowi * fl)3224 xfrm_secpath_reject(int idx, struct sk_buff *skb, const struct flowi *fl)
3225 {
3226 struct sec_path *sp = skb_sec_path(skb);
3227 struct xfrm_state *x;
3228
3229 if (!sp || idx < 0 || idx >= sp->len)
3230 return 0;
3231 x = sp->xvec[idx];
3232 if (!x->type->reject)
3233 return 0;
3234 return x->type->reject(x, skb, fl);
3235 }
3236
3237 /* When skb is transformed back to its "native" form, we have to
3238 * check policy restrictions. At the moment we make this in maximally
3239 * stupid way. Shame on me. :-) Of course, connected sockets must
3240 * have policy cached at them.
3241 */
3242
3243 static inline int
xfrm_state_ok(const struct xfrm_tmpl * tmpl,const struct xfrm_state * x,unsigned short family,u32 if_id)3244 xfrm_state_ok(const struct xfrm_tmpl *tmpl, const struct xfrm_state *x,
3245 unsigned short family, u32 if_id)
3246 {
3247 if (xfrm_state_kern(x))
3248 return tmpl->optional && !xfrm_state_addr_cmp(tmpl, x, tmpl->encap_family);
3249 return x->id.proto == tmpl->id.proto &&
3250 (x->id.spi == tmpl->id.spi || !tmpl->id.spi) &&
3251 (x->props.reqid == tmpl->reqid || !tmpl->reqid) &&
3252 x->props.mode == tmpl->mode &&
3253 (tmpl->allalgs || (tmpl->aalgos & (1<<x->props.aalgo)) ||
3254 !(xfrm_id_proto_match(tmpl->id.proto, IPSEC_PROTO_ANY))) &&
3255 !(x->props.mode != XFRM_MODE_TRANSPORT &&
3256 xfrm_state_addr_cmp(tmpl, x, family)) &&
3257 (if_id == 0 || if_id == x->if_id);
3258 }
3259
3260 /*
3261 * 0 or more than 0 is returned when validation is succeeded (either bypass
3262 * because of optional transport mode, or next index of the matched secpath
3263 * state with the template.
3264 * -1 is returned when no matching template is found.
3265 * Otherwise "-2 - errored_index" is returned.
3266 */
3267 static inline int
xfrm_policy_ok(const struct xfrm_tmpl * tmpl,const struct sec_path * sp,int start,unsigned short family,u32 if_id)3268 xfrm_policy_ok(const struct xfrm_tmpl *tmpl, const struct sec_path *sp, int start,
3269 unsigned short family, u32 if_id)
3270 {
3271 int idx = start;
3272
3273 if (tmpl->optional) {
3274 if (tmpl->mode == XFRM_MODE_TRANSPORT)
3275 return start;
3276 } else
3277 start = -1;
3278 for (; idx < sp->len; idx++) {
3279 if (xfrm_state_ok(tmpl, sp->xvec[idx], family, if_id))
3280 return ++idx;
3281 if (sp->xvec[idx]->props.mode != XFRM_MODE_TRANSPORT) {
3282 if (idx < sp->verified_cnt) {
3283 /* Secpath entry previously verified, consider optional and
3284 * continue searching
3285 */
3286 continue;
3287 }
3288
3289 if (start == -1)
3290 start = -2-idx;
3291 break;
3292 }
3293 }
3294 return start;
3295 }
3296
3297 static void
decode_session4(struct sk_buff * skb,struct flowi * fl,bool reverse)3298 decode_session4(struct sk_buff *skb, struct flowi *fl, bool reverse)
3299 {
3300 const struct iphdr *iph = ip_hdr(skb);
3301 int ihl = iph->ihl;
3302 u8 *xprth = skb_network_header(skb) + ihl * 4;
3303 struct flowi4 *fl4 = &fl->u.ip4;
3304 int oif = 0;
3305
3306 if (skb_dst(skb) && skb_dst(skb)->dev)
3307 oif = skb_dst(skb)->dev->ifindex;
3308
3309 memset(fl4, 0, sizeof(struct flowi4));
3310 fl4->flowi4_mark = skb->mark;
3311 fl4->flowi4_oif = reverse ? skb->skb_iif : oif;
3312
3313 fl4->flowi4_proto = iph->protocol;
3314 fl4->daddr = reverse ? iph->saddr : iph->daddr;
3315 fl4->saddr = reverse ? iph->daddr : iph->saddr;
3316 fl4->flowi4_tos = iph->tos & ~INET_ECN_MASK;
3317
3318 if (!ip_is_fragment(iph)) {
3319 switch (iph->protocol) {
3320 case IPPROTO_UDP:
3321 case IPPROTO_UDPLITE:
3322 case IPPROTO_TCP:
3323 case IPPROTO_SCTP:
3324 case IPPROTO_DCCP:
3325 if (xprth + 4 < skb->data ||
3326 pskb_may_pull(skb, xprth + 4 - skb->data)) {
3327 __be16 *ports;
3328
3329 xprth = skb_network_header(skb) + ihl * 4;
3330 ports = (__be16 *)xprth;
3331
3332 fl4->fl4_sport = ports[!!reverse];
3333 fl4->fl4_dport = ports[!reverse];
3334 }
3335 break;
3336 case IPPROTO_ICMP:
3337 if (xprth + 2 < skb->data ||
3338 pskb_may_pull(skb, xprth + 2 - skb->data)) {
3339 u8 *icmp;
3340
3341 xprth = skb_network_header(skb) + ihl * 4;
3342 icmp = xprth;
3343
3344 fl4->fl4_icmp_type = icmp[0];
3345 fl4->fl4_icmp_code = icmp[1];
3346 }
3347 break;
3348 case IPPROTO_GRE:
3349 if (xprth + 12 < skb->data ||
3350 pskb_may_pull(skb, xprth + 12 - skb->data)) {
3351 __be16 *greflags;
3352 __be32 *gre_hdr;
3353
3354 xprth = skb_network_header(skb) + ihl * 4;
3355 greflags = (__be16 *)xprth;
3356 gre_hdr = (__be32 *)xprth;
3357
3358 if (greflags[0] & GRE_KEY) {
3359 if (greflags[0] & GRE_CSUM)
3360 gre_hdr++;
3361 fl4->fl4_gre_key = gre_hdr[1];
3362 }
3363 }
3364 break;
3365 default:
3366 break;
3367 }
3368 }
3369 }
3370
3371 #if IS_ENABLED(CONFIG_IPV6)
3372 static void
decode_session6(struct sk_buff * skb,struct flowi * fl,bool reverse)3373 decode_session6(struct sk_buff *skb, struct flowi *fl, bool reverse)
3374 {
3375 struct flowi6 *fl6 = &fl->u.ip6;
3376 int onlyproto = 0;
3377 const struct ipv6hdr *hdr = ipv6_hdr(skb);
3378 u32 offset = sizeof(*hdr);
3379 struct ipv6_opt_hdr *exthdr;
3380 const unsigned char *nh = skb_network_header(skb);
3381 u16 nhoff = IP6CB(skb)->nhoff;
3382 int oif = 0;
3383 u8 nexthdr;
3384
3385 if (!nhoff)
3386 nhoff = offsetof(struct ipv6hdr, nexthdr);
3387
3388 nexthdr = nh[nhoff];
3389
3390 if (skb_dst(skb) && skb_dst(skb)->dev)
3391 oif = skb_dst(skb)->dev->ifindex;
3392
3393 memset(fl6, 0, sizeof(struct flowi6));
3394 fl6->flowi6_mark = skb->mark;
3395 fl6->flowi6_oif = reverse ? skb->skb_iif : oif;
3396
3397 fl6->daddr = reverse ? hdr->saddr : hdr->daddr;
3398 fl6->saddr = reverse ? hdr->daddr : hdr->saddr;
3399
3400 while (nh + offset + sizeof(*exthdr) < skb->data ||
3401 pskb_may_pull(skb, nh + offset + sizeof(*exthdr) - skb->data)) {
3402 nh = skb_network_header(skb);
3403 exthdr = (struct ipv6_opt_hdr *)(nh + offset);
3404
3405 switch (nexthdr) {
3406 case NEXTHDR_FRAGMENT:
3407 onlyproto = 1;
3408 fallthrough;
3409 case NEXTHDR_ROUTING:
3410 case NEXTHDR_HOP:
3411 case NEXTHDR_DEST:
3412 offset += ipv6_optlen(exthdr);
3413 nexthdr = exthdr->nexthdr;
3414 break;
3415 case IPPROTO_UDP:
3416 case IPPROTO_UDPLITE:
3417 case IPPROTO_TCP:
3418 case IPPROTO_SCTP:
3419 case IPPROTO_DCCP:
3420 if (!onlyproto && (nh + offset + 4 < skb->data ||
3421 pskb_may_pull(skb, nh + offset + 4 - skb->data))) {
3422 __be16 *ports;
3423
3424 nh = skb_network_header(skb);
3425 ports = (__be16 *)(nh + offset);
3426 fl6->fl6_sport = ports[!!reverse];
3427 fl6->fl6_dport = ports[!reverse];
3428 }
3429 fl6->flowi6_proto = nexthdr;
3430 return;
3431 case IPPROTO_ICMPV6:
3432 if (!onlyproto && (nh + offset + 2 < skb->data ||
3433 pskb_may_pull(skb, nh + offset + 2 - skb->data))) {
3434 u8 *icmp;
3435
3436 nh = skb_network_header(skb);
3437 icmp = (u8 *)(nh + offset);
3438 fl6->fl6_icmp_type = icmp[0];
3439 fl6->fl6_icmp_code = icmp[1];
3440 }
3441 fl6->flowi6_proto = nexthdr;
3442 return;
3443 case IPPROTO_GRE:
3444 if (!onlyproto &&
3445 (nh + offset + 12 < skb->data ||
3446 pskb_may_pull(skb, nh + offset + 12 - skb->data))) {
3447 struct gre_base_hdr *gre_hdr;
3448 __be32 *gre_key;
3449
3450 nh = skb_network_header(skb);
3451 gre_hdr = (struct gre_base_hdr *)(nh + offset);
3452 gre_key = (__be32 *)(gre_hdr + 1);
3453
3454 if (gre_hdr->flags & GRE_KEY) {
3455 if (gre_hdr->flags & GRE_CSUM)
3456 gre_key++;
3457 fl6->fl6_gre_key = *gre_key;
3458 }
3459 }
3460 fl6->flowi6_proto = nexthdr;
3461 return;
3462
3463 #if IS_ENABLED(CONFIG_IPV6_MIP6)
3464 case IPPROTO_MH:
3465 offset += ipv6_optlen(exthdr);
3466 if (!onlyproto && (nh + offset + 3 < skb->data ||
3467 pskb_may_pull(skb, nh + offset + 3 - skb->data))) {
3468 struct ip6_mh *mh;
3469
3470 nh = skb_network_header(skb);
3471 mh = (struct ip6_mh *)(nh + offset);
3472 fl6->fl6_mh_type = mh->ip6mh_type;
3473 }
3474 fl6->flowi6_proto = nexthdr;
3475 return;
3476 #endif
3477 default:
3478 fl6->flowi6_proto = nexthdr;
3479 return;
3480 }
3481 }
3482 }
3483 #endif
3484
__xfrm_decode_session(struct sk_buff * skb,struct flowi * fl,unsigned int family,int reverse)3485 int __xfrm_decode_session(struct sk_buff *skb, struct flowi *fl,
3486 unsigned int family, int reverse)
3487 {
3488 switch (family) {
3489 case AF_INET:
3490 decode_session4(skb, fl, reverse);
3491 break;
3492 #if IS_ENABLED(CONFIG_IPV6)
3493 case AF_INET6:
3494 decode_session6(skb, fl, reverse);
3495 break;
3496 #endif
3497 default:
3498 return -EAFNOSUPPORT;
3499 }
3500
3501 return security_xfrm_decode_session(skb, &fl->flowi_secid);
3502 }
3503 EXPORT_SYMBOL(__xfrm_decode_session);
3504
secpath_has_nontransport(const struct sec_path * sp,int k,int * idxp)3505 static inline int secpath_has_nontransport(const struct sec_path *sp, int k, int *idxp)
3506 {
3507 for (; k < sp->len; k++) {
3508 if (sp->xvec[k]->props.mode != XFRM_MODE_TRANSPORT) {
3509 *idxp = k;
3510 return 1;
3511 }
3512 }
3513
3514 return 0;
3515 }
3516
__xfrm_policy_check(struct sock * sk,int dir,struct sk_buff * skb,unsigned short family)3517 int __xfrm_policy_check(struct sock *sk, int dir, struct sk_buff *skb,
3518 unsigned short family)
3519 {
3520 struct net *net = dev_net(skb->dev);
3521 struct xfrm_policy *pol;
3522 struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
3523 int npols = 0;
3524 int xfrm_nr;
3525 int pi;
3526 int reverse;
3527 struct flowi fl;
3528 int xerr_idx = -1;
3529 const struct xfrm_if_cb *ifcb;
3530 struct sec_path *sp;
3531 u32 if_id = 0;
3532
3533 rcu_read_lock();
3534 ifcb = xfrm_if_get_cb();
3535
3536 if (ifcb) {
3537 struct xfrm_if_decode_session_result r;
3538
3539 if (ifcb->decode_session(skb, family, &r)) {
3540 if_id = r.if_id;
3541 net = r.net;
3542 }
3543 }
3544 rcu_read_unlock();
3545
3546 reverse = dir & ~XFRM_POLICY_MASK;
3547 dir &= XFRM_POLICY_MASK;
3548
3549 if (__xfrm_decode_session(skb, &fl, family, reverse) < 0) {
3550 XFRM_INC_STATS(net, LINUX_MIB_XFRMINHDRERROR);
3551 return 0;
3552 }
3553
3554 nf_nat_decode_session(skb, &fl, family);
3555
3556 /* First, check used SA against their selectors. */
3557 sp = skb_sec_path(skb);
3558 if (sp) {
3559 int i;
3560
3561 for (i = sp->len - 1; i >= 0; i--) {
3562 struct xfrm_state *x = sp->xvec[i];
3563 if (!xfrm_selector_match(&x->sel, &fl, family)) {
3564 XFRM_INC_STATS(net, LINUX_MIB_XFRMINSTATEMISMATCH);
3565 return 0;
3566 }
3567 }
3568 }
3569
3570 pol = NULL;
3571 sk = sk_to_full_sk(sk);
3572 if (sk && sk->sk_policy[dir]) {
3573 pol = xfrm_sk_policy_lookup(sk, dir, &fl, family, if_id);
3574 if (IS_ERR(pol)) {
3575 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
3576 return 0;
3577 }
3578 }
3579
3580 if (!pol)
3581 pol = xfrm_policy_lookup(net, &fl, family, dir, if_id);
3582
3583 if (IS_ERR(pol)) {
3584 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
3585 return 0;
3586 }
3587
3588 if (!pol) {
3589 if (net->xfrm.policy_default[dir] == XFRM_USERPOLICY_BLOCK) {
3590 XFRM_INC_STATS(net, LINUX_MIB_XFRMINNOPOLS);
3591 return 0;
3592 }
3593
3594 if (sp && secpath_has_nontransport(sp, 0, &xerr_idx)) {
3595 xfrm_secpath_reject(xerr_idx, skb, &fl);
3596 XFRM_INC_STATS(net, LINUX_MIB_XFRMINNOPOLS);
3597 return 0;
3598 }
3599 return 1;
3600 }
3601
3602 /* This lockless write can happen from different cpus. */
3603 WRITE_ONCE(pol->curlft.use_time, ktime_get_real_seconds());
3604
3605 pols[0] = pol;
3606 npols++;
3607 #ifdef CONFIG_XFRM_SUB_POLICY
3608 if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
3609 pols[1] = xfrm_policy_lookup_bytype(net, XFRM_POLICY_TYPE_MAIN,
3610 &fl, family,
3611 XFRM_POLICY_IN, if_id);
3612 if (pols[1]) {
3613 if (IS_ERR(pols[1])) {
3614 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLERROR);
3615 xfrm_pol_put(pols[0]);
3616 return 0;
3617 }
3618 /* This write can happen from different cpus. */
3619 WRITE_ONCE(pols[1]->curlft.use_time,
3620 ktime_get_real_seconds());
3621 npols++;
3622 }
3623 }
3624 #endif
3625
3626 if (pol->action == XFRM_POLICY_ALLOW) {
3627 static struct sec_path dummy;
3628 struct xfrm_tmpl *tp[XFRM_MAX_DEPTH];
3629 struct xfrm_tmpl *stp[XFRM_MAX_DEPTH];
3630 struct xfrm_tmpl **tpp = tp;
3631 int ti = 0;
3632 int i, k;
3633
3634 sp = skb_sec_path(skb);
3635 if (!sp)
3636 sp = &dummy;
3637
3638 for (pi = 0; pi < npols; pi++) {
3639 if (pols[pi] != pol &&
3640 pols[pi]->action != XFRM_POLICY_ALLOW) {
3641 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
3642 goto reject;
3643 }
3644 if (ti + pols[pi]->xfrm_nr >= XFRM_MAX_DEPTH) {
3645 XFRM_INC_STATS(net, LINUX_MIB_XFRMINBUFFERERROR);
3646 goto reject_error;
3647 }
3648 for (i = 0; i < pols[pi]->xfrm_nr; i++)
3649 tpp[ti++] = &pols[pi]->xfrm_vec[i];
3650 }
3651 xfrm_nr = ti;
3652
3653 if (npols > 1) {
3654 xfrm_tmpl_sort(stp, tpp, xfrm_nr, family);
3655 tpp = stp;
3656 }
3657
3658 /* For each tunnel xfrm, find the first matching tmpl.
3659 * For each tmpl before that, find corresponding xfrm.
3660 * Order is _important_. Later we will implement
3661 * some barriers, but at the moment barriers
3662 * are implied between each two transformations.
3663 * Upon success, marks secpath entries as having been
3664 * verified to allow them to be skipped in future policy
3665 * checks (e.g. nested tunnels).
3666 */
3667 for (i = xfrm_nr-1, k = 0; i >= 0; i--) {
3668 k = xfrm_policy_ok(tpp[i], sp, k, family, if_id);
3669 if (k < 0) {
3670 if (k < -1)
3671 /* "-2 - errored_index" returned */
3672 xerr_idx = -(2+k);
3673 XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
3674 goto reject;
3675 }
3676 }
3677
3678 if (secpath_has_nontransport(sp, k, &xerr_idx)) {
3679 XFRM_INC_STATS(net, LINUX_MIB_XFRMINTMPLMISMATCH);
3680 goto reject;
3681 }
3682
3683 xfrm_pols_put(pols, npols);
3684 sp->verified_cnt = k;
3685
3686 return 1;
3687 }
3688 XFRM_INC_STATS(net, LINUX_MIB_XFRMINPOLBLOCK);
3689
3690 reject:
3691 xfrm_secpath_reject(xerr_idx, skb, &fl);
3692 reject_error:
3693 xfrm_pols_put(pols, npols);
3694 return 0;
3695 }
3696 EXPORT_SYMBOL(__xfrm_policy_check);
3697
__xfrm_route_forward(struct sk_buff * skb,unsigned short family)3698 int __xfrm_route_forward(struct sk_buff *skb, unsigned short family)
3699 {
3700 struct net *net = dev_net(skb->dev);
3701 struct flowi fl;
3702 struct dst_entry *dst;
3703 int res = 1;
3704
3705 if (xfrm_decode_session(skb, &fl, family) < 0) {
3706 XFRM_INC_STATS(net, LINUX_MIB_XFRMFWDHDRERROR);
3707 return 0;
3708 }
3709
3710 skb_dst_force(skb);
3711 if (!skb_dst(skb)) {
3712 XFRM_INC_STATS(net, LINUX_MIB_XFRMFWDHDRERROR);
3713 return 0;
3714 }
3715
3716 dst = xfrm_lookup(net, skb_dst(skb), &fl, NULL, XFRM_LOOKUP_QUEUE);
3717 if (IS_ERR(dst)) {
3718 res = 0;
3719 dst = NULL;
3720 }
3721 skb_dst_set(skb, dst);
3722 return res;
3723 }
3724 EXPORT_SYMBOL(__xfrm_route_forward);
3725
3726 /* Optimize later using cookies and generation ids. */
3727
xfrm_dst_check(struct dst_entry * dst,u32 cookie)3728 static struct dst_entry *xfrm_dst_check(struct dst_entry *dst, u32 cookie)
3729 {
3730 /* Code (such as __xfrm4_bundle_create()) sets dst->obsolete
3731 * to DST_OBSOLETE_FORCE_CHK to force all XFRM destinations to
3732 * get validated by dst_ops->check on every use. We do this
3733 * because when a normal route referenced by an XFRM dst is
3734 * obsoleted we do not go looking around for all parent
3735 * referencing XFRM dsts so that we can invalidate them. It
3736 * is just too much work. Instead we make the checks here on
3737 * every use. For example:
3738 *
3739 * XFRM dst A --> IPv4 dst X
3740 *
3741 * X is the "xdst->route" of A (X is also the "dst->path" of A
3742 * in this example). If X is marked obsolete, "A" will not
3743 * notice. That's what we are validating here via the
3744 * stale_bundle() check.
3745 *
3746 * When a dst is removed from the fib tree, DST_OBSOLETE_DEAD will
3747 * be marked on it.
3748 * This will force stale_bundle() to fail on any xdst bundle with
3749 * this dst linked in it.
3750 */
3751 if (dst->obsolete < 0 && !stale_bundle(dst))
3752 return dst;
3753
3754 return NULL;
3755 }
3756
stale_bundle(struct dst_entry * dst)3757 static int stale_bundle(struct dst_entry *dst)
3758 {
3759 return !xfrm_bundle_ok((struct xfrm_dst *)dst);
3760 }
3761
xfrm_dst_ifdown(struct dst_entry * dst,struct net_device * dev)3762 void xfrm_dst_ifdown(struct dst_entry *dst, struct net_device *dev)
3763 {
3764 while ((dst = xfrm_dst_child(dst)) && dst->xfrm && dst->dev == dev) {
3765 dst->dev = blackhole_netdev;
3766 dev_hold(dst->dev);
3767 dev_put(dev);
3768 }
3769 }
3770 EXPORT_SYMBOL(xfrm_dst_ifdown);
3771
xfrm_link_failure(struct sk_buff * skb)3772 static void xfrm_link_failure(struct sk_buff *skb)
3773 {
3774 /* Impossible. Such dst must be popped before reaches point of failure. */
3775 }
3776
xfrm_negative_advice(struct dst_entry * dst)3777 static struct dst_entry *xfrm_negative_advice(struct dst_entry *dst)
3778 {
3779 if (dst) {
3780 if (dst->obsolete) {
3781 dst_release(dst);
3782 dst = NULL;
3783 }
3784 }
3785 return dst;
3786 }
3787
xfrm_init_pmtu(struct xfrm_dst ** bundle,int nr)3788 static void xfrm_init_pmtu(struct xfrm_dst **bundle, int nr)
3789 {
3790 while (nr--) {
3791 struct xfrm_dst *xdst = bundle[nr];
3792 u32 pmtu, route_mtu_cached;
3793 struct dst_entry *dst;
3794
3795 dst = &xdst->u.dst;
3796 pmtu = dst_mtu(xfrm_dst_child(dst));
3797 xdst->child_mtu_cached = pmtu;
3798
3799 pmtu = xfrm_state_mtu(dst->xfrm, pmtu);
3800
3801 route_mtu_cached = dst_mtu(xdst->route);
3802 xdst->route_mtu_cached = route_mtu_cached;
3803
3804 if (pmtu > route_mtu_cached)
3805 pmtu = route_mtu_cached;
3806
3807 dst_metric_set(dst, RTAX_MTU, pmtu);
3808 }
3809 }
3810
3811 /* Check that the bundle accepts the flow and its components are
3812 * still valid.
3813 */
3814
xfrm_bundle_ok(struct xfrm_dst * first)3815 static int xfrm_bundle_ok(struct xfrm_dst *first)
3816 {
3817 struct xfrm_dst *bundle[XFRM_MAX_DEPTH];
3818 struct dst_entry *dst = &first->u.dst;
3819 struct xfrm_dst *xdst;
3820 int start_from, nr;
3821 u32 mtu;
3822
3823 if (!dst_check(xfrm_dst_path(dst), ((struct xfrm_dst *)dst)->path_cookie) ||
3824 (dst->dev && !netif_running(dst->dev)))
3825 return 0;
3826
3827 if (dst->flags & DST_XFRM_QUEUE)
3828 return 1;
3829
3830 start_from = nr = 0;
3831 do {
3832 struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
3833
3834 if (dst->xfrm->km.state != XFRM_STATE_VALID)
3835 return 0;
3836 if (xdst->xfrm_genid != dst->xfrm->genid)
3837 return 0;
3838 if (xdst->num_pols > 0 &&
3839 xdst->policy_genid != atomic_read(&xdst->pols[0]->genid))
3840 return 0;
3841
3842 bundle[nr++] = xdst;
3843
3844 mtu = dst_mtu(xfrm_dst_child(dst));
3845 if (xdst->child_mtu_cached != mtu) {
3846 start_from = nr;
3847 xdst->child_mtu_cached = mtu;
3848 }
3849
3850 if (!dst_check(xdst->route, xdst->route_cookie))
3851 return 0;
3852 mtu = dst_mtu(xdst->route);
3853 if (xdst->route_mtu_cached != mtu) {
3854 start_from = nr;
3855 xdst->route_mtu_cached = mtu;
3856 }
3857
3858 dst = xfrm_dst_child(dst);
3859 } while (dst->xfrm);
3860
3861 if (likely(!start_from))
3862 return 1;
3863
3864 xdst = bundle[start_from - 1];
3865 mtu = xdst->child_mtu_cached;
3866 while (start_from--) {
3867 dst = &xdst->u.dst;
3868
3869 mtu = xfrm_state_mtu(dst->xfrm, mtu);
3870 if (mtu > xdst->route_mtu_cached)
3871 mtu = xdst->route_mtu_cached;
3872 dst_metric_set(dst, RTAX_MTU, mtu);
3873 if (!start_from)
3874 break;
3875
3876 xdst = bundle[start_from - 1];
3877 xdst->child_mtu_cached = mtu;
3878 }
3879
3880 return 1;
3881 }
3882
xfrm_default_advmss(const struct dst_entry * dst)3883 static unsigned int xfrm_default_advmss(const struct dst_entry *dst)
3884 {
3885 return dst_metric_advmss(xfrm_dst_path(dst));
3886 }
3887
xfrm_mtu(const struct dst_entry * dst)3888 static unsigned int xfrm_mtu(const struct dst_entry *dst)
3889 {
3890 unsigned int mtu = dst_metric_raw(dst, RTAX_MTU);
3891
3892 return mtu ? : dst_mtu(xfrm_dst_path(dst));
3893 }
3894
xfrm_get_dst_nexthop(const struct dst_entry * dst,const void * daddr)3895 static const void *xfrm_get_dst_nexthop(const struct dst_entry *dst,
3896 const void *daddr)
3897 {
3898 while (dst->xfrm) {
3899 const struct xfrm_state *xfrm = dst->xfrm;
3900
3901 dst = xfrm_dst_child(dst);
3902
3903 if (xfrm->props.mode == XFRM_MODE_TRANSPORT)
3904 continue;
3905 if (xfrm->type->flags & XFRM_TYPE_REMOTE_COADDR)
3906 daddr = xfrm->coaddr;
3907 else if (!(xfrm->type->flags & XFRM_TYPE_LOCAL_COADDR))
3908 daddr = &xfrm->id.daddr;
3909 }
3910 return daddr;
3911 }
3912
xfrm_neigh_lookup(const struct dst_entry * dst,struct sk_buff * skb,const void * daddr)3913 static struct neighbour *xfrm_neigh_lookup(const struct dst_entry *dst,
3914 struct sk_buff *skb,
3915 const void *daddr)
3916 {
3917 const struct dst_entry *path = xfrm_dst_path(dst);
3918
3919 if (!skb)
3920 daddr = xfrm_get_dst_nexthop(dst, daddr);
3921 return path->ops->neigh_lookup(path, skb, daddr);
3922 }
3923
xfrm_confirm_neigh(const struct dst_entry * dst,const void * daddr)3924 static void xfrm_confirm_neigh(const struct dst_entry *dst, const void *daddr)
3925 {
3926 const struct dst_entry *path = xfrm_dst_path(dst);
3927
3928 daddr = xfrm_get_dst_nexthop(dst, daddr);
3929 path->ops->confirm_neigh(path, daddr);
3930 }
3931
xfrm_policy_register_afinfo(const struct xfrm_policy_afinfo * afinfo,int family)3932 int xfrm_policy_register_afinfo(const struct xfrm_policy_afinfo *afinfo, int family)
3933 {
3934 int err = 0;
3935
3936 if (WARN_ON(family >= ARRAY_SIZE(xfrm_policy_afinfo)))
3937 return -EAFNOSUPPORT;
3938
3939 spin_lock(&xfrm_policy_afinfo_lock);
3940 if (unlikely(xfrm_policy_afinfo[family] != NULL))
3941 err = -EEXIST;
3942 else {
3943 struct dst_ops *dst_ops = afinfo->dst_ops;
3944 if (likely(dst_ops->kmem_cachep == NULL))
3945 dst_ops->kmem_cachep = xfrm_dst_cache;
3946 if (likely(dst_ops->check == NULL))
3947 dst_ops->check = xfrm_dst_check;
3948 if (likely(dst_ops->default_advmss == NULL))
3949 dst_ops->default_advmss = xfrm_default_advmss;
3950 if (likely(dst_ops->mtu == NULL))
3951 dst_ops->mtu = xfrm_mtu;
3952 if (likely(dst_ops->negative_advice == NULL))
3953 dst_ops->negative_advice = xfrm_negative_advice;
3954 if (likely(dst_ops->link_failure == NULL))
3955 dst_ops->link_failure = xfrm_link_failure;
3956 if (likely(dst_ops->neigh_lookup == NULL))
3957 dst_ops->neigh_lookup = xfrm_neigh_lookup;
3958 if (likely(!dst_ops->confirm_neigh))
3959 dst_ops->confirm_neigh = xfrm_confirm_neigh;
3960 rcu_assign_pointer(xfrm_policy_afinfo[family], afinfo);
3961 }
3962 spin_unlock(&xfrm_policy_afinfo_lock);
3963
3964 return err;
3965 }
3966 EXPORT_SYMBOL(xfrm_policy_register_afinfo);
3967
xfrm_policy_unregister_afinfo(const struct xfrm_policy_afinfo * afinfo)3968 void xfrm_policy_unregister_afinfo(const struct xfrm_policy_afinfo *afinfo)
3969 {
3970 struct dst_ops *dst_ops = afinfo->dst_ops;
3971 int i;
3972
3973 for (i = 0; i < ARRAY_SIZE(xfrm_policy_afinfo); i++) {
3974 if (xfrm_policy_afinfo[i] != afinfo)
3975 continue;
3976 RCU_INIT_POINTER(xfrm_policy_afinfo[i], NULL);
3977 break;
3978 }
3979
3980 synchronize_rcu();
3981
3982 dst_ops->kmem_cachep = NULL;
3983 dst_ops->check = NULL;
3984 dst_ops->negative_advice = NULL;
3985 dst_ops->link_failure = NULL;
3986 }
3987 EXPORT_SYMBOL(xfrm_policy_unregister_afinfo);
3988
xfrm_if_register_cb(const struct xfrm_if_cb * ifcb)3989 void xfrm_if_register_cb(const struct xfrm_if_cb *ifcb)
3990 {
3991 spin_lock(&xfrm_if_cb_lock);
3992 rcu_assign_pointer(xfrm_if_cb, ifcb);
3993 spin_unlock(&xfrm_if_cb_lock);
3994 }
3995 EXPORT_SYMBOL(xfrm_if_register_cb);
3996
xfrm_if_unregister_cb(void)3997 void xfrm_if_unregister_cb(void)
3998 {
3999 RCU_INIT_POINTER(xfrm_if_cb, NULL);
4000 synchronize_rcu();
4001 }
4002 EXPORT_SYMBOL(xfrm_if_unregister_cb);
4003
4004 #ifdef CONFIG_XFRM_STATISTICS
xfrm_statistics_init(struct net * net)4005 static int __net_init xfrm_statistics_init(struct net *net)
4006 {
4007 int rv;
4008 net->mib.xfrm_statistics = alloc_percpu(struct linux_xfrm_mib);
4009 if (!net->mib.xfrm_statistics)
4010 return -ENOMEM;
4011 rv = xfrm_proc_init(net);
4012 if (rv < 0)
4013 free_percpu(net->mib.xfrm_statistics);
4014 return rv;
4015 }
4016
xfrm_statistics_fini(struct net * net)4017 static void xfrm_statistics_fini(struct net *net)
4018 {
4019 xfrm_proc_fini(net);
4020 free_percpu(net->mib.xfrm_statistics);
4021 }
4022 #else
xfrm_statistics_init(struct net * net)4023 static int __net_init xfrm_statistics_init(struct net *net)
4024 {
4025 return 0;
4026 }
4027
xfrm_statistics_fini(struct net * net)4028 static void xfrm_statistics_fini(struct net *net)
4029 {
4030 }
4031 #endif
4032
xfrm_policy_init(struct net * net)4033 static int __net_init xfrm_policy_init(struct net *net)
4034 {
4035 unsigned int hmask, sz;
4036 int dir, err;
4037
4038 if (net_eq(net, &init_net)) {
4039 xfrm_dst_cache = kmem_cache_create("xfrm_dst_cache",
4040 sizeof(struct xfrm_dst),
4041 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4042 NULL);
4043 err = rhashtable_init(&xfrm_policy_inexact_table,
4044 &xfrm_pol_inexact_params);
4045 BUG_ON(err);
4046 }
4047
4048 hmask = 8 - 1;
4049 sz = (hmask+1) * sizeof(struct hlist_head);
4050
4051 net->xfrm.policy_byidx = xfrm_hash_alloc(sz);
4052 if (!net->xfrm.policy_byidx)
4053 goto out_byidx;
4054 net->xfrm.policy_idx_hmask = hmask;
4055
4056 for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
4057 struct xfrm_policy_hash *htab;
4058
4059 net->xfrm.policy_count[dir] = 0;
4060 net->xfrm.policy_count[XFRM_POLICY_MAX + dir] = 0;
4061 INIT_HLIST_HEAD(&net->xfrm.policy_inexact[dir]);
4062
4063 htab = &net->xfrm.policy_bydst[dir];
4064 htab->table = xfrm_hash_alloc(sz);
4065 if (!htab->table)
4066 goto out_bydst;
4067 htab->hmask = hmask;
4068 htab->dbits4 = 32;
4069 htab->sbits4 = 32;
4070 htab->dbits6 = 128;
4071 htab->sbits6 = 128;
4072 }
4073 net->xfrm.policy_hthresh.lbits4 = 32;
4074 net->xfrm.policy_hthresh.rbits4 = 32;
4075 net->xfrm.policy_hthresh.lbits6 = 128;
4076 net->xfrm.policy_hthresh.rbits6 = 128;
4077
4078 seqlock_init(&net->xfrm.policy_hthresh.lock);
4079
4080 INIT_LIST_HEAD(&net->xfrm.policy_all);
4081 INIT_LIST_HEAD(&net->xfrm.inexact_bins);
4082 INIT_WORK(&net->xfrm.policy_hash_work, xfrm_hash_resize);
4083 INIT_WORK(&net->xfrm.policy_hthresh.work, xfrm_hash_rebuild);
4084 return 0;
4085
4086 out_bydst:
4087 for (dir--; dir >= 0; dir--) {
4088 struct xfrm_policy_hash *htab;
4089
4090 htab = &net->xfrm.policy_bydst[dir];
4091 xfrm_hash_free(htab->table, sz);
4092 }
4093 xfrm_hash_free(net->xfrm.policy_byidx, sz);
4094 out_byidx:
4095 return -ENOMEM;
4096 }
4097
xfrm_policy_fini(struct net * net)4098 static void xfrm_policy_fini(struct net *net)
4099 {
4100 struct xfrm_pol_inexact_bin *b, *t;
4101 unsigned int sz;
4102 int dir;
4103
4104 flush_work(&net->xfrm.policy_hash_work);
4105 #ifdef CONFIG_XFRM_SUB_POLICY
4106 xfrm_policy_flush(net, XFRM_POLICY_TYPE_SUB, false);
4107 #endif
4108 xfrm_policy_flush(net, XFRM_POLICY_TYPE_MAIN, false);
4109
4110 WARN_ON(!list_empty(&net->xfrm.policy_all));
4111
4112 for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
4113 struct xfrm_policy_hash *htab;
4114
4115 WARN_ON(!hlist_empty(&net->xfrm.policy_inexact[dir]));
4116
4117 htab = &net->xfrm.policy_bydst[dir];
4118 sz = (htab->hmask + 1) * sizeof(struct hlist_head);
4119 WARN_ON(!hlist_empty(htab->table));
4120 xfrm_hash_free(htab->table, sz);
4121 }
4122
4123 sz = (net->xfrm.policy_idx_hmask + 1) * sizeof(struct hlist_head);
4124 WARN_ON(!hlist_empty(net->xfrm.policy_byidx));
4125 xfrm_hash_free(net->xfrm.policy_byidx, sz);
4126
4127 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
4128 list_for_each_entry_safe(b, t, &net->xfrm.inexact_bins, inexact_bins)
4129 __xfrm_policy_inexact_prune_bin(b, true);
4130 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
4131 }
4132
xfrm_net_init(struct net * net)4133 static int __net_init xfrm_net_init(struct net *net)
4134 {
4135 int rv;
4136
4137 /* Initialize the per-net locks here */
4138 spin_lock_init(&net->xfrm.xfrm_state_lock);
4139 spin_lock_init(&net->xfrm.xfrm_policy_lock);
4140 seqcount_spinlock_init(&net->xfrm.xfrm_policy_hash_generation, &net->xfrm.xfrm_policy_lock);
4141 mutex_init(&net->xfrm.xfrm_cfg_mutex);
4142 net->xfrm.policy_default[XFRM_POLICY_IN] = XFRM_USERPOLICY_ACCEPT;
4143 net->xfrm.policy_default[XFRM_POLICY_FWD] = XFRM_USERPOLICY_ACCEPT;
4144 net->xfrm.policy_default[XFRM_POLICY_OUT] = XFRM_USERPOLICY_ACCEPT;
4145
4146 rv = xfrm_statistics_init(net);
4147 if (rv < 0)
4148 goto out_statistics;
4149 rv = xfrm_state_init(net);
4150 if (rv < 0)
4151 goto out_state;
4152 rv = xfrm_policy_init(net);
4153 if (rv < 0)
4154 goto out_policy;
4155 rv = xfrm_sysctl_init(net);
4156 if (rv < 0)
4157 goto out_sysctl;
4158
4159 return 0;
4160
4161 out_sysctl:
4162 xfrm_policy_fini(net);
4163 out_policy:
4164 xfrm_state_fini(net);
4165 out_state:
4166 xfrm_statistics_fini(net);
4167 out_statistics:
4168 return rv;
4169 }
4170
xfrm_net_exit(struct net * net)4171 static void __net_exit xfrm_net_exit(struct net *net)
4172 {
4173 xfrm_sysctl_fini(net);
4174 xfrm_policy_fini(net);
4175 xfrm_state_fini(net);
4176 xfrm_statistics_fini(net);
4177 }
4178
4179 static struct pernet_operations __net_initdata xfrm_net_ops = {
4180 .init = xfrm_net_init,
4181 .exit = xfrm_net_exit,
4182 };
4183
xfrm_init(void)4184 void __init xfrm_init(void)
4185 {
4186 register_pernet_subsys(&xfrm_net_ops);
4187 xfrm_dev_init();
4188 xfrm_input_init();
4189
4190 #ifdef CONFIG_XFRM_ESPINTCP
4191 espintcp_init();
4192 #endif
4193 }
4194
4195 #ifdef CONFIG_AUDITSYSCALL
xfrm_audit_common_policyinfo(struct xfrm_policy * xp,struct audit_buffer * audit_buf)4196 static void xfrm_audit_common_policyinfo(struct xfrm_policy *xp,
4197 struct audit_buffer *audit_buf)
4198 {
4199 struct xfrm_sec_ctx *ctx = xp->security;
4200 struct xfrm_selector *sel = &xp->selector;
4201
4202 if (ctx)
4203 audit_log_format(audit_buf, " sec_alg=%u sec_doi=%u sec_obj=%s",
4204 ctx->ctx_alg, ctx->ctx_doi, ctx->ctx_str);
4205
4206 switch (sel->family) {
4207 case AF_INET:
4208 audit_log_format(audit_buf, " src=%pI4", &sel->saddr.a4);
4209 if (sel->prefixlen_s != 32)
4210 audit_log_format(audit_buf, " src_prefixlen=%d",
4211 sel->prefixlen_s);
4212 audit_log_format(audit_buf, " dst=%pI4", &sel->daddr.a4);
4213 if (sel->prefixlen_d != 32)
4214 audit_log_format(audit_buf, " dst_prefixlen=%d",
4215 sel->prefixlen_d);
4216 break;
4217 case AF_INET6:
4218 audit_log_format(audit_buf, " src=%pI6", sel->saddr.a6);
4219 if (sel->prefixlen_s != 128)
4220 audit_log_format(audit_buf, " src_prefixlen=%d",
4221 sel->prefixlen_s);
4222 audit_log_format(audit_buf, " dst=%pI6", sel->daddr.a6);
4223 if (sel->prefixlen_d != 128)
4224 audit_log_format(audit_buf, " dst_prefixlen=%d",
4225 sel->prefixlen_d);
4226 break;
4227 }
4228 }
4229
xfrm_audit_policy_add(struct xfrm_policy * xp,int result,bool task_valid)4230 void xfrm_audit_policy_add(struct xfrm_policy *xp, int result, bool task_valid)
4231 {
4232 struct audit_buffer *audit_buf;
4233
4234 audit_buf = xfrm_audit_start("SPD-add");
4235 if (audit_buf == NULL)
4236 return;
4237 xfrm_audit_helper_usrinfo(task_valid, audit_buf);
4238 audit_log_format(audit_buf, " res=%u", result);
4239 xfrm_audit_common_policyinfo(xp, audit_buf);
4240 audit_log_end(audit_buf);
4241 }
4242 EXPORT_SYMBOL_GPL(xfrm_audit_policy_add);
4243
xfrm_audit_policy_delete(struct xfrm_policy * xp,int result,bool task_valid)4244 void xfrm_audit_policy_delete(struct xfrm_policy *xp, int result,
4245 bool task_valid)
4246 {
4247 struct audit_buffer *audit_buf;
4248
4249 audit_buf = xfrm_audit_start("SPD-delete");
4250 if (audit_buf == NULL)
4251 return;
4252 xfrm_audit_helper_usrinfo(task_valid, audit_buf);
4253 audit_log_format(audit_buf, " res=%u", result);
4254 xfrm_audit_common_policyinfo(xp, audit_buf);
4255 audit_log_end(audit_buf);
4256 }
4257 EXPORT_SYMBOL_GPL(xfrm_audit_policy_delete);
4258 #endif
4259
4260 #ifdef CONFIG_XFRM_MIGRATE
xfrm_migrate_selector_match(const struct xfrm_selector * sel_cmp,const struct xfrm_selector * sel_tgt)4261 static bool xfrm_migrate_selector_match(const struct xfrm_selector *sel_cmp,
4262 const struct xfrm_selector *sel_tgt)
4263 {
4264 if (sel_cmp->proto == IPSEC_ULPROTO_ANY) {
4265 if (sel_tgt->family == sel_cmp->family &&
4266 xfrm_addr_equal(&sel_tgt->daddr, &sel_cmp->daddr,
4267 sel_cmp->family) &&
4268 xfrm_addr_equal(&sel_tgt->saddr, &sel_cmp->saddr,
4269 sel_cmp->family) &&
4270 sel_tgt->prefixlen_d == sel_cmp->prefixlen_d &&
4271 sel_tgt->prefixlen_s == sel_cmp->prefixlen_s) {
4272 return true;
4273 }
4274 } else {
4275 if (memcmp(sel_tgt, sel_cmp, sizeof(*sel_tgt)) == 0) {
4276 return true;
4277 }
4278 }
4279 return false;
4280 }
4281
xfrm_migrate_policy_find(const struct xfrm_selector * sel,u8 dir,u8 type,struct net * net,u32 if_id)4282 static struct xfrm_policy *xfrm_migrate_policy_find(const struct xfrm_selector *sel,
4283 u8 dir, u8 type, struct net *net, u32 if_id)
4284 {
4285 struct xfrm_policy *pol, *ret = NULL;
4286 struct hlist_head *chain;
4287 u32 priority = ~0U;
4288
4289 spin_lock_bh(&net->xfrm.xfrm_policy_lock);
4290 chain = policy_hash_direct(net, &sel->daddr, &sel->saddr, sel->family, dir);
4291 hlist_for_each_entry(pol, chain, bydst) {
4292 if ((if_id == 0 || pol->if_id == if_id) &&
4293 xfrm_migrate_selector_match(sel, &pol->selector) &&
4294 pol->type == type) {
4295 ret = pol;
4296 priority = ret->priority;
4297 break;
4298 }
4299 }
4300 chain = &net->xfrm.policy_inexact[dir];
4301 hlist_for_each_entry(pol, chain, bydst_inexact_list) {
4302 if ((pol->priority >= priority) && ret)
4303 break;
4304
4305 if ((if_id == 0 || pol->if_id == if_id) &&
4306 xfrm_migrate_selector_match(sel, &pol->selector) &&
4307 pol->type == type) {
4308 ret = pol;
4309 break;
4310 }
4311 }
4312
4313 xfrm_pol_hold(ret);
4314
4315 spin_unlock_bh(&net->xfrm.xfrm_policy_lock);
4316
4317 return ret;
4318 }
4319
migrate_tmpl_match(const struct xfrm_migrate * m,const struct xfrm_tmpl * t)4320 static int migrate_tmpl_match(const struct xfrm_migrate *m, const struct xfrm_tmpl *t)
4321 {
4322 int match = 0;
4323
4324 if (t->mode == m->mode && t->id.proto == m->proto &&
4325 (m->reqid == 0 || t->reqid == m->reqid)) {
4326 switch (t->mode) {
4327 case XFRM_MODE_TUNNEL:
4328 case XFRM_MODE_BEET:
4329 if (xfrm_addr_equal(&t->id.daddr, &m->old_daddr,
4330 m->old_family) &&
4331 xfrm_addr_equal(&t->saddr, &m->old_saddr,
4332 m->old_family)) {
4333 match = 1;
4334 }
4335 break;
4336 case XFRM_MODE_TRANSPORT:
4337 /* in case of transport mode, template does not store
4338 any IP addresses, hence we just compare mode and
4339 protocol */
4340 match = 1;
4341 break;
4342 default:
4343 break;
4344 }
4345 }
4346 return match;
4347 }
4348
4349 /* update endpoint address(es) of template(s) */
xfrm_policy_migrate(struct xfrm_policy * pol,struct xfrm_migrate * m,int num_migrate)4350 static int xfrm_policy_migrate(struct xfrm_policy *pol,
4351 struct xfrm_migrate *m, int num_migrate)
4352 {
4353 struct xfrm_migrate *mp;
4354 int i, j, n = 0;
4355
4356 write_lock_bh(&pol->lock);
4357 if (unlikely(pol->walk.dead)) {
4358 /* target policy has been deleted */
4359 write_unlock_bh(&pol->lock);
4360 return -ENOENT;
4361 }
4362
4363 for (i = 0; i < pol->xfrm_nr; i++) {
4364 for (j = 0, mp = m; j < num_migrate; j++, mp++) {
4365 if (!migrate_tmpl_match(mp, &pol->xfrm_vec[i]))
4366 continue;
4367 n++;
4368 if (pol->xfrm_vec[i].mode != XFRM_MODE_TUNNEL &&
4369 pol->xfrm_vec[i].mode != XFRM_MODE_BEET)
4370 continue;
4371 /* update endpoints */
4372 memcpy(&pol->xfrm_vec[i].id.daddr, &mp->new_daddr,
4373 sizeof(pol->xfrm_vec[i].id.daddr));
4374 memcpy(&pol->xfrm_vec[i].saddr, &mp->new_saddr,
4375 sizeof(pol->xfrm_vec[i].saddr));
4376 pol->xfrm_vec[i].encap_family = mp->new_family;
4377 /* flush bundles */
4378 atomic_inc(&pol->genid);
4379 }
4380 }
4381
4382 write_unlock_bh(&pol->lock);
4383
4384 if (!n)
4385 return -ENODATA;
4386
4387 return 0;
4388 }
4389
xfrm_migrate_check(const struct xfrm_migrate * m,int num_migrate)4390 static int xfrm_migrate_check(const struct xfrm_migrate *m, int num_migrate)
4391 {
4392 int i, j;
4393
4394 if (num_migrate < 1 || num_migrate > XFRM_MAX_DEPTH)
4395 return -EINVAL;
4396
4397 for (i = 0; i < num_migrate; i++) {
4398 if (xfrm_addr_any(&m[i].new_daddr, m[i].new_family) ||
4399 xfrm_addr_any(&m[i].new_saddr, m[i].new_family))
4400 return -EINVAL;
4401
4402 /* check if there is any duplicated entry */
4403 for (j = i + 1; j < num_migrate; j++) {
4404 if (!memcmp(&m[i].old_daddr, &m[j].old_daddr,
4405 sizeof(m[i].old_daddr)) &&
4406 !memcmp(&m[i].old_saddr, &m[j].old_saddr,
4407 sizeof(m[i].old_saddr)) &&
4408 m[i].proto == m[j].proto &&
4409 m[i].mode == m[j].mode &&
4410 m[i].reqid == m[j].reqid &&
4411 m[i].old_family == m[j].old_family)
4412 return -EINVAL;
4413 }
4414 }
4415
4416 return 0;
4417 }
4418
xfrm_migrate(const struct xfrm_selector * sel,u8 dir,u8 type,struct xfrm_migrate * m,int num_migrate,struct xfrm_kmaddress * k,struct net * net,struct xfrm_encap_tmpl * encap,u32 if_id)4419 int xfrm_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
4420 struct xfrm_migrate *m, int num_migrate,
4421 struct xfrm_kmaddress *k, struct net *net,
4422 struct xfrm_encap_tmpl *encap, u32 if_id)
4423 {
4424 int i, err, nx_cur = 0, nx_new = 0;
4425 struct xfrm_policy *pol = NULL;
4426 struct xfrm_state *x, *xc;
4427 struct xfrm_state *x_cur[XFRM_MAX_DEPTH];
4428 struct xfrm_state *x_new[XFRM_MAX_DEPTH];
4429 struct xfrm_migrate *mp;
4430
4431 /* Stage 0 - sanity checks */
4432 if ((err = xfrm_migrate_check(m, num_migrate)) < 0)
4433 goto out;
4434
4435 if (dir >= XFRM_POLICY_MAX) {
4436 err = -EINVAL;
4437 goto out;
4438 }
4439
4440 /* Stage 1 - find policy */
4441 if ((pol = xfrm_migrate_policy_find(sel, dir, type, net, if_id)) == NULL) {
4442 err = -ENOENT;
4443 goto out;
4444 }
4445
4446 /* Stage 2 - find and update state(s) */
4447 for (i = 0, mp = m; i < num_migrate; i++, mp++) {
4448 if ((x = xfrm_migrate_state_find(mp, net, if_id))) {
4449 x_cur[nx_cur] = x;
4450 nx_cur++;
4451 xc = xfrm_state_migrate(x, mp, encap);
4452 if (xc) {
4453 x_new[nx_new] = xc;
4454 nx_new++;
4455 } else {
4456 err = -ENODATA;
4457 goto restore_state;
4458 }
4459 }
4460 }
4461
4462 /* Stage 3 - update policy */
4463 if ((err = xfrm_policy_migrate(pol, m, num_migrate)) < 0)
4464 goto restore_state;
4465
4466 /* Stage 4 - delete old state(s) */
4467 if (nx_cur) {
4468 xfrm_states_put(x_cur, nx_cur);
4469 xfrm_states_delete(x_cur, nx_cur);
4470 }
4471
4472 /* Stage 5 - announce */
4473 km_migrate(sel, dir, type, m, num_migrate, k, encap);
4474
4475 xfrm_pol_put(pol);
4476
4477 return 0;
4478 out:
4479 return err;
4480
4481 restore_state:
4482 if (pol)
4483 xfrm_pol_put(pol);
4484 if (nx_cur)
4485 xfrm_states_put(x_cur, nx_cur);
4486 if (nx_new)
4487 xfrm_states_delete(x_new, nx_new);
4488
4489 return err;
4490 }
4491 EXPORT_SYMBOL(xfrm_migrate);
4492 #endif
4493