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