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