]> err.no Git - linux-2.6/blob - net/xfrm/xfrm_policy.c
Merge master.kernel.org:/pub/scm/linux/kernel/git/jejb/scsi-rc-fixes-2.6
[linux-2.6] / net / xfrm / xfrm_policy.c
1 /*
2  * xfrm_policy.c
3  *
4  * Changes:
5  *      Mitsuru KANDA @USAGI
6  *      Kazunori MIYAZAWA @USAGI
7  *      Kunihiro Ishiguro <kunihiro@ipinfusion.com>
8  *              IPv6 support
9  *      Kazunori MIYAZAWA @USAGI
10  *      YOSHIFUJI Hideaki
11  *              Split up af-specific portion
12  *      Derek Atkins <derek@ihtfp.com>          Add the post_input processor
13  *
14  */
15
16 #include <linux/slab.h>
17 #include <linux/kmod.h>
18 #include <linux/list.h>
19 #include <linux/spinlock.h>
20 #include <linux/workqueue.h>
21 #include <linux/notifier.h>
22 #include <linux/netdevice.h>
23 #include <linux/netfilter.h>
24 #include <linux/module.h>
25 #include <linux/cache.h>
26 #include <net/xfrm.h>
27 #include <net/ip.h>
28 #include <linux/audit.h>
29 #include <linux/cache.h>
30
31 #include "xfrm_hash.h"
32
33 int sysctl_xfrm_larval_drop __read_mostly;
34
35 DEFINE_MUTEX(xfrm_cfg_mutex);
36 EXPORT_SYMBOL(xfrm_cfg_mutex);
37
38 static DEFINE_RWLOCK(xfrm_policy_lock);
39
40 unsigned int xfrm_policy_count[XFRM_POLICY_MAX*2];
41 EXPORT_SYMBOL(xfrm_policy_count);
42
43 static DEFINE_RWLOCK(xfrm_policy_afinfo_lock);
44 static struct xfrm_policy_afinfo *xfrm_policy_afinfo[NPROTO];
45
46 static struct kmem_cache *xfrm_dst_cache __read_mostly;
47
48 static struct work_struct xfrm_policy_gc_work;
49 static HLIST_HEAD(xfrm_policy_gc_list);
50 static DEFINE_SPINLOCK(xfrm_policy_gc_lock);
51
52 static struct xfrm_policy_afinfo *xfrm_policy_get_afinfo(unsigned short family);
53 static void xfrm_policy_put_afinfo(struct xfrm_policy_afinfo *afinfo);
54 static struct xfrm_policy_afinfo *xfrm_policy_lock_afinfo(unsigned int family);
55 static void xfrm_policy_unlock_afinfo(struct xfrm_policy_afinfo *afinfo);
56
57 static inline int
58 __xfrm4_selector_match(struct xfrm_selector *sel, struct flowi *fl)
59 {
60         return  addr_match(&fl->fl4_dst, &sel->daddr, sel->prefixlen_d) &&
61                 addr_match(&fl->fl4_src, &sel->saddr, sel->prefixlen_s) &&
62                 !((xfrm_flowi_dport(fl) ^ sel->dport) & sel->dport_mask) &&
63                 !((xfrm_flowi_sport(fl) ^ sel->sport) & sel->sport_mask) &&
64                 (fl->proto == sel->proto || !sel->proto) &&
65                 (fl->oif == sel->ifindex || !sel->ifindex);
66 }
67
68 static inline int
69 __xfrm6_selector_match(struct xfrm_selector *sel, struct flowi *fl)
70 {
71         return  addr_match(&fl->fl6_dst, &sel->daddr, sel->prefixlen_d) &&
72                 addr_match(&fl->fl6_src, &sel->saddr, sel->prefixlen_s) &&
73                 !((xfrm_flowi_dport(fl) ^ sel->dport) & sel->dport_mask) &&
74                 !((xfrm_flowi_sport(fl) ^ sel->sport) & sel->sport_mask) &&
75                 (fl->proto == sel->proto || !sel->proto) &&
76                 (fl->oif == sel->ifindex || !sel->ifindex);
77 }
78
79 int xfrm_selector_match(struct xfrm_selector *sel, struct flowi *fl,
80                     unsigned short family)
81 {
82         switch (family) {
83         case AF_INET:
84                 return __xfrm4_selector_match(sel, fl);
85         case AF_INET6:
86                 return __xfrm6_selector_match(sel, fl);
87         }
88         return 0;
89 }
90
91 int xfrm_register_type(struct xfrm_type *type, unsigned short family)
92 {
93         struct xfrm_policy_afinfo *afinfo = xfrm_policy_lock_afinfo(family);
94         struct xfrm_type **typemap;
95         int err = 0;
96
97         if (unlikely(afinfo == NULL))
98                 return -EAFNOSUPPORT;
99         typemap = afinfo->type_map;
100
101         if (likely(typemap[type->proto] == NULL))
102                 typemap[type->proto] = type;
103         else
104                 err = -EEXIST;
105         xfrm_policy_unlock_afinfo(afinfo);
106         return err;
107 }
108 EXPORT_SYMBOL(xfrm_register_type);
109
110 int xfrm_unregister_type(struct xfrm_type *type, unsigned short family)
111 {
112         struct xfrm_policy_afinfo *afinfo = xfrm_policy_lock_afinfo(family);
113         struct xfrm_type **typemap;
114         int err = 0;
115
116         if (unlikely(afinfo == NULL))
117                 return -EAFNOSUPPORT;
118         typemap = afinfo->type_map;
119
120         if (unlikely(typemap[type->proto] != type))
121                 err = -ENOENT;
122         else
123                 typemap[type->proto] = NULL;
124         xfrm_policy_unlock_afinfo(afinfo);
125         return err;
126 }
127 EXPORT_SYMBOL(xfrm_unregister_type);
128
129 struct xfrm_type *xfrm_get_type(u8 proto, unsigned short family)
130 {
131         struct xfrm_policy_afinfo *afinfo;
132         struct xfrm_type **typemap;
133         struct xfrm_type *type;
134         int modload_attempted = 0;
135
136 retry:
137         afinfo = xfrm_policy_get_afinfo(family);
138         if (unlikely(afinfo == NULL))
139                 return NULL;
140         typemap = afinfo->type_map;
141
142         type = typemap[proto];
143         if (unlikely(type && !try_module_get(type->owner)))
144                 type = NULL;
145         if (!type && !modload_attempted) {
146                 xfrm_policy_put_afinfo(afinfo);
147                 request_module("xfrm-type-%d-%d",
148                                (int) family, (int) proto);
149                 modload_attempted = 1;
150                 goto retry;
151         }
152
153         xfrm_policy_put_afinfo(afinfo);
154         return type;
155 }
156
157 int xfrm_dst_lookup(struct xfrm_dst **dst, struct flowi *fl,
158                     unsigned short family)
159 {
160         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
161         int err = 0;
162
163         if (unlikely(afinfo == NULL))
164                 return -EAFNOSUPPORT;
165
166         if (likely(afinfo->dst_lookup != NULL))
167                 err = afinfo->dst_lookup(dst, fl);
168         else
169                 err = -EINVAL;
170         xfrm_policy_put_afinfo(afinfo);
171         return err;
172 }
173 EXPORT_SYMBOL(xfrm_dst_lookup);
174
175 void xfrm_put_type(struct xfrm_type *type)
176 {
177         module_put(type->owner);
178 }
179
180 int xfrm_register_mode(struct xfrm_mode *mode, int family)
181 {
182         struct xfrm_policy_afinfo *afinfo;
183         struct xfrm_mode **modemap;
184         int err;
185
186         if (unlikely(mode->encap >= XFRM_MODE_MAX))
187                 return -EINVAL;
188
189         afinfo = xfrm_policy_lock_afinfo(family);
190         if (unlikely(afinfo == NULL))
191                 return -EAFNOSUPPORT;
192
193         err = -EEXIST;
194         modemap = afinfo->mode_map;
195         if (likely(modemap[mode->encap] == NULL)) {
196                 modemap[mode->encap] = mode;
197                 err = 0;
198         }
199
200         xfrm_policy_unlock_afinfo(afinfo);
201         return err;
202 }
203 EXPORT_SYMBOL(xfrm_register_mode);
204
205 int xfrm_unregister_mode(struct xfrm_mode *mode, int family)
206 {
207         struct xfrm_policy_afinfo *afinfo;
208         struct xfrm_mode **modemap;
209         int err;
210
211         if (unlikely(mode->encap >= XFRM_MODE_MAX))
212                 return -EINVAL;
213
214         afinfo = xfrm_policy_lock_afinfo(family);
215         if (unlikely(afinfo == NULL))
216                 return -EAFNOSUPPORT;
217
218         err = -ENOENT;
219         modemap = afinfo->mode_map;
220         if (likely(modemap[mode->encap] == mode)) {
221                 modemap[mode->encap] = NULL;
222                 err = 0;
223         }
224
225         xfrm_policy_unlock_afinfo(afinfo);
226         return err;
227 }
228 EXPORT_SYMBOL(xfrm_unregister_mode);
229
230 struct xfrm_mode *xfrm_get_mode(unsigned int encap, int family)
231 {
232         struct xfrm_policy_afinfo *afinfo;
233         struct xfrm_mode *mode;
234         int modload_attempted = 0;
235
236         if (unlikely(encap >= XFRM_MODE_MAX))
237                 return NULL;
238
239 retry:
240         afinfo = xfrm_policy_get_afinfo(family);
241         if (unlikely(afinfo == NULL))
242                 return NULL;
243
244         mode = afinfo->mode_map[encap];
245         if (unlikely(mode && !try_module_get(mode->owner)))
246                 mode = NULL;
247         if (!mode && !modload_attempted) {
248                 xfrm_policy_put_afinfo(afinfo);
249                 request_module("xfrm-mode-%d-%d", family, encap);
250                 modload_attempted = 1;
251                 goto retry;
252         }
253
254         xfrm_policy_put_afinfo(afinfo);
255         return mode;
256 }
257
258 void xfrm_put_mode(struct xfrm_mode *mode)
259 {
260         module_put(mode->owner);
261 }
262
263 static inline unsigned long make_jiffies(long secs)
264 {
265         if (secs >= (MAX_SCHEDULE_TIMEOUT-1)/HZ)
266                 return MAX_SCHEDULE_TIMEOUT-1;
267         else
268                 return secs*HZ;
269 }
270
271 static void xfrm_policy_timer(unsigned long data)
272 {
273         struct xfrm_policy *xp = (struct xfrm_policy*)data;
274         unsigned long now = get_seconds();
275         long next = LONG_MAX;
276         int warn = 0;
277         int dir;
278
279         read_lock(&xp->lock);
280
281         if (xp->dead)
282                 goto out;
283
284         dir = xfrm_policy_id2dir(xp->index);
285
286         if (xp->lft.hard_add_expires_seconds) {
287                 long tmo = xp->lft.hard_add_expires_seconds +
288                         xp->curlft.add_time - now;
289                 if (tmo <= 0)
290                         goto expired;
291                 if (tmo < next)
292                         next = tmo;
293         }
294         if (xp->lft.hard_use_expires_seconds) {
295                 long tmo = xp->lft.hard_use_expires_seconds +
296                         (xp->curlft.use_time ? : xp->curlft.add_time) - now;
297                 if (tmo <= 0)
298                         goto expired;
299                 if (tmo < next)
300                         next = tmo;
301         }
302         if (xp->lft.soft_add_expires_seconds) {
303                 long tmo = xp->lft.soft_add_expires_seconds +
304                         xp->curlft.add_time - now;
305                 if (tmo <= 0) {
306                         warn = 1;
307                         tmo = XFRM_KM_TIMEOUT;
308                 }
309                 if (tmo < next)
310                         next = tmo;
311         }
312         if (xp->lft.soft_use_expires_seconds) {
313                 long tmo = xp->lft.soft_use_expires_seconds +
314                         (xp->curlft.use_time ? : xp->curlft.add_time) - now;
315                 if (tmo <= 0) {
316                         warn = 1;
317                         tmo = XFRM_KM_TIMEOUT;
318                 }
319                 if (tmo < next)
320                         next = tmo;
321         }
322
323         if (warn)
324                 km_policy_expired(xp, dir, 0, 0);
325         if (next != LONG_MAX &&
326             !mod_timer(&xp->timer, jiffies + make_jiffies(next)))
327                 xfrm_pol_hold(xp);
328
329 out:
330         read_unlock(&xp->lock);
331         xfrm_pol_put(xp);
332         return;
333
334 expired:
335         read_unlock(&xp->lock);
336         if (!xfrm_policy_delete(xp, dir))
337                 km_policy_expired(xp, dir, 1, 0);
338         xfrm_pol_put(xp);
339 }
340
341
342 /* Allocate xfrm_policy. Not used here, it is supposed to be used by pfkeyv2
343  * SPD calls.
344  */
345
346 struct xfrm_policy *xfrm_policy_alloc(gfp_t gfp)
347 {
348         struct xfrm_policy *policy;
349
350         policy = kzalloc(sizeof(struct xfrm_policy), gfp);
351
352         if (policy) {
353                 INIT_HLIST_NODE(&policy->bydst);
354                 INIT_HLIST_NODE(&policy->byidx);
355                 rwlock_init(&policy->lock);
356                 atomic_set(&policy->refcnt, 1);
357                 init_timer(&policy->timer);
358                 policy->timer.data = (unsigned long)policy;
359                 policy->timer.function = xfrm_policy_timer;
360         }
361         return policy;
362 }
363 EXPORT_SYMBOL(xfrm_policy_alloc);
364
365 /* Destroy xfrm_policy: descendant resources must be released to this moment. */
366
367 void __xfrm_policy_destroy(struct xfrm_policy *policy)
368 {
369         BUG_ON(!policy->dead);
370
371         BUG_ON(policy->bundles);
372
373         if (del_timer(&policy->timer))
374                 BUG();
375
376         security_xfrm_policy_free(policy);
377         kfree(policy);
378 }
379 EXPORT_SYMBOL(__xfrm_policy_destroy);
380
381 static void xfrm_policy_gc_kill(struct xfrm_policy *policy)
382 {
383         struct dst_entry *dst;
384
385         while ((dst = policy->bundles) != NULL) {
386                 policy->bundles = dst->next;
387                 dst_free(dst);
388         }
389
390         if (del_timer(&policy->timer))
391                 atomic_dec(&policy->refcnt);
392
393         if (atomic_read(&policy->refcnt) > 1)
394                 flow_cache_flush();
395
396         xfrm_pol_put(policy);
397 }
398
399 static void xfrm_policy_gc_task(struct work_struct *work)
400 {
401         struct xfrm_policy *policy;
402         struct hlist_node *entry, *tmp;
403         struct hlist_head gc_list;
404
405         spin_lock_bh(&xfrm_policy_gc_lock);
406         gc_list.first = xfrm_policy_gc_list.first;
407         INIT_HLIST_HEAD(&xfrm_policy_gc_list);
408         spin_unlock_bh(&xfrm_policy_gc_lock);
409
410         hlist_for_each_entry_safe(policy, entry, tmp, &gc_list, bydst)
411                 xfrm_policy_gc_kill(policy);
412 }
413
414 /* Rule must be locked. Release descentant resources, announce
415  * entry dead. The rule must be unlinked from lists to the moment.
416  */
417
418 static void xfrm_policy_kill(struct xfrm_policy *policy)
419 {
420         int dead;
421
422         write_lock_bh(&policy->lock);
423         dead = policy->dead;
424         policy->dead = 1;
425         write_unlock_bh(&policy->lock);
426
427         if (unlikely(dead)) {
428                 WARN_ON(1);
429                 return;
430         }
431
432         spin_lock(&xfrm_policy_gc_lock);
433         hlist_add_head(&policy->bydst, &xfrm_policy_gc_list);
434         spin_unlock(&xfrm_policy_gc_lock);
435
436         schedule_work(&xfrm_policy_gc_work);
437 }
438
439 struct xfrm_policy_hash {
440         struct hlist_head       *table;
441         unsigned int            hmask;
442 };
443
444 static struct hlist_head xfrm_policy_inexact[XFRM_POLICY_MAX*2];
445 static struct xfrm_policy_hash xfrm_policy_bydst[XFRM_POLICY_MAX*2] __read_mostly;
446 static struct hlist_head *xfrm_policy_byidx __read_mostly;
447 static unsigned int xfrm_idx_hmask __read_mostly;
448 static unsigned int xfrm_policy_hashmax __read_mostly = 1 * 1024 * 1024;
449
450 static inline unsigned int idx_hash(u32 index)
451 {
452         return __idx_hash(index, xfrm_idx_hmask);
453 }
454
455 static struct hlist_head *policy_hash_bysel(struct xfrm_selector *sel, unsigned short family, int dir)
456 {
457         unsigned int hmask = xfrm_policy_bydst[dir].hmask;
458         unsigned int hash = __sel_hash(sel, family, hmask);
459
460         return (hash == hmask + 1 ?
461                 &xfrm_policy_inexact[dir] :
462                 xfrm_policy_bydst[dir].table + hash);
463 }
464
465 static struct hlist_head *policy_hash_direct(xfrm_address_t *daddr, xfrm_address_t *saddr, unsigned short family, int dir)
466 {
467         unsigned int hmask = xfrm_policy_bydst[dir].hmask;
468         unsigned int hash = __addr_hash(daddr, saddr, family, hmask);
469
470         return xfrm_policy_bydst[dir].table + hash;
471 }
472
473 static void xfrm_dst_hash_transfer(struct hlist_head *list,
474                                    struct hlist_head *ndsttable,
475                                    unsigned int nhashmask)
476 {
477         struct hlist_node *entry, *tmp;
478         struct xfrm_policy *pol;
479
480         hlist_for_each_entry_safe(pol, entry, tmp, list, bydst) {
481                 unsigned int h;
482
483                 h = __addr_hash(&pol->selector.daddr, &pol->selector.saddr,
484                                 pol->family, nhashmask);
485                 hlist_add_head(&pol->bydst, ndsttable+h);
486         }
487 }
488
489 static void xfrm_idx_hash_transfer(struct hlist_head *list,
490                                    struct hlist_head *nidxtable,
491                                    unsigned int nhashmask)
492 {
493         struct hlist_node *entry, *tmp;
494         struct xfrm_policy *pol;
495
496         hlist_for_each_entry_safe(pol, entry, tmp, list, byidx) {
497                 unsigned int h;
498
499                 h = __idx_hash(pol->index, nhashmask);
500                 hlist_add_head(&pol->byidx, nidxtable+h);
501         }
502 }
503
504 static unsigned long xfrm_new_hash_mask(unsigned int old_hmask)
505 {
506         return ((old_hmask + 1) << 1) - 1;
507 }
508
509 static void xfrm_bydst_resize(int dir)
510 {
511         unsigned int hmask = xfrm_policy_bydst[dir].hmask;
512         unsigned int nhashmask = xfrm_new_hash_mask(hmask);
513         unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
514         struct hlist_head *odst = xfrm_policy_bydst[dir].table;
515         struct hlist_head *ndst = xfrm_hash_alloc(nsize);
516         int i;
517
518         if (!ndst)
519                 return;
520
521         write_lock_bh(&xfrm_policy_lock);
522
523         for (i = hmask; i >= 0; i--)
524                 xfrm_dst_hash_transfer(odst + i, ndst, nhashmask);
525
526         xfrm_policy_bydst[dir].table = ndst;
527         xfrm_policy_bydst[dir].hmask = nhashmask;
528
529         write_unlock_bh(&xfrm_policy_lock);
530
531         xfrm_hash_free(odst, (hmask + 1) * sizeof(struct hlist_head));
532 }
533
534 static void xfrm_byidx_resize(int total)
535 {
536         unsigned int hmask = xfrm_idx_hmask;
537         unsigned int nhashmask = xfrm_new_hash_mask(hmask);
538         unsigned int nsize = (nhashmask + 1) * sizeof(struct hlist_head);
539         struct hlist_head *oidx = xfrm_policy_byidx;
540         struct hlist_head *nidx = xfrm_hash_alloc(nsize);
541         int i;
542
543         if (!nidx)
544                 return;
545
546         write_lock_bh(&xfrm_policy_lock);
547
548         for (i = hmask; i >= 0; i--)
549                 xfrm_idx_hash_transfer(oidx + i, nidx, nhashmask);
550
551         xfrm_policy_byidx = nidx;
552         xfrm_idx_hmask = nhashmask;
553
554         write_unlock_bh(&xfrm_policy_lock);
555
556         xfrm_hash_free(oidx, (hmask + 1) * sizeof(struct hlist_head));
557 }
558
559 static inline int xfrm_bydst_should_resize(int dir, int *total)
560 {
561         unsigned int cnt = xfrm_policy_count[dir];
562         unsigned int hmask = xfrm_policy_bydst[dir].hmask;
563
564         if (total)
565                 *total += cnt;
566
567         if ((hmask + 1) < xfrm_policy_hashmax &&
568             cnt > hmask)
569                 return 1;
570
571         return 0;
572 }
573
574 static inline int xfrm_byidx_should_resize(int total)
575 {
576         unsigned int hmask = xfrm_idx_hmask;
577
578         if ((hmask + 1) < xfrm_policy_hashmax &&
579             total > hmask)
580                 return 1;
581
582         return 0;
583 }
584
585 void xfrm_spd_getinfo(struct xfrmk_spdinfo *si)
586 {
587         read_lock_bh(&xfrm_policy_lock);
588         si->incnt = xfrm_policy_count[XFRM_POLICY_IN];
589         si->outcnt = xfrm_policy_count[XFRM_POLICY_OUT];
590         si->fwdcnt = xfrm_policy_count[XFRM_POLICY_FWD];
591         si->inscnt = xfrm_policy_count[XFRM_POLICY_IN+XFRM_POLICY_MAX];
592         si->outscnt = xfrm_policy_count[XFRM_POLICY_OUT+XFRM_POLICY_MAX];
593         si->fwdscnt = xfrm_policy_count[XFRM_POLICY_FWD+XFRM_POLICY_MAX];
594         si->spdhcnt = xfrm_idx_hmask;
595         si->spdhmcnt = xfrm_policy_hashmax;
596         read_unlock_bh(&xfrm_policy_lock);
597 }
598 EXPORT_SYMBOL(xfrm_spd_getinfo);
599
600 static DEFINE_MUTEX(hash_resize_mutex);
601 static void xfrm_hash_resize(struct work_struct *__unused)
602 {
603         int dir, total;
604
605         mutex_lock(&hash_resize_mutex);
606
607         total = 0;
608         for (dir = 0; dir < XFRM_POLICY_MAX * 2; dir++) {
609                 if (xfrm_bydst_should_resize(dir, &total))
610                         xfrm_bydst_resize(dir);
611         }
612         if (xfrm_byidx_should_resize(total))
613                 xfrm_byidx_resize(total);
614
615         mutex_unlock(&hash_resize_mutex);
616 }
617
618 static DECLARE_WORK(xfrm_hash_work, xfrm_hash_resize);
619
620 /* Generate new index... KAME seems to generate them ordered by cost
621  * of an absolute inpredictability of ordering of rules. This will not pass. */
622 static u32 xfrm_gen_index(u8 type, int dir)
623 {
624         static u32 idx_generator;
625
626         for (;;) {
627                 struct hlist_node *entry;
628                 struct hlist_head *list;
629                 struct xfrm_policy *p;
630                 u32 idx;
631                 int found;
632
633                 idx = (idx_generator | dir);
634                 idx_generator += 8;
635                 if (idx == 0)
636                         idx = 8;
637                 list = xfrm_policy_byidx + idx_hash(idx);
638                 found = 0;
639                 hlist_for_each_entry(p, entry, list, byidx) {
640                         if (p->index == idx) {
641                                 found = 1;
642                                 break;
643                         }
644                 }
645                 if (!found)
646                         return idx;
647         }
648 }
649
650 static inline int selector_cmp(struct xfrm_selector *s1, struct xfrm_selector *s2)
651 {
652         u32 *p1 = (u32 *) s1;
653         u32 *p2 = (u32 *) s2;
654         int len = sizeof(struct xfrm_selector) / sizeof(u32);
655         int i;
656
657         for (i = 0; i < len; i++) {
658                 if (p1[i] != p2[i])
659                         return 1;
660         }
661
662         return 0;
663 }
664
665 int xfrm_policy_insert(int dir, struct xfrm_policy *policy, int excl)
666 {
667         struct xfrm_policy *pol;
668         struct xfrm_policy *delpol;
669         struct hlist_head *chain;
670         struct hlist_node *entry, *newpos;
671         struct dst_entry *gc_list;
672
673         write_lock_bh(&xfrm_policy_lock);
674         chain = policy_hash_bysel(&policy->selector, policy->family, dir);
675         delpol = NULL;
676         newpos = NULL;
677         hlist_for_each_entry(pol, entry, chain, bydst) {
678                 if (pol->type == policy->type &&
679                     !selector_cmp(&pol->selector, &policy->selector) &&
680                     xfrm_sec_ctx_match(pol->security, policy->security) &&
681                     !WARN_ON(delpol)) {
682                         if (excl) {
683                                 write_unlock_bh(&xfrm_policy_lock);
684                                 return -EEXIST;
685                         }
686                         delpol = pol;
687                         if (policy->priority > pol->priority)
688                                 continue;
689                 } else if (policy->priority >= pol->priority) {
690                         newpos = &pol->bydst;
691                         continue;
692                 }
693                 if (delpol)
694                         break;
695         }
696         if (newpos)
697                 hlist_add_after(newpos, &policy->bydst);
698         else
699                 hlist_add_head(&policy->bydst, chain);
700         xfrm_pol_hold(policy);
701         xfrm_policy_count[dir]++;
702         atomic_inc(&flow_cache_genid);
703         if (delpol) {
704                 hlist_del(&delpol->bydst);
705                 hlist_del(&delpol->byidx);
706                 xfrm_policy_count[dir]--;
707         }
708         policy->index = delpol ? delpol->index : xfrm_gen_index(policy->type, dir);
709         hlist_add_head(&policy->byidx, xfrm_policy_byidx+idx_hash(policy->index));
710         policy->curlft.add_time = get_seconds();
711         policy->curlft.use_time = 0;
712         if (!mod_timer(&policy->timer, jiffies + HZ))
713                 xfrm_pol_hold(policy);
714         write_unlock_bh(&xfrm_policy_lock);
715
716         if (delpol)
717                 xfrm_policy_kill(delpol);
718         else if (xfrm_bydst_should_resize(dir, NULL))
719                 schedule_work(&xfrm_hash_work);
720
721         read_lock_bh(&xfrm_policy_lock);
722         gc_list = NULL;
723         entry = &policy->bydst;
724         hlist_for_each_entry_continue(policy, entry, bydst) {
725                 struct dst_entry *dst;
726
727                 write_lock(&policy->lock);
728                 dst = policy->bundles;
729                 if (dst) {
730                         struct dst_entry *tail = dst;
731                         while (tail->next)
732                                 tail = tail->next;
733                         tail->next = gc_list;
734                         gc_list = dst;
735
736                         policy->bundles = NULL;
737                 }
738                 write_unlock(&policy->lock);
739         }
740         read_unlock_bh(&xfrm_policy_lock);
741
742         while (gc_list) {
743                 struct dst_entry *dst = gc_list;
744
745                 gc_list = dst->next;
746                 dst_free(dst);
747         }
748
749         return 0;
750 }
751 EXPORT_SYMBOL(xfrm_policy_insert);
752
753 struct xfrm_policy *xfrm_policy_bysel_ctx(u8 type, int dir,
754                                           struct xfrm_selector *sel,
755                                           struct xfrm_sec_ctx *ctx, int delete,
756                                           int *err)
757 {
758         struct xfrm_policy *pol, *ret;
759         struct hlist_head *chain;
760         struct hlist_node *entry;
761
762         *err = 0;
763         write_lock_bh(&xfrm_policy_lock);
764         chain = policy_hash_bysel(sel, sel->family, dir);
765         ret = NULL;
766         hlist_for_each_entry(pol, entry, chain, bydst) {
767                 if (pol->type == type &&
768                     !selector_cmp(sel, &pol->selector) &&
769                     xfrm_sec_ctx_match(ctx, pol->security)) {
770                         xfrm_pol_hold(pol);
771                         if (delete) {
772                                 *err = security_xfrm_policy_delete(pol);
773                                 if (*err) {
774                                         write_unlock_bh(&xfrm_policy_lock);
775                                         return pol;
776                                 }
777                                 hlist_del(&pol->bydst);
778                                 hlist_del(&pol->byidx);
779                                 xfrm_policy_count[dir]--;
780                         }
781                         ret = pol;
782                         break;
783                 }
784         }
785         write_unlock_bh(&xfrm_policy_lock);
786
787         if (ret && delete) {
788                 atomic_inc(&flow_cache_genid);
789                 xfrm_policy_kill(ret);
790         }
791         return ret;
792 }
793 EXPORT_SYMBOL(xfrm_policy_bysel_ctx);
794
795 struct xfrm_policy *xfrm_policy_byid(u8 type, int dir, u32 id, int delete,
796                                      int *err)
797 {
798         struct xfrm_policy *pol, *ret;
799         struct hlist_head *chain;
800         struct hlist_node *entry;
801
802         *err = -ENOENT;
803         if (xfrm_policy_id2dir(id) != dir)
804                 return NULL;
805
806         *err = 0;
807         write_lock_bh(&xfrm_policy_lock);
808         chain = xfrm_policy_byidx + idx_hash(id);
809         ret = NULL;
810         hlist_for_each_entry(pol, entry, chain, byidx) {
811                 if (pol->type == type && pol->index == id) {
812                         xfrm_pol_hold(pol);
813                         if (delete) {
814                                 *err = security_xfrm_policy_delete(pol);
815                                 if (*err) {
816                                         write_unlock_bh(&xfrm_policy_lock);
817                                         return pol;
818                                 }
819                                 hlist_del(&pol->bydst);
820                                 hlist_del(&pol->byidx);
821                                 xfrm_policy_count[dir]--;
822                         }
823                         ret = pol;
824                         break;
825                 }
826         }
827         write_unlock_bh(&xfrm_policy_lock);
828
829         if (ret && delete) {
830                 atomic_inc(&flow_cache_genid);
831                 xfrm_policy_kill(ret);
832         }
833         return ret;
834 }
835 EXPORT_SYMBOL(xfrm_policy_byid);
836
837 void xfrm_policy_flush(u8 type, struct xfrm_audit *audit_info)
838 {
839         int dir;
840
841         write_lock_bh(&xfrm_policy_lock);
842         for (dir = 0; dir < XFRM_POLICY_MAX; dir++) {
843                 struct xfrm_policy *pol;
844                 struct hlist_node *entry;
845                 int i, killed;
846
847                 killed = 0;
848         again1:
849                 hlist_for_each_entry(pol, entry,
850                                      &xfrm_policy_inexact[dir], bydst) {
851                         if (pol->type != type)
852                                 continue;
853                         hlist_del(&pol->bydst);
854                         hlist_del(&pol->byidx);
855                         write_unlock_bh(&xfrm_policy_lock);
856
857                         xfrm_audit_log(audit_info->loginuid, audit_info->secid,
858                                        AUDIT_MAC_IPSEC_DELSPD, 1, pol, NULL);
859
860                         xfrm_policy_kill(pol);
861                         killed++;
862
863                         write_lock_bh(&xfrm_policy_lock);
864                         goto again1;
865                 }
866
867                 for (i = xfrm_policy_bydst[dir].hmask; i >= 0; i--) {
868         again2:
869                         hlist_for_each_entry(pol, entry,
870                                              xfrm_policy_bydst[dir].table + i,
871                                              bydst) {
872                                 if (pol->type != type)
873                                         continue;
874                                 hlist_del(&pol->bydst);
875                                 hlist_del(&pol->byidx);
876                                 write_unlock_bh(&xfrm_policy_lock);
877
878                                 xfrm_audit_log(audit_info->loginuid,
879                                                audit_info->secid,
880                                                AUDIT_MAC_IPSEC_DELSPD, 1,
881                                                pol, NULL);
882
883                                 xfrm_policy_kill(pol);
884                                 killed++;
885
886                                 write_lock_bh(&xfrm_policy_lock);
887                                 goto again2;
888                         }
889                 }
890
891                 xfrm_policy_count[dir] -= killed;
892         }
893         atomic_inc(&flow_cache_genid);
894         write_unlock_bh(&xfrm_policy_lock);
895 }
896 EXPORT_SYMBOL(xfrm_policy_flush);
897
898 int xfrm_policy_walk(u8 type, int (*func)(struct xfrm_policy *, int, int, void*),
899                      void *data)
900 {
901         struct xfrm_policy *pol, *last = NULL;
902         struct hlist_node *entry;
903         int dir, last_dir = 0, count, error;
904
905         read_lock_bh(&xfrm_policy_lock);
906         count = 0;
907
908         for (dir = 0; dir < 2*XFRM_POLICY_MAX; dir++) {
909                 struct hlist_head *table = xfrm_policy_bydst[dir].table;
910                 int i;
911
912                 hlist_for_each_entry(pol, entry,
913                                      &xfrm_policy_inexact[dir], bydst) {
914                         if (pol->type != type)
915                                 continue;
916                         if (last) {
917                                 error = func(last, last_dir % XFRM_POLICY_MAX,
918                                              count, data);
919                                 if (error)
920                                         goto out;
921                         }
922                         last = pol;
923                         last_dir = dir;
924                         count++;
925                 }
926                 for (i = xfrm_policy_bydst[dir].hmask; i >= 0; i--) {
927                         hlist_for_each_entry(pol, entry, table + i, bydst) {
928                                 if (pol->type != type)
929                                         continue;
930                                 if (last) {
931                                         error = func(last, last_dir % XFRM_POLICY_MAX,
932                                                      count, data);
933                                         if (error)
934                                                 goto out;
935                                 }
936                                 last = pol;
937                                 last_dir = dir;
938                                 count++;
939                         }
940                 }
941         }
942         if (count == 0) {
943                 error = -ENOENT;
944                 goto out;
945         }
946         error = func(last, last_dir % XFRM_POLICY_MAX, 0, data);
947 out:
948         read_unlock_bh(&xfrm_policy_lock);
949         return error;
950 }
951 EXPORT_SYMBOL(xfrm_policy_walk);
952
953 /*
954  * Find policy to apply to this flow.
955  *
956  * Returns 0 if policy found, else an -errno.
957  */
958 static int xfrm_policy_match(struct xfrm_policy *pol, struct flowi *fl,
959                              u8 type, u16 family, int dir)
960 {
961         struct xfrm_selector *sel = &pol->selector;
962         int match, ret = -ESRCH;
963
964         if (pol->family != family ||
965             pol->type != type)
966                 return ret;
967
968         match = xfrm_selector_match(sel, fl, family);
969         if (match)
970                 ret = security_xfrm_policy_lookup(pol, fl->secid, dir);
971
972         return ret;
973 }
974
975 static struct xfrm_policy *xfrm_policy_lookup_bytype(u8 type, struct flowi *fl,
976                                                      u16 family, u8 dir)
977 {
978         int err;
979         struct xfrm_policy *pol, *ret;
980         xfrm_address_t *daddr, *saddr;
981         struct hlist_node *entry;
982         struct hlist_head *chain;
983         u32 priority = ~0U;
984
985         daddr = xfrm_flowi_daddr(fl, family);
986         saddr = xfrm_flowi_saddr(fl, family);
987         if (unlikely(!daddr || !saddr))
988                 return NULL;
989
990         read_lock_bh(&xfrm_policy_lock);
991         chain = policy_hash_direct(daddr, saddr, family, dir);
992         ret = NULL;
993         hlist_for_each_entry(pol, entry, chain, bydst) {
994                 err = xfrm_policy_match(pol, fl, type, family, dir);
995                 if (err) {
996                         if (err == -ESRCH)
997                                 continue;
998                         else {
999                                 ret = ERR_PTR(err);
1000                                 goto fail;
1001                         }
1002                 } else {
1003                         ret = pol;
1004                         priority = ret->priority;
1005                         break;
1006                 }
1007         }
1008         chain = &xfrm_policy_inexact[dir];
1009         hlist_for_each_entry(pol, entry, chain, bydst) {
1010                 err = xfrm_policy_match(pol, fl, type, family, dir);
1011                 if (err) {
1012                         if (err == -ESRCH)
1013                                 continue;
1014                         else {
1015                                 ret = ERR_PTR(err);
1016                                 goto fail;
1017                         }
1018                 } else if (pol->priority < priority) {
1019                         ret = pol;
1020                         break;
1021                 }
1022         }
1023         if (ret)
1024                 xfrm_pol_hold(ret);
1025 fail:
1026         read_unlock_bh(&xfrm_policy_lock);
1027
1028         return ret;
1029 }
1030
1031 static int xfrm_policy_lookup(struct flowi *fl, u16 family, u8 dir,
1032                                void **objp, atomic_t **obj_refp)
1033 {
1034         struct xfrm_policy *pol;
1035         int err = 0;
1036
1037 #ifdef CONFIG_XFRM_SUB_POLICY
1038         pol = xfrm_policy_lookup_bytype(XFRM_POLICY_TYPE_SUB, fl, family, dir);
1039         if (IS_ERR(pol)) {
1040                 err = PTR_ERR(pol);
1041                 pol = NULL;
1042         }
1043         if (pol || err)
1044                 goto end;
1045 #endif
1046         pol = xfrm_policy_lookup_bytype(XFRM_POLICY_TYPE_MAIN, fl, family, dir);
1047         if (IS_ERR(pol)) {
1048                 err = PTR_ERR(pol);
1049                 pol = NULL;
1050         }
1051 #ifdef CONFIG_XFRM_SUB_POLICY
1052 end:
1053 #endif
1054         if ((*objp = (void *) pol) != NULL)
1055                 *obj_refp = &pol->refcnt;
1056         return err;
1057 }
1058
1059 static inline int policy_to_flow_dir(int dir)
1060 {
1061         if (XFRM_POLICY_IN == FLOW_DIR_IN &&
1062             XFRM_POLICY_OUT == FLOW_DIR_OUT &&
1063             XFRM_POLICY_FWD == FLOW_DIR_FWD)
1064                 return dir;
1065         switch (dir) {
1066         default:
1067         case XFRM_POLICY_IN:
1068                 return FLOW_DIR_IN;
1069         case XFRM_POLICY_OUT:
1070                 return FLOW_DIR_OUT;
1071         case XFRM_POLICY_FWD:
1072                 return FLOW_DIR_FWD;
1073         }
1074 }
1075
1076 static struct xfrm_policy *xfrm_sk_policy_lookup(struct sock *sk, int dir, struct flowi *fl)
1077 {
1078         struct xfrm_policy *pol;
1079
1080         read_lock_bh(&xfrm_policy_lock);
1081         if ((pol = sk->sk_policy[dir]) != NULL) {
1082                 int match = xfrm_selector_match(&pol->selector, fl,
1083                                                 sk->sk_family);
1084                 int err = 0;
1085
1086                 if (match) {
1087                         err = security_xfrm_policy_lookup(pol, fl->secid,
1088                                         policy_to_flow_dir(dir));
1089                         if (!err)
1090                                 xfrm_pol_hold(pol);
1091                         else if (err == -ESRCH)
1092                                 pol = NULL;
1093                         else
1094                                 pol = ERR_PTR(err);
1095                 } else
1096                         pol = NULL;
1097         }
1098         read_unlock_bh(&xfrm_policy_lock);
1099         return pol;
1100 }
1101
1102 static void __xfrm_policy_link(struct xfrm_policy *pol, int dir)
1103 {
1104         struct hlist_head *chain = policy_hash_bysel(&pol->selector,
1105                                                      pol->family, dir);
1106
1107         hlist_add_head(&pol->bydst, chain);
1108         hlist_add_head(&pol->byidx, xfrm_policy_byidx+idx_hash(pol->index));
1109         xfrm_policy_count[dir]++;
1110         xfrm_pol_hold(pol);
1111
1112         if (xfrm_bydst_should_resize(dir, NULL))
1113                 schedule_work(&xfrm_hash_work);
1114 }
1115
1116 static struct xfrm_policy *__xfrm_policy_unlink(struct xfrm_policy *pol,
1117                                                 int dir)
1118 {
1119         if (hlist_unhashed(&pol->bydst))
1120                 return NULL;
1121
1122         hlist_del(&pol->bydst);
1123         hlist_del(&pol->byidx);
1124         xfrm_policy_count[dir]--;
1125
1126         return pol;
1127 }
1128
1129 int xfrm_policy_delete(struct xfrm_policy *pol, int dir)
1130 {
1131         write_lock_bh(&xfrm_policy_lock);
1132         pol = __xfrm_policy_unlink(pol, dir);
1133         write_unlock_bh(&xfrm_policy_lock);
1134         if (pol) {
1135                 if (dir < XFRM_POLICY_MAX)
1136                         atomic_inc(&flow_cache_genid);
1137                 xfrm_policy_kill(pol);
1138                 return 0;
1139         }
1140         return -ENOENT;
1141 }
1142 EXPORT_SYMBOL(xfrm_policy_delete);
1143
1144 int xfrm_sk_policy_insert(struct sock *sk, int dir, struct xfrm_policy *pol)
1145 {
1146         struct xfrm_policy *old_pol;
1147
1148 #ifdef CONFIG_XFRM_SUB_POLICY
1149         if (pol && pol->type != XFRM_POLICY_TYPE_MAIN)
1150                 return -EINVAL;
1151 #endif
1152
1153         write_lock_bh(&xfrm_policy_lock);
1154         old_pol = sk->sk_policy[dir];
1155         sk->sk_policy[dir] = pol;
1156         if (pol) {
1157                 pol->curlft.add_time = get_seconds();
1158                 pol->index = xfrm_gen_index(pol->type, XFRM_POLICY_MAX+dir);
1159                 __xfrm_policy_link(pol, XFRM_POLICY_MAX+dir);
1160         }
1161         if (old_pol)
1162                 __xfrm_policy_unlink(old_pol, XFRM_POLICY_MAX+dir);
1163         write_unlock_bh(&xfrm_policy_lock);
1164
1165         if (old_pol) {
1166                 xfrm_policy_kill(old_pol);
1167         }
1168         return 0;
1169 }
1170
1171 static struct xfrm_policy *clone_policy(struct xfrm_policy *old, int dir)
1172 {
1173         struct xfrm_policy *newp = xfrm_policy_alloc(GFP_ATOMIC);
1174
1175         if (newp) {
1176                 newp->selector = old->selector;
1177                 if (security_xfrm_policy_clone(old, newp)) {
1178                         kfree(newp);
1179                         return NULL;  /* ENOMEM */
1180                 }
1181                 newp->lft = old->lft;
1182                 newp->curlft = old->curlft;
1183                 newp->action = old->action;
1184                 newp->flags = old->flags;
1185                 newp->xfrm_nr = old->xfrm_nr;
1186                 newp->index = old->index;
1187                 newp->type = old->type;
1188                 memcpy(newp->xfrm_vec, old->xfrm_vec,
1189                        newp->xfrm_nr*sizeof(struct xfrm_tmpl));
1190                 write_lock_bh(&xfrm_policy_lock);
1191                 __xfrm_policy_link(newp, XFRM_POLICY_MAX+dir);
1192                 write_unlock_bh(&xfrm_policy_lock);
1193                 xfrm_pol_put(newp);
1194         }
1195         return newp;
1196 }
1197
1198 int __xfrm_sk_clone_policy(struct sock *sk)
1199 {
1200         struct xfrm_policy *p0 = sk->sk_policy[0],
1201                            *p1 = sk->sk_policy[1];
1202
1203         sk->sk_policy[0] = sk->sk_policy[1] = NULL;
1204         if (p0 && (sk->sk_policy[0] = clone_policy(p0, 0)) == NULL)
1205                 return -ENOMEM;
1206         if (p1 && (sk->sk_policy[1] = clone_policy(p1, 1)) == NULL)
1207                 return -ENOMEM;
1208         return 0;
1209 }
1210
1211 static int
1212 xfrm_get_saddr(xfrm_address_t *local, xfrm_address_t *remote,
1213                unsigned short family)
1214 {
1215         int err;
1216         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1217
1218         if (unlikely(afinfo == NULL))
1219                 return -EINVAL;
1220         err = afinfo->get_saddr(local, remote);
1221         xfrm_policy_put_afinfo(afinfo);
1222         return err;
1223 }
1224
1225 /* Resolve list of templates for the flow, given policy. */
1226
1227 static int
1228 xfrm_tmpl_resolve_one(struct xfrm_policy *policy, struct flowi *fl,
1229                       struct xfrm_state **xfrm,
1230                       unsigned short family)
1231 {
1232         int nx;
1233         int i, error;
1234         xfrm_address_t *daddr = xfrm_flowi_daddr(fl, family);
1235         xfrm_address_t *saddr = xfrm_flowi_saddr(fl, family);
1236         xfrm_address_t tmp;
1237
1238         for (nx=0, i = 0; i < policy->xfrm_nr; i++) {
1239                 struct xfrm_state *x;
1240                 xfrm_address_t *remote = daddr;
1241                 xfrm_address_t *local  = saddr;
1242                 struct xfrm_tmpl *tmpl = &policy->xfrm_vec[i];
1243
1244                 if (tmpl->mode == XFRM_MODE_TUNNEL) {
1245                         remote = &tmpl->id.daddr;
1246                         local = &tmpl->saddr;
1247                         family = tmpl->encap_family;
1248                         if (xfrm_addr_any(local, family)) {
1249                                 error = xfrm_get_saddr(&tmp, remote, family);
1250                                 if (error)
1251                                         goto fail;
1252                                 local = &tmp;
1253                         }
1254                 }
1255
1256                 x = xfrm_state_find(remote, local, fl, tmpl, policy, &error, family);
1257
1258                 if (x && x->km.state == XFRM_STATE_VALID) {
1259                         xfrm[nx++] = x;
1260                         daddr = remote;
1261                         saddr = local;
1262                         continue;
1263                 }
1264                 if (x) {
1265                         error = (x->km.state == XFRM_STATE_ERROR ?
1266                                  -EINVAL : -EAGAIN);
1267                         xfrm_state_put(x);
1268                 }
1269
1270                 if (!tmpl->optional)
1271                         goto fail;
1272         }
1273         return nx;
1274
1275 fail:
1276         for (nx--; nx>=0; nx--)
1277                 xfrm_state_put(xfrm[nx]);
1278         return error;
1279 }
1280
1281 static int
1282 xfrm_tmpl_resolve(struct xfrm_policy **pols, int npols, struct flowi *fl,
1283                   struct xfrm_state **xfrm,
1284                   unsigned short family)
1285 {
1286         struct xfrm_state *tp[XFRM_MAX_DEPTH];
1287         struct xfrm_state **tpp = (npols > 1) ? tp : xfrm;
1288         int cnx = 0;
1289         int error;
1290         int ret;
1291         int i;
1292
1293         for (i = 0; i < npols; i++) {
1294                 if (cnx + pols[i]->xfrm_nr >= XFRM_MAX_DEPTH) {
1295                         error = -ENOBUFS;
1296                         goto fail;
1297                 }
1298
1299                 ret = xfrm_tmpl_resolve_one(pols[i], fl, &tpp[cnx], family);
1300                 if (ret < 0) {
1301                         error = ret;
1302                         goto fail;
1303                 } else
1304                         cnx += ret;
1305         }
1306
1307         /* found states are sorted for outbound processing */
1308         if (npols > 1)
1309                 xfrm_state_sort(xfrm, tpp, cnx, family);
1310
1311         return cnx;
1312
1313  fail:
1314         for (cnx--; cnx>=0; cnx--)
1315                 xfrm_state_put(tpp[cnx]);
1316         return error;
1317
1318 }
1319
1320 /* Check that the bundle accepts the flow and its components are
1321  * still valid.
1322  */
1323
1324 static struct dst_entry *
1325 xfrm_find_bundle(struct flowi *fl, struct xfrm_policy *policy, unsigned short family)
1326 {
1327         struct dst_entry *x;
1328         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1329         if (unlikely(afinfo == NULL))
1330                 return ERR_PTR(-EINVAL);
1331         x = afinfo->find_bundle(fl, policy);
1332         xfrm_policy_put_afinfo(afinfo);
1333         return x;
1334 }
1335
1336 /* Allocate chain of dst_entry's, attach known xfrm's, calculate
1337  * all the metrics... Shortly, bundle a bundle.
1338  */
1339
1340 static int
1341 xfrm_bundle_create(struct xfrm_policy *policy, struct xfrm_state **xfrm, int nx,
1342                    struct flowi *fl, struct dst_entry **dst_p,
1343                    unsigned short family)
1344 {
1345         int err;
1346         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1347         if (unlikely(afinfo == NULL))
1348                 return -EINVAL;
1349         err = afinfo->bundle_create(policy, xfrm, nx, fl, dst_p);
1350         xfrm_policy_put_afinfo(afinfo);
1351         return err;
1352 }
1353
1354 static int inline
1355 xfrm_dst_alloc_copy(void **target, void *src, int size)
1356 {
1357         if (!*target) {
1358                 *target = kmalloc(size, GFP_ATOMIC);
1359                 if (!*target)
1360                         return -ENOMEM;
1361         }
1362         memcpy(*target, src, size);
1363         return 0;
1364 }
1365
1366 static int inline
1367 xfrm_dst_update_parent(struct dst_entry *dst, struct xfrm_selector *sel)
1368 {
1369 #ifdef CONFIG_XFRM_SUB_POLICY
1370         struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
1371         return xfrm_dst_alloc_copy((void **)&(xdst->partner),
1372                                    sel, sizeof(*sel));
1373 #else
1374         return 0;
1375 #endif
1376 }
1377
1378 static int inline
1379 xfrm_dst_update_origin(struct dst_entry *dst, struct flowi *fl)
1380 {
1381 #ifdef CONFIG_XFRM_SUB_POLICY
1382         struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
1383         return xfrm_dst_alloc_copy((void **)&(xdst->origin), fl, sizeof(*fl));
1384 #else
1385         return 0;
1386 #endif
1387 }
1388
1389 static int stale_bundle(struct dst_entry *dst);
1390
1391 /* Main function: finds/creates a bundle for given flow.
1392  *
1393  * At the moment we eat a raw IP route. Mostly to speed up lookups
1394  * on interfaces with disabled IPsec.
1395  */
1396 int __xfrm_lookup(struct dst_entry **dst_p, struct flowi *fl,
1397                   struct sock *sk, int flags)
1398 {
1399         struct xfrm_policy *policy;
1400         struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
1401         int npols;
1402         int pol_dead;
1403         int xfrm_nr;
1404         int pi;
1405         struct xfrm_state *xfrm[XFRM_MAX_DEPTH];
1406         struct dst_entry *dst, *dst_orig = *dst_p;
1407         int nx = 0;
1408         int err;
1409         u32 genid;
1410         u16 family;
1411         u8 dir = policy_to_flow_dir(XFRM_POLICY_OUT);
1412
1413 restart:
1414         genid = atomic_read(&flow_cache_genid);
1415         policy = NULL;
1416         for (pi = 0; pi < ARRAY_SIZE(pols); pi++)
1417                 pols[pi] = NULL;
1418         npols = 0;
1419         pol_dead = 0;
1420         xfrm_nr = 0;
1421
1422         if (sk && sk->sk_policy[1]) {
1423                 policy = xfrm_sk_policy_lookup(sk, XFRM_POLICY_OUT, fl);
1424                 if (IS_ERR(policy))
1425                         return PTR_ERR(policy);
1426         }
1427
1428         if (!policy) {
1429                 /* To accelerate a bit...  */
1430                 if ((dst_orig->flags & DST_NOXFRM) ||
1431                     !xfrm_policy_count[XFRM_POLICY_OUT])
1432                         return 0;
1433
1434                 policy = flow_cache_lookup(fl, dst_orig->ops->family,
1435                                            dir, xfrm_policy_lookup);
1436                 if (IS_ERR(policy))
1437                         return PTR_ERR(policy);
1438         }
1439
1440         if (!policy)
1441                 return 0;
1442
1443         family = dst_orig->ops->family;
1444         policy->curlft.use_time = get_seconds();
1445         pols[0] = policy;
1446         npols ++;
1447         xfrm_nr += pols[0]->xfrm_nr;
1448
1449         switch (policy->action) {
1450         case XFRM_POLICY_BLOCK:
1451                 /* Prohibit the flow */
1452                 err = -EPERM;
1453                 goto error;
1454
1455         case XFRM_POLICY_ALLOW:
1456 #ifndef CONFIG_XFRM_SUB_POLICY
1457                 if (policy->xfrm_nr == 0) {
1458                         /* Flow passes not transformed. */
1459                         xfrm_pol_put(policy);
1460                         return 0;
1461                 }
1462 #endif
1463
1464                 /* Try to find matching bundle.
1465                  *
1466                  * LATER: help from flow cache. It is optional, this
1467                  * is required only for output policy.
1468                  */
1469                 dst = xfrm_find_bundle(fl, policy, family);
1470                 if (IS_ERR(dst)) {
1471                         err = PTR_ERR(dst);
1472                         goto error;
1473                 }
1474
1475                 if (dst)
1476                         break;
1477
1478 #ifdef CONFIG_XFRM_SUB_POLICY
1479                 if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
1480                         pols[1] = xfrm_policy_lookup_bytype(XFRM_POLICY_TYPE_MAIN,
1481                                                             fl, family,
1482                                                             XFRM_POLICY_OUT);
1483                         if (pols[1]) {
1484                                 if (IS_ERR(pols[1])) {
1485                                         err = PTR_ERR(pols[1]);
1486                                         goto error;
1487                                 }
1488                                 if (pols[1]->action == XFRM_POLICY_BLOCK) {
1489                                         err = -EPERM;
1490                                         goto error;
1491                                 }
1492                                 npols ++;
1493                                 xfrm_nr += pols[1]->xfrm_nr;
1494                         }
1495                 }
1496
1497                 /*
1498                  * Because neither flowi nor bundle information knows about
1499                  * transformation template size. On more than one policy usage
1500                  * we can realize whether all of them is bypass or not after
1501                  * they are searched. See above not-transformed bypass
1502                  * is surrounded by non-sub policy configuration, too.
1503                  */
1504                 if (xfrm_nr == 0) {
1505                         /* Flow passes not transformed. */
1506                         xfrm_pols_put(pols, npols);
1507                         return 0;
1508                 }
1509
1510 #endif
1511                 nx = xfrm_tmpl_resolve(pols, npols, fl, xfrm, family);
1512
1513                 if (unlikely(nx<0)) {
1514                         err = nx;
1515                         if (err == -EAGAIN && sysctl_xfrm_larval_drop) {
1516                                 /* EREMOTE tells the caller to generate
1517                                  * a one-shot blackhole route.
1518                                  */
1519                                 xfrm_pol_put(policy);
1520                                 return -EREMOTE;
1521                         }
1522                         if (err == -EAGAIN && flags) {
1523                                 DECLARE_WAITQUEUE(wait, current);
1524
1525                                 add_wait_queue(&km_waitq, &wait);
1526                                 set_current_state(TASK_INTERRUPTIBLE);
1527                                 schedule();
1528                                 set_current_state(TASK_RUNNING);
1529                                 remove_wait_queue(&km_waitq, &wait);
1530
1531                                 nx = xfrm_tmpl_resolve(pols, npols, fl, xfrm, family);
1532
1533                                 if (nx == -EAGAIN && signal_pending(current)) {
1534                                         err = -ERESTART;
1535                                         goto error;
1536                                 }
1537                                 if (nx == -EAGAIN ||
1538                                     genid != atomic_read(&flow_cache_genid)) {
1539                                         xfrm_pols_put(pols, npols);
1540                                         goto restart;
1541                                 }
1542                                 err = nx;
1543                         }
1544                         if (err < 0)
1545                                 goto error;
1546                 }
1547                 if (nx == 0) {
1548                         /* Flow passes not transformed. */
1549                         xfrm_pols_put(pols, npols);
1550                         return 0;
1551                 }
1552
1553                 dst = dst_orig;
1554                 err = xfrm_bundle_create(policy, xfrm, nx, fl, &dst, family);
1555
1556                 if (unlikely(err)) {
1557                         int i;
1558                         for (i=0; i<nx; i++)
1559                                 xfrm_state_put(xfrm[i]);
1560                         goto error;
1561                 }
1562
1563                 for (pi = 0; pi < npols; pi++) {
1564                         read_lock_bh(&pols[pi]->lock);
1565                         pol_dead |= pols[pi]->dead;
1566                         read_unlock_bh(&pols[pi]->lock);
1567                 }
1568
1569                 write_lock_bh(&policy->lock);
1570                 if (unlikely(pol_dead || stale_bundle(dst))) {
1571                         /* Wow! While we worked on resolving, this
1572                          * policy has gone. Retry. It is not paranoia,
1573                          * we just cannot enlist new bundle to dead object.
1574                          * We can't enlist stable bundles either.
1575                          */
1576                         write_unlock_bh(&policy->lock);
1577                         if (dst)
1578                                 dst_free(dst);
1579
1580                         err = -EHOSTUNREACH;
1581                         goto error;
1582                 }
1583
1584                 if (npols > 1)
1585                         err = xfrm_dst_update_parent(dst, &pols[1]->selector);
1586                 else
1587                         err = xfrm_dst_update_origin(dst, fl);
1588                 if (unlikely(err)) {
1589                         write_unlock_bh(&policy->lock);
1590                         if (dst)
1591                                 dst_free(dst);
1592                         goto error;
1593                 }
1594
1595                 dst->next = policy->bundles;
1596                 policy->bundles = dst;
1597                 dst_hold(dst);
1598                 write_unlock_bh(&policy->lock);
1599         }
1600         *dst_p = dst;
1601         dst_release(dst_orig);
1602         xfrm_pols_put(pols, npols);
1603         return 0;
1604
1605 error:
1606         dst_release(dst_orig);
1607         xfrm_pols_put(pols, npols);
1608         *dst_p = NULL;
1609         return err;
1610 }
1611 EXPORT_SYMBOL(__xfrm_lookup);
1612
1613 int xfrm_lookup(struct dst_entry **dst_p, struct flowi *fl,
1614                 struct sock *sk, int flags)
1615 {
1616         int err = __xfrm_lookup(dst_p, fl, sk, flags);
1617
1618         if (err == -EREMOTE) {
1619                 dst_release(*dst_p);
1620                 *dst_p = NULL;
1621                 err = -EAGAIN;
1622         }
1623
1624         return err;
1625 }
1626 EXPORT_SYMBOL(xfrm_lookup);
1627
1628 static inline int
1629 xfrm_secpath_reject(int idx, struct sk_buff *skb, struct flowi *fl)
1630 {
1631         struct xfrm_state *x;
1632         int err;
1633
1634         if (!skb->sp || idx < 0 || idx >= skb->sp->len)
1635                 return 0;
1636         x = skb->sp->xvec[idx];
1637         if (!x->type->reject)
1638                 return 0;
1639         xfrm_state_hold(x);
1640         err = x->type->reject(x, skb, fl);
1641         xfrm_state_put(x);
1642         return err;
1643 }
1644
1645 /* When skb is transformed back to its "native" form, we have to
1646  * check policy restrictions. At the moment we make this in maximally
1647  * stupid way. Shame on me. :-) Of course, connected sockets must
1648  * have policy cached at them.
1649  */
1650
1651 static inline int
1652 xfrm_state_ok(struct xfrm_tmpl *tmpl, struct xfrm_state *x,
1653               unsigned short family)
1654 {
1655         if (xfrm_state_kern(x))
1656                 return tmpl->optional && !xfrm_state_addr_cmp(tmpl, x, tmpl->encap_family);
1657         return  x->id.proto == tmpl->id.proto &&
1658                 (x->id.spi == tmpl->id.spi || !tmpl->id.spi) &&
1659                 (x->props.reqid == tmpl->reqid || !tmpl->reqid) &&
1660                 x->props.mode == tmpl->mode &&
1661                 ((tmpl->aalgos & (1<<x->props.aalgo)) ||
1662                  !(xfrm_id_proto_match(tmpl->id.proto, IPSEC_PROTO_ANY))) &&
1663                 !(x->props.mode != XFRM_MODE_TRANSPORT &&
1664                   xfrm_state_addr_cmp(tmpl, x, family));
1665 }
1666
1667 /*
1668  * 0 or more than 0 is returned when validation is succeeded (either bypass
1669  * because of optional transport mode, or next index of the mathced secpath
1670  * state with the template.
1671  * -1 is returned when no matching template is found.
1672  * Otherwise "-2 - errored_index" is returned.
1673  */
1674 static inline int
1675 xfrm_policy_ok(struct xfrm_tmpl *tmpl, struct sec_path *sp, int start,
1676                unsigned short family)
1677 {
1678         int idx = start;
1679
1680         if (tmpl->optional) {
1681                 if (tmpl->mode == XFRM_MODE_TRANSPORT)
1682                         return start;
1683         } else
1684                 start = -1;
1685         for (; idx < sp->len; idx++) {
1686                 if (xfrm_state_ok(tmpl, sp->xvec[idx], family))
1687                         return ++idx;
1688                 if (sp->xvec[idx]->props.mode != XFRM_MODE_TRANSPORT) {
1689                         if (start == -1)
1690                                 start = -2-idx;
1691                         break;
1692                 }
1693         }
1694         return start;
1695 }
1696
1697 int
1698 xfrm_decode_session(struct sk_buff *skb, struct flowi *fl, unsigned short family)
1699 {
1700         struct xfrm_policy_afinfo *afinfo = xfrm_policy_get_afinfo(family);
1701         int err;
1702
1703         if (unlikely(afinfo == NULL))
1704                 return -EAFNOSUPPORT;
1705
1706         afinfo->decode_session(skb, fl);
1707         err = security_xfrm_decode_session(skb, &fl->secid);
1708         xfrm_policy_put_afinfo(afinfo);
1709         return err;
1710 }
1711 EXPORT_SYMBOL(xfrm_decode_session);
1712
1713 static inline int secpath_has_nontransport(struct sec_path *sp, int k, int *idxp)
1714 {
1715         for (; k < sp->len; k++) {
1716                 if (sp->xvec[k]->props.mode != XFRM_MODE_TRANSPORT) {
1717                         *idxp = k;
1718                         return 1;
1719                 }
1720         }
1721
1722         return 0;
1723 }
1724
1725 int __xfrm_policy_check(struct sock *sk, int dir, struct sk_buff *skb,
1726                         unsigned short family)
1727 {
1728         struct xfrm_policy *pol;
1729         struct xfrm_policy *pols[XFRM_POLICY_TYPE_MAX];
1730         int npols = 0;
1731         int xfrm_nr;
1732         int pi;
1733         struct flowi fl;
1734         u8 fl_dir = policy_to_flow_dir(dir);
1735         int xerr_idx = -1;
1736
1737         if (xfrm_decode_session(skb, &fl, family) < 0)
1738                 return 0;
1739         nf_nat_decode_session(skb, &fl, family);
1740
1741         /* First, check used SA against their selectors. */
1742         if (skb->sp) {
1743                 int i;
1744
1745                 for (i=skb->sp->len-1; i>=0; i--) {
1746                         struct xfrm_state *x = skb->sp->xvec[i];
1747                         if (!xfrm_selector_match(&x->sel, &fl, family))
1748                                 return 0;
1749                 }
1750         }
1751
1752         pol = NULL;
1753         if (sk && sk->sk_policy[dir]) {
1754                 pol = xfrm_sk_policy_lookup(sk, dir, &fl);
1755                 if (IS_ERR(pol))
1756                         return 0;
1757         }
1758
1759         if (!pol)
1760                 pol = flow_cache_lookup(&fl, family, fl_dir,
1761                                         xfrm_policy_lookup);
1762
1763         if (IS_ERR(pol))
1764                 return 0;
1765
1766         if (!pol) {
1767                 if (skb->sp && secpath_has_nontransport(skb->sp, 0, &xerr_idx)) {
1768                         xfrm_secpath_reject(xerr_idx, skb, &fl);
1769                         return 0;
1770                 }
1771                 return 1;
1772         }
1773
1774         pol->curlft.use_time = get_seconds();
1775
1776         pols[0] = pol;
1777         npols ++;
1778 #ifdef CONFIG_XFRM_SUB_POLICY
1779         if (pols[0]->type != XFRM_POLICY_TYPE_MAIN) {
1780                 pols[1] = xfrm_policy_lookup_bytype(XFRM_POLICY_TYPE_MAIN,
1781                                                     &fl, family,
1782                                                     XFRM_POLICY_IN);
1783                 if (pols[1]) {
1784                         if (IS_ERR(pols[1]))
1785                                 return 0;
1786                         pols[1]->curlft.use_time = get_seconds();
1787                         npols ++;
1788                 }
1789         }
1790 #endif
1791
1792         if (pol->action == XFRM_POLICY_ALLOW) {
1793                 struct sec_path *sp;
1794                 static struct sec_path dummy;
1795                 struct xfrm_tmpl *tp[XFRM_MAX_DEPTH];
1796                 struct xfrm_tmpl *stp[XFRM_MAX_DEPTH];
1797                 struct xfrm_tmpl **tpp = tp;
1798                 int ti = 0;
1799                 int i, k;
1800
1801                 if ((sp = skb->sp) == NULL)
1802                         sp = &dummy;
1803
1804                 for (pi = 0; pi < npols; pi++) {
1805                         if (pols[pi] != pol &&
1806                             pols[pi]->action != XFRM_POLICY_ALLOW)
1807                                 goto reject;
1808                         if (ti + pols[pi]->xfrm_nr >= XFRM_MAX_DEPTH)
1809                                 goto reject_error;
1810                         for (i = 0; i < pols[pi]->xfrm_nr; i++)
1811                                 tpp[ti++] = &pols[pi]->xfrm_vec[i];
1812                 }
1813                 xfrm_nr = ti;
1814                 if (npols > 1) {
1815                         xfrm_tmpl_sort(stp, tpp, xfrm_nr, family);
1816                         tpp = stp;
1817                 }
1818
1819                 /* For each tunnel xfrm, find the first matching tmpl.
1820                  * For each tmpl before that, find corresponding xfrm.
1821                  * Order is _important_. Later we will implement
1822                  * some barriers, but at the moment barriers
1823                  * are implied between each two transformations.
1824                  */
1825                 for (i = xfrm_nr-1, k = 0; i >= 0; i--) {
1826                         k = xfrm_policy_ok(tpp[i], sp, k, family);
1827                         if (k < 0) {
1828                                 if (k < -1)
1829                                         /* "-2 - errored_index" returned */
1830                                         xerr_idx = -(2+k);
1831                                 goto reject;
1832                         }
1833                 }
1834
1835                 if (secpath_has_nontransport(sp, k, &xerr_idx))
1836                         goto reject;
1837
1838                 xfrm_pols_put(pols, npols);
1839                 return 1;
1840         }
1841
1842 reject:
1843         xfrm_secpath_reject(xerr_idx, skb, &fl);
1844 reject_error:
1845         xfrm_pols_put(pols, npols);
1846         return 0;
1847 }
1848 EXPORT_SYMBOL(__xfrm_policy_check);
1849
1850 int __xfrm_route_forward(struct sk_buff *skb, unsigned short family)
1851 {
1852         struct flowi fl;
1853
1854         if (xfrm_decode_session(skb, &fl, family) < 0)
1855                 return 0;
1856
1857         return xfrm_lookup(&skb->dst, &fl, NULL, 0) == 0;
1858 }
1859 EXPORT_SYMBOL(__xfrm_route_forward);
1860
1861 /* Optimize later using cookies and generation ids. */
1862
1863 static struct dst_entry *xfrm_dst_check(struct dst_entry *dst, u32 cookie)
1864 {
1865         /* Code (such as __xfrm4_bundle_create()) sets dst->obsolete
1866          * to "-1" to force all XFRM destinations to get validated by
1867          * dst_ops->check on every use.  We do this because when a
1868          * normal route referenced by an XFRM dst is obsoleted we do
1869          * not go looking around for all parent referencing XFRM dsts
1870          * so that we can invalidate them.  It is just too much work.
1871          * Instead we make the checks here on every use.  For example:
1872          *
1873          *      XFRM dst A --> IPv4 dst X
1874          *
1875          * X is the "xdst->route" of A (X is also the "dst->path" of A
1876          * in this example).  If X is marked obsolete, "A" will not
1877          * notice.  That's what we are validating here via the
1878          * stale_bundle() check.
1879          *
1880          * When a policy's bundle is pruned, we dst_free() the XFRM
1881          * dst which causes it's ->obsolete field to be set to a
1882          * positive non-zero integer.  If an XFRM dst has been pruned
1883          * like this, we want to force a new route lookup.
1884          */
1885         if (dst->obsolete < 0 && !stale_bundle(dst))
1886                 return dst;
1887
1888         return NULL;
1889 }
1890
1891 static int stale_bundle(struct dst_entry *dst)
1892 {
1893         return !xfrm_bundle_ok(NULL, (struct xfrm_dst *)dst, NULL, AF_UNSPEC, 0);
1894 }
1895
1896 void xfrm_dst_ifdown(struct dst_entry *dst, struct net_device *dev)
1897 {
1898         while ((dst = dst->child) && dst->xfrm && dst->dev == dev) {
1899                 dst->dev = &loopback_dev;
1900                 dev_hold(&loopback_dev);
1901                 dev_put(dev);
1902         }
1903 }
1904 EXPORT_SYMBOL(xfrm_dst_ifdown);
1905
1906 static void xfrm_link_failure(struct sk_buff *skb)
1907 {
1908         /* Impossible. Such dst must be popped before reaches point of failure. */
1909         return;
1910 }
1911
1912 static struct dst_entry *xfrm_negative_advice(struct dst_entry *dst)
1913 {
1914         if (dst) {
1915                 if (dst->obsolete) {
1916                         dst_release(dst);
1917                         dst = NULL;
1918                 }
1919         }
1920         return dst;
1921 }
1922
1923 static void prune_one_bundle(struct xfrm_policy *pol, int (*func)(struct dst_entry *), struct dst_entry **gc_list_p)
1924 {
1925         struct dst_entry *dst, **dstp;
1926
1927         write_lock(&pol->lock);
1928         dstp = &pol->bundles;
1929         while ((dst=*dstp) != NULL) {
1930                 if (func(dst)) {
1931                         *dstp = dst->next;
1932                         dst->next = *gc_list_p;
1933                         *gc_list_p = dst;
1934                 } else {
1935                         dstp = &dst->next;
1936                 }
1937         }
1938         write_unlock(&pol->lock);
1939 }
1940
1941 static void xfrm_prune_bundles(int (*func)(struct dst_entry *))
1942 {
1943         struct dst_entry *gc_list = NULL;
1944         int dir;
1945
1946         read_lock_bh(&xfrm_policy_lock);
1947         for (dir = 0; dir < XFRM_POLICY_MAX * 2; dir++) {
1948                 struct xfrm_policy *pol;
1949                 struct hlist_node *entry;
1950                 struct hlist_head *table;
1951                 int i;
1952
1953                 hlist_for_each_entry(pol, entry,
1954                                      &xfrm_policy_inexact[dir], bydst)
1955                         prune_one_bundle(pol, func, &gc_list);
1956
1957                 table = xfrm_policy_bydst[dir].table;
1958                 for (i = xfrm_policy_bydst[dir].hmask; i >= 0; i--) {
1959                         hlist_for_each_entry(pol, entry, table + i, bydst)
1960                                 prune_one_bundle(pol, func, &gc_list);
1961                 }
1962         }
1963         read_unlock_bh(&xfrm_policy_lock);
1964
1965         while (gc_list) {
1966                 struct dst_entry *dst = gc_list;
1967                 gc_list = dst->next;
1968                 dst_free(dst);
1969         }
1970 }
1971
1972 static int unused_bundle(struct dst_entry *dst)
1973 {
1974         return !atomic_read(&dst->__refcnt);
1975 }
1976
1977 static void __xfrm_garbage_collect(void)
1978 {
1979         xfrm_prune_bundles(unused_bundle);
1980 }
1981
1982 static int xfrm_flush_bundles(void)
1983 {
1984         xfrm_prune_bundles(stale_bundle);
1985         return 0;
1986 }
1987
1988 void xfrm_init_pmtu(struct dst_entry *dst)
1989 {
1990         do {
1991                 struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
1992                 u32 pmtu, route_mtu_cached;
1993
1994                 pmtu = dst_mtu(dst->child);
1995                 xdst->child_mtu_cached = pmtu;
1996
1997                 pmtu = xfrm_state_mtu(dst->xfrm, pmtu);
1998
1999                 route_mtu_cached = dst_mtu(xdst->route);
2000                 xdst->route_mtu_cached = route_mtu_cached;
2001
2002                 if (pmtu > route_mtu_cached)
2003                         pmtu = route_mtu_cached;
2004
2005                 dst->metrics[RTAX_MTU-1] = pmtu;
2006         } while ((dst = dst->next));
2007 }
2008
2009 EXPORT_SYMBOL(xfrm_init_pmtu);
2010
2011 /* Check that the bundle accepts the flow and its components are
2012  * still valid.
2013  */
2014
2015 int xfrm_bundle_ok(struct xfrm_policy *pol, struct xfrm_dst *first,
2016                 struct flowi *fl, int family, int strict)
2017 {
2018         struct dst_entry *dst = &first->u.dst;
2019         struct xfrm_dst *last;
2020         u32 mtu;
2021
2022         if (!dst_check(dst->path, ((struct xfrm_dst *)dst)->path_cookie) ||
2023             (dst->dev && !netif_running(dst->dev)))
2024                 return 0;
2025 #ifdef CONFIG_XFRM_SUB_POLICY
2026         if (fl) {
2027                 if (first->origin && !flow_cache_uli_match(first->origin, fl))
2028                         return 0;
2029                 if (first->partner &&
2030                     !xfrm_selector_match(first->partner, fl, family))
2031                         return 0;
2032         }
2033 #endif
2034
2035         last = NULL;
2036
2037         do {
2038                 struct xfrm_dst *xdst = (struct xfrm_dst *)dst;
2039
2040                 if (fl && !xfrm_selector_match(&dst->xfrm->sel, fl, family))
2041                         return 0;
2042                 if (fl && pol &&
2043                     !security_xfrm_state_pol_flow_match(dst->xfrm, pol, fl))
2044                         return 0;
2045                 if (dst->xfrm->km.state != XFRM_STATE_VALID)
2046                         return 0;
2047                 if (xdst->genid != dst->xfrm->genid)
2048                         return 0;
2049
2050                 if (strict && fl && dst->xfrm->props.mode != XFRM_MODE_TUNNEL &&
2051                     !xfrm_state_addr_flow_check(dst->xfrm, fl, family))
2052                         return 0;
2053
2054                 mtu = dst_mtu(dst->child);
2055                 if (xdst->child_mtu_cached != mtu) {
2056                         last = xdst;
2057                         xdst->child_mtu_cached = mtu;
2058                 }
2059
2060                 if (!dst_check(xdst->route, xdst->route_cookie))
2061                         return 0;
2062                 mtu = dst_mtu(xdst->route);
2063                 if (xdst->route_mtu_cached != mtu) {
2064                         last = xdst;
2065                         xdst->route_mtu_cached = mtu;
2066                 }
2067
2068                 dst = dst->child;
2069         } while (dst->xfrm);
2070
2071         if (likely(!last))
2072                 return 1;
2073
2074         mtu = last->child_mtu_cached;
2075         for (;;) {
2076                 dst = &last->u.dst;
2077
2078                 mtu = xfrm_state_mtu(dst->xfrm, mtu);
2079                 if (mtu > last->route_mtu_cached)
2080                         mtu = last->route_mtu_cached;
2081                 dst->metrics[RTAX_MTU-1] = mtu;
2082
2083                 if (last == first)
2084                         break;
2085
2086                 last = last->u.next;
2087                 last->child_mtu_cached = mtu;
2088         }
2089
2090         return 1;
2091 }
2092
2093 EXPORT_SYMBOL(xfrm_bundle_ok);
2094
2095 #ifdef CONFIG_AUDITSYSCALL
2096 /* Audit addition and deletion of SAs and ipsec policy */
2097
2098 void xfrm_audit_log(uid_t auid, u32 sid, int type, int result,
2099                     struct xfrm_policy *xp, struct xfrm_state *x)
2100 {
2101
2102         char *secctx;
2103         u32 secctx_len;
2104         struct xfrm_sec_ctx *sctx = NULL;
2105         struct audit_buffer *audit_buf;
2106         int family;
2107         extern int audit_enabled;
2108
2109         if (audit_enabled == 0)
2110                 return;
2111
2112         BUG_ON((type == AUDIT_MAC_IPSEC_ADDSA ||
2113                 type == AUDIT_MAC_IPSEC_DELSA) && !x);
2114         BUG_ON((type == AUDIT_MAC_IPSEC_ADDSPD ||
2115                 type == AUDIT_MAC_IPSEC_DELSPD) && !xp);
2116
2117         audit_buf = audit_log_start(current->audit_context, GFP_ATOMIC, type);
2118         if (audit_buf == NULL)
2119                 return;
2120
2121         switch(type) {
2122         case AUDIT_MAC_IPSEC_ADDSA:
2123                 audit_log_format(audit_buf, "SAD add: auid=%u", auid);
2124                 break;
2125         case AUDIT_MAC_IPSEC_DELSA:
2126                 audit_log_format(audit_buf, "SAD delete: auid=%u", auid);
2127                 break;
2128         case AUDIT_MAC_IPSEC_ADDSPD:
2129                 audit_log_format(audit_buf, "SPD add: auid=%u", auid);
2130                 break;
2131         case AUDIT_MAC_IPSEC_DELSPD:
2132                 audit_log_format(audit_buf, "SPD delete: auid=%u", auid);
2133                 break;
2134         default:
2135                 return;
2136         }
2137
2138         if (sid != 0 &&
2139                 security_secid_to_secctx(sid, &secctx, &secctx_len) == 0)
2140                 audit_log_format(audit_buf, " subj=%s", secctx);
2141         else
2142                 audit_log_task_context(audit_buf);
2143
2144         if (xp) {
2145                 family = xp->selector.family;
2146                 if (xp->security)
2147                         sctx = xp->security;
2148         } else {
2149                 family = x->props.family;
2150                 if (x->security)
2151                         sctx = x->security;
2152         }
2153
2154         if (sctx)
2155                 audit_log_format(audit_buf,
2156                                 " sec_alg=%u sec_doi=%u sec_obj=%s",
2157                                 sctx->ctx_alg, sctx->ctx_doi, sctx->ctx_str);
2158
2159         switch(family) {
2160         case AF_INET:
2161                 {
2162                         struct in_addr saddr, daddr;
2163                         if (xp) {
2164                                 saddr.s_addr = xp->selector.saddr.a4;
2165                                 daddr.s_addr = xp->selector.daddr.a4;
2166                         } else {
2167                                 saddr.s_addr = x->props.saddr.a4;
2168                                 daddr.s_addr = x->id.daddr.a4;
2169                         }
2170                         audit_log_format(audit_buf,
2171                                          " src=%u.%u.%u.%u dst=%u.%u.%u.%u",
2172                                          NIPQUAD(saddr), NIPQUAD(daddr));
2173                 }
2174                         break;
2175         case AF_INET6:
2176                 {
2177                         struct in6_addr saddr6, daddr6;
2178                         if (xp) {
2179                                 memcpy(&saddr6, xp->selector.saddr.a6,
2180                                         sizeof(struct in6_addr));
2181                                 memcpy(&daddr6, xp->selector.daddr.a6,
2182                                         sizeof(struct in6_addr));
2183                         } else {
2184                                 memcpy(&saddr6, x->props.saddr.a6,
2185                                         sizeof(struct in6_addr));
2186                                 memcpy(&daddr6, x->id.daddr.a6,
2187                                         sizeof(struct in6_addr));
2188                         }
2189                         audit_log_format(audit_buf,
2190                                          " src=" NIP6_FMT " dst=" NIP6_FMT,
2191                                          NIP6(saddr6), NIP6(daddr6));
2192                 }
2193                 break;
2194         }
2195
2196         if (x)
2197                 audit_log_format(audit_buf, " spi=%lu(0x%lx) protocol=%s",
2198                                 (unsigned long)ntohl(x->id.spi),
2199                                 (unsigned long)ntohl(x->id.spi),
2200                                 x->id.proto == IPPROTO_AH ? "AH" :
2201                                 (x->id.proto == IPPROTO_ESP ?
2202                                 "ESP" : "IPCOMP"));
2203
2204         audit_log_format(audit_buf, " res=%u", result);
2205         audit_log_end(audit_buf);
2206 }
2207
2208 EXPORT_SYMBOL(xfrm_audit_log);
2209 #endif /* CONFIG_AUDITSYSCALL */
2210
2211 int xfrm_policy_register_afinfo(struct xfrm_policy_afinfo *afinfo)
2212 {
2213         int err = 0;
2214         if (unlikely(afinfo == NULL))
2215                 return -EINVAL;
2216         if (unlikely(afinfo->family >= NPROTO))
2217                 return -EAFNOSUPPORT;
2218         write_lock_bh(&xfrm_policy_afinfo_lock);
2219         if (unlikely(xfrm_policy_afinfo[afinfo->family] != NULL))
2220                 err = -ENOBUFS;
2221         else {
2222                 struct dst_ops *dst_ops = afinfo->dst_ops;
2223                 if (likely(dst_ops->kmem_cachep == NULL))
2224                         dst_ops->kmem_cachep = xfrm_dst_cache;
2225                 if (likely(dst_ops->check == NULL))
2226                         dst_ops->check = xfrm_dst_check;
2227                 if (likely(dst_ops->negative_advice == NULL))
2228                         dst_ops->negative_advice = xfrm_negative_advice;
2229                 if (likely(dst_ops->link_failure == NULL))
2230                         dst_ops->link_failure = xfrm_link_failure;
2231                 if (likely(afinfo->garbage_collect == NULL))
2232                         afinfo->garbage_collect = __xfrm_garbage_collect;
2233                 xfrm_policy_afinfo[afinfo->family] = afinfo;
2234         }
2235         write_unlock_bh(&xfrm_policy_afinfo_lock);
2236         return err;
2237 }
2238 EXPORT_SYMBOL(xfrm_policy_register_afinfo);
2239
2240 int xfrm_policy_unregister_afinfo(struct xfrm_policy_afinfo *afinfo)
2241 {
2242         int err = 0;
2243         if (unlikely(afinfo == NULL))
2244                 return -EINVAL;
2245         if (unlikely(afinfo->family >= NPROTO))
2246                 return -EAFNOSUPPORT;
2247         write_lock_bh(&xfrm_policy_afinfo_lock);
2248         if (likely(xfrm_policy_afinfo[afinfo->family] != NULL)) {
2249                 if (unlikely(xfrm_policy_afinfo[afinfo->family] != afinfo))
2250                         err = -EINVAL;
2251                 else {
2252                         struct dst_ops *dst_ops = afinfo->dst_ops;
2253                         xfrm_policy_afinfo[afinfo->family] = NULL;
2254                         dst_ops->kmem_cachep = NULL;
2255                         dst_ops->check = NULL;
2256                         dst_ops->negative_advice = NULL;
2257                         dst_ops->link_failure = NULL;
2258                         afinfo->garbage_collect = NULL;
2259                 }
2260         }
2261         write_unlock_bh(&xfrm_policy_afinfo_lock);
2262         return err;
2263 }
2264 EXPORT_SYMBOL(xfrm_policy_unregister_afinfo);
2265
2266 static struct xfrm_policy_afinfo *xfrm_policy_get_afinfo(unsigned short family)
2267 {
2268         struct xfrm_policy_afinfo *afinfo;
2269         if (unlikely(family >= NPROTO))
2270                 return NULL;
2271         read_lock(&xfrm_policy_afinfo_lock);
2272         afinfo = xfrm_policy_afinfo[family];
2273         if (unlikely(!afinfo))
2274                 read_unlock(&xfrm_policy_afinfo_lock);
2275         return afinfo;
2276 }
2277
2278 static void xfrm_policy_put_afinfo(struct xfrm_policy_afinfo *afinfo)
2279 {
2280         read_unlock(&xfrm_policy_afinfo_lock);
2281 }
2282
2283 static struct xfrm_policy_afinfo *xfrm_policy_lock_afinfo(unsigned int family)
2284 {
2285         struct xfrm_policy_afinfo *afinfo;
2286         if (unlikely(family >= NPROTO))
2287                 return NULL;
2288         write_lock_bh(&xfrm_policy_afinfo_lock);
2289         afinfo = xfrm_policy_afinfo[family];
2290         if (unlikely(!afinfo))
2291                 write_unlock_bh(&xfrm_policy_afinfo_lock);
2292         return afinfo;
2293 }
2294
2295 static void xfrm_policy_unlock_afinfo(struct xfrm_policy_afinfo *afinfo)
2296 {
2297         write_unlock_bh(&xfrm_policy_afinfo_lock);
2298 }
2299
2300 static int xfrm_dev_event(struct notifier_block *this, unsigned long event, void *ptr)
2301 {
2302         switch (event) {
2303         case NETDEV_DOWN:
2304                 xfrm_flush_bundles();
2305         }
2306         return NOTIFY_DONE;
2307 }
2308
2309 static struct notifier_block xfrm_dev_notifier = {
2310         xfrm_dev_event,
2311         NULL,
2312         0
2313 };
2314
2315 static void __init xfrm_policy_init(void)
2316 {
2317         unsigned int hmask, sz;
2318         int dir;
2319
2320         xfrm_dst_cache = kmem_cache_create("xfrm_dst_cache",
2321                                            sizeof(struct xfrm_dst),
2322                                            0, SLAB_HWCACHE_ALIGN|SLAB_PANIC,
2323                                            NULL, NULL);
2324
2325         hmask = 8 - 1;
2326         sz = (hmask+1) * sizeof(struct hlist_head);
2327
2328         xfrm_policy_byidx = xfrm_hash_alloc(sz);
2329         xfrm_idx_hmask = hmask;
2330         if (!xfrm_policy_byidx)
2331                 panic("XFRM: failed to allocate byidx hash\n");
2332
2333         for (dir = 0; dir < XFRM_POLICY_MAX * 2; dir++) {
2334                 struct xfrm_policy_hash *htab;
2335
2336                 INIT_HLIST_HEAD(&xfrm_policy_inexact[dir]);
2337
2338                 htab = &xfrm_policy_bydst[dir];
2339                 htab->table = xfrm_hash_alloc(sz);
2340                 htab->hmask = hmask;
2341                 if (!htab->table)
2342                         panic("XFRM: failed to allocate bydst hash\n");
2343         }
2344
2345         INIT_WORK(&xfrm_policy_gc_work, xfrm_policy_gc_task);
2346         register_netdevice_notifier(&xfrm_dev_notifier);
2347 }
2348
2349 void __init xfrm_init(void)
2350 {
2351         xfrm_state_init();
2352         xfrm_policy_init();
2353         xfrm_input_init();
2354 }
2355
2356 #ifdef CONFIG_XFRM_MIGRATE
2357 static int xfrm_migrate_selector_match(struct xfrm_selector *sel_cmp,
2358                                        struct xfrm_selector *sel_tgt)
2359 {
2360         if (sel_cmp->proto == IPSEC_ULPROTO_ANY) {
2361                 if (sel_tgt->family == sel_cmp->family &&
2362                     xfrm_addr_cmp(&sel_tgt->daddr, &sel_cmp->daddr,
2363                                   sel_cmp->family) == 0 &&
2364                     xfrm_addr_cmp(&sel_tgt->saddr, &sel_cmp->saddr,
2365                                   sel_cmp->family) == 0 &&
2366                     sel_tgt->prefixlen_d == sel_cmp->prefixlen_d &&
2367                     sel_tgt->prefixlen_s == sel_cmp->prefixlen_s) {
2368                         return 1;
2369                 }
2370         } else {
2371                 if (memcmp(sel_tgt, sel_cmp, sizeof(*sel_tgt)) == 0) {
2372                         return 1;
2373                 }
2374         }
2375         return 0;
2376 }
2377
2378 static struct xfrm_policy * xfrm_migrate_policy_find(struct xfrm_selector *sel,
2379                                                      u8 dir, u8 type)
2380 {
2381         struct xfrm_policy *pol, *ret = NULL;
2382         struct hlist_node *entry;
2383         struct hlist_head *chain;
2384         u32 priority = ~0U;
2385
2386         read_lock_bh(&xfrm_policy_lock);
2387         chain = policy_hash_direct(&sel->daddr, &sel->saddr, sel->family, dir);
2388         hlist_for_each_entry(pol, entry, chain, bydst) {
2389                 if (xfrm_migrate_selector_match(sel, &pol->selector) &&
2390                     pol->type == type) {
2391                         ret = pol;
2392                         priority = ret->priority;
2393                         break;
2394                 }
2395         }
2396         chain = &xfrm_policy_inexact[dir];
2397         hlist_for_each_entry(pol, entry, chain, bydst) {
2398                 if (xfrm_migrate_selector_match(sel, &pol->selector) &&
2399                     pol->type == type &&
2400                     pol->priority < priority) {
2401                         ret = pol;
2402                         break;
2403                 }
2404         }
2405
2406         if (ret)
2407                 xfrm_pol_hold(ret);
2408
2409         read_unlock_bh(&xfrm_policy_lock);
2410
2411         return ret;
2412 }
2413
2414 static int migrate_tmpl_match(struct xfrm_migrate *m, struct xfrm_tmpl *t)
2415 {
2416         int match = 0;
2417
2418         if (t->mode == m->mode && t->id.proto == m->proto &&
2419             (m->reqid == 0 || t->reqid == m->reqid)) {
2420                 switch (t->mode) {
2421                 case XFRM_MODE_TUNNEL:
2422                 case XFRM_MODE_BEET:
2423                         if (xfrm_addr_cmp(&t->id.daddr, &m->old_daddr,
2424                                           m->old_family) == 0 &&
2425                             xfrm_addr_cmp(&t->saddr, &m->old_saddr,
2426                                           m->old_family) == 0) {
2427                                 match = 1;
2428                         }
2429                         break;
2430                 case XFRM_MODE_TRANSPORT:
2431                         /* in case of transport mode, template does not store
2432                            any IP addresses, hence we just compare mode and
2433                            protocol */
2434                         match = 1;
2435                         break;
2436                 default:
2437                         break;
2438                 }
2439         }
2440         return match;
2441 }
2442
2443 /* update endpoint address(es) of template(s) */
2444 static int xfrm_policy_migrate(struct xfrm_policy *pol,
2445                                struct xfrm_migrate *m, int num_migrate)
2446 {
2447         struct xfrm_migrate *mp;
2448         struct dst_entry *dst;
2449         int i, j, n = 0;
2450
2451         write_lock_bh(&pol->lock);
2452         if (unlikely(pol->dead)) {
2453                 /* target policy has been deleted */
2454                 write_unlock_bh(&pol->lock);
2455                 return -ENOENT;
2456         }
2457
2458         for (i = 0; i < pol->xfrm_nr; i++) {
2459                 for (j = 0, mp = m; j < num_migrate; j++, mp++) {
2460                         if (!migrate_tmpl_match(mp, &pol->xfrm_vec[i]))
2461                                 continue;
2462                         n++;
2463                         if (pol->xfrm_vec[i].mode != XFRM_MODE_TUNNEL)
2464                                 continue;
2465                         /* update endpoints */
2466                         memcpy(&pol->xfrm_vec[i].id.daddr, &mp->new_daddr,
2467                                sizeof(pol->xfrm_vec[i].id.daddr));
2468                         memcpy(&pol->xfrm_vec[i].saddr, &mp->new_saddr,
2469                                sizeof(pol->xfrm_vec[i].saddr));
2470                         pol->xfrm_vec[i].encap_family = mp->new_family;
2471                         /* flush bundles */
2472                         while ((dst = pol->bundles) != NULL) {
2473                                 pol->bundles = dst->next;
2474                                 dst_free(dst);
2475                         }
2476                 }
2477         }
2478
2479         write_unlock_bh(&pol->lock);
2480
2481         if (!n)
2482                 return -ENODATA;
2483
2484         return 0;
2485 }
2486
2487 static int xfrm_migrate_check(struct xfrm_migrate *m, int num_migrate)
2488 {
2489         int i, j;
2490
2491         if (num_migrate < 1 || num_migrate > XFRM_MAX_DEPTH)
2492                 return -EINVAL;
2493
2494         for (i = 0; i < num_migrate; i++) {
2495                 if ((xfrm_addr_cmp(&m[i].old_daddr, &m[i].new_daddr,
2496                                    m[i].old_family) == 0) &&
2497                     (xfrm_addr_cmp(&m[i].old_saddr, &m[i].new_saddr,
2498                                    m[i].old_family) == 0))
2499                         return -EINVAL;
2500                 if (xfrm_addr_any(&m[i].new_daddr, m[i].new_family) ||
2501                     xfrm_addr_any(&m[i].new_saddr, m[i].new_family))
2502                         return -EINVAL;
2503
2504                 /* check if there is any duplicated entry */
2505                 for (j = i + 1; j < num_migrate; j++) {
2506                         if (!memcmp(&m[i].old_daddr, &m[j].old_daddr,
2507                                     sizeof(m[i].old_daddr)) &&
2508                             !memcmp(&m[i].old_saddr, &m[j].old_saddr,
2509                                     sizeof(m[i].old_saddr)) &&
2510                             m[i].proto == m[j].proto &&
2511                             m[i].mode == m[j].mode &&
2512                             m[i].reqid == m[j].reqid &&
2513                             m[i].old_family == m[j].old_family)
2514                                 return -EINVAL;
2515                 }
2516         }
2517
2518         return 0;
2519 }
2520
2521 int xfrm_migrate(struct xfrm_selector *sel, u8 dir, u8 type,
2522                  struct xfrm_migrate *m, int num_migrate)
2523 {
2524         int i, err, nx_cur = 0, nx_new = 0;
2525         struct xfrm_policy *pol = NULL;
2526         struct xfrm_state *x, *xc;
2527         struct xfrm_state *x_cur[XFRM_MAX_DEPTH];
2528         struct xfrm_state *x_new[XFRM_MAX_DEPTH];
2529         struct xfrm_migrate *mp;
2530
2531         if ((err = xfrm_migrate_check(m, num_migrate)) < 0)
2532                 goto out;
2533
2534         /* Stage 1 - find policy */
2535         if ((pol = xfrm_migrate_policy_find(sel, dir, type)) == NULL) {
2536                 err = -ENOENT;
2537                 goto out;
2538         }
2539
2540         /* Stage 2 - find and update state(s) */
2541         for (i = 0, mp = m; i < num_migrate; i++, mp++) {
2542                 if ((x = xfrm_migrate_state_find(mp))) {
2543                         x_cur[nx_cur] = x;
2544                         nx_cur++;
2545                         if ((xc = xfrm_state_migrate(x, mp))) {
2546                                 x_new[nx_new] = xc;
2547                                 nx_new++;
2548                         } else {
2549                                 err = -ENODATA;
2550                                 goto restore_state;
2551                         }
2552                 }
2553         }
2554
2555         /* Stage 3 - update policy */
2556         if ((err = xfrm_policy_migrate(pol, m, num_migrate)) < 0)
2557                 goto restore_state;
2558
2559         /* Stage 4 - delete old state(s) */
2560         if (nx_cur) {
2561                 xfrm_states_put(x_cur, nx_cur);
2562                 xfrm_states_delete(x_cur, nx_cur);
2563         }
2564
2565         /* Stage 5 - announce */
2566         km_migrate(sel, dir, type, m, num_migrate);
2567
2568         xfrm_pol_put(pol);
2569
2570         return 0;
2571 out:
2572         return err;
2573
2574 restore_state:
2575         if (pol)
2576                 xfrm_pol_put(pol);
2577         if (nx_cur)
2578                 xfrm_states_put(x_cur, nx_cur);
2579         if (nx_new)
2580                 xfrm_states_delete(x_new, nx_new);
2581
2582         return err;
2583 }
2584 EXPORT_SYMBOL(xfrm_migrate);
2585 #endif
2586