Revert "xfrm: state and policy should fail if XFRMA_IF_ID 0"
[linux-2.6-microblaze.git] / net / xfrm / xfrm_user.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* xfrm_user.c: User interface to configure xfrm engine.
3  *
4  * Copyright (C) 2002 David S. Miller (davem@redhat.com)
5  *
6  * Changes:
7  *      Mitsuru KANDA @USAGI
8  *      Kazunori MIYAZAWA @USAGI
9  *      Kunihiro Ishiguro <kunihiro@ipinfusion.com>
10  *              IPv6 support
11  *
12  */
13
14 #include <linux/compat.h>
15 #include <linux/crypto.h>
16 #include <linux/module.h>
17 #include <linux/kernel.h>
18 #include <linux/types.h>
19 #include <linux/slab.h>
20 #include <linux/socket.h>
21 #include <linux/string.h>
22 #include <linux/net.h>
23 #include <linux/skbuff.h>
24 #include <linux/pfkeyv2.h>
25 #include <linux/ipsec.h>
26 #include <linux/init.h>
27 #include <linux/security.h>
28 #include <net/sock.h>
29 #include <net/xfrm.h>
30 #include <net/netlink.h>
31 #include <net/ah.h>
32 #include <linux/uaccess.h>
33 #if IS_ENABLED(CONFIG_IPV6)
34 #include <linux/in6.h>
35 #endif
36 #include <asm/unaligned.h>
37
38 static int verify_one_alg(struct nlattr **attrs, enum xfrm_attr_type_t type)
39 {
40         struct nlattr *rt = attrs[type];
41         struct xfrm_algo *algp;
42
43         if (!rt)
44                 return 0;
45
46         algp = nla_data(rt);
47         if (nla_len(rt) < (int)xfrm_alg_len(algp))
48                 return -EINVAL;
49
50         switch (type) {
51         case XFRMA_ALG_AUTH:
52         case XFRMA_ALG_CRYPT:
53         case XFRMA_ALG_COMP:
54                 break;
55
56         default:
57                 return -EINVAL;
58         }
59
60         algp->alg_name[sizeof(algp->alg_name) - 1] = '\0';
61         return 0;
62 }
63
64 static int verify_auth_trunc(struct nlattr **attrs)
65 {
66         struct nlattr *rt = attrs[XFRMA_ALG_AUTH_TRUNC];
67         struct xfrm_algo_auth *algp;
68
69         if (!rt)
70                 return 0;
71
72         algp = nla_data(rt);
73         if (nla_len(rt) < (int)xfrm_alg_auth_len(algp))
74                 return -EINVAL;
75
76         algp->alg_name[sizeof(algp->alg_name) - 1] = '\0';
77         return 0;
78 }
79
80 static int verify_aead(struct nlattr **attrs)
81 {
82         struct nlattr *rt = attrs[XFRMA_ALG_AEAD];
83         struct xfrm_algo_aead *algp;
84
85         if (!rt)
86                 return 0;
87
88         algp = nla_data(rt);
89         if (nla_len(rt) < (int)aead_len(algp))
90                 return -EINVAL;
91
92         algp->alg_name[sizeof(algp->alg_name) - 1] = '\0';
93         return 0;
94 }
95
96 static void verify_one_addr(struct nlattr **attrs, enum xfrm_attr_type_t type,
97                            xfrm_address_t **addrp)
98 {
99         struct nlattr *rt = attrs[type];
100
101         if (rt && addrp)
102                 *addrp = nla_data(rt);
103 }
104
105 static inline int verify_sec_ctx_len(struct nlattr **attrs)
106 {
107         struct nlattr *rt = attrs[XFRMA_SEC_CTX];
108         struct xfrm_user_sec_ctx *uctx;
109
110         if (!rt)
111                 return 0;
112
113         uctx = nla_data(rt);
114         if (uctx->len > nla_len(rt) ||
115             uctx->len != (sizeof(struct xfrm_user_sec_ctx) + uctx->ctx_len))
116                 return -EINVAL;
117
118         return 0;
119 }
120
121 static inline int verify_replay(struct xfrm_usersa_info *p,
122                                 struct nlattr **attrs)
123 {
124         struct nlattr *rt = attrs[XFRMA_REPLAY_ESN_VAL];
125         struct xfrm_replay_state_esn *rs;
126
127         if (!rt)
128                 return (p->flags & XFRM_STATE_ESN) ? -EINVAL : 0;
129
130         rs = nla_data(rt);
131
132         if (rs->bmp_len > XFRMA_REPLAY_ESN_MAX / sizeof(rs->bmp[0]) / 8)
133                 return -EINVAL;
134
135         if (nla_len(rt) < (int)xfrm_replay_state_esn_len(rs) &&
136             nla_len(rt) != sizeof(*rs))
137                 return -EINVAL;
138
139         /* As only ESP and AH support ESN feature. */
140         if ((p->id.proto != IPPROTO_ESP) && (p->id.proto != IPPROTO_AH))
141                 return -EINVAL;
142
143         if (p->replay_window != 0)
144                 return -EINVAL;
145
146         return 0;
147 }
148
149 static int verify_newsa_info(struct xfrm_usersa_info *p,
150                              struct nlattr **attrs)
151 {
152         int err;
153
154         err = -EINVAL;
155         switch (p->family) {
156         case AF_INET:
157                 break;
158
159         case AF_INET6:
160 #if IS_ENABLED(CONFIG_IPV6)
161                 break;
162 #else
163                 err = -EAFNOSUPPORT;
164                 goto out;
165 #endif
166
167         default:
168                 goto out;
169         }
170
171         switch (p->sel.family) {
172         case AF_UNSPEC:
173                 break;
174
175         case AF_INET:
176                 if (p->sel.prefixlen_d > 32 || p->sel.prefixlen_s > 32)
177                         goto out;
178
179                 break;
180
181         case AF_INET6:
182 #if IS_ENABLED(CONFIG_IPV6)
183                 if (p->sel.prefixlen_d > 128 || p->sel.prefixlen_s > 128)
184                         goto out;
185
186                 break;
187 #else
188                 err = -EAFNOSUPPORT;
189                 goto out;
190 #endif
191
192         default:
193                 goto out;
194         }
195
196         err = -EINVAL;
197         switch (p->id.proto) {
198         case IPPROTO_AH:
199                 if ((!attrs[XFRMA_ALG_AUTH]     &&
200                      !attrs[XFRMA_ALG_AUTH_TRUNC]) ||
201                     attrs[XFRMA_ALG_AEAD]       ||
202                     attrs[XFRMA_ALG_CRYPT]      ||
203                     attrs[XFRMA_ALG_COMP]       ||
204                     attrs[XFRMA_TFCPAD])
205                         goto out;
206                 break;
207
208         case IPPROTO_ESP:
209                 if (attrs[XFRMA_ALG_COMP])
210                         goto out;
211                 if (!attrs[XFRMA_ALG_AUTH] &&
212                     !attrs[XFRMA_ALG_AUTH_TRUNC] &&
213                     !attrs[XFRMA_ALG_CRYPT] &&
214                     !attrs[XFRMA_ALG_AEAD])
215                         goto out;
216                 if ((attrs[XFRMA_ALG_AUTH] ||
217                      attrs[XFRMA_ALG_AUTH_TRUNC] ||
218                      attrs[XFRMA_ALG_CRYPT]) &&
219                     attrs[XFRMA_ALG_AEAD])
220                         goto out;
221                 if (attrs[XFRMA_TFCPAD] &&
222                     p->mode != XFRM_MODE_TUNNEL)
223                         goto out;
224                 break;
225
226         case IPPROTO_COMP:
227                 if (!attrs[XFRMA_ALG_COMP]      ||
228                     attrs[XFRMA_ALG_AEAD]       ||
229                     attrs[XFRMA_ALG_AUTH]       ||
230                     attrs[XFRMA_ALG_AUTH_TRUNC] ||
231                     attrs[XFRMA_ALG_CRYPT]      ||
232                     attrs[XFRMA_TFCPAD]         ||
233                     (ntohl(p->id.spi) >= 0x10000))
234                         goto out;
235                 break;
236
237 #if IS_ENABLED(CONFIG_IPV6)
238         case IPPROTO_DSTOPTS:
239         case IPPROTO_ROUTING:
240                 if (attrs[XFRMA_ALG_COMP]       ||
241                     attrs[XFRMA_ALG_AUTH]       ||
242                     attrs[XFRMA_ALG_AUTH_TRUNC] ||
243                     attrs[XFRMA_ALG_AEAD]       ||
244                     attrs[XFRMA_ALG_CRYPT]      ||
245                     attrs[XFRMA_ENCAP]          ||
246                     attrs[XFRMA_SEC_CTX]        ||
247                     attrs[XFRMA_TFCPAD]         ||
248                     !attrs[XFRMA_COADDR])
249                         goto out;
250                 break;
251 #endif
252
253         default:
254                 goto out;
255         }
256
257         if ((err = verify_aead(attrs)))
258                 goto out;
259         if ((err = verify_auth_trunc(attrs)))
260                 goto out;
261         if ((err = verify_one_alg(attrs, XFRMA_ALG_AUTH)))
262                 goto out;
263         if ((err = verify_one_alg(attrs, XFRMA_ALG_CRYPT)))
264                 goto out;
265         if ((err = verify_one_alg(attrs, XFRMA_ALG_COMP)))
266                 goto out;
267         if ((err = verify_sec_ctx_len(attrs)))
268                 goto out;
269         if ((err = verify_replay(p, attrs)))
270                 goto out;
271
272         err = -EINVAL;
273         switch (p->mode) {
274         case XFRM_MODE_TRANSPORT:
275         case XFRM_MODE_TUNNEL:
276         case XFRM_MODE_ROUTEOPTIMIZATION:
277         case XFRM_MODE_BEET:
278                 break;
279
280         default:
281                 goto out;
282         }
283
284         err = 0;
285
286         if (attrs[XFRMA_MTIMER_THRESH])
287                 if (!attrs[XFRMA_ENCAP])
288                         err = -EINVAL;
289
290 out:
291         return err;
292 }
293
294 static int attach_one_algo(struct xfrm_algo **algpp, u8 *props,
295                            struct xfrm_algo_desc *(*get_byname)(const char *, int),
296                            struct nlattr *rta)
297 {
298         struct xfrm_algo *p, *ualg;
299         struct xfrm_algo_desc *algo;
300
301         if (!rta)
302                 return 0;
303
304         ualg = nla_data(rta);
305
306         algo = get_byname(ualg->alg_name, 1);
307         if (!algo)
308                 return -ENOSYS;
309         *props = algo->desc.sadb_alg_id;
310
311         p = kmemdup(ualg, xfrm_alg_len(ualg), GFP_KERNEL);
312         if (!p)
313                 return -ENOMEM;
314
315         strcpy(p->alg_name, algo->name);
316         *algpp = p;
317         return 0;
318 }
319
320 static int attach_crypt(struct xfrm_state *x, struct nlattr *rta)
321 {
322         struct xfrm_algo *p, *ualg;
323         struct xfrm_algo_desc *algo;
324
325         if (!rta)
326                 return 0;
327
328         ualg = nla_data(rta);
329
330         algo = xfrm_ealg_get_byname(ualg->alg_name, 1);
331         if (!algo)
332                 return -ENOSYS;
333         x->props.ealgo = algo->desc.sadb_alg_id;
334
335         p = kmemdup(ualg, xfrm_alg_len(ualg), GFP_KERNEL);
336         if (!p)
337                 return -ENOMEM;
338
339         strcpy(p->alg_name, algo->name);
340         x->ealg = p;
341         x->geniv = algo->uinfo.encr.geniv;
342         return 0;
343 }
344
345 static int attach_auth(struct xfrm_algo_auth **algpp, u8 *props,
346                        struct nlattr *rta)
347 {
348         struct xfrm_algo *ualg;
349         struct xfrm_algo_auth *p;
350         struct xfrm_algo_desc *algo;
351
352         if (!rta)
353                 return 0;
354
355         ualg = nla_data(rta);
356
357         algo = xfrm_aalg_get_byname(ualg->alg_name, 1);
358         if (!algo)
359                 return -ENOSYS;
360         *props = algo->desc.sadb_alg_id;
361
362         p = kmalloc(sizeof(*p) + (ualg->alg_key_len + 7) / 8, GFP_KERNEL);
363         if (!p)
364                 return -ENOMEM;
365
366         strcpy(p->alg_name, algo->name);
367         p->alg_key_len = ualg->alg_key_len;
368         p->alg_trunc_len = algo->uinfo.auth.icv_truncbits;
369         memcpy(p->alg_key, ualg->alg_key, (ualg->alg_key_len + 7) / 8);
370
371         *algpp = p;
372         return 0;
373 }
374
375 static int attach_auth_trunc(struct xfrm_algo_auth **algpp, u8 *props,
376                              struct nlattr *rta)
377 {
378         struct xfrm_algo_auth *p, *ualg;
379         struct xfrm_algo_desc *algo;
380
381         if (!rta)
382                 return 0;
383
384         ualg = nla_data(rta);
385
386         algo = xfrm_aalg_get_byname(ualg->alg_name, 1);
387         if (!algo)
388                 return -ENOSYS;
389         if (ualg->alg_trunc_len > algo->uinfo.auth.icv_fullbits)
390                 return -EINVAL;
391         *props = algo->desc.sadb_alg_id;
392
393         p = kmemdup(ualg, xfrm_alg_auth_len(ualg), GFP_KERNEL);
394         if (!p)
395                 return -ENOMEM;
396
397         strcpy(p->alg_name, algo->name);
398         if (!p->alg_trunc_len)
399                 p->alg_trunc_len = algo->uinfo.auth.icv_truncbits;
400
401         *algpp = p;
402         return 0;
403 }
404
405 static int attach_aead(struct xfrm_state *x, struct nlattr *rta)
406 {
407         struct xfrm_algo_aead *p, *ualg;
408         struct xfrm_algo_desc *algo;
409
410         if (!rta)
411                 return 0;
412
413         ualg = nla_data(rta);
414
415         algo = xfrm_aead_get_byname(ualg->alg_name, ualg->alg_icv_len, 1);
416         if (!algo)
417                 return -ENOSYS;
418         x->props.ealgo = algo->desc.sadb_alg_id;
419
420         p = kmemdup(ualg, aead_len(ualg), GFP_KERNEL);
421         if (!p)
422                 return -ENOMEM;
423
424         strcpy(p->alg_name, algo->name);
425         x->aead = p;
426         x->geniv = algo->uinfo.aead.geniv;
427         return 0;
428 }
429
430 static inline int xfrm_replay_verify_len(struct xfrm_replay_state_esn *replay_esn,
431                                          struct nlattr *rp)
432 {
433         struct xfrm_replay_state_esn *up;
434         unsigned int ulen;
435
436         if (!replay_esn || !rp)
437                 return 0;
438
439         up = nla_data(rp);
440         ulen = xfrm_replay_state_esn_len(up);
441
442         /* Check the overall length and the internal bitmap length to avoid
443          * potential overflow. */
444         if (nla_len(rp) < (int)ulen ||
445             xfrm_replay_state_esn_len(replay_esn) != ulen ||
446             replay_esn->bmp_len != up->bmp_len)
447                 return -EINVAL;
448
449         if (up->replay_window > up->bmp_len * sizeof(__u32) * 8)
450                 return -EINVAL;
451
452         return 0;
453 }
454
455 static int xfrm_alloc_replay_state_esn(struct xfrm_replay_state_esn **replay_esn,
456                                        struct xfrm_replay_state_esn **preplay_esn,
457                                        struct nlattr *rta)
458 {
459         struct xfrm_replay_state_esn *p, *pp, *up;
460         unsigned int klen, ulen;
461
462         if (!rta)
463                 return 0;
464
465         up = nla_data(rta);
466         klen = xfrm_replay_state_esn_len(up);
467         ulen = nla_len(rta) >= (int)klen ? klen : sizeof(*up);
468
469         p = kzalloc(klen, GFP_KERNEL);
470         if (!p)
471                 return -ENOMEM;
472
473         pp = kzalloc(klen, GFP_KERNEL);
474         if (!pp) {
475                 kfree(p);
476                 return -ENOMEM;
477         }
478
479         memcpy(p, up, ulen);
480         memcpy(pp, up, ulen);
481
482         *replay_esn = p;
483         *preplay_esn = pp;
484
485         return 0;
486 }
487
488 static inline unsigned int xfrm_user_sec_ctx_size(struct xfrm_sec_ctx *xfrm_ctx)
489 {
490         unsigned int len = 0;
491
492         if (xfrm_ctx) {
493                 len += sizeof(struct xfrm_user_sec_ctx);
494                 len += xfrm_ctx->ctx_len;
495         }
496         return len;
497 }
498
499 static void copy_from_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p)
500 {
501         memcpy(&x->id, &p->id, sizeof(x->id));
502         memcpy(&x->sel, &p->sel, sizeof(x->sel));
503         memcpy(&x->lft, &p->lft, sizeof(x->lft));
504         x->props.mode = p->mode;
505         x->props.replay_window = min_t(unsigned int, p->replay_window,
506                                         sizeof(x->replay.bitmap) * 8);
507         x->props.reqid = p->reqid;
508         x->props.family = p->family;
509         memcpy(&x->props.saddr, &p->saddr, sizeof(x->props.saddr));
510         x->props.flags = p->flags;
511
512         if (!x->sel.family && !(p->flags & XFRM_STATE_AF_UNSPEC))
513                 x->sel.family = p->family;
514 }
515
516 /*
517  * someday when pfkey also has support, we could have the code
518  * somehow made shareable and move it to xfrm_state.c - JHS
519  *
520 */
521 static void xfrm_update_ae_params(struct xfrm_state *x, struct nlattr **attrs,
522                                   int update_esn)
523 {
524         struct nlattr *rp = attrs[XFRMA_REPLAY_VAL];
525         struct nlattr *re = update_esn ? attrs[XFRMA_REPLAY_ESN_VAL] : NULL;
526         struct nlattr *lt = attrs[XFRMA_LTIME_VAL];
527         struct nlattr *et = attrs[XFRMA_ETIMER_THRESH];
528         struct nlattr *rt = attrs[XFRMA_REPLAY_THRESH];
529         struct nlattr *mt = attrs[XFRMA_MTIMER_THRESH];
530
531         if (re) {
532                 struct xfrm_replay_state_esn *replay_esn;
533                 replay_esn = nla_data(re);
534                 memcpy(x->replay_esn, replay_esn,
535                        xfrm_replay_state_esn_len(replay_esn));
536                 memcpy(x->preplay_esn, replay_esn,
537                        xfrm_replay_state_esn_len(replay_esn));
538         }
539
540         if (rp) {
541                 struct xfrm_replay_state *replay;
542                 replay = nla_data(rp);
543                 memcpy(&x->replay, replay, sizeof(*replay));
544                 memcpy(&x->preplay, replay, sizeof(*replay));
545         }
546
547         if (lt) {
548                 struct xfrm_lifetime_cur *ltime;
549                 ltime = nla_data(lt);
550                 x->curlft.bytes = ltime->bytes;
551                 x->curlft.packets = ltime->packets;
552                 x->curlft.add_time = ltime->add_time;
553                 x->curlft.use_time = ltime->use_time;
554         }
555
556         if (et)
557                 x->replay_maxage = nla_get_u32(et);
558
559         if (rt)
560                 x->replay_maxdiff = nla_get_u32(rt);
561
562         if (mt)
563                 x->mapping_maxage = nla_get_u32(mt);
564 }
565
566 static void xfrm_smark_init(struct nlattr **attrs, struct xfrm_mark *m)
567 {
568         if (attrs[XFRMA_SET_MARK]) {
569                 m->v = nla_get_u32(attrs[XFRMA_SET_MARK]);
570                 if (attrs[XFRMA_SET_MARK_MASK])
571                         m->m = nla_get_u32(attrs[XFRMA_SET_MARK_MASK]);
572                 else
573                         m->m = 0xffffffff;
574         } else {
575                 m->v = m->m = 0;
576         }
577 }
578
579 static struct xfrm_state *xfrm_state_construct(struct net *net,
580                                                struct xfrm_usersa_info *p,
581                                                struct nlattr **attrs,
582                                                int *errp)
583 {
584         struct xfrm_state *x = xfrm_state_alloc(net);
585         int err = -ENOMEM;
586
587         if (!x)
588                 goto error_no_put;
589
590         copy_from_user_state(x, p);
591
592         if (attrs[XFRMA_ENCAP]) {
593                 x->encap = kmemdup(nla_data(attrs[XFRMA_ENCAP]),
594                                    sizeof(*x->encap), GFP_KERNEL);
595                 if (x->encap == NULL)
596                         goto error;
597         }
598
599         if (attrs[XFRMA_COADDR]) {
600                 x->coaddr = kmemdup(nla_data(attrs[XFRMA_COADDR]),
601                                     sizeof(*x->coaddr), GFP_KERNEL);
602                 if (x->coaddr == NULL)
603                         goto error;
604         }
605
606         if (attrs[XFRMA_SA_EXTRA_FLAGS])
607                 x->props.extra_flags = nla_get_u32(attrs[XFRMA_SA_EXTRA_FLAGS]);
608
609         if ((err = attach_aead(x, attrs[XFRMA_ALG_AEAD])))
610                 goto error;
611         if ((err = attach_auth_trunc(&x->aalg, &x->props.aalgo,
612                                      attrs[XFRMA_ALG_AUTH_TRUNC])))
613                 goto error;
614         if (!x->props.aalgo) {
615                 if ((err = attach_auth(&x->aalg, &x->props.aalgo,
616                                        attrs[XFRMA_ALG_AUTH])))
617                         goto error;
618         }
619         if ((err = attach_crypt(x, attrs[XFRMA_ALG_CRYPT])))
620                 goto error;
621         if ((err = attach_one_algo(&x->calg, &x->props.calgo,
622                                    xfrm_calg_get_byname,
623                                    attrs[XFRMA_ALG_COMP])))
624                 goto error;
625
626         if (attrs[XFRMA_TFCPAD])
627                 x->tfcpad = nla_get_u32(attrs[XFRMA_TFCPAD]);
628
629         xfrm_mark_get(attrs, &x->mark);
630
631         xfrm_smark_init(attrs, &x->props.smark);
632
633         if (attrs[XFRMA_IF_ID])
634                 x->if_id = nla_get_u32(attrs[XFRMA_IF_ID]);
635
636         err = __xfrm_init_state(x, false, attrs[XFRMA_OFFLOAD_DEV]);
637         if (err)
638                 goto error;
639
640         if (attrs[XFRMA_SEC_CTX]) {
641                 err = security_xfrm_state_alloc(x,
642                                                 nla_data(attrs[XFRMA_SEC_CTX]));
643                 if (err)
644                         goto error;
645         }
646
647         if ((err = xfrm_alloc_replay_state_esn(&x->replay_esn, &x->preplay_esn,
648                                                attrs[XFRMA_REPLAY_ESN_VAL])))
649                 goto error;
650
651         x->km.seq = p->seq;
652         x->replay_maxdiff = net->xfrm.sysctl_aevent_rseqth;
653         /* sysctl_xfrm_aevent_etime is in 100ms units */
654         x->replay_maxage = (net->xfrm.sysctl_aevent_etime*HZ)/XFRM_AE_ETH_M;
655
656         if ((err = xfrm_init_replay(x)))
657                 goto error;
658
659         /* override default values from above */
660         xfrm_update_ae_params(x, attrs, 0);
661
662         /* configure the hardware if offload is requested */
663         if (attrs[XFRMA_OFFLOAD_DEV]) {
664                 err = xfrm_dev_state_add(net, x,
665                                          nla_data(attrs[XFRMA_OFFLOAD_DEV]));
666                 if (err)
667                         goto error;
668         }
669
670         return x;
671
672 error:
673         x->km.state = XFRM_STATE_DEAD;
674         xfrm_state_put(x);
675 error_no_put:
676         *errp = err;
677         return NULL;
678 }
679
680 static int xfrm_add_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
681                 struct nlattr **attrs)
682 {
683         struct net *net = sock_net(skb->sk);
684         struct xfrm_usersa_info *p = nlmsg_data(nlh);
685         struct xfrm_state *x;
686         int err;
687         struct km_event c;
688
689         err = verify_newsa_info(p, attrs);
690         if (err)
691                 return err;
692
693         x = xfrm_state_construct(net, p, attrs, &err);
694         if (!x)
695                 return err;
696
697         xfrm_state_hold(x);
698         if (nlh->nlmsg_type == XFRM_MSG_NEWSA)
699                 err = xfrm_state_add(x);
700         else
701                 err = xfrm_state_update(x);
702
703         xfrm_audit_state_add(x, err ? 0 : 1, true);
704
705         if (err < 0) {
706                 x->km.state = XFRM_STATE_DEAD;
707                 xfrm_dev_state_delete(x);
708                 __xfrm_state_put(x);
709                 goto out;
710         }
711
712         if (x->km.state == XFRM_STATE_VOID)
713                 x->km.state = XFRM_STATE_VALID;
714
715         c.seq = nlh->nlmsg_seq;
716         c.portid = nlh->nlmsg_pid;
717         c.event = nlh->nlmsg_type;
718
719         km_state_notify(x, &c);
720 out:
721         xfrm_state_put(x);
722         return err;
723 }
724
725 static struct xfrm_state *xfrm_user_state_lookup(struct net *net,
726                                                  struct xfrm_usersa_id *p,
727                                                  struct nlattr **attrs,
728                                                  int *errp)
729 {
730         struct xfrm_state *x = NULL;
731         struct xfrm_mark m;
732         int err;
733         u32 mark = xfrm_mark_get(attrs, &m);
734
735         if (xfrm_id_proto_match(p->proto, IPSEC_PROTO_ANY)) {
736                 err = -ESRCH;
737                 x = xfrm_state_lookup(net, mark, &p->daddr, p->spi, p->proto, p->family);
738         } else {
739                 xfrm_address_t *saddr = NULL;
740
741                 verify_one_addr(attrs, XFRMA_SRCADDR, &saddr);
742                 if (!saddr) {
743                         err = -EINVAL;
744                         goto out;
745                 }
746
747                 err = -ESRCH;
748                 x = xfrm_state_lookup_byaddr(net, mark,
749                                              &p->daddr, saddr,
750                                              p->proto, p->family);
751         }
752
753  out:
754         if (!x && errp)
755                 *errp = err;
756         return x;
757 }
758
759 static int xfrm_del_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
760                 struct nlattr **attrs)
761 {
762         struct net *net = sock_net(skb->sk);
763         struct xfrm_state *x;
764         int err = -ESRCH;
765         struct km_event c;
766         struct xfrm_usersa_id *p = nlmsg_data(nlh);
767
768         x = xfrm_user_state_lookup(net, p, attrs, &err);
769         if (x == NULL)
770                 return err;
771
772         if ((err = security_xfrm_state_delete(x)) != 0)
773                 goto out;
774
775         if (xfrm_state_kern(x)) {
776                 err = -EPERM;
777                 goto out;
778         }
779
780         err = xfrm_state_delete(x);
781
782         if (err < 0)
783                 goto out;
784
785         c.seq = nlh->nlmsg_seq;
786         c.portid = nlh->nlmsg_pid;
787         c.event = nlh->nlmsg_type;
788         km_state_notify(x, &c);
789
790 out:
791         xfrm_audit_state_delete(x, err ? 0 : 1, true);
792         xfrm_state_put(x);
793         return err;
794 }
795
796 static void copy_to_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p)
797 {
798         memset(p, 0, sizeof(*p));
799         memcpy(&p->id, &x->id, sizeof(p->id));
800         memcpy(&p->sel, &x->sel, sizeof(p->sel));
801         memcpy(&p->lft, &x->lft, sizeof(p->lft));
802         memcpy(&p->curlft, &x->curlft, sizeof(p->curlft));
803         put_unaligned(x->stats.replay_window, &p->stats.replay_window);
804         put_unaligned(x->stats.replay, &p->stats.replay);
805         put_unaligned(x->stats.integrity_failed, &p->stats.integrity_failed);
806         memcpy(&p->saddr, &x->props.saddr, sizeof(p->saddr));
807         p->mode = x->props.mode;
808         p->replay_window = x->props.replay_window;
809         p->reqid = x->props.reqid;
810         p->family = x->props.family;
811         p->flags = x->props.flags;
812         p->seq = x->km.seq;
813 }
814
815 struct xfrm_dump_info {
816         struct sk_buff *in_skb;
817         struct sk_buff *out_skb;
818         u32 nlmsg_seq;
819         u16 nlmsg_flags;
820 };
821
822 static int copy_sec_ctx(struct xfrm_sec_ctx *s, struct sk_buff *skb)
823 {
824         struct xfrm_user_sec_ctx *uctx;
825         struct nlattr *attr;
826         int ctx_size = sizeof(*uctx) + s->ctx_len;
827
828         attr = nla_reserve(skb, XFRMA_SEC_CTX, ctx_size);
829         if (attr == NULL)
830                 return -EMSGSIZE;
831
832         uctx = nla_data(attr);
833         uctx->exttype = XFRMA_SEC_CTX;
834         uctx->len = ctx_size;
835         uctx->ctx_doi = s->ctx_doi;
836         uctx->ctx_alg = s->ctx_alg;
837         uctx->ctx_len = s->ctx_len;
838         memcpy(uctx + 1, s->ctx_str, s->ctx_len);
839
840         return 0;
841 }
842
843 static int copy_user_offload(struct xfrm_state_offload *xso, struct sk_buff *skb)
844 {
845         struct xfrm_user_offload *xuo;
846         struct nlattr *attr;
847
848         attr = nla_reserve(skb, XFRMA_OFFLOAD_DEV, sizeof(*xuo));
849         if (attr == NULL)
850                 return -EMSGSIZE;
851
852         xuo = nla_data(attr);
853         memset(xuo, 0, sizeof(*xuo));
854         xuo->ifindex = xso->dev->ifindex;
855         xuo->flags = xso->flags;
856
857         return 0;
858 }
859
860 static bool xfrm_redact(void)
861 {
862         return IS_ENABLED(CONFIG_SECURITY) &&
863                 security_locked_down(LOCKDOWN_XFRM_SECRET);
864 }
865
866 static int copy_to_user_auth(struct xfrm_algo_auth *auth, struct sk_buff *skb)
867 {
868         struct xfrm_algo *algo;
869         struct xfrm_algo_auth *ap;
870         struct nlattr *nla;
871         bool redact_secret = xfrm_redact();
872
873         nla = nla_reserve(skb, XFRMA_ALG_AUTH,
874                           sizeof(*algo) + (auth->alg_key_len + 7) / 8);
875         if (!nla)
876                 return -EMSGSIZE;
877         algo = nla_data(nla);
878         strncpy(algo->alg_name, auth->alg_name, sizeof(algo->alg_name));
879
880         if (redact_secret && auth->alg_key_len)
881                 memset(algo->alg_key, 0, (auth->alg_key_len + 7) / 8);
882         else
883                 memcpy(algo->alg_key, auth->alg_key,
884                        (auth->alg_key_len + 7) / 8);
885         algo->alg_key_len = auth->alg_key_len;
886
887         nla = nla_reserve(skb, XFRMA_ALG_AUTH_TRUNC, xfrm_alg_auth_len(auth));
888         if (!nla)
889                 return -EMSGSIZE;
890         ap = nla_data(nla);
891         memcpy(ap, auth, sizeof(struct xfrm_algo_auth));
892         if (redact_secret && auth->alg_key_len)
893                 memset(ap->alg_key, 0, (auth->alg_key_len + 7) / 8);
894         else
895                 memcpy(ap->alg_key, auth->alg_key,
896                        (auth->alg_key_len + 7) / 8);
897         return 0;
898 }
899
900 static int copy_to_user_aead(struct xfrm_algo_aead *aead, struct sk_buff *skb)
901 {
902         struct nlattr *nla = nla_reserve(skb, XFRMA_ALG_AEAD, aead_len(aead));
903         struct xfrm_algo_aead *ap;
904         bool redact_secret = xfrm_redact();
905
906         if (!nla)
907                 return -EMSGSIZE;
908
909         ap = nla_data(nla);
910         memcpy(ap, aead, sizeof(*aead));
911
912         if (redact_secret && aead->alg_key_len)
913                 memset(ap->alg_key, 0, (aead->alg_key_len + 7) / 8);
914         else
915                 memcpy(ap->alg_key, aead->alg_key,
916                        (aead->alg_key_len + 7) / 8);
917         return 0;
918 }
919
920 static int copy_to_user_ealg(struct xfrm_algo *ealg, struct sk_buff *skb)
921 {
922         struct xfrm_algo *ap;
923         bool redact_secret = xfrm_redact();
924         struct nlattr *nla = nla_reserve(skb, XFRMA_ALG_CRYPT,
925                                          xfrm_alg_len(ealg));
926         if (!nla)
927                 return -EMSGSIZE;
928
929         ap = nla_data(nla);
930         memcpy(ap, ealg, sizeof(*ealg));
931
932         if (redact_secret && ealg->alg_key_len)
933                 memset(ap->alg_key, 0, (ealg->alg_key_len + 7) / 8);
934         else
935                 memcpy(ap->alg_key, ealg->alg_key,
936                        (ealg->alg_key_len + 7) / 8);
937
938         return 0;
939 }
940
941 static int xfrm_smark_put(struct sk_buff *skb, struct xfrm_mark *m)
942 {
943         int ret = 0;
944
945         if (m->v | m->m) {
946                 ret = nla_put_u32(skb, XFRMA_SET_MARK, m->v);
947                 if (!ret)
948                         ret = nla_put_u32(skb, XFRMA_SET_MARK_MASK, m->m);
949         }
950         return ret;
951 }
952
953 /* Don't change this without updating xfrm_sa_len! */
954 static int copy_to_user_state_extra(struct xfrm_state *x,
955                                     struct xfrm_usersa_info *p,
956                                     struct sk_buff *skb)
957 {
958         int ret = 0;
959
960         copy_to_user_state(x, p);
961
962         if (x->props.extra_flags) {
963                 ret = nla_put_u32(skb, XFRMA_SA_EXTRA_FLAGS,
964                                   x->props.extra_flags);
965                 if (ret)
966                         goto out;
967         }
968
969         if (x->coaddr) {
970                 ret = nla_put(skb, XFRMA_COADDR, sizeof(*x->coaddr), x->coaddr);
971                 if (ret)
972                         goto out;
973         }
974         if (x->lastused) {
975                 ret = nla_put_u64_64bit(skb, XFRMA_LASTUSED, x->lastused,
976                                         XFRMA_PAD);
977                 if (ret)
978                         goto out;
979         }
980         if (x->aead) {
981                 ret = copy_to_user_aead(x->aead, skb);
982                 if (ret)
983                         goto out;
984         }
985         if (x->aalg) {
986                 ret = copy_to_user_auth(x->aalg, skb);
987                 if (ret)
988                         goto out;
989         }
990         if (x->ealg) {
991                 ret = copy_to_user_ealg(x->ealg, skb);
992                 if (ret)
993                         goto out;
994         }
995         if (x->calg) {
996                 ret = nla_put(skb, XFRMA_ALG_COMP, sizeof(*(x->calg)), x->calg);
997                 if (ret)
998                         goto out;
999         }
1000         if (x->encap) {
1001                 ret = nla_put(skb, XFRMA_ENCAP, sizeof(*x->encap), x->encap);
1002                 if (ret)
1003                         goto out;
1004         }
1005         if (x->tfcpad) {
1006                 ret = nla_put_u32(skb, XFRMA_TFCPAD, x->tfcpad);
1007                 if (ret)
1008                         goto out;
1009         }
1010         ret = xfrm_mark_put(skb, &x->mark);
1011         if (ret)
1012                 goto out;
1013
1014         ret = xfrm_smark_put(skb, &x->props.smark);
1015         if (ret)
1016                 goto out;
1017
1018         if (x->replay_esn)
1019                 ret = nla_put(skb, XFRMA_REPLAY_ESN_VAL,
1020                               xfrm_replay_state_esn_len(x->replay_esn),
1021                               x->replay_esn);
1022         else
1023                 ret = nla_put(skb, XFRMA_REPLAY_VAL, sizeof(x->replay),
1024                               &x->replay);
1025         if (ret)
1026                 goto out;
1027         if(x->xso.dev)
1028                 ret = copy_user_offload(&x->xso, skb);
1029         if (ret)
1030                 goto out;
1031         if (x->if_id) {
1032                 ret = nla_put_u32(skb, XFRMA_IF_ID, x->if_id);
1033                 if (ret)
1034                         goto out;
1035         }
1036         if (x->security) {
1037                 ret = copy_sec_ctx(x->security, skb);
1038                 if (ret)
1039                         goto out;
1040         }
1041         if (x->mapping_maxage)
1042                 ret = nla_put_u32(skb, XFRMA_MTIMER_THRESH, x->mapping_maxage);
1043 out:
1044         return ret;
1045 }
1046
1047 static int dump_one_state(struct xfrm_state *x, int count, void *ptr)
1048 {
1049         struct xfrm_dump_info *sp = ptr;
1050         struct sk_buff *in_skb = sp->in_skb;
1051         struct sk_buff *skb = sp->out_skb;
1052         struct xfrm_translator *xtr;
1053         struct xfrm_usersa_info *p;
1054         struct nlmsghdr *nlh;
1055         int err;
1056
1057         nlh = nlmsg_put(skb, NETLINK_CB(in_skb).portid, sp->nlmsg_seq,
1058                         XFRM_MSG_NEWSA, sizeof(*p), sp->nlmsg_flags);
1059         if (nlh == NULL)
1060                 return -EMSGSIZE;
1061
1062         p = nlmsg_data(nlh);
1063
1064         err = copy_to_user_state_extra(x, p, skb);
1065         if (err) {
1066                 nlmsg_cancel(skb, nlh);
1067                 return err;
1068         }
1069         nlmsg_end(skb, nlh);
1070
1071         xtr = xfrm_get_translator();
1072         if (xtr) {
1073                 err = xtr->alloc_compat(skb, nlh);
1074
1075                 xfrm_put_translator(xtr);
1076                 if (err) {
1077                         nlmsg_cancel(skb, nlh);
1078                         return err;
1079                 }
1080         }
1081
1082         return 0;
1083 }
1084
1085 static int xfrm_dump_sa_done(struct netlink_callback *cb)
1086 {
1087         struct xfrm_state_walk *walk = (struct xfrm_state_walk *) &cb->args[1];
1088         struct sock *sk = cb->skb->sk;
1089         struct net *net = sock_net(sk);
1090
1091         if (cb->args[0])
1092                 xfrm_state_walk_done(walk, net);
1093         return 0;
1094 }
1095
1096 static int xfrm_dump_sa(struct sk_buff *skb, struct netlink_callback *cb)
1097 {
1098         struct net *net = sock_net(skb->sk);
1099         struct xfrm_state_walk *walk = (struct xfrm_state_walk *) &cb->args[1];
1100         struct xfrm_dump_info info;
1101
1102         BUILD_BUG_ON(sizeof(struct xfrm_state_walk) >
1103                      sizeof(cb->args) - sizeof(cb->args[0]));
1104
1105         info.in_skb = cb->skb;
1106         info.out_skb = skb;
1107         info.nlmsg_seq = cb->nlh->nlmsg_seq;
1108         info.nlmsg_flags = NLM_F_MULTI;
1109
1110         if (!cb->args[0]) {
1111                 struct nlattr *attrs[XFRMA_MAX+1];
1112                 struct xfrm_address_filter *filter = NULL;
1113                 u8 proto = 0;
1114                 int err;
1115
1116                 err = nlmsg_parse_deprecated(cb->nlh, 0, attrs, XFRMA_MAX,
1117                                              xfrma_policy, cb->extack);
1118                 if (err < 0)
1119                         return err;
1120
1121                 if (attrs[XFRMA_ADDRESS_FILTER]) {
1122                         filter = kmemdup(nla_data(attrs[XFRMA_ADDRESS_FILTER]),
1123                                          sizeof(*filter), GFP_KERNEL);
1124                         if (filter == NULL)
1125                                 return -ENOMEM;
1126                 }
1127
1128                 if (attrs[XFRMA_PROTO])
1129                         proto = nla_get_u8(attrs[XFRMA_PROTO]);
1130
1131                 xfrm_state_walk_init(walk, proto, filter);
1132                 cb->args[0] = 1;
1133         }
1134
1135         (void) xfrm_state_walk(net, walk, dump_one_state, &info);
1136
1137         return skb->len;
1138 }
1139
1140 static struct sk_buff *xfrm_state_netlink(struct sk_buff *in_skb,
1141                                           struct xfrm_state *x, u32 seq)
1142 {
1143         struct xfrm_dump_info info;
1144         struct sk_buff *skb;
1145         int err;
1146
1147         skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
1148         if (!skb)
1149                 return ERR_PTR(-ENOMEM);
1150
1151         info.in_skb = in_skb;
1152         info.out_skb = skb;
1153         info.nlmsg_seq = seq;
1154         info.nlmsg_flags = 0;
1155
1156         err = dump_one_state(x, 0, &info);
1157         if (err) {
1158                 kfree_skb(skb);
1159                 return ERR_PTR(err);
1160         }
1161
1162         return skb;
1163 }
1164
1165 /* A wrapper for nlmsg_multicast() checking that nlsk is still available.
1166  * Must be called with RCU read lock.
1167  */
1168 static inline int xfrm_nlmsg_multicast(struct net *net, struct sk_buff *skb,
1169                                        u32 pid, unsigned int group)
1170 {
1171         struct sock *nlsk = rcu_dereference(net->xfrm.nlsk);
1172         struct xfrm_translator *xtr;
1173
1174         if (!nlsk) {
1175                 kfree_skb(skb);
1176                 return -EPIPE;
1177         }
1178
1179         xtr = xfrm_get_translator();
1180         if (xtr) {
1181                 int err = xtr->alloc_compat(skb, nlmsg_hdr(skb));
1182
1183                 xfrm_put_translator(xtr);
1184                 if (err) {
1185                         kfree_skb(skb);
1186                         return err;
1187                 }
1188         }
1189
1190         return nlmsg_multicast(nlsk, skb, pid, group, GFP_ATOMIC);
1191 }
1192
1193 static inline unsigned int xfrm_spdinfo_msgsize(void)
1194 {
1195         return NLMSG_ALIGN(4)
1196                + nla_total_size(sizeof(struct xfrmu_spdinfo))
1197                + nla_total_size(sizeof(struct xfrmu_spdhinfo))
1198                + nla_total_size(sizeof(struct xfrmu_spdhthresh))
1199                + nla_total_size(sizeof(struct xfrmu_spdhthresh));
1200 }
1201
1202 static int build_spdinfo(struct sk_buff *skb, struct net *net,
1203                          u32 portid, u32 seq, u32 flags)
1204 {
1205         struct xfrmk_spdinfo si;
1206         struct xfrmu_spdinfo spc;
1207         struct xfrmu_spdhinfo sph;
1208         struct xfrmu_spdhthresh spt4, spt6;
1209         struct nlmsghdr *nlh;
1210         int err;
1211         u32 *f;
1212         unsigned lseq;
1213
1214         nlh = nlmsg_put(skb, portid, seq, XFRM_MSG_NEWSPDINFO, sizeof(u32), 0);
1215         if (nlh == NULL) /* shouldn't really happen ... */
1216                 return -EMSGSIZE;
1217
1218         f = nlmsg_data(nlh);
1219         *f = flags;
1220         xfrm_spd_getinfo(net, &si);
1221         spc.incnt = si.incnt;
1222         spc.outcnt = si.outcnt;
1223         spc.fwdcnt = si.fwdcnt;
1224         spc.inscnt = si.inscnt;
1225         spc.outscnt = si.outscnt;
1226         spc.fwdscnt = si.fwdscnt;
1227         sph.spdhcnt = si.spdhcnt;
1228         sph.spdhmcnt = si.spdhmcnt;
1229
1230         do {
1231                 lseq = read_seqbegin(&net->xfrm.policy_hthresh.lock);
1232
1233                 spt4.lbits = net->xfrm.policy_hthresh.lbits4;
1234                 spt4.rbits = net->xfrm.policy_hthresh.rbits4;
1235                 spt6.lbits = net->xfrm.policy_hthresh.lbits6;
1236                 spt6.rbits = net->xfrm.policy_hthresh.rbits6;
1237         } while (read_seqretry(&net->xfrm.policy_hthresh.lock, lseq));
1238
1239         err = nla_put(skb, XFRMA_SPD_INFO, sizeof(spc), &spc);
1240         if (!err)
1241                 err = nla_put(skb, XFRMA_SPD_HINFO, sizeof(sph), &sph);
1242         if (!err)
1243                 err = nla_put(skb, XFRMA_SPD_IPV4_HTHRESH, sizeof(spt4), &spt4);
1244         if (!err)
1245                 err = nla_put(skb, XFRMA_SPD_IPV6_HTHRESH, sizeof(spt6), &spt6);
1246         if (err) {
1247                 nlmsg_cancel(skb, nlh);
1248                 return err;
1249         }
1250
1251         nlmsg_end(skb, nlh);
1252         return 0;
1253 }
1254
1255 static int xfrm_set_spdinfo(struct sk_buff *skb, struct nlmsghdr *nlh,
1256                             struct nlattr **attrs)
1257 {
1258         struct net *net = sock_net(skb->sk);
1259         struct xfrmu_spdhthresh *thresh4 = NULL;
1260         struct xfrmu_spdhthresh *thresh6 = NULL;
1261
1262         /* selector prefixlen thresholds to hash policies */
1263         if (attrs[XFRMA_SPD_IPV4_HTHRESH]) {
1264                 struct nlattr *rta = attrs[XFRMA_SPD_IPV4_HTHRESH];
1265
1266                 if (nla_len(rta) < sizeof(*thresh4))
1267                         return -EINVAL;
1268                 thresh4 = nla_data(rta);
1269                 if (thresh4->lbits > 32 || thresh4->rbits > 32)
1270                         return -EINVAL;
1271         }
1272         if (attrs[XFRMA_SPD_IPV6_HTHRESH]) {
1273                 struct nlattr *rta = attrs[XFRMA_SPD_IPV6_HTHRESH];
1274
1275                 if (nla_len(rta) < sizeof(*thresh6))
1276                         return -EINVAL;
1277                 thresh6 = nla_data(rta);
1278                 if (thresh6->lbits > 128 || thresh6->rbits > 128)
1279                         return -EINVAL;
1280         }
1281
1282         if (thresh4 || thresh6) {
1283                 write_seqlock(&net->xfrm.policy_hthresh.lock);
1284                 if (thresh4) {
1285                         net->xfrm.policy_hthresh.lbits4 = thresh4->lbits;
1286                         net->xfrm.policy_hthresh.rbits4 = thresh4->rbits;
1287                 }
1288                 if (thresh6) {
1289                         net->xfrm.policy_hthresh.lbits6 = thresh6->lbits;
1290                         net->xfrm.policy_hthresh.rbits6 = thresh6->rbits;
1291                 }
1292                 write_sequnlock(&net->xfrm.policy_hthresh.lock);
1293
1294                 xfrm_policy_hash_rebuild(net);
1295         }
1296
1297         return 0;
1298 }
1299
1300 static int xfrm_get_spdinfo(struct sk_buff *skb, struct nlmsghdr *nlh,
1301                 struct nlattr **attrs)
1302 {
1303         struct net *net = sock_net(skb->sk);
1304         struct sk_buff *r_skb;
1305         u32 *flags = nlmsg_data(nlh);
1306         u32 sportid = NETLINK_CB(skb).portid;
1307         u32 seq = nlh->nlmsg_seq;
1308         int err;
1309
1310         r_skb = nlmsg_new(xfrm_spdinfo_msgsize(), GFP_ATOMIC);
1311         if (r_skb == NULL)
1312                 return -ENOMEM;
1313
1314         err = build_spdinfo(r_skb, net, sportid, seq, *flags);
1315         BUG_ON(err < 0);
1316
1317         return nlmsg_unicast(net->xfrm.nlsk, r_skb, sportid);
1318 }
1319
1320 static inline unsigned int xfrm_sadinfo_msgsize(void)
1321 {
1322         return NLMSG_ALIGN(4)
1323                + nla_total_size(sizeof(struct xfrmu_sadhinfo))
1324                + nla_total_size(4); /* XFRMA_SAD_CNT */
1325 }
1326
1327 static int build_sadinfo(struct sk_buff *skb, struct net *net,
1328                          u32 portid, u32 seq, u32 flags)
1329 {
1330         struct xfrmk_sadinfo si;
1331         struct xfrmu_sadhinfo sh;
1332         struct nlmsghdr *nlh;
1333         int err;
1334         u32 *f;
1335
1336         nlh = nlmsg_put(skb, portid, seq, XFRM_MSG_NEWSADINFO, sizeof(u32), 0);
1337         if (nlh == NULL) /* shouldn't really happen ... */
1338                 return -EMSGSIZE;
1339
1340         f = nlmsg_data(nlh);
1341         *f = flags;
1342         xfrm_sad_getinfo(net, &si);
1343
1344         sh.sadhmcnt = si.sadhmcnt;
1345         sh.sadhcnt = si.sadhcnt;
1346
1347         err = nla_put_u32(skb, XFRMA_SAD_CNT, si.sadcnt);
1348         if (!err)
1349                 err = nla_put(skb, XFRMA_SAD_HINFO, sizeof(sh), &sh);
1350         if (err) {
1351                 nlmsg_cancel(skb, nlh);
1352                 return err;
1353         }
1354
1355         nlmsg_end(skb, nlh);
1356         return 0;
1357 }
1358
1359 static int xfrm_get_sadinfo(struct sk_buff *skb, struct nlmsghdr *nlh,
1360                 struct nlattr **attrs)
1361 {
1362         struct net *net = sock_net(skb->sk);
1363         struct sk_buff *r_skb;
1364         u32 *flags = nlmsg_data(nlh);
1365         u32 sportid = NETLINK_CB(skb).portid;
1366         u32 seq = nlh->nlmsg_seq;
1367         int err;
1368
1369         r_skb = nlmsg_new(xfrm_sadinfo_msgsize(), GFP_ATOMIC);
1370         if (r_skb == NULL)
1371                 return -ENOMEM;
1372
1373         err = build_sadinfo(r_skb, net, sportid, seq, *flags);
1374         BUG_ON(err < 0);
1375
1376         return nlmsg_unicast(net->xfrm.nlsk, r_skb, sportid);
1377 }
1378
1379 static int xfrm_get_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
1380                 struct nlattr **attrs)
1381 {
1382         struct net *net = sock_net(skb->sk);
1383         struct xfrm_usersa_id *p = nlmsg_data(nlh);
1384         struct xfrm_state *x;
1385         struct sk_buff *resp_skb;
1386         int err = -ESRCH;
1387
1388         x = xfrm_user_state_lookup(net, p, attrs, &err);
1389         if (x == NULL)
1390                 goto out_noput;
1391
1392         resp_skb = xfrm_state_netlink(skb, x, nlh->nlmsg_seq);
1393         if (IS_ERR(resp_skb)) {
1394                 err = PTR_ERR(resp_skb);
1395         } else {
1396                 err = nlmsg_unicast(net->xfrm.nlsk, resp_skb, NETLINK_CB(skb).portid);
1397         }
1398         xfrm_state_put(x);
1399 out_noput:
1400         return err;
1401 }
1402
1403 static int xfrm_alloc_userspi(struct sk_buff *skb, struct nlmsghdr *nlh,
1404                 struct nlattr **attrs)
1405 {
1406         struct net *net = sock_net(skb->sk);
1407         struct xfrm_state *x;
1408         struct xfrm_userspi_info *p;
1409         struct xfrm_translator *xtr;
1410         struct sk_buff *resp_skb;
1411         xfrm_address_t *daddr;
1412         int family;
1413         int err;
1414         u32 mark;
1415         struct xfrm_mark m;
1416         u32 if_id = 0;
1417
1418         p = nlmsg_data(nlh);
1419         err = verify_spi_info(p->info.id.proto, p->min, p->max);
1420         if (err)
1421                 goto out_noput;
1422
1423         family = p->info.family;
1424         daddr = &p->info.id.daddr;
1425
1426         x = NULL;
1427
1428         mark = xfrm_mark_get(attrs, &m);
1429
1430         if (attrs[XFRMA_IF_ID])
1431                 if_id = nla_get_u32(attrs[XFRMA_IF_ID]);
1432
1433         if (p->info.seq) {
1434                 x = xfrm_find_acq_byseq(net, mark, p->info.seq);
1435                 if (x && !xfrm_addr_equal(&x->id.daddr, daddr, family)) {
1436                         xfrm_state_put(x);
1437                         x = NULL;
1438                 }
1439         }
1440
1441         if (!x)
1442                 x = xfrm_find_acq(net, &m, p->info.mode, p->info.reqid,
1443                                   if_id, p->info.id.proto, daddr,
1444                                   &p->info.saddr, 1,
1445                                   family);
1446         err = -ENOENT;
1447         if (x == NULL)
1448                 goto out_noput;
1449
1450         err = xfrm_alloc_spi(x, p->min, p->max);
1451         if (err)
1452                 goto out;
1453
1454         resp_skb = xfrm_state_netlink(skb, x, nlh->nlmsg_seq);
1455         if (IS_ERR(resp_skb)) {
1456                 err = PTR_ERR(resp_skb);
1457                 goto out;
1458         }
1459
1460         xtr = xfrm_get_translator();
1461         if (xtr) {
1462                 err = xtr->alloc_compat(skb, nlmsg_hdr(skb));
1463
1464                 xfrm_put_translator(xtr);
1465                 if (err) {
1466                         kfree_skb(resp_skb);
1467                         goto out;
1468                 }
1469         }
1470
1471         err = nlmsg_unicast(net->xfrm.nlsk, resp_skb, NETLINK_CB(skb).portid);
1472
1473 out:
1474         xfrm_state_put(x);
1475 out_noput:
1476         return err;
1477 }
1478
1479 static int verify_policy_dir(u8 dir)
1480 {
1481         switch (dir) {
1482         case XFRM_POLICY_IN:
1483         case XFRM_POLICY_OUT:
1484         case XFRM_POLICY_FWD:
1485                 break;
1486
1487         default:
1488                 return -EINVAL;
1489         }
1490
1491         return 0;
1492 }
1493
1494 static int verify_policy_type(u8 type)
1495 {
1496         switch (type) {
1497         case XFRM_POLICY_TYPE_MAIN:
1498 #ifdef CONFIG_XFRM_SUB_POLICY
1499         case XFRM_POLICY_TYPE_SUB:
1500 #endif
1501                 break;
1502
1503         default:
1504                 return -EINVAL;
1505         }
1506
1507         return 0;
1508 }
1509
1510 static int verify_newpolicy_info(struct xfrm_userpolicy_info *p)
1511 {
1512         int ret;
1513
1514         switch (p->share) {
1515         case XFRM_SHARE_ANY:
1516         case XFRM_SHARE_SESSION:
1517         case XFRM_SHARE_USER:
1518         case XFRM_SHARE_UNIQUE:
1519                 break;
1520
1521         default:
1522                 return -EINVAL;
1523         }
1524
1525         switch (p->action) {
1526         case XFRM_POLICY_ALLOW:
1527         case XFRM_POLICY_BLOCK:
1528                 break;
1529
1530         default:
1531                 return -EINVAL;
1532         }
1533
1534         switch (p->sel.family) {
1535         case AF_INET:
1536                 if (p->sel.prefixlen_d > 32 || p->sel.prefixlen_s > 32)
1537                         return -EINVAL;
1538
1539                 break;
1540
1541         case AF_INET6:
1542 #if IS_ENABLED(CONFIG_IPV6)
1543                 if (p->sel.prefixlen_d > 128 || p->sel.prefixlen_s > 128)
1544                         return -EINVAL;
1545
1546                 break;
1547 #else
1548                 return  -EAFNOSUPPORT;
1549 #endif
1550
1551         default:
1552                 return -EINVAL;
1553         }
1554
1555         ret = verify_policy_dir(p->dir);
1556         if (ret)
1557                 return ret;
1558         if (p->index && (xfrm_policy_id2dir(p->index) != p->dir))
1559                 return -EINVAL;
1560
1561         return 0;
1562 }
1563
1564 static int copy_from_user_sec_ctx(struct xfrm_policy *pol, struct nlattr **attrs)
1565 {
1566         struct nlattr *rt = attrs[XFRMA_SEC_CTX];
1567         struct xfrm_user_sec_ctx *uctx;
1568
1569         if (!rt)
1570                 return 0;
1571
1572         uctx = nla_data(rt);
1573         return security_xfrm_policy_alloc(&pol->security, uctx, GFP_KERNEL);
1574 }
1575
1576 static void copy_templates(struct xfrm_policy *xp, struct xfrm_user_tmpl *ut,
1577                            int nr)
1578 {
1579         int i;
1580
1581         xp->xfrm_nr = nr;
1582         for (i = 0; i < nr; i++, ut++) {
1583                 struct xfrm_tmpl *t = &xp->xfrm_vec[i];
1584
1585                 memcpy(&t->id, &ut->id, sizeof(struct xfrm_id));
1586                 memcpy(&t->saddr, &ut->saddr,
1587                        sizeof(xfrm_address_t));
1588                 t->reqid = ut->reqid;
1589                 t->mode = ut->mode;
1590                 t->share = ut->share;
1591                 t->optional = ut->optional;
1592                 t->aalgos = ut->aalgos;
1593                 t->ealgos = ut->ealgos;
1594                 t->calgos = ut->calgos;
1595                 /* If all masks are ~0, then we allow all algorithms. */
1596                 t->allalgs = !~(t->aalgos & t->ealgos & t->calgos);
1597                 t->encap_family = ut->family;
1598         }
1599 }
1600
1601 static int validate_tmpl(int nr, struct xfrm_user_tmpl *ut, u16 family)
1602 {
1603         u16 prev_family;
1604         int i;
1605
1606         if (nr > XFRM_MAX_DEPTH)
1607                 return -EINVAL;
1608
1609         prev_family = family;
1610
1611         for (i = 0; i < nr; i++) {
1612                 /* We never validated the ut->family value, so many
1613                  * applications simply leave it at zero.  The check was
1614                  * never made and ut->family was ignored because all
1615                  * templates could be assumed to have the same family as
1616                  * the policy itself.  Now that we will have ipv4-in-ipv6
1617                  * and ipv6-in-ipv4 tunnels, this is no longer true.
1618                  */
1619                 if (!ut[i].family)
1620                         ut[i].family = family;
1621
1622                 switch (ut[i].mode) {
1623                 case XFRM_MODE_TUNNEL:
1624                 case XFRM_MODE_BEET:
1625                         break;
1626                 default:
1627                         if (ut[i].family != prev_family)
1628                                 return -EINVAL;
1629                         break;
1630                 }
1631                 if (ut[i].mode >= XFRM_MODE_MAX)
1632                         return -EINVAL;
1633
1634                 prev_family = ut[i].family;
1635
1636                 switch (ut[i].family) {
1637                 case AF_INET:
1638                         break;
1639 #if IS_ENABLED(CONFIG_IPV6)
1640                 case AF_INET6:
1641                         break;
1642 #endif
1643                 default:
1644                         return -EINVAL;
1645                 }
1646
1647                 if (!xfrm_id_proto_valid(ut[i].id.proto))
1648                         return -EINVAL;
1649         }
1650
1651         return 0;
1652 }
1653
1654 static int copy_from_user_tmpl(struct xfrm_policy *pol, struct nlattr **attrs)
1655 {
1656         struct nlattr *rt = attrs[XFRMA_TMPL];
1657
1658         if (!rt) {
1659                 pol->xfrm_nr = 0;
1660         } else {
1661                 struct xfrm_user_tmpl *utmpl = nla_data(rt);
1662                 int nr = nla_len(rt) / sizeof(*utmpl);
1663                 int err;
1664
1665                 err = validate_tmpl(nr, utmpl, pol->family);
1666                 if (err)
1667                         return err;
1668
1669                 copy_templates(pol, utmpl, nr);
1670         }
1671         return 0;
1672 }
1673
1674 static int copy_from_user_policy_type(u8 *tp, struct nlattr **attrs)
1675 {
1676         struct nlattr *rt = attrs[XFRMA_POLICY_TYPE];
1677         struct xfrm_userpolicy_type *upt;
1678         u8 type = XFRM_POLICY_TYPE_MAIN;
1679         int err;
1680
1681         if (rt) {
1682                 upt = nla_data(rt);
1683                 type = upt->type;
1684         }
1685
1686         err = verify_policy_type(type);
1687         if (err)
1688                 return err;
1689
1690         *tp = type;
1691         return 0;
1692 }
1693
1694 static void copy_from_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p)
1695 {
1696         xp->priority = p->priority;
1697         xp->index = p->index;
1698         memcpy(&xp->selector, &p->sel, sizeof(xp->selector));
1699         memcpy(&xp->lft, &p->lft, sizeof(xp->lft));
1700         xp->action = p->action;
1701         xp->flags = p->flags;
1702         xp->family = p->sel.family;
1703         /* XXX xp->share = p->share; */
1704 }
1705
1706 static void copy_to_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p, int dir)
1707 {
1708         memset(p, 0, sizeof(*p));
1709         memcpy(&p->sel, &xp->selector, sizeof(p->sel));
1710         memcpy(&p->lft, &xp->lft, sizeof(p->lft));
1711         memcpy(&p->curlft, &xp->curlft, sizeof(p->curlft));
1712         p->priority = xp->priority;
1713         p->index = xp->index;
1714         p->sel.family = xp->family;
1715         p->dir = dir;
1716         p->action = xp->action;
1717         p->flags = xp->flags;
1718         p->share = XFRM_SHARE_ANY; /* XXX xp->share */
1719 }
1720
1721 static struct xfrm_policy *xfrm_policy_construct(struct net *net, struct xfrm_userpolicy_info *p, struct nlattr **attrs, int *errp)
1722 {
1723         struct xfrm_policy *xp = xfrm_policy_alloc(net, GFP_KERNEL);
1724         int err;
1725
1726         if (!xp) {
1727                 *errp = -ENOMEM;
1728                 return NULL;
1729         }
1730
1731         copy_from_user_policy(xp, p);
1732
1733         err = copy_from_user_policy_type(&xp->type, attrs);
1734         if (err)
1735                 goto error;
1736
1737         if (!(err = copy_from_user_tmpl(xp, attrs)))
1738                 err = copy_from_user_sec_ctx(xp, attrs);
1739         if (err)
1740                 goto error;
1741
1742         xfrm_mark_get(attrs, &xp->mark);
1743
1744         if (attrs[XFRMA_IF_ID])
1745                 xp->if_id = nla_get_u32(attrs[XFRMA_IF_ID]);
1746
1747         return xp;
1748  error:
1749         *errp = err;
1750         xp->walk.dead = 1;
1751         xfrm_policy_destroy(xp);
1752         return NULL;
1753 }
1754
1755 static int xfrm_add_policy(struct sk_buff *skb, struct nlmsghdr *nlh,
1756                 struct nlattr **attrs)
1757 {
1758         struct net *net = sock_net(skb->sk);
1759         struct xfrm_userpolicy_info *p = nlmsg_data(nlh);
1760         struct xfrm_policy *xp;
1761         struct km_event c;
1762         int err;
1763         int excl;
1764
1765         err = verify_newpolicy_info(p);
1766         if (err)
1767                 return err;
1768         err = verify_sec_ctx_len(attrs);
1769         if (err)
1770                 return err;
1771
1772         xp = xfrm_policy_construct(net, p, attrs, &err);
1773         if (!xp)
1774                 return err;
1775
1776         /* shouldn't excl be based on nlh flags??
1777          * Aha! this is anti-netlink really i.e  more pfkey derived
1778          * in netlink excl is a flag and you wouldn't need
1779          * a type XFRM_MSG_UPDPOLICY - JHS */
1780         excl = nlh->nlmsg_type == XFRM_MSG_NEWPOLICY;
1781         err = xfrm_policy_insert(p->dir, xp, excl);
1782         xfrm_audit_policy_add(xp, err ? 0 : 1, true);
1783
1784         if (err) {
1785                 security_xfrm_policy_free(xp->security);
1786                 kfree(xp);
1787                 return err;
1788         }
1789
1790         c.event = nlh->nlmsg_type;
1791         c.seq = nlh->nlmsg_seq;
1792         c.portid = nlh->nlmsg_pid;
1793         km_policy_notify(xp, p->dir, &c);
1794
1795         xfrm_pol_put(xp);
1796
1797         return 0;
1798 }
1799
1800 static int copy_to_user_tmpl(struct xfrm_policy *xp, struct sk_buff *skb)
1801 {
1802         struct xfrm_user_tmpl vec[XFRM_MAX_DEPTH];
1803         int i;
1804
1805         if (xp->xfrm_nr == 0)
1806                 return 0;
1807
1808         for (i = 0; i < xp->xfrm_nr; i++) {
1809                 struct xfrm_user_tmpl *up = &vec[i];
1810                 struct xfrm_tmpl *kp = &xp->xfrm_vec[i];
1811
1812                 memset(up, 0, sizeof(*up));
1813                 memcpy(&up->id, &kp->id, sizeof(up->id));
1814                 up->family = kp->encap_family;
1815                 memcpy(&up->saddr, &kp->saddr, sizeof(up->saddr));
1816                 up->reqid = kp->reqid;
1817                 up->mode = kp->mode;
1818                 up->share = kp->share;
1819                 up->optional = kp->optional;
1820                 up->aalgos = kp->aalgos;
1821                 up->ealgos = kp->ealgos;
1822                 up->calgos = kp->calgos;
1823         }
1824
1825         return nla_put(skb, XFRMA_TMPL,
1826                        sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr, vec);
1827 }
1828
1829 static inline int copy_to_user_state_sec_ctx(struct xfrm_state *x, struct sk_buff *skb)
1830 {
1831         if (x->security) {
1832                 return copy_sec_ctx(x->security, skb);
1833         }
1834         return 0;
1835 }
1836
1837 static inline int copy_to_user_sec_ctx(struct xfrm_policy *xp, struct sk_buff *skb)
1838 {
1839         if (xp->security)
1840                 return copy_sec_ctx(xp->security, skb);
1841         return 0;
1842 }
1843 static inline unsigned int userpolicy_type_attrsize(void)
1844 {
1845 #ifdef CONFIG_XFRM_SUB_POLICY
1846         return nla_total_size(sizeof(struct xfrm_userpolicy_type));
1847 #else
1848         return 0;
1849 #endif
1850 }
1851
1852 #ifdef CONFIG_XFRM_SUB_POLICY
1853 static int copy_to_user_policy_type(u8 type, struct sk_buff *skb)
1854 {
1855         struct xfrm_userpolicy_type upt;
1856
1857         /* Sadly there are two holes in struct xfrm_userpolicy_type */
1858         memset(&upt, 0, sizeof(upt));
1859         upt.type = type;
1860
1861         return nla_put(skb, XFRMA_POLICY_TYPE, sizeof(upt), &upt);
1862 }
1863
1864 #else
1865 static inline int copy_to_user_policy_type(u8 type, struct sk_buff *skb)
1866 {
1867         return 0;
1868 }
1869 #endif
1870
1871 static int dump_one_policy(struct xfrm_policy *xp, int dir, int count, void *ptr)
1872 {
1873         struct xfrm_dump_info *sp = ptr;
1874         struct xfrm_userpolicy_info *p;
1875         struct sk_buff *in_skb = sp->in_skb;
1876         struct sk_buff *skb = sp->out_skb;
1877         struct xfrm_translator *xtr;
1878         struct nlmsghdr *nlh;
1879         int err;
1880
1881         nlh = nlmsg_put(skb, NETLINK_CB(in_skb).portid, sp->nlmsg_seq,
1882                         XFRM_MSG_NEWPOLICY, sizeof(*p), sp->nlmsg_flags);
1883         if (nlh == NULL)
1884                 return -EMSGSIZE;
1885
1886         p = nlmsg_data(nlh);
1887         copy_to_user_policy(xp, p, dir);
1888         err = copy_to_user_tmpl(xp, skb);
1889         if (!err)
1890                 err = copy_to_user_sec_ctx(xp, skb);
1891         if (!err)
1892                 err = copy_to_user_policy_type(xp->type, skb);
1893         if (!err)
1894                 err = xfrm_mark_put(skb, &xp->mark);
1895         if (!err)
1896                 err = xfrm_if_id_put(skb, xp->if_id);
1897         if (err) {
1898                 nlmsg_cancel(skb, nlh);
1899                 return err;
1900         }
1901         nlmsg_end(skb, nlh);
1902
1903         xtr = xfrm_get_translator();
1904         if (xtr) {
1905                 err = xtr->alloc_compat(skb, nlh);
1906
1907                 xfrm_put_translator(xtr);
1908                 if (err) {
1909                         nlmsg_cancel(skb, nlh);
1910                         return err;
1911                 }
1912         }
1913
1914         return 0;
1915 }
1916
1917 static int xfrm_dump_policy_done(struct netlink_callback *cb)
1918 {
1919         struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *)cb->args;
1920         struct net *net = sock_net(cb->skb->sk);
1921
1922         xfrm_policy_walk_done(walk, net);
1923         return 0;
1924 }
1925
1926 static int xfrm_dump_policy_start(struct netlink_callback *cb)
1927 {
1928         struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *)cb->args;
1929
1930         BUILD_BUG_ON(sizeof(*walk) > sizeof(cb->args));
1931
1932         xfrm_policy_walk_init(walk, XFRM_POLICY_TYPE_ANY);
1933         return 0;
1934 }
1935
1936 static int xfrm_dump_policy(struct sk_buff *skb, struct netlink_callback *cb)
1937 {
1938         struct net *net = sock_net(skb->sk);
1939         struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *)cb->args;
1940         struct xfrm_dump_info info;
1941
1942         info.in_skb = cb->skb;
1943         info.out_skb = skb;
1944         info.nlmsg_seq = cb->nlh->nlmsg_seq;
1945         info.nlmsg_flags = NLM_F_MULTI;
1946
1947         (void) xfrm_policy_walk(net, walk, dump_one_policy, &info);
1948
1949         return skb->len;
1950 }
1951
1952 static struct sk_buff *xfrm_policy_netlink(struct sk_buff *in_skb,
1953                                           struct xfrm_policy *xp,
1954                                           int dir, u32 seq)
1955 {
1956         struct xfrm_dump_info info;
1957         struct sk_buff *skb;
1958         int err;
1959
1960         skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
1961         if (!skb)
1962                 return ERR_PTR(-ENOMEM);
1963
1964         info.in_skb = in_skb;
1965         info.out_skb = skb;
1966         info.nlmsg_seq = seq;
1967         info.nlmsg_flags = 0;
1968
1969         err = dump_one_policy(xp, dir, 0, &info);
1970         if (err) {
1971                 kfree_skb(skb);
1972                 return ERR_PTR(err);
1973         }
1974
1975         return skb;
1976 }
1977
1978 static int xfrm_notify_userpolicy(struct net *net)
1979 {
1980         struct xfrm_userpolicy_default *up;
1981         int len = NLMSG_ALIGN(sizeof(*up));
1982         struct nlmsghdr *nlh;
1983         struct sk_buff *skb;
1984         int err;
1985
1986         skb = nlmsg_new(len, GFP_ATOMIC);
1987         if (skb == NULL)
1988                 return -ENOMEM;
1989
1990         nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_GETDEFAULT, sizeof(*up), 0);
1991         if (nlh == NULL) {
1992                 kfree_skb(skb);
1993                 return -EMSGSIZE;
1994         }
1995
1996         up = nlmsg_data(nlh);
1997         up->in = net->xfrm.policy_default & XFRM_POL_DEFAULT_IN ?
1998                         XFRM_USERPOLICY_BLOCK : XFRM_USERPOLICY_ACCEPT;
1999         up->fwd = net->xfrm.policy_default & XFRM_POL_DEFAULT_FWD ?
2000                         XFRM_USERPOLICY_BLOCK : XFRM_USERPOLICY_ACCEPT;
2001         up->out = net->xfrm.policy_default & XFRM_POL_DEFAULT_OUT ?
2002                         XFRM_USERPOLICY_BLOCK : XFRM_USERPOLICY_ACCEPT;
2003
2004         nlmsg_end(skb, nlh);
2005
2006         rcu_read_lock();
2007         err = xfrm_nlmsg_multicast(net, skb, 0, XFRMNLGRP_POLICY);
2008         rcu_read_unlock();
2009
2010         return err;
2011 }
2012
2013 static int xfrm_set_default(struct sk_buff *skb, struct nlmsghdr *nlh,
2014                             struct nlattr **attrs)
2015 {
2016         struct net *net = sock_net(skb->sk);
2017         struct xfrm_userpolicy_default *up = nlmsg_data(nlh);
2018
2019         if (up->in == XFRM_USERPOLICY_BLOCK)
2020                 net->xfrm.policy_default |= XFRM_POL_DEFAULT_IN;
2021         else if (up->in == XFRM_USERPOLICY_ACCEPT)
2022                 net->xfrm.policy_default &= ~XFRM_POL_DEFAULT_IN;
2023
2024         if (up->fwd == XFRM_USERPOLICY_BLOCK)
2025                 net->xfrm.policy_default |= XFRM_POL_DEFAULT_FWD;
2026         else if (up->fwd == XFRM_USERPOLICY_ACCEPT)
2027                 net->xfrm.policy_default &= ~XFRM_POL_DEFAULT_FWD;
2028
2029         if (up->out == XFRM_USERPOLICY_BLOCK)
2030                 net->xfrm.policy_default |= XFRM_POL_DEFAULT_OUT;
2031         else if (up->out == XFRM_USERPOLICY_ACCEPT)
2032                 net->xfrm.policy_default &= ~XFRM_POL_DEFAULT_OUT;
2033
2034         rt_genid_bump_all(net);
2035
2036         xfrm_notify_userpolicy(net);
2037         return 0;
2038 }
2039
2040 static int xfrm_get_default(struct sk_buff *skb, struct nlmsghdr *nlh,
2041                             struct nlattr **attrs)
2042 {
2043         struct sk_buff *r_skb;
2044         struct nlmsghdr *r_nlh;
2045         struct net *net = sock_net(skb->sk);
2046         struct xfrm_userpolicy_default *r_up;
2047         int len = NLMSG_ALIGN(sizeof(struct xfrm_userpolicy_default));
2048         u32 portid = NETLINK_CB(skb).portid;
2049         u32 seq = nlh->nlmsg_seq;
2050
2051         r_skb = nlmsg_new(len, GFP_ATOMIC);
2052         if (!r_skb)
2053                 return -ENOMEM;
2054
2055         r_nlh = nlmsg_put(r_skb, portid, seq, XFRM_MSG_GETDEFAULT, sizeof(*r_up), 0);
2056         if (!r_nlh) {
2057                 kfree_skb(r_skb);
2058                 return -EMSGSIZE;
2059         }
2060
2061         r_up = nlmsg_data(r_nlh);
2062
2063         r_up->in = net->xfrm.policy_default & XFRM_POL_DEFAULT_IN ?
2064                         XFRM_USERPOLICY_BLOCK : XFRM_USERPOLICY_ACCEPT;
2065         r_up->fwd = net->xfrm.policy_default & XFRM_POL_DEFAULT_FWD ?
2066                         XFRM_USERPOLICY_BLOCK : XFRM_USERPOLICY_ACCEPT;
2067         r_up->out = net->xfrm.policy_default & XFRM_POL_DEFAULT_OUT ?
2068                         XFRM_USERPOLICY_BLOCK : XFRM_USERPOLICY_ACCEPT;
2069         nlmsg_end(r_skb, r_nlh);
2070
2071         return nlmsg_unicast(net->xfrm.nlsk, r_skb, portid);
2072 }
2073
2074 static int xfrm_get_policy(struct sk_buff *skb, struct nlmsghdr *nlh,
2075                 struct nlattr **attrs)
2076 {
2077         struct net *net = sock_net(skb->sk);
2078         struct xfrm_policy *xp;
2079         struct xfrm_userpolicy_id *p;
2080         u8 type = XFRM_POLICY_TYPE_MAIN;
2081         int err;
2082         struct km_event c;
2083         int delete;
2084         struct xfrm_mark m;
2085         u32 if_id = 0;
2086
2087         p = nlmsg_data(nlh);
2088         delete = nlh->nlmsg_type == XFRM_MSG_DELPOLICY;
2089
2090         err = copy_from_user_policy_type(&type, attrs);
2091         if (err)
2092                 return err;
2093
2094         err = verify_policy_dir(p->dir);
2095         if (err)
2096                 return err;
2097
2098         if (attrs[XFRMA_IF_ID])
2099                 if_id = nla_get_u32(attrs[XFRMA_IF_ID]);
2100
2101         xfrm_mark_get(attrs, &m);
2102
2103         if (p->index)
2104                 xp = xfrm_policy_byid(net, &m, if_id, type, p->dir,
2105                                       p->index, delete, &err);
2106         else {
2107                 struct nlattr *rt = attrs[XFRMA_SEC_CTX];
2108                 struct xfrm_sec_ctx *ctx;
2109
2110                 err = verify_sec_ctx_len(attrs);
2111                 if (err)
2112                         return err;
2113
2114                 ctx = NULL;
2115                 if (rt) {
2116                         struct xfrm_user_sec_ctx *uctx = nla_data(rt);
2117
2118                         err = security_xfrm_policy_alloc(&ctx, uctx, GFP_KERNEL);
2119                         if (err)
2120                                 return err;
2121                 }
2122                 xp = xfrm_policy_bysel_ctx(net, &m, if_id, type, p->dir,
2123                                            &p->sel, ctx, delete, &err);
2124                 security_xfrm_policy_free(ctx);
2125         }
2126         if (xp == NULL)
2127                 return -ENOENT;
2128
2129         if (!delete) {
2130                 struct sk_buff *resp_skb;
2131
2132                 resp_skb = xfrm_policy_netlink(skb, xp, p->dir, nlh->nlmsg_seq);
2133                 if (IS_ERR(resp_skb)) {
2134                         err = PTR_ERR(resp_skb);
2135                 } else {
2136                         err = nlmsg_unicast(net->xfrm.nlsk, resp_skb,
2137                                             NETLINK_CB(skb).portid);
2138                 }
2139         } else {
2140                 xfrm_audit_policy_delete(xp, err ? 0 : 1, true);
2141
2142                 if (err != 0)
2143                         goto out;
2144
2145                 c.data.byid = p->index;
2146                 c.event = nlh->nlmsg_type;
2147                 c.seq = nlh->nlmsg_seq;
2148                 c.portid = nlh->nlmsg_pid;
2149                 km_policy_notify(xp, p->dir, &c);
2150         }
2151
2152 out:
2153         xfrm_pol_put(xp);
2154         return err;
2155 }
2156
2157 static int xfrm_flush_sa(struct sk_buff *skb, struct nlmsghdr *nlh,
2158                 struct nlattr **attrs)
2159 {
2160         struct net *net = sock_net(skb->sk);
2161         struct km_event c;
2162         struct xfrm_usersa_flush *p = nlmsg_data(nlh);
2163         int err;
2164
2165         err = xfrm_state_flush(net, p->proto, true, false);
2166         if (err) {
2167                 if (err == -ESRCH) /* empty table */
2168                         return 0;
2169                 return err;
2170         }
2171         c.data.proto = p->proto;
2172         c.event = nlh->nlmsg_type;
2173         c.seq = nlh->nlmsg_seq;
2174         c.portid = nlh->nlmsg_pid;
2175         c.net = net;
2176         km_state_notify(NULL, &c);
2177
2178         return 0;
2179 }
2180
2181 static inline unsigned int xfrm_aevent_msgsize(struct xfrm_state *x)
2182 {
2183         unsigned int replay_size = x->replay_esn ?
2184                               xfrm_replay_state_esn_len(x->replay_esn) :
2185                               sizeof(struct xfrm_replay_state);
2186
2187         return NLMSG_ALIGN(sizeof(struct xfrm_aevent_id))
2188                + nla_total_size(replay_size)
2189                + nla_total_size_64bit(sizeof(struct xfrm_lifetime_cur))
2190                + nla_total_size(sizeof(struct xfrm_mark))
2191                + nla_total_size(4) /* XFRM_AE_RTHR */
2192                + nla_total_size(4); /* XFRM_AE_ETHR */
2193 }
2194
2195 static int build_aevent(struct sk_buff *skb, struct xfrm_state *x, const struct km_event *c)
2196 {
2197         struct xfrm_aevent_id *id;
2198         struct nlmsghdr *nlh;
2199         int err;
2200
2201         nlh = nlmsg_put(skb, c->portid, c->seq, XFRM_MSG_NEWAE, sizeof(*id), 0);
2202         if (nlh == NULL)
2203                 return -EMSGSIZE;
2204
2205         id = nlmsg_data(nlh);
2206         memset(&id->sa_id, 0, sizeof(id->sa_id));
2207         memcpy(&id->sa_id.daddr, &x->id.daddr, sizeof(x->id.daddr));
2208         id->sa_id.spi = x->id.spi;
2209         id->sa_id.family = x->props.family;
2210         id->sa_id.proto = x->id.proto;
2211         memcpy(&id->saddr, &x->props.saddr, sizeof(x->props.saddr));
2212         id->reqid = x->props.reqid;
2213         id->flags = c->data.aevent;
2214
2215         if (x->replay_esn) {
2216                 err = nla_put(skb, XFRMA_REPLAY_ESN_VAL,
2217                               xfrm_replay_state_esn_len(x->replay_esn),
2218                               x->replay_esn);
2219         } else {
2220                 err = nla_put(skb, XFRMA_REPLAY_VAL, sizeof(x->replay),
2221                               &x->replay);
2222         }
2223         if (err)
2224                 goto out_cancel;
2225         err = nla_put_64bit(skb, XFRMA_LTIME_VAL, sizeof(x->curlft), &x->curlft,
2226                             XFRMA_PAD);
2227         if (err)
2228                 goto out_cancel;
2229
2230         if (id->flags & XFRM_AE_RTHR) {
2231                 err = nla_put_u32(skb, XFRMA_REPLAY_THRESH, x->replay_maxdiff);
2232                 if (err)
2233                         goto out_cancel;
2234         }
2235         if (id->flags & XFRM_AE_ETHR) {
2236                 err = nla_put_u32(skb, XFRMA_ETIMER_THRESH,
2237                                   x->replay_maxage * 10 / HZ);
2238                 if (err)
2239                         goto out_cancel;
2240         }
2241         err = xfrm_mark_put(skb, &x->mark);
2242         if (err)
2243                 goto out_cancel;
2244
2245         err = xfrm_if_id_put(skb, x->if_id);
2246         if (err)
2247                 goto out_cancel;
2248
2249         nlmsg_end(skb, nlh);
2250         return 0;
2251
2252 out_cancel:
2253         nlmsg_cancel(skb, nlh);
2254         return err;
2255 }
2256
2257 static int xfrm_get_ae(struct sk_buff *skb, struct nlmsghdr *nlh,
2258                 struct nlattr **attrs)
2259 {
2260         struct net *net = sock_net(skb->sk);
2261         struct xfrm_state *x;
2262         struct sk_buff *r_skb;
2263         int err;
2264         struct km_event c;
2265         u32 mark;
2266         struct xfrm_mark m;
2267         struct xfrm_aevent_id *p = nlmsg_data(nlh);
2268         struct xfrm_usersa_id *id = &p->sa_id;
2269
2270         mark = xfrm_mark_get(attrs, &m);
2271
2272         x = xfrm_state_lookup(net, mark, &id->daddr, id->spi, id->proto, id->family);
2273         if (x == NULL)
2274                 return -ESRCH;
2275
2276         r_skb = nlmsg_new(xfrm_aevent_msgsize(x), GFP_ATOMIC);
2277         if (r_skb == NULL) {
2278                 xfrm_state_put(x);
2279                 return -ENOMEM;
2280         }
2281
2282         /*
2283          * XXX: is this lock really needed - none of the other
2284          * gets lock (the concern is things getting updated
2285          * while we are still reading) - jhs
2286         */
2287         spin_lock_bh(&x->lock);
2288         c.data.aevent = p->flags;
2289         c.seq = nlh->nlmsg_seq;
2290         c.portid = nlh->nlmsg_pid;
2291
2292         err = build_aevent(r_skb, x, &c);
2293         BUG_ON(err < 0);
2294
2295         err = nlmsg_unicast(net->xfrm.nlsk, r_skb, NETLINK_CB(skb).portid);
2296         spin_unlock_bh(&x->lock);
2297         xfrm_state_put(x);
2298         return err;
2299 }
2300
2301 static int xfrm_new_ae(struct sk_buff *skb, struct nlmsghdr *nlh,
2302                 struct nlattr **attrs)
2303 {
2304         struct net *net = sock_net(skb->sk);
2305         struct xfrm_state *x;
2306         struct km_event c;
2307         int err = -EINVAL;
2308         u32 mark = 0;
2309         struct xfrm_mark m;
2310         struct xfrm_aevent_id *p = nlmsg_data(nlh);
2311         struct nlattr *rp = attrs[XFRMA_REPLAY_VAL];
2312         struct nlattr *re = attrs[XFRMA_REPLAY_ESN_VAL];
2313         struct nlattr *lt = attrs[XFRMA_LTIME_VAL];
2314         struct nlattr *et = attrs[XFRMA_ETIMER_THRESH];
2315         struct nlattr *rt = attrs[XFRMA_REPLAY_THRESH];
2316
2317         if (!lt && !rp && !re && !et && !rt)
2318                 return err;
2319
2320         /* pedantic mode - thou shalt sayeth replaceth */
2321         if (!(nlh->nlmsg_flags&NLM_F_REPLACE))
2322                 return err;
2323
2324         mark = xfrm_mark_get(attrs, &m);
2325
2326         x = xfrm_state_lookup(net, mark, &p->sa_id.daddr, p->sa_id.spi, p->sa_id.proto, p->sa_id.family);
2327         if (x == NULL)
2328                 return -ESRCH;
2329
2330         if (x->km.state != XFRM_STATE_VALID)
2331                 goto out;
2332
2333         err = xfrm_replay_verify_len(x->replay_esn, re);
2334         if (err)
2335                 goto out;
2336
2337         spin_lock_bh(&x->lock);
2338         xfrm_update_ae_params(x, attrs, 1);
2339         spin_unlock_bh(&x->lock);
2340
2341         c.event = nlh->nlmsg_type;
2342         c.seq = nlh->nlmsg_seq;
2343         c.portid = nlh->nlmsg_pid;
2344         c.data.aevent = XFRM_AE_CU;
2345         km_state_notify(x, &c);
2346         err = 0;
2347 out:
2348         xfrm_state_put(x);
2349         return err;
2350 }
2351
2352 static int xfrm_flush_policy(struct sk_buff *skb, struct nlmsghdr *nlh,
2353                 struct nlattr **attrs)
2354 {
2355         struct net *net = sock_net(skb->sk);
2356         struct km_event c;
2357         u8 type = XFRM_POLICY_TYPE_MAIN;
2358         int err;
2359
2360         err = copy_from_user_policy_type(&type, attrs);
2361         if (err)
2362                 return err;
2363
2364         err = xfrm_policy_flush(net, type, true);
2365         if (err) {
2366                 if (err == -ESRCH) /* empty table */
2367                         return 0;
2368                 return err;
2369         }
2370
2371         c.data.type = type;
2372         c.event = nlh->nlmsg_type;
2373         c.seq = nlh->nlmsg_seq;
2374         c.portid = nlh->nlmsg_pid;
2375         c.net = net;
2376         km_policy_notify(NULL, 0, &c);
2377         return 0;
2378 }
2379
2380 static int xfrm_add_pol_expire(struct sk_buff *skb, struct nlmsghdr *nlh,
2381                 struct nlattr **attrs)
2382 {
2383         struct net *net = sock_net(skb->sk);
2384         struct xfrm_policy *xp;
2385         struct xfrm_user_polexpire *up = nlmsg_data(nlh);
2386         struct xfrm_userpolicy_info *p = &up->pol;
2387         u8 type = XFRM_POLICY_TYPE_MAIN;
2388         int err = -ENOENT;
2389         struct xfrm_mark m;
2390         u32 if_id = 0;
2391
2392         err = copy_from_user_policy_type(&type, attrs);
2393         if (err)
2394                 return err;
2395
2396         err = verify_policy_dir(p->dir);
2397         if (err)
2398                 return err;
2399
2400         if (attrs[XFRMA_IF_ID])
2401                 if_id = nla_get_u32(attrs[XFRMA_IF_ID]);
2402
2403         xfrm_mark_get(attrs, &m);
2404
2405         if (p->index)
2406                 xp = xfrm_policy_byid(net, &m, if_id, type, p->dir, p->index,
2407                                       0, &err);
2408         else {
2409                 struct nlattr *rt = attrs[XFRMA_SEC_CTX];
2410                 struct xfrm_sec_ctx *ctx;
2411
2412                 err = verify_sec_ctx_len(attrs);
2413                 if (err)
2414                         return err;
2415
2416                 ctx = NULL;
2417                 if (rt) {
2418                         struct xfrm_user_sec_ctx *uctx = nla_data(rt);
2419
2420                         err = security_xfrm_policy_alloc(&ctx, uctx, GFP_KERNEL);
2421                         if (err)
2422                                 return err;
2423                 }
2424                 xp = xfrm_policy_bysel_ctx(net, &m, if_id, type, p->dir,
2425                                            &p->sel, ctx, 0, &err);
2426                 security_xfrm_policy_free(ctx);
2427         }
2428         if (xp == NULL)
2429                 return -ENOENT;
2430
2431         if (unlikely(xp->walk.dead))
2432                 goto out;
2433
2434         err = 0;
2435         if (up->hard) {
2436                 xfrm_policy_delete(xp, p->dir);
2437                 xfrm_audit_policy_delete(xp, 1, true);
2438         }
2439         km_policy_expired(xp, p->dir, up->hard, nlh->nlmsg_pid);
2440
2441 out:
2442         xfrm_pol_put(xp);
2443         return err;
2444 }
2445
2446 static int xfrm_add_sa_expire(struct sk_buff *skb, struct nlmsghdr *nlh,
2447                 struct nlattr **attrs)
2448 {
2449         struct net *net = sock_net(skb->sk);
2450         struct xfrm_state *x;
2451         int err;
2452         struct xfrm_user_expire *ue = nlmsg_data(nlh);
2453         struct xfrm_usersa_info *p = &ue->state;
2454         struct xfrm_mark m;
2455         u32 mark = xfrm_mark_get(attrs, &m);
2456
2457         x = xfrm_state_lookup(net, mark, &p->id.daddr, p->id.spi, p->id.proto, p->family);
2458
2459         err = -ENOENT;
2460         if (x == NULL)
2461                 return err;
2462
2463         spin_lock_bh(&x->lock);
2464         err = -EINVAL;
2465         if (x->km.state != XFRM_STATE_VALID)
2466                 goto out;
2467         km_state_expired(x, ue->hard, nlh->nlmsg_pid);
2468
2469         if (ue->hard) {
2470                 __xfrm_state_delete(x);
2471                 xfrm_audit_state_delete(x, 1, true);
2472         }
2473         err = 0;
2474 out:
2475         spin_unlock_bh(&x->lock);
2476         xfrm_state_put(x);
2477         return err;
2478 }
2479
2480 static int xfrm_add_acquire(struct sk_buff *skb, struct nlmsghdr *nlh,
2481                 struct nlattr **attrs)
2482 {
2483         struct net *net = sock_net(skb->sk);
2484         struct xfrm_policy *xp;
2485         struct xfrm_user_tmpl *ut;
2486         int i;
2487         struct nlattr *rt = attrs[XFRMA_TMPL];
2488         struct xfrm_mark mark;
2489
2490         struct xfrm_user_acquire *ua = nlmsg_data(nlh);
2491         struct xfrm_state *x = xfrm_state_alloc(net);
2492         int err = -ENOMEM;
2493
2494         if (!x)
2495                 goto nomem;
2496
2497         xfrm_mark_get(attrs, &mark);
2498
2499         err = verify_newpolicy_info(&ua->policy);
2500         if (err)
2501                 goto free_state;
2502         err = verify_sec_ctx_len(attrs);
2503         if (err)
2504                 goto free_state;
2505
2506         /*   build an XP */
2507         xp = xfrm_policy_construct(net, &ua->policy, attrs, &err);
2508         if (!xp)
2509                 goto free_state;
2510
2511         memcpy(&x->id, &ua->id, sizeof(ua->id));
2512         memcpy(&x->props.saddr, &ua->saddr, sizeof(ua->saddr));
2513         memcpy(&x->sel, &ua->sel, sizeof(ua->sel));
2514         xp->mark.m = x->mark.m = mark.m;
2515         xp->mark.v = x->mark.v = mark.v;
2516         ut = nla_data(rt);
2517         /* extract the templates and for each call km_key */
2518         for (i = 0; i < xp->xfrm_nr; i++, ut++) {
2519                 struct xfrm_tmpl *t = &xp->xfrm_vec[i];
2520                 memcpy(&x->id, &t->id, sizeof(x->id));
2521                 x->props.mode = t->mode;
2522                 x->props.reqid = t->reqid;
2523                 x->props.family = ut->family;
2524                 t->aalgos = ua->aalgos;
2525                 t->ealgos = ua->ealgos;
2526                 t->calgos = ua->calgos;
2527                 err = km_query(x, t, xp);
2528
2529         }
2530
2531         xfrm_state_free(x);
2532         kfree(xp);
2533
2534         return 0;
2535
2536 free_state:
2537         xfrm_state_free(x);
2538 nomem:
2539         return err;
2540 }
2541
2542 #ifdef CONFIG_XFRM_MIGRATE
2543 static int copy_from_user_migrate(struct xfrm_migrate *ma,
2544                                   struct xfrm_kmaddress *k,
2545                                   struct nlattr **attrs, int *num)
2546 {
2547         struct nlattr *rt = attrs[XFRMA_MIGRATE];
2548         struct xfrm_user_migrate *um;
2549         int i, num_migrate;
2550
2551         if (k != NULL) {
2552                 struct xfrm_user_kmaddress *uk;
2553
2554                 uk = nla_data(attrs[XFRMA_KMADDRESS]);
2555                 memcpy(&k->local, &uk->local, sizeof(k->local));
2556                 memcpy(&k->remote, &uk->remote, sizeof(k->remote));
2557                 k->family = uk->family;
2558                 k->reserved = uk->reserved;
2559         }
2560
2561         um = nla_data(rt);
2562         num_migrate = nla_len(rt) / sizeof(*um);
2563
2564         if (num_migrate <= 0 || num_migrate > XFRM_MAX_DEPTH)
2565                 return -EINVAL;
2566
2567         for (i = 0; i < num_migrate; i++, um++, ma++) {
2568                 memcpy(&ma->old_daddr, &um->old_daddr, sizeof(ma->old_daddr));
2569                 memcpy(&ma->old_saddr, &um->old_saddr, sizeof(ma->old_saddr));
2570                 memcpy(&ma->new_daddr, &um->new_daddr, sizeof(ma->new_daddr));
2571                 memcpy(&ma->new_saddr, &um->new_saddr, sizeof(ma->new_saddr));
2572
2573                 ma->proto = um->proto;
2574                 ma->mode = um->mode;
2575                 ma->reqid = um->reqid;
2576
2577                 ma->old_family = um->old_family;
2578                 ma->new_family = um->new_family;
2579         }
2580
2581         *num = i;
2582         return 0;
2583 }
2584
2585 static int xfrm_do_migrate(struct sk_buff *skb, struct nlmsghdr *nlh,
2586                            struct nlattr **attrs)
2587 {
2588         struct xfrm_userpolicy_id *pi = nlmsg_data(nlh);
2589         struct xfrm_migrate m[XFRM_MAX_DEPTH];
2590         struct xfrm_kmaddress km, *kmp;
2591         u8 type;
2592         int err;
2593         int n = 0;
2594         struct net *net = sock_net(skb->sk);
2595         struct xfrm_encap_tmpl  *encap = NULL;
2596         u32 if_id = 0;
2597
2598         if (attrs[XFRMA_MIGRATE] == NULL)
2599                 return -EINVAL;
2600
2601         kmp = attrs[XFRMA_KMADDRESS] ? &km : NULL;
2602
2603         err = copy_from_user_policy_type(&type, attrs);
2604         if (err)
2605                 return err;
2606
2607         err = copy_from_user_migrate((struct xfrm_migrate *)m, kmp, attrs, &n);
2608         if (err)
2609                 return err;
2610
2611         if (!n)
2612                 return 0;
2613
2614         if (attrs[XFRMA_ENCAP]) {
2615                 encap = kmemdup(nla_data(attrs[XFRMA_ENCAP]),
2616                                 sizeof(*encap), GFP_KERNEL);
2617                 if (!encap)
2618                         return -ENOMEM;
2619         }
2620
2621         if (attrs[XFRMA_IF_ID])
2622                 if_id = nla_get_u32(attrs[XFRMA_IF_ID]);
2623
2624         err = xfrm_migrate(&pi->sel, pi->dir, type, m, n, kmp, net, encap, if_id);
2625
2626         kfree(encap);
2627
2628         return err;
2629 }
2630 #else
2631 static int xfrm_do_migrate(struct sk_buff *skb, struct nlmsghdr *nlh,
2632                            struct nlattr **attrs)
2633 {
2634         return -ENOPROTOOPT;
2635 }
2636 #endif
2637
2638 #ifdef CONFIG_XFRM_MIGRATE
2639 static int copy_to_user_migrate(const struct xfrm_migrate *m, struct sk_buff *skb)
2640 {
2641         struct xfrm_user_migrate um;
2642
2643         memset(&um, 0, sizeof(um));
2644         um.proto = m->proto;
2645         um.mode = m->mode;
2646         um.reqid = m->reqid;
2647         um.old_family = m->old_family;
2648         memcpy(&um.old_daddr, &m->old_daddr, sizeof(um.old_daddr));
2649         memcpy(&um.old_saddr, &m->old_saddr, sizeof(um.old_saddr));
2650         um.new_family = m->new_family;
2651         memcpy(&um.new_daddr, &m->new_daddr, sizeof(um.new_daddr));
2652         memcpy(&um.new_saddr, &m->new_saddr, sizeof(um.new_saddr));
2653
2654         return nla_put(skb, XFRMA_MIGRATE, sizeof(um), &um);
2655 }
2656
2657 static int copy_to_user_kmaddress(const struct xfrm_kmaddress *k, struct sk_buff *skb)
2658 {
2659         struct xfrm_user_kmaddress uk;
2660
2661         memset(&uk, 0, sizeof(uk));
2662         uk.family = k->family;
2663         uk.reserved = k->reserved;
2664         memcpy(&uk.local, &k->local, sizeof(uk.local));
2665         memcpy(&uk.remote, &k->remote, sizeof(uk.remote));
2666
2667         return nla_put(skb, XFRMA_KMADDRESS, sizeof(uk), &uk);
2668 }
2669
2670 static inline unsigned int xfrm_migrate_msgsize(int num_migrate, int with_kma,
2671                                                 int with_encp)
2672 {
2673         return NLMSG_ALIGN(sizeof(struct xfrm_userpolicy_id))
2674               + (with_kma ? nla_total_size(sizeof(struct xfrm_kmaddress)) : 0)
2675               + (with_encp ? nla_total_size(sizeof(struct xfrm_encap_tmpl)) : 0)
2676               + nla_total_size(sizeof(struct xfrm_user_migrate) * num_migrate)
2677               + userpolicy_type_attrsize();
2678 }
2679
2680 static int build_migrate(struct sk_buff *skb, const struct xfrm_migrate *m,
2681                          int num_migrate, const struct xfrm_kmaddress *k,
2682                          const struct xfrm_selector *sel,
2683                          const struct xfrm_encap_tmpl *encap, u8 dir, u8 type)
2684 {
2685         const struct xfrm_migrate *mp;
2686         struct xfrm_userpolicy_id *pol_id;
2687         struct nlmsghdr *nlh;
2688         int i, err;
2689
2690         nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_MIGRATE, sizeof(*pol_id), 0);
2691         if (nlh == NULL)
2692                 return -EMSGSIZE;
2693
2694         pol_id = nlmsg_data(nlh);
2695         /* copy data from selector, dir, and type to the pol_id */
2696         memset(pol_id, 0, sizeof(*pol_id));
2697         memcpy(&pol_id->sel, sel, sizeof(pol_id->sel));
2698         pol_id->dir = dir;
2699
2700         if (k != NULL) {
2701                 err = copy_to_user_kmaddress(k, skb);
2702                 if (err)
2703                         goto out_cancel;
2704         }
2705         if (encap) {
2706                 err = nla_put(skb, XFRMA_ENCAP, sizeof(*encap), encap);
2707                 if (err)
2708                         goto out_cancel;
2709         }
2710         err = copy_to_user_policy_type(type, skb);
2711         if (err)
2712                 goto out_cancel;
2713         for (i = 0, mp = m ; i < num_migrate; i++, mp++) {
2714                 err = copy_to_user_migrate(mp, skb);
2715                 if (err)
2716                         goto out_cancel;
2717         }
2718
2719         nlmsg_end(skb, nlh);
2720         return 0;
2721
2722 out_cancel:
2723         nlmsg_cancel(skb, nlh);
2724         return err;
2725 }
2726
2727 static int xfrm_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
2728                              const struct xfrm_migrate *m, int num_migrate,
2729                              const struct xfrm_kmaddress *k,
2730                              const struct xfrm_encap_tmpl *encap)
2731 {
2732         struct net *net = &init_net;
2733         struct sk_buff *skb;
2734         int err;
2735
2736         skb = nlmsg_new(xfrm_migrate_msgsize(num_migrate, !!k, !!encap),
2737                         GFP_ATOMIC);
2738         if (skb == NULL)
2739                 return -ENOMEM;
2740
2741         /* build migrate */
2742         err = build_migrate(skb, m, num_migrate, k, sel, encap, dir, type);
2743         BUG_ON(err < 0);
2744
2745         return xfrm_nlmsg_multicast(net, skb, 0, XFRMNLGRP_MIGRATE);
2746 }
2747 #else
2748 static int xfrm_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
2749                              const struct xfrm_migrate *m, int num_migrate,
2750                              const struct xfrm_kmaddress *k,
2751                              const struct xfrm_encap_tmpl *encap)
2752 {
2753         return -ENOPROTOOPT;
2754 }
2755 #endif
2756
2757 #define XMSGSIZE(type) sizeof(struct type)
2758
2759 const int xfrm_msg_min[XFRM_NR_MSGTYPES] = {
2760         [XFRM_MSG_NEWSA       - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_info),
2761         [XFRM_MSG_DELSA       - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_id),
2762         [XFRM_MSG_GETSA       - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_id),
2763         [XFRM_MSG_NEWPOLICY   - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_info),
2764         [XFRM_MSG_DELPOLICY   - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id),
2765         [XFRM_MSG_GETPOLICY   - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id),
2766         [XFRM_MSG_ALLOCSPI    - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userspi_info),
2767         [XFRM_MSG_ACQUIRE     - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_acquire),
2768         [XFRM_MSG_EXPIRE      - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_expire),
2769         [XFRM_MSG_UPDPOLICY   - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_info),
2770         [XFRM_MSG_UPDSA       - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_info),
2771         [XFRM_MSG_POLEXPIRE   - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_polexpire),
2772         [XFRM_MSG_FLUSHSA     - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_flush),
2773         [XFRM_MSG_FLUSHPOLICY - XFRM_MSG_BASE] = 0,
2774         [XFRM_MSG_NEWAE       - XFRM_MSG_BASE] = XMSGSIZE(xfrm_aevent_id),
2775         [XFRM_MSG_GETAE       - XFRM_MSG_BASE] = XMSGSIZE(xfrm_aevent_id),
2776         [XFRM_MSG_REPORT      - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_report),
2777         [XFRM_MSG_MIGRATE     - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id),
2778         [XFRM_MSG_GETSADINFO  - XFRM_MSG_BASE] = sizeof(u32),
2779         [XFRM_MSG_NEWSPDINFO  - XFRM_MSG_BASE] = sizeof(u32),
2780         [XFRM_MSG_GETSPDINFO  - XFRM_MSG_BASE] = sizeof(u32),
2781         [XFRM_MSG_SETDEFAULT  - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_default),
2782         [XFRM_MSG_GETDEFAULT  - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_default),
2783 };
2784 EXPORT_SYMBOL_GPL(xfrm_msg_min);
2785
2786 #undef XMSGSIZE
2787
2788 const struct nla_policy xfrma_policy[XFRMA_MAX+1] = {
2789         [XFRMA_SA]              = { .len = sizeof(struct xfrm_usersa_info)},
2790         [XFRMA_POLICY]          = { .len = sizeof(struct xfrm_userpolicy_info)},
2791         [XFRMA_LASTUSED]        = { .type = NLA_U64},
2792         [XFRMA_ALG_AUTH_TRUNC]  = { .len = sizeof(struct xfrm_algo_auth)},
2793         [XFRMA_ALG_AEAD]        = { .len = sizeof(struct xfrm_algo_aead) },
2794         [XFRMA_ALG_AUTH]        = { .len = sizeof(struct xfrm_algo) },
2795         [XFRMA_ALG_CRYPT]       = { .len = sizeof(struct xfrm_algo) },
2796         [XFRMA_ALG_COMP]        = { .len = sizeof(struct xfrm_algo) },
2797         [XFRMA_ENCAP]           = { .len = sizeof(struct xfrm_encap_tmpl) },
2798         [XFRMA_TMPL]            = { .len = sizeof(struct xfrm_user_tmpl) },
2799         [XFRMA_SEC_CTX]         = { .len = sizeof(struct xfrm_sec_ctx) },
2800         [XFRMA_LTIME_VAL]       = { .len = sizeof(struct xfrm_lifetime_cur) },
2801         [XFRMA_REPLAY_VAL]      = { .len = sizeof(struct xfrm_replay_state) },
2802         [XFRMA_REPLAY_THRESH]   = { .type = NLA_U32 },
2803         [XFRMA_ETIMER_THRESH]   = { .type = NLA_U32 },
2804         [XFRMA_SRCADDR]         = { .len = sizeof(xfrm_address_t) },
2805         [XFRMA_COADDR]          = { .len = sizeof(xfrm_address_t) },
2806         [XFRMA_POLICY_TYPE]     = { .len = sizeof(struct xfrm_userpolicy_type)},
2807         [XFRMA_MIGRATE]         = { .len = sizeof(struct xfrm_user_migrate) },
2808         [XFRMA_KMADDRESS]       = { .len = sizeof(struct xfrm_user_kmaddress) },
2809         [XFRMA_MARK]            = { .len = sizeof(struct xfrm_mark) },
2810         [XFRMA_TFCPAD]          = { .type = NLA_U32 },
2811         [XFRMA_REPLAY_ESN_VAL]  = { .len = sizeof(struct xfrm_replay_state_esn) },
2812         [XFRMA_SA_EXTRA_FLAGS]  = { .type = NLA_U32 },
2813         [XFRMA_PROTO]           = { .type = NLA_U8 },
2814         [XFRMA_ADDRESS_FILTER]  = { .len = sizeof(struct xfrm_address_filter) },
2815         [XFRMA_OFFLOAD_DEV]     = { .len = sizeof(struct xfrm_user_offload) },
2816         [XFRMA_SET_MARK]        = { .type = NLA_U32 },
2817         [XFRMA_SET_MARK_MASK]   = { .type = NLA_U32 },
2818         [XFRMA_IF_ID]           = { .type = NLA_U32 },
2819 };
2820 EXPORT_SYMBOL_GPL(xfrma_policy);
2821
2822 static const struct nla_policy xfrma_spd_policy[XFRMA_SPD_MAX+1] = {
2823         [XFRMA_SPD_IPV4_HTHRESH] = { .len = sizeof(struct xfrmu_spdhthresh) },
2824         [XFRMA_SPD_IPV6_HTHRESH] = { .len = sizeof(struct xfrmu_spdhthresh) },
2825 };
2826
2827 static const struct xfrm_link {
2828         int (*doit)(struct sk_buff *, struct nlmsghdr *, struct nlattr **);
2829         int (*start)(struct netlink_callback *);
2830         int (*dump)(struct sk_buff *, struct netlink_callback *);
2831         int (*done)(struct netlink_callback *);
2832         const struct nla_policy *nla_pol;
2833         int nla_max;
2834 } xfrm_dispatch[XFRM_NR_MSGTYPES] = {
2835         [XFRM_MSG_NEWSA       - XFRM_MSG_BASE] = { .doit = xfrm_add_sa        },
2836         [XFRM_MSG_DELSA       - XFRM_MSG_BASE] = { .doit = xfrm_del_sa        },
2837         [XFRM_MSG_GETSA       - XFRM_MSG_BASE] = { .doit = xfrm_get_sa,
2838                                                    .dump = xfrm_dump_sa,
2839                                                    .done = xfrm_dump_sa_done  },
2840         [XFRM_MSG_NEWPOLICY   - XFRM_MSG_BASE] = { .doit = xfrm_add_policy    },
2841         [XFRM_MSG_DELPOLICY   - XFRM_MSG_BASE] = { .doit = xfrm_get_policy    },
2842         [XFRM_MSG_GETPOLICY   - XFRM_MSG_BASE] = { .doit = xfrm_get_policy,
2843                                                    .start = xfrm_dump_policy_start,
2844                                                    .dump = xfrm_dump_policy,
2845                                                    .done = xfrm_dump_policy_done },
2846         [XFRM_MSG_ALLOCSPI    - XFRM_MSG_BASE] = { .doit = xfrm_alloc_userspi },
2847         [XFRM_MSG_ACQUIRE     - XFRM_MSG_BASE] = { .doit = xfrm_add_acquire   },
2848         [XFRM_MSG_EXPIRE      - XFRM_MSG_BASE] = { .doit = xfrm_add_sa_expire },
2849         [XFRM_MSG_UPDPOLICY   - XFRM_MSG_BASE] = { .doit = xfrm_add_policy    },
2850         [XFRM_MSG_UPDSA       - XFRM_MSG_BASE] = { .doit = xfrm_add_sa        },
2851         [XFRM_MSG_POLEXPIRE   - XFRM_MSG_BASE] = { .doit = xfrm_add_pol_expire},
2852         [XFRM_MSG_FLUSHSA     - XFRM_MSG_BASE] = { .doit = xfrm_flush_sa      },
2853         [XFRM_MSG_FLUSHPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_flush_policy  },
2854         [XFRM_MSG_NEWAE       - XFRM_MSG_BASE] = { .doit = xfrm_new_ae  },
2855         [XFRM_MSG_GETAE       - XFRM_MSG_BASE] = { .doit = xfrm_get_ae  },
2856         [XFRM_MSG_MIGRATE     - XFRM_MSG_BASE] = { .doit = xfrm_do_migrate    },
2857         [XFRM_MSG_GETSADINFO  - XFRM_MSG_BASE] = { .doit = xfrm_get_sadinfo   },
2858         [XFRM_MSG_NEWSPDINFO  - XFRM_MSG_BASE] = { .doit = xfrm_set_spdinfo,
2859                                                    .nla_pol = xfrma_spd_policy,
2860                                                    .nla_max = XFRMA_SPD_MAX },
2861         [XFRM_MSG_GETSPDINFO  - XFRM_MSG_BASE] = { .doit = xfrm_get_spdinfo   },
2862         [XFRM_MSG_SETDEFAULT  - XFRM_MSG_BASE] = { .doit = xfrm_set_default   },
2863         [XFRM_MSG_GETDEFAULT  - XFRM_MSG_BASE] = { .doit = xfrm_get_default   },
2864 };
2865
2866 static int xfrm_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh,
2867                              struct netlink_ext_ack *extack)
2868 {
2869         struct net *net = sock_net(skb->sk);
2870         struct nlattr *attrs[XFRMA_MAX+1];
2871         const struct xfrm_link *link;
2872         struct nlmsghdr *nlh64 = NULL;
2873         int type, err;
2874
2875         type = nlh->nlmsg_type;
2876         if (type > XFRM_MSG_MAX)
2877                 return -EINVAL;
2878
2879         type -= XFRM_MSG_BASE;
2880         link = &xfrm_dispatch[type];
2881
2882         /* All operations require privileges, even GET */
2883         if (!netlink_net_capable(skb, CAP_NET_ADMIN))
2884                 return -EPERM;
2885
2886         if (in_compat_syscall()) {
2887                 struct xfrm_translator *xtr = xfrm_get_translator();
2888
2889                 if (!xtr)
2890                         return -EOPNOTSUPP;
2891
2892                 nlh64 = xtr->rcv_msg_compat(nlh, link->nla_max,
2893                                             link->nla_pol, extack);
2894                 xfrm_put_translator(xtr);
2895                 if (IS_ERR(nlh64))
2896                         return PTR_ERR(nlh64);
2897                 if (nlh64)
2898                         nlh = nlh64;
2899         }
2900
2901         if ((type == (XFRM_MSG_GETSA - XFRM_MSG_BASE) ||
2902              type == (XFRM_MSG_GETPOLICY - XFRM_MSG_BASE)) &&
2903             (nlh->nlmsg_flags & NLM_F_DUMP)) {
2904                 struct netlink_dump_control c = {
2905                         .start = link->start,
2906                         .dump = link->dump,
2907                         .done = link->done,
2908                 };
2909
2910                 if (link->dump == NULL) {
2911                         err = -EINVAL;
2912                         goto err;
2913                 }
2914
2915                 err = netlink_dump_start(net->xfrm.nlsk, skb, nlh, &c);
2916                 goto err;
2917         }
2918
2919         err = nlmsg_parse_deprecated(nlh, xfrm_msg_min[type], attrs,
2920                                      link->nla_max ? : XFRMA_MAX,
2921                                      link->nla_pol ? : xfrma_policy, extack);
2922         if (err < 0)
2923                 goto err;
2924
2925         if (link->doit == NULL) {
2926                 err = -EINVAL;
2927                 goto err;
2928         }
2929
2930         err = link->doit(skb, nlh, attrs);
2931
2932         /* We need to free skb allocated in xfrm_alloc_compat() before
2933          * returning from this function, because consume_skb() won't take
2934          * care of frag_list since netlink destructor sets
2935          * sbk->head to NULL. (see netlink_skb_destructor())
2936          */
2937         if (skb_has_frag_list(skb)) {
2938                 kfree_skb(skb_shinfo(skb)->frag_list);
2939                 skb_shinfo(skb)->frag_list = NULL;
2940         }
2941
2942 err:
2943         kvfree(nlh64);
2944         return err;
2945 }
2946
2947 static void xfrm_netlink_rcv(struct sk_buff *skb)
2948 {
2949         struct net *net = sock_net(skb->sk);
2950
2951         mutex_lock(&net->xfrm.xfrm_cfg_mutex);
2952         netlink_rcv_skb(skb, &xfrm_user_rcv_msg);
2953         mutex_unlock(&net->xfrm.xfrm_cfg_mutex);
2954 }
2955
2956 static inline unsigned int xfrm_expire_msgsize(void)
2957 {
2958         return NLMSG_ALIGN(sizeof(struct xfrm_user_expire))
2959                + nla_total_size(sizeof(struct xfrm_mark));
2960 }
2961
2962 static int build_expire(struct sk_buff *skb, struct xfrm_state *x, const struct km_event *c)
2963 {
2964         struct xfrm_user_expire *ue;
2965         struct nlmsghdr *nlh;
2966         int err;
2967
2968         nlh = nlmsg_put(skb, c->portid, 0, XFRM_MSG_EXPIRE, sizeof(*ue), 0);
2969         if (nlh == NULL)
2970                 return -EMSGSIZE;
2971
2972         ue = nlmsg_data(nlh);
2973         copy_to_user_state(x, &ue->state);
2974         ue->hard = (c->data.hard != 0) ? 1 : 0;
2975         /* clear the padding bytes */
2976         memset_after(ue, 0, hard);
2977
2978         err = xfrm_mark_put(skb, &x->mark);
2979         if (err)
2980                 return err;
2981
2982         err = xfrm_if_id_put(skb, x->if_id);
2983         if (err)
2984                 return err;
2985
2986         nlmsg_end(skb, nlh);
2987         return 0;
2988 }
2989
2990 static int xfrm_exp_state_notify(struct xfrm_state *x, const struct km_event *c)
2991 {
2992         struct net *net = xs_net(x);
2993         struct sk_buff *skb;
2994
2995         skb = nlmsg_new(xfrm_expire_msgsize(), GFP_ATOMIC);
2996         if (skb == NULL)
2997                 return -ENOMEM;
2998
2999         if (build_expire(skb, x, c) < 0) {
3000                 kfree_skb(skb);
3001                 return -EMSGSIZE;
3002         }
3003
3004         return xfrm_nlmsg_multicast(net, skb, 0, XFRMNLGRP_EXPIRE);
3005 }
3006
3007 static int xfrm_aevent_state_notify(struct xfrm_state *x, const struct km_event *c)
3008 {
3009         struct net *net = xs_net(x);
3010         struct sk_buff *skb;
3011         int err;
3012
3013         skb = nlmsg_new(xfrm_aevent_msgsize(x), GFP_ATOMIC);
3014         if (skb == NULL)
3015                 return -ENOMEM;
3016
3017         err = build_aevent(skb, x, c);
3018         BUG_ON(err < 0);
3019
3020         return xfrm_nlmsg_multicast(net, skb, 0, XFRMNLGRP_AEVENTS);
3021 }
3022
3023 static int xfrm_notify_sa_flush(const struct km_event *c)
3024 {
3025         struct net *net = c->net;
3026         struct xfrm_usersa_flush *p;
3027         struct nlmsghdr *nlh;
3028         struct sk_buff *skb;
3029         int len = NLMSG_ALIGN(sizeof(struct xfrm_usersa_flush));
3030
3031         skb = nlmsg_new(len, GFP_ATOMIC);
3032         if (skb == NULL)
3033                 return -ENOMEM;
3034
3035         nlh = nlmsg_put(skb, c->portid, c->seq, XFRM_MSG_FLUSHSA, sizeof(*p), 0);
3036         if (nlh == NULL) {
3037                 kfree_skb(skb);
3038                 return -EMSGSIZE;
3039         }
3040
3041         p = nlmsg_data(nlh);
3042         p->proto = c->data.proto;
3043
3044         nlmsg_end(skb, nlh);
3045
3046         return xfrm_nlmsg_multicast(net, skb, 0, XFRMNLGRP_SA);
3047 }
3048
3049 static inline unsigned int xfrm_sa_len(struct xfrm_state *x)
3050 {
3051         unsigned int l = 0;
3052         if (x->aead)
3053                 l += nla_total_size(aead_len(x->aead));
3054         if (x->aalg) {
3055                 l += nla_total_size(sizeof(struct xfrm_algo) +
3056                                     (x->aalg->alg_key_len + 7) / 8);
3057                 l += nla_total_size(xfrm_alg_auth_len(x->aalg));
3058         }
3059         if (x->ealg)
3060                 l += nla_total_size(xfrm_alg_len(x->ealg));
3061         if (x->calg)
3062                 l += nla_total_size(sizeof(*x->calg));
3063         if (x->encap)
3064                 l += nla_total_size(sizeof(*x->encap));
3065         if (x->tfcpad)
3066                 l += nla_total_size(sizeof(x->tfcpad));
3067         if (x->replay_esn)
3068                 l += nla_total_size(xfrm_replay_state_esn_len(x->replay_esn));
3069         else
3070                 l += nla_total_size(sizeof(struct xfrm_replay_state));
3071         if (x->security)
3072                 l += nla_total_size(sizeof(struct xfrm_user_sec_ctx) +
3073                                     x->security->ctx_len);
3074         if (x->coaddr)
3075                 l += nla_total_size(sizeof(*x->coaddr));
3076         if (x->props.extra_flags)
3077                 l += nla_total_size(sizeof(x->props.extra_flags));
3078         if (x->xso.dev)
3079                  l += nla_total_size(sizeof(struct xfrm_user_offload));
3080         if (x->props.smark.v | x->props.smark.m) {
3081                 l += nla_total_size(sizeof(x->props.smark.v));
3082                 l += nla_total_size(sizeof(x->props.smark.m));
3083         }
3084         if (x->if_id)
3085                 l += nla_total_size(sizeof(x->if_id));
3086
3087         /* Must count x->lastused as it may become non-zero behind our back. */
3088         l += nla_total_size_64bit(sizeof(u64));
3089
3090         if (x->mapping_maxage)
3091                 l += nla_total_size(sizeof(x->mapping_maxage));
3092
3093         return l;
3094 }
3095
3096 static int xfrm_notify_sa(struct xfrm_state *x, const struct km_event *c)
3097 {
3098         struct net *net = xs_net(x);
3099         struct xfrm_usersa_info *p;
3100         struct xfrm_usersa_id *id;
3101         struct nlmsghdr *nlh;
3102         struct sk_buff *skb;
3103         unsigned int len = xfrm_sa_len(x);
3104         unsigned int headlen;
3105         int err;
3106
3107         headlen = sizeof(*p);
3108         if (c->event == XFRM_MSG_DELSA) {
3109                 len += nla_total_size(headlen);
3110                 headlen = sizeof(*id);
3111                 len += nla_total_size(sizeof(struct xfrm_mark));
3112         }
3113         len += NLMSG_ALIGN(headlen);
3114
3115         skb = nlmsg_new(len, GFP_ATOMIC);
3116         if (skb == NULL)
3117                 return -ENOMEM;
3118
3119         nlh = nlmsg_put(skb, c->portid, c->seq, c->event, headlen, 0);
3120         err = -EMSGSIZE;
3121         if (nlh == NULL)
3122                 goto out_free_skb;
3123
3124         p = nlmsg_data(nlh);
3125         if (c->event == XFRM_MSG_DELSA) {
3126                 struct nlattr *attr;
3127
3128                 id = nlmsg_data(nlh);
3129                 memset(id, 0, sizeof(*id));
3130                 memcpy(&id->daddr, &x->id.daddr, sizeof(id->daddr));
3131                 id->spi = x->id.spi;
3132                 id->family = x->props.family;
3133                 id->proto = x->id.proto;
3134
3135                 attr = nla_reserve(skb, XFRMA_SA, sizeof(*p));
3136                 err = -EMSGSIZE;
3137                 if (attr == NULL)
3138                         goto out_free_skb;
3139
3140                 p = nla_data(attr);
3141         }
3142         err = copy_to_user_state_extra(x, p, skb);
3143         if (err)
3144                 goto out_free_skb;
3145
3146         nlmsg_end(skb, nlh);
3147
3148         return xfrm_nlmsg_multicast(net, skb, 0, XFRMNLGRP_SA);
3149
3150 out_free_skb:
3151         kfree_skb(skb);
3152         return err;
3153 }
3154
3155 static int xfrm_send_state_notify(struct xfrm_state *x, const struct km_event *c)
3156 {
3157
3158         switch (c->event) {
3159         case XFRM_MSG_EXPIRE:
3160                 return xfrm_exp_state_notify(x, c);
3161         case XFRM_MSG_NEWAE:
3162                 return xfrm_aevent_state_notify(x, c);
3163         case XFRM_MSG_DELSA:
3164         case XFRM_MSG_UPDSA:
3165         case XFRM_MSG_NEWSA:
3166                 return xfrm_notify_sa(x, c);
3167         case XFRM_MSG_FLUSHSA:
3168                 return xfrm_notify_sa_flush(c);
3169         default:
3170                 printk(KERN_NOTICE "xfrm_user: Unknown SA event %d\n",
3171                        c->event);
3172                 break;
3173         }
3174
3175         return 0;
3176
3177 }
3178
3179 static inline unsigned int xfrm_acquire_msgsize(struct xfrm_state *x,
3180                                                 struct xfrm_policy *xp)
3181 {
3182         return NLMSG_ALIGN(sizeof(struct xfrm_user_acquire))
3183                + nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr)
3184                + nla_total_size(sizeof(struct xfrm_mark))
3185                + nla_total_size(xfrm_user_sec_ctx_size(x->security))
3186                + userpolicy_type_attrsize();
3187 }
3188
3189 static int build_acquire(struct sk_buff *skb, struct xfrm_state *x,
3190                          struct xfrm_tmpl *xt, struct xfrm_policy *xp)
3191 {
3192         __u32 seq = xfrm_get_acqseq();
3193         struct xfrm_user_acquire *ua;
3194         struct nlmsghdr *nlh;
3195         int err;
3196
3197         nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_ACQUIRE, sizeof(*ua), 0);
3198         if (nlh == NULL)
3199                 return -EMSGSIZE;
3200
3201         ua = nlmsg_data(nlh);
3202         memcpy(&ua->id, &x->id, sizeof(ua->id));
3203         memcpy(&ua->saddr, &x->props.saddr, sizeof(ua->saddr));
3204         memcpy(&ua->sel, &x->sel, sizeof(ua->sel));
3205         copy_to_user_policy(xp, &ua->policy, XFRM_POLICY_OUT);
3206         ua->aalgos = xt->aalgos;
3207         ua->ealgos = xt->ealgos;
3208         ua->calgos = xt->calgos;
3209         ua->seq = x->km.seq = seq;
3210
3211         err = copy_to_user_tmpl(xp, skb);
3212         if (!err)
3213                 err = copy_to_user_state_sec_ctx(x, skb);
3214         if (!err)
3215                 err = copy_to_user_policy_type(xp->type, skb);
3216         if (!err)
3217                 err = xfrm_mark_put(skb, &xp->mark);
3218         if (!err)
3219                 err = xfrm_if_id_put(skb, xp->if_id);
3220         if (err) {
3221                 nlmsg_cancel(skb, nlh);
3222                 return err;
3223         }
3224
3225         nlmsg_end(skb, nlh);
3226         return 0;
3227 }
3228
3229 static int xfrm_send_acquire(struct xfrm_state *x, struct xfrm_tmpl *xt,
3230                              struct xfrm_policy *xp)
3231 {
3232         struct net *net = xs_net(x);
3233         struct sk_buff *skb;
3234         int err;
3235
3236         skb = nlmsg_new(xfrm_acquire_msgsize(x, xp), GFP_ATOMIC);
3237         if (skb == NULL)
3238                 return -ENOMEM;
3239
3240         err = build_acquire(skb, x, xt, xp);
3241         BUG_ON(err < 0);
3242
3243         return xfrm_nlmsg_multicast(net, skb, 0, XFRMNLGRP_ACQUIRE);
3244 }
3245
3246 /* User gives us xfrm_user_policy_info followed by an array of 0
3247  * or more templates.
3248  */
3249 static struct xfrm_policy *xfrm_compile_policy(struct sock *sk, int opt,
3250                                                u8 *data, int len, int *dir)
3251 {
3252         struct net *net = sock_net(sk);
3253         struct xfrm_userpolicy_info *p = (struct xfrm_userpolicy_info *)data;
3254         struct xfrm_user_tmpl *ut = (struct xfrm_user_tmpl *) (p + 1);
3255         struct xfrm_policy *xp;
3256         int nr;
3257
3258         switch (sk->sk_family) {
3259         case AF_INET:
3260                 if (opt != IP_XFRM_POLICY) {
3261                         *dir = -EOPNOTSUPP;
3262                         return NULL;
3263                 }
3264                 break;
3265 #if IS_ENABLED(CONFIG_IPV6)
3266         case AF_INET6:
3267                 if (opt != IPV6_XFRM_POLICY) {
3268                         *dir = -EOPNOTSUPP;
3269                         return NULL;
3270                 }
3271                 break;
3272 #endif
3273         default:
3274                 *dir = -EINVAL;
3275                 return NULL;
3276         }
3277
3278         *dir = -EINVAL;
3279
3280         if (len < sizeof(*p) ||
3281             verify_newpolicy_info(p))
3282                 return NULL;
3283
3284         nr = ((len - sizeof(*p)) / sizeof(*ut));
3285         if (validate_tmpl(nr, ut, p->sel.family))
3286                 return NULL;
3287
3288         if (p->dir > XFRM_POLICY_OUT)
3289                 return NULL;
3290
3291         xp = xfrm_policy_alloc(net, GFP_ATOMIC);
3292         if (xp == NULL) {
3293                 *dir = -ENOBUFS;
3294                 return NULL;
3295         }
3296
3297         copy_from_user_policy(xp, p);
3298         xp->type = XFRM_POLICY_TYPE_MAIN;
3299         copy_templates(xp, ut, nr);
3300
3301         *dir = p->dir;
3302
3303         return xp;
3304 }
3305
3306 static inline unsigned int xfrm_polexpire_msgsize(struct xfrm_policy *xp)
3307 {
3308         return NLMSG_ALIGN(sizeof(struct xfrm_user_polexpire))
3309                + nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr)
3310                + nla_total_size(xfrm_user_sec_ctx_size(xp->security))
3311                + nla_total_size(sizeof(struct xfrm_mark))
3312                + userpolicy_type_attrsize();
3313 }
3314
3315 static int build_polexpire(struct sk_buff *skb, struct xfrm_policy *xp,
3316                            int dir, const struct km_event *c)
3317 {
3318         struct xfrm_user_polexpire *upe;
3319         int hard = c->data.hard;
3320         struct nlmsghdr *nlh;
3321         int err;
3322
3323         nlh = nlmsg_put(skb, c->portid, 0, XFRM_MSG_POLEXPIRE, sizeof(*upe), 0);
3324         if (nlh == NULL)
3325                 return -EMSGSIZE;
3326
3327         upe = nlmsg_data(nlh);
3328         copy_to_user_policy(xp, &upe->pol, dir);
3329         err = copy_to_user_tmpl(xp, skb);
3330         if (!err)
3331                 err = copy_to_user_sec_ctx(xp, skb);
3332         if (!err)
3333                 err = copy_to_user_policy_type(xp->type, skb);
3334         if (!err)
3335                 err = xfrm_mark_put(skb, &xp->mark);
3336         if (!err)
3337                 err = xfrm_if_id_put(skb, xp->if_id);
3338         if (err) {
3339                 nlmsg_cancel(skb, nlh);
3340                 return err;
3341         }
3342         upe->hard = !!hard;
3343
3344         nlmsg_end(skb, nlh);
3345         return 0;
3346 }
3347
3348 static int xfrm_exp_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c)
3349 {
3350         struct net *net = xp_net(xp);
3351         struct sk_buff *skb;
3352         int err;
3353
3354         skb = nlmsg_new(xfrm_polexpire_msgsize(xp), GFP_ATOMIC);
3355         if (skb == NULL)
3356                 return -ENOMEM;
3357
3358         err = build_polexpire(skb, xp, dir, c);
3359         BUG_ON(err < 0);
3360
3361         return xfrm_nlmsg_multicast(net, skb, 0, XFRMNLGRP_EXPIRE);
3362 }
3363
3364 static int xfrm_notify_policy(struct xfrm_policy *xp, int dir, const struct km_event *c)
3365 {
3366         unsigned int len = nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr);
3367         struct net *net = xp_net(xp);
3368         struct xfrm_userpolicy_info *p;
3369         struct xfrm_userpolicy_id *id;
3370         struct nlmsghdr *nlh;
3371         struct sk_buff *skb;
3372         unsigned int headlen;
3373         int err;
3374
3375         headlen = sizeof(*p);
3376         if (c->event == XFRM_MSG_DELPOLICY) {
3377                 len += nla_total_size(headlen);
3378                 headlen = sizeof(*id);
3379         }
3380         len += userpolicy_type_attrsize();
3381         len += nla_total_size(sizeof(struct xfrm_mark));
3382         len += NLMSG_ALIGN(headlen);
3383
3384         skb = nlmsg_new(len, GFP_ATOMIC);
3385         if (skb == NULL)
3386                 return -ENOMEM;
3387
3388         nlh = nlmsg_put(skb, c->portid, c->seq, c->event, headlen, 0);
3389         err = -EMSGSIZE;
3390         if (nlh == NULL)
3391                 goto out_free_skb;
3392
3393         p = nlmsg_data(nlh);
3394         if (c->event == XFRM_MSG_DELPOLICY) {
3395                 struct nlattr *attr;
3396
3397                 id = nlmsg_data(nlh);
3398                 memset(id, 0, sizeof(*id));
3399                 id->dir = dir;
3400                 if (c->data.byid)
3401                         id->index = xp->index;
3402                 else
3403                         memcpy(&id->sel, &xp->selector, sizeof(id->sel));
3404
3405                 attr = nla_reserve(skb, XFRMA_POLICY, sizeof(*p));
3406                 err = -EMSGSIZE;
3407                 if (attr == NULL)
3408                         goto out_free_skb;
3409
3410                 p = nla_data(attr);
3411         }
3412
3413         copy_to_user_policy(xp, p, dir);
3414         err = copy_to_user_tmpl(xp, skb);
3415         if (!err)
3416                 err = copy_to_user_policy_type(xp->type, skb);
3417         if (!err)
3418                 err = xfrm_mark_put(skb, &xp->mark);
3419         if (!err)
3420                 err = xfrm_if_id_put(skb, xp->if_id);
3421         if (err)
3422                 goto out_free_skb;
3423
3424         nlmsg_end(skb, nlh);
3425
3426         return xfrm_nlmsg_multicast(net, skb, 0, XFRMNLGRP_POLICY);
3427
3428 out_free_skb:
3429         kfree_skb(skb);
3430         return err;
3431 }
3432
3433 static int xfrm_notify_policy_flush(const struct km_event *c)
3434 {
3435         struct net *net = c->net;
3436         struct nlmsghdr *nlh;
3437         struct sk_buff *skb;
3438         int err;
3439
3440         skb = nlmsg_new(userpolicy_type_attrsize(), GFP_ATOMIC);
3441         if (skb == NULL)
3442                 return -ENOMEM;
3443
3444         nlh = nlmsg_put(skb, c->portid, c->seq, XFRM_MSG_FLUSHPOLICY, 0, 0);
3445         err = -EMSGSIZE;
3446         if (nlh == NULL)
3447                 goto out_free_skb;
3448         err = copy_to_user_policy_type(c->data.type, skb);
3449         if (err)
3450                 goto out_free_skb;
3451
3452         nlmsg_end(skb, nlh);
3453
3454         return xfrm_nlmsg_multicast(net, skb, 0, XFRMNLGRP_POLICY);
3455
3456 out_free_skb:
3457         kfree_skb(skb);
3458         return err;
3459 }
3460
3461 static int xfrm_send_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c)
3462 {
3463
3464         switch (c->event) {
3465         case XFRM_MSG_NEWPOLICY:
3466         case XFRM_MSG_UPDPOLICY:
3467         case XFRM_MSG_DELPOLICY:
3468                 return xfrm_notify_policy(xp, dir, c);
3469         case XFRM_MSG_FLUSHPOLICY:
3470                 return xfrm_notify_policy_flush(c);
3471         case XFRM_MSG_POLEXPIRE:
3472                 return xfrm_exp_policy_notify(xp, dir, c);
3473         default:
3474                 printk(KERN_NOTICE "xfrm_user: Unknown Policy event %d\n",
3475                        c->event);
3476         }
3477
3478         return 0;
3479
3480 }
3481
3482 static inline unsigned int xfrm_report_msgsize(void)
3483 {
3484         return NLMSG_ALIGN(sizeof(struct xfrm_user_report));
3485 }
3486
3487 static int build_report(struct sk_buff *skb, u8 proto,
3488                         struct xfrm_selector *sel, xfrm_address_t *addr)
3489 {
3490         struct xfrm_user_report *ur;
3491         struct nlmsghdr *nlh;
3492
3493         nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_REPORT, sizeof(*ur), 0);
3494         if (nlh == NULL)
3495                 return -EMSGSIZE;
3496
3497         ur = nlmsg_data(nlh);
3498         ur->proto = proto;
3499         memcpy(&ur->sel, sel, sizeof(ur->sel));
3500
3501         if (addr) {
3502                 int err = nla_put(skb, XFRMA_COADDR, sizeof(*addr), addr);
3503                 if (err) {
3504                         nlmsg_cancel(skb, nlh);
3505                         return err;
3506                 }
3507         }
3508         nlmsg_end(skb, nlh);
3509         return 0;
3510 }
3511
3512 static int xfrm_send_report(struct net *net, u8 proto,
3513                             struct xfrm_selector *sel, xfrm_address_t *addr)
3514 {
3515         struct sk_buff *skb;
3516         int err;
3517
3518         skb = nlmsg_new(xfrm_report_msgsize(), GFP_ATOMIC);
3519         if (skb == NULL)
3520                 return -ENOMEM;
3521
3522         err = build_report(skb, proto, sel, addr);
3523         BUG_ON(err < 0);
3524
3525         return xfrm_nlmsg_multicast(net, skb, 0, XFRMNLGRP_REPORT);
3526 }
3527
3528 static inline unsigned int xfrm_mapping_msgsize(void)
3529 {
3530         return NLMSG_ALIGN(sizeof(struct xfrm_user_mapping));
3531 }
3532
3533 static int build_mapping(struct sk_buff *skb, struct xfrm_state *x,
3534                          xfrm_address_t *new_saddr, __be16 new_sport)
3535 {
3536         struct xfrm_user_mapping *um;
3537         struct nlmsghdr *nlh;
3538
3539         nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_MAPPING, sizeof(*um), 0);
3540         if (nlh == NULL)
3541                 return -EMSGSIZE;
3542
3543         um = nlmsg_data(nlh);
3544
3545         memcpy(&um->id.daddr, &x->id.daddr, sizeof(um->id.daddr));
3546         um->id.spi = x->id.spi;
3547         um->id.family = x->props.family;
3548         um->id.proto = x->id.proto;
3549         memcpy(&um->new_saddr, new_saddr, sizeof(um->new_saddr));
3550         memcpy(&um->old_saddr, &x->props.saddr, sizeof(um->old_saddr));
3551         um->new_sport = new_sport;
3552         um->old_sport = x->encap->encap_sport;
3553         um->reqid = x->props.reqid;
3554
3555         nlmsg_end(skb, nlh);
3556         return 0;
3557 }
3558
3559 static int xfrm_send_mapping(struct xfrm_state *x, xfrm_address_t *ipaddr,
3560                              __be16 sport)
3561 {
3562         struct net *net = xs_net(x);
3563         struct sk_buff *skb;
3564         int err;
3565
3566         if (x->id.proto != IPPROTO_ESP)
3567                 return -EINVAL;
3568
3569         if (!x->encap)
3570                 return -EINVAL;
3571
3572         skb = nlmsg_new(xfrm_mapping_msgsize(), GFP_ATOMIC);
3573         if (skb == NULL)
3574                 return -ENOMEM;
3575
3576         err = build_mapping(skb, x, ipaddr, sport);
3577         BUG_ON(err < 0);
3578
3579         return xfrm_nlmsg_multicast(net, skb, 0, XFRMNLGRP_MAPPING);
3580 }
3581
3582 static bool xfrm_is_alive(const struct km_event *c)
3583 {
3584         return (bool)xfrm_acquire_is_on(c->net);
3585 }
3586
3587 static struct xfrm_mgr netlink_mgr = {
3588         .notify         = xfrm_send_state_notify,
3589         .acquire        = xfrm_send_acquire,
3590         .compile_policy = xfrm_compile_policy,
3591         .notify_policy  = xfrm_send_policy_notify,
3592         .report         = xfrm_send_report,
3593         .migrate        = xfrm_send_migrate,
3594         .new_mapping    = xfrm_send_mapping,
3595         .is_alive       = xfrm_is_alive,
3596 };
3597
3598 static int __net_init xfrm_user_net_init(struct net *net)
3599 {
3600         struct sock *nlsk;
3601         struct netlink_kernel_cfg cfg = {
3602                 .groups = XFRMNLGRP_MAX,
3603                 .input  = xfrm_netlink_rcv,
3604         };
3605
3606         nlsk = netlink_kernel_create(net, NETLINK_XFRM, &cfg);
3607         if (nlsk == NULL)
3608                 return -ENOMEM;
3609         net->xfrm.nlsk_stash = nlsk; /* Don't set to NULL */
3610         rcu_assign_pointer(net->xfrm.nlsk, nlsk);
3611         return 0;
3612 }
3613
3614 static void __net_exit xfrm_user_net_pre_exit(struct net *net)
3615 {
3616         RCU_INIT_POINTER(net->xfrm.nlsk, NULL);
3617 }
3618
3619 static void __net_exit xfrm_user_net_exit(struct list_head *net_exit_list)
3620 {
3621         struct net *net;
3622
3623         list_for_each_entry(net, net_exit_list, exit_list)
3624                 netlink_kernel_release(net->xfrm.nlsk_stash);
3625 }
3626
3627 static struct pernet_operations xfrm_user_net_ops = {
3628         .init       = xfrm_user_net_init,
3629         .pre_exit   = xfrm_user_net_pre_exit,
3630         .exit_batch = xfrm_user_net_exit,
3631 };
3632
3633 static int __init xfrm_user_init(void)
3634 {
3635         int rv;
3636
3637         printk(KERN_INFO "Initializing XFRM netlink socket\n");
3638
3639         rv = register_pernet_subsys(&xfrm_user_net_ops);
3640         if (rv < 0)
3641                 return rv;
3642         rv = xfrm_register_km(&netlink_mgr);
3643         if (rv < 0)
3644                 unregister_pernet_subsys(&xfrm_user_net_ops);
3645         return rv;
3646 }
3647
3648 static void __exit xfrm_user_exit(void)
3649 {
3650         xfrm_unregister_km(&netlink_mgr);
3651         unregister_pernet_subsys(&xfrm_user_net_ops);
3652 }
3653
3654 module_init(xfrm_user_init);
3655 module_exit(xfrm_user_exit);
3656 MODULE_LICENSE("GPL");
3657 MODULE_ALIAS_NET_PF_PROTO(PF_NETLINK, NETLINK_XFRM);