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