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