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