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