Correct .gbs.conf settings
[platform/adaptation/renesas_rcar/renesas_kernel.git] / net / key / af_key.c
1 /*
2  * net/key/af_key.c     An implementation of PF_KEYv2 sockets.
3  *
4  *              This program is free software; you can redistribute it and/or
5  *              modify it under the terms of the GNU General Public License
6  *              as published by the Free Software Foundation; either version
7  *              2 of the License, or (at your option) any later version.
8  *
9  * Authors:     Maxim Giryaev   <gem@asplinux.ru>
10  *              David S. Miller <davem@redhat.com>
11  *              Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
12  *              Kunihiro Ishiguro <kunihiro@ipinfusion.com>
13  *              Kazunori MIYAZAWA / USAGI Project <miyazawa@linux-ipv6.org>
14  *              Derek Atkins <derek@ihtfp.com>
15  */
16
17 #include <linux/capability.h>
18 #include <linux/module.h>
19 #include <linux/kernel.h>
20 #include <linux/socket.h>
21 #include <linux/pfkeyv2.h>
22 #include <linux/ipsec.h>
23 #include <linux/skbuff.h>
24 #include <linux/rtnetlink.h>
25 #include <linux/in.h>
26 #include <linux/in6.h>
27 #include <linux/proc_fs.h>
28 #include <linux/init.h>
29 #include <linux/slab.h>
30 #include <net/net_namespace.h>
31 #include <net/netns/generic.h>
32 #include <net/xfrm.h>
33
34 #include <net/sock.h>
35
36 #define _X2KEY(x) ((x) == XFRM_INF ? 0 : (x))
37 #define _KEY2X(x) ((x) == 0 ? XFRM_INF : (x))
38
39 static int pfkey_net_id __read_mostly;
40 struct netns_pfkey {
41         /* List of all pfkey sockets. */
42         struct hlist_head table;
43         atomic_t socks_nr;
44 };
45 static DEFINE_MUTEX(pfkey_mutex);
46
47 #define DUMMY_MARK 0
48 static const struct xfrm_mark dummy_mark = {0, 0};
49 struct pfkey_sock {
50         /* struct sock must be the first member of struct pfkey_sock */
51         struct sock     sk;
52         int             registered;
53         int             promisc;
54
55         struct {
56                 uint8_t         msg_version;
57                 uint32_t        msg_portid;
58                 int             (*dump)(struct pfkey_sock *sk);
59                 void            (*done)(struct pfkey_sock *sk);
60                 union {
61                         struct xfrm_policy_walk policy;
62                         struct xfrm_state_walk  state;
63                 } u;
64                 struct sk_buff  *skb;
65         } dump;
66 };
67
68 static inline struct pfkey_sock *pfkey_sk(struct sock *sk)
69 {
70         return (struct pfkey_sock *)sk;
71 }
72
73 static int pfkey_can_dump(const struct sock *sk)
74 {
75         if (3 * atomic_read(&sk->sk_rmem_alloc) <= 2 * sk->sk_rcvbuf)
76                 return 1;
77         return 0;
78 }
79
80 static void pfkey_terminate_dump(struct pfkey_sock *pfk)
81 {
82         if (pfk->dump.dump) {
83                 if (pfk->dump.skb) {
84                         kfree_skb(pfk->dump.skb);
85                         pfk->dump.skb = NULL;
86                 }
87                 pfk->dump.done(pfk);
88                 pfk->dump.dump = NULL;
89                 pfk->dump.done = NULL;
90         }
91 }
92
93 static void pfkey_sock_destruct(struct sock *sk)
94 {
95         struct net *net = sock_net(sk);
96         struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id);
97
98         pfkey_terminate_dump(pfkey_sk(sk));
99         skb_queue_purge(&sk->sk_receive_queue);
100
101         if (!sock_flag(sk, SOCK_DEAD)) {
102                 pr_err("Attempt to release alive pfkey socket: %p\n", sk);
103                 return;
104         }
105
106         WARN_ON(atomic_read(&sk->sk_rmem_alloc));
107         WARN_ON(atomic_read(&sk->sk_wmem_alloc));
108
109         atomic_dec(&net_pfkey->socks_nr);
110 }
111
112 static const struct proto_ops pfkey_ops;
113
114 static void pfkey_insert(struct sock *sk)
115 {
116         struct net *net = sock_net(sk);
117         struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id);
118
119         mutex_lock(&pfkey_mutex);
120         sk_add_node_rcu(sk, &net_pfkey->table);
121         mutex_unlock(&pfkey_mutex);
122 }
123
124 static void pfkey_remove(struct sock *sk)
125 {
126         mutex_lock(&pfkey_mutex);
127         sk_del_node_init_rcu(sk);
128         mutex_unlock(&pfkey_mutex);
129 }
130
131 static struct proto key_proto = {
132         .name     = "KEY",
133         .owner    = THIS_MODULE,
134         .obj_size = sizeof(struct pfkey_sock),
135 };
136
137 static int pfkey_create(struct net *net, struct socket *sock, int protocol,
138                         int kern)
139 {
140         struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id);
141         struct sock *sk;
142         int err;
143
144         if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
145                 return -EPERM;
146         if (sock->type != SOCK_RAW)
147                 return -ESOCKTNOSUPPORT;
148         if (protocol != PF_KEY_V2)
149                 return -EPROTONOSUPPORT;
150
151         err = -ENOMEM;
152         sk = sk_alloc(net, PF_KEY, GFP_KERNEL, &key_proto);
153         if (sk == NULL)
154                 goto out;
155
156         sock->ops = &pfkey_ops;
157         sock_init_data(sock, sk);
158
159         sk->sk_family = PF_KEY;
160         sk->sk_destruct = pfkey_sock_destruct;
161
162         atomic_inc(&net_pfkey->socks_nr);
163
164         pfkey_insert(sk);
165
166         return 0;
167 out:
168         return err;
169 }
170
171 static int pfkey_release(struct socket *sock)
172 {
173         struct sock *sk = sock->sk;
174
175         if (!sk)
176                 return 0;
177
178         pfkey_remove(sk);
179
180         sock_orphan(sk);
181         sock->sk = NULL;
182         skb_queue_purge(&sk->sk_write_queue);
183
184         synchronize_rcu();
185         sock_put(sk);
186
187         return 0;
188 }
189
190 static int pfkey_broadcast_one(struct sk_buff *skb, struct sk_buff **skb2,
191                                gfp_t allocation, struct sock *sk)
192 {
193         int err = -ENOBUFS;
194
195         sock_hold(sk);
196         if (*skb2 == NULL) {
197                 if (atomic_read(&skb->users) != 1) {
198                         *skb2 = skb_clone(skb, allocation);
199                 } else {
200                         *skb2 = skb;
201                         atomic_inc(&skb->users);
202                 }
203         }
204         if (*skb2 != NULL) {
205                 if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) {
206                         skb_set_owner_r(*skb2, sk);
207                         skb_queue_tail(&sk->sk_receive_queue, *skb2);
208                         sk->sk_data_ready(sk, (*skb2)->len);
209                         *skb2 = NULL;
210                         err = 0;
211                 }
212         }
213         sock_put(sk);
214         return err;
215 }
216
217 /* Send SKB to all pfkey sockets matching selected criteria.  */
218 #define BROADCAST_ALL           0
219 #define BROADCAST_ONE           1
220 #define BROADCAST_REGISTERED    2
221 #define BROADCAST_PROMISC_ONLY  4
222 static int pfkey_broadcast(struct sk_buff *skb, gfp_t allocation,
223                            int broadcast_flags, struct sock *one_sk,
224                            struct net *net)
225 {
226         struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id);
227         struct sock *sk;
228         struct sk_buff *skb2 = NULL;
229         int err = -ESRCH;
230
231         /* XXX Do we need something like netlink_overrun?  I think
232          * XXX PF_KEY socket apps will not mind current behavior.
233          */
234         if (!skb)
235                 return -ENOMEM;
236
237         rcu_read_lock();
238         sk_for_each_rcu(sk, &net_pfkey->table) {
239                 struct pfkey_sock *pfk = pfkey_sk(sk);
240                 int err2;
241
242                 /* Yes, it means that if you are meant to receive this
243                  * pfkey message you receive it twice as promiscuous
244                  * socket.
245                  */
246                 if (pfk->promisc)
247                         pfkey_broadcast_one(skb, &skb2, allocation, sk);
248
249                 /* the exact target will be processed later */
250                 if (sk == one_sk)
251                         continue;
252                 if (broadcast_flags != BROADCAST_ALL) {
253                         if (broadcast_flags & BROADCAST_PROMISC_ONLY)
254                                 continue;
255                         if ((broadcast_flags & BROADCAST_REGISTERED) &&
256                             !pfk->registered)
257                                 continue;
258                         if (broadcast_flags & BROADCAST_ONE)
259                                 continue;
260                 }
261
262                 err2 = pfkey_broadcast_one(skb, &skb2, allocation, sk);
263
264                 /* Error is cleare after succecful sending to at least one
265                  * registered KM */
266                 if ((broadcast_flags & BROADCAST_REGISTERED) && err)
267                         err = err2;
268         }
269         rcu_read_unlock();
270
271         if (one_sk != NULL)
272                 err = pfkey_broadcast_one(skb, &skb2, allocation, one_sk);
273
274         kfree_skb(skb2);
275         kfree_skb(skb);
276         return err;
277 }
278
279 static int pfkey_do_dump(struct pfkey_sock *pfk)
280 {
281         struct sadb_msg *hdr;
282         int rc;
283
284         rc = pfk->dump.dump(pfk);
285         if (rc == -ENOBUFS)
286                 return 0;
287
288         if (pfk->dump.skb) {
289                 if (!pfkey_can_dump(&pfk->sk))
290                         return 0;
291
292                 hdr = (struct sadb_msg *) pfk->dump.skb->data;
293                 hdr->sadb_msg_seq = 0;
294                 hdr->sadb_msg_errno = rc;
295                 pfkey_broadcast(pfk->dump.skb, GFP_ATOMIC, BROADCAST_ONE,
296                                 &pfk->sk, sock_net(&pfk->sk));
297                 pfk->dump.skb = NULL;
298         }
299
300         pfkey_terminate_dump(pfk);
301         return rc;
302 }
303
304 static inline void pfkey_hdr_dup(struct sadb_msg *new,
305                                  const struct sadb_msg *orig)
306 {
307         *new = *orig;
308 }
309
310 static int pfkey_error(const struct sadb_msg *orig, int err, struct sock *sk)
311 {
312         struct sk_buff *skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_KERNEL);
313         struct sadb_msg *hdr;
314
315         if (!skb)
316                 return -ENOBUFS;
317
318         /* Woe be to the platform trying to support PFKEY yet
319          * having normal errnos outside the 1-255 range, inclusive.
320          */
321         err = -err;
322         if (err == ERESTARTSYS ||
323             err == ERESTARTNOHAND ||
324             err == ERESTARTNOINTR)
325                 err = EINTR;
326         if (err >= 512)
327                 err = EINVAL;
328         BUG_ON(err <= 0 || err >= 256);
329
330         hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
331         pfkey_hdr_dup(hdr, orig);
332         hdr->sadb_msg_errno = (uint8_t) err;
333         hdr->sadb_msg_len = (sizeof(struct sadb_msg) /
334                              sizeof(uint64_t));
335
336         pfkey_broadcast(skb, GFP_KERNEL, BROADCAST_ONE, sk, sock_net(sk));
337
338         return 0;
339 }
340
341 static const u8 sadb_ext_min_len[] = {
342         [SADB_EXT_RESERVED]             = (u8) 0,
343         [SADB_EXT_SA]                   = (u8) sizeof(struct sadb_sa),
344         [SADB_EXT_LIFETIME_CURRENT]     = (u8) sizeof(struct sadb_lifetime),
345         [SADB_EXT_LIFETIME_HARD]        = (u8) sizeof(struct sadb_lifetime),
346         [SADB_EXT_LIFETIME_SOFT]        = (u8) sizeof(struct sadb_lifetime),
347         [SADB_EXT_ADDRESS_SRC]          = (u8) sizeof(struct sadb_address),
348         [SADB_EXT_ADDRESS_DST]          = (u8) sizeof(struct sadb_address),
349         [SADB_EXT_ADDRESS_PROXY]        = (u8) sizeof(struct sadb_address),
350         [SADB_EXT_KEY_AUTH]             = (u8) sizeof(struct sadb_key),
351         [SADB_EXT_KEY_ENCRYPT]          = (u8) sizeof(struct sadb_key),
352         [SADB_EXT_IDENTITY_SRC]         = (u8) sizeof(struct sadb_ident),
353         [SADB_EXT_IDENTITY_DST]         = (u8) sizeof(struct sadb_ident),
354         [SADB_EXT_SENSITIVITY]          = (u8) sizeof(struct sadb_sens),
355         [SADB_EXT_PROPOSAL]             = (u8) sizeof(struct sadb_prop),
356         [SADB_EXT_SUPPORTED_AUTH]       = (u8) sizeof(struct sadb_supported),
357         [SADB_EXT_SUPPORTED_ENCRYPT]    = (u8) sizeof(struct sadb_supported),
358         [SADB_EXT_SPIRANGE]             = (u8) sizeof(struct sadb_spirange),
359         [SADB_X_EXT_KMPRIVATE]          = (u8) sizeof(struct sadb_x_kmprivate),
360         [SADB_X_EXT_POLICY]             = (u8) sizeof(struct sadb_x_policy),
361         [SADB_X_EXT_SA2]                = (u8) sizeof(struct sadb_x_sa2),
362         [SADB_X_EXT_NAT_T_TYPE]         = (u8) sizeof(struct sadb_x_nat_t_type),
363         [SADB_X_EXT_NAT_T_SPORT]        = (u8) sizeof(struct sadb_x_nat_t_port),
364         [SADB_X_EXT_NAT_T_DPORT]        = (u8) sizeof(struct sadb_x_nat_t_port),
365         [SADB_X_EXT_NAT_T_OA]           = (u8) sizeof(struct sadb_address),
366         [SADB_X_EXT_SEC_CTX]            = (u8) sizeof(struct sadb_x_sec_ctx),
367         [SADB_X_EXT_KMADDRESS]          = (u8) sizeof(struct sadb_x_kmaddress),
368 };
369
370 /* Verify sadb_address_{len,prefixlen} against sa_family.  */
371 static int verify_address_len(const void *p)
372 {
373         const struct sadb_address *sp = p;
374         const struct sockaddr *addr = (const struct sockaddr *)(sp + 1);
375         const struct sockaddr_in *sin;
376 #if IS_ENABLED(CONFIG_IPV6)
377         const struct sockaddr_in6 *sin6;
378 #endif
379         int len;
380
381         switch (addr->sa_family) {
382         case AF_INET:
383                 len = DIV_ROUND_UP(sizeof(*sp) + sizeof(*sin), sizeof(uint64_t));
384                 if (sp->sadb_address_len != len ||
385                     sp->sadb_address_prefixlen > 32)
386                         return -EINVAL;
387                 break;
388 #if IS_ENABLED(CONFIG_IPV6)
389         case AF_INET6:
390                 len = DIV_ROUND_UP(sizeof(*sp) + sizeof(*sin6), sizeof(uint64_t));
391                 if (sp->sadb_address_len != len ||
392                     sp->sadb_address_prefixlen > 128)
393                         return -EINVAL;
394                 break;
395 #endif
396         default:
397                 /* It is user using kernel to keep track of security
398                  * associations for another protocol, such as
399                  * OSPF/RSVP/RIPV2/MIP.  It is user's job to verify
400                  * lengths.
401                  *
402                  * XXX Actually, association/policy database is not yet
403                  * XXX able to cope with arbitrary sockaddr families.
404                  * XXX When it can, remove this -EINVAL.  -DaveM
405                  */
406                 return -EINVAL;
407                 break;
408         }
409
410         return 0;
411 }
412
413 static inline int pfkey_sec_ctx_len(const struct sadb_x_sec_ctx *sec_ctx)
414 {
415         return DIV_ROUND_UP(sizeof(struct sadb_x_sec_ctx) +
416                             sec_ctx->sadb_x_ctx_len,
417                             sizeof(uint64_t));
418 }
419
420 static inline int verify_sec_ctx_len(const void *p)
421 {
422         const struct sadb_x_sec_ctx *sec_ctx = p;
423         int len = sec_ctx->sadb_x_ctx_len;
424
425         if (len > PAGE_SIZE)
426                 return -EINVAL;
427
428         len = pfkey_sec_ctx_len(sec_ctx);
429
430         if (sec_ctx->sadb_x_sec_len != len)
431                 return -EINVAL;
432
433         return 0;
434 }
435
436 static inline struct xfrm_user_sec_ctx *pfkey_sadb2xfrm_user_sec_ctx(const struct sadb_x_sec_ctx *sec_ctx,
437                                                                      gfp_t gfp)
438 {
439         struct xfrm_user_sec_ctx *uctx = NULL;
440         int ctx_size = sec_ctx->sadb_x_ctx_len;
441
442         uctx = kmalloc((sizeof(*uctx)+ctx_size), gfp);
443
444         if (!uctx)
445                 return NULL;
446
447         uctx->len = pfkey_sec_ctx_len(sec_ctx);
448         uctx->exttype = sec_ctx->sadb_x_sec_exttype;
449         uctx->ctx_doi = sec_ctx->sadb_x_ctx_doi;
450         uctx->ctx_alg = sec_ctx->sadb_x_ctx_alg;
451         uctx->ctx_len = sec_ctx->sadb_x_ctx_len;
452         memcpy(uctx + 1, sec_ctx + 1,
453                uctx->ctx_len);
454
455         return uctx;
456 }
457
458 static int present_and_same_family(const struct sadb_address *src,
459                                    const struct sadb_address *dst)
460 {
461         const struct sockaddr *s_addr, *d_addr;
462
463         if (!src || !dst)
464                 return 0;
465
466         s_addr = (const struct sockaddr *)(src + 1);
467         d_addr = (const struct sockaddr *)(dst + 1);
468         if (s_addr->sa_family != d_addr->sa_family)
469                 return 0;
470         if (s_addr->sa_family != AF_INET
471 #if IS_ENABLED(CONFIG_IPV6)
472             && s_addr->sa_family != AF_INET6
473 #endif
474                 )
475                 return 0;
476
477         return 1;
478 }
479
480 static int parse_exthdrs(struct sk_buff *skb, const struct sadb_msg *hdr, void **ext_hdrs)
481 {
482         const char *p = (char *) hdr;
483         int len = skb->len;
484
485         len -= sizeof(*hdr);
486         p += sizeof(*hdr);
487         while (len > 0) {
488                 const struct sadb_ext *ehdr = (const struct sadb_ext *) p;
489                 uint16_t ext_type;
490                 int ext_len;
491
492                 ext_len  = ehdr->sadb_ext_len;
493                 ext_len *= sizeof(uint64_t);
494                 ext_type = ehdr->sadb_ext_type;
495                 if (ext_len < sizeof(uint64_t) ||
496                     ext_len > len ||
497                     ext_type == SADB_EXT_RESERVED)
498                         return -EINVAL;
499
500                 if (ext_type <= SADB_EXT_MAX) {
501                         int min = (int) sadb_ext_min_len[ext_type];
502                         if (ext_len < min)
503                                 return -EINVAL;
504                         if (ext_hdrs[ext_type-1] != NULL)
505                                 return -EINVAL;
506                         if (ext_type == SADB_EXT_ADDRESS_SRC ||
507                             ext_type == SADB_EXT_ADDRESS_DST ||
508                             ext_type == SADB_EXT_ADDRESS_PROXY ||
509                             ext_type == SADB_X_EXT_NAT_T_OA) {
510                                 if (verify_address_len(p))
511                                         return -EINVAL;
512                         }
513                         if (ext_type == SADB_X_EXT_SEC_CTX) {
514                                 if (verify_sec_ctx_len(p))
515                                         return -EINVAL;
516                         }
517                         ext_hdrs[ext_type-1] = (void *) p;
518                 }
519                 p   += ext_len;
520                 len -= ext_len;
521         }
522
523         return 0;
524 }
525
526 static uint16_t
527 pfkey_satype2proto(uint8_t satype)
528 {
529         switch (satype) {
530         case SADB_SATYPE_UNSPEC:
531                 return IPSEC_PROTO_ANY;
532         case SADB_SATYPE_AH:
533                 return IPPROTO_AH;
534         case SADB_SATYPE_ESP:
535                 return IPPROTO_ESP;
536         case SADB_X_SATYPE_IPCOMP:
537                 return IPPROTO_COMP;
538                 break;
539         default:
540                 return 0;
541         }
542         /* NOTREACHED */
543 }
544
545 static uint8_t
546 pfkey_proto2satype(uint16_t proto)
547 {
548         switch (proto) {
549         case IPPROTO_AH:
550                 return SADB_SATYPE_AH;
551         case IPPROTO_ESP:
552                 return SADB_SATYPE_ESP;
553         case IPPROTO_COMP:
554                 return SADB_X_SATYPE_IPCOMP;
555                 break;
556         default:
557                 return 0;
558         }
559         /* NOTREACHED */
560 }
561
562 /* BTW, this scheme means that there is no way with PFKEY2 sockets to
563  * say specifically 'just raw sockets' as we encode them as 255.
564  */
565
566 static uint8_t pfkey_proto_to_xfrm(uint8_t proto)
567 {
568         return proto == IPSEC_PROTO_ANY ? 0 : proto;
569 }
570
571 static uint8_t pfkey_proto_from_xfrm(uint8_t proto)
572 {
573         return proto ? proto : IPSEC_PROTO_ANY;
574 }
575
576 static inline int pfkey_sockaddr_len(sa_family_t family)
577 {
578         switch (family) {
579         case AF_INET:
580                 return sizeof(struct sockaddr_in);
581 #if IS_ENABLED(CONFIG_IPV6)
582         case AF_INET6:
583                 return sizeof(struct sockaddr_in6);
584 #endif
585         }
586         return 0;
587 }
588
589 static
590 int pfkey_sockaddr_extract(const struct sockaddr *sa, xfrm_address_t *xaddr)
591 {
592         switch (sa->sa_family) {
593         case AF_INET:
594                 xaddr->a4 =
595                         ((struct sockaddr_in *)sa)->sin_addr.s_addr;
596                 return AF_INET;
597 #if IS_ENABLED(CONFIG_IPV6)
598         case AF_INET6:
599                 memcpy(xaddr->a6,
600                        &((struct sockaddr_in6 *)sa)->sin6_addr,
601                        sizeof(struct in6_addr));
602                 return AF_INET6;
603 #endif
604         }
605         return 0;
606 }
607
608 static
609 int pfkey_sadb_addr2xfrm_addr(const struct sadb_address *addr, xfrm_address_t *xaddr)
610 {
611         return pfkey_sockaddr_extract((struct sockaddr *)(addr + 1),
612                                       xaddr);
613 }
614
615 static struct  xfrm_state *pfkey_xfrm_state_lookup(struct net *net, const struct sadb_msg *hdr, void * const *ext_hdrs)
616 {
617         const struct sadb_sa *sa;
618         const struct sadb_address *addr;
619         uint16_t proto;
620         unsigned short family;
621         xfrm_address_t *xaddr;
622
623         sa = ext_hdrs[SADB_EXT_SA - 1];
624         if (sa == NULL)
625                 return NULL;
626
627         proto = pfkey_satype2proto(hdr->sadb_msg_satype);
628         if (proto == 0)
629                 return NULL;
630
631         /* sadb_address_len should be checked by caller */
632         addr = ext_hdrs[SADB_EXT_ADDRESS_DST - 1];
633         if (addr == NULL)
634                 return NULL;
635
636         family = ((const struct sockaddr *)(addr + 1))->sa_family;
637         switch (family) {
638         case AF_INET:
639                 xaddr = (xfrm_address_t *)&((const struct sockaddr_in *)(addr + 1))->sin_addr;
640                 break;
641 #if IS_ENABLED(CONFIG_IPV6)
642         case AF_INET6:
643                 xaddr = (xfrm_address_t *)&((const struct sockaddr_in6 *)(addr + 1))->sin6_addr;
644                 break;
645 #endif
646         default:
647                 xaddr = NULL;
648         }
649
650         if (!xaddr)
651                 return NULL;
652
653         return xfrm_state_lookup(net, DUMMY_MARK, xaddr, sa->sadb_sa_spi, proto, family);
654 }
655
656 #define PFKEY_ALIGN8(a) (1 + (((a) - 1) | (8 - 1)))
657
658 static int
659 pfkey_sockaddr_size(sa_family_t family)
660 {
661         return PFKEY_ALIGN8(pfkey_sockaddr_len(family));
662 }
663
664 static inline int pfkey_mode_from_xfrm(int mode)
665 {
666         switch(mode) {
667         case XFRM_MODE_TRANSPORT:
668                 return IPSEC_MODE_TRANSPORT;
669         case XFRM_MODE_TUNNEL:
670                 return IPSEC_MODE_TUNNEL;
671         case XFRM_MODE_BEET:
672                 return IPSEC_MODE_BEET;
673         default:
674                 return -1;
675         }
676 }
677
678 static inline int pfkey_mode_to_xfrm(int mode)
679 {
680         switch(mode) {
681         case IPSEC_MODE_ANY:    /*XXX*/
682         case IPSEC_MODE_TRANSPORT:
683                 return XFRM_MODE_TRANSPORT;
684         case IPSEC_MODE_TUNNEL:
685                 return XFRM_MODE_TUNNEL;
686         case IPSEC_MODE_BEET:
687                 return XFRM_MODE_BEET;
688         default:
689                 return -1;
690         }
691 }
692
693 static unsigned int pfkey_sockaddr_fill(const xfrm_address_t *xaddr, __be16 port,
694                                         struct sockaddr *sa,
695                                         unsigned short family)
696 {
697         switch (family) {
698         case AF_INET:
699             {
700                 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
701                 sin->sin_family = AF_INET;
702                 sin->sin_port = port;
703                 sin->sin_addr.s_addr = xaddr->a4;
704                 memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
705                 return 32;
706             }
707 #if IS_ENABLED(CONFIG_IPV6)
708         case AF_INET6:
709             {
710                 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
711                 sin6->sin6_family = AF_INET6;
712                 sin6->sin6_port = port;
713                 sin6->sin6_flowinfo = 0;
714                 sin6->sin6_addr = *(struct in6_addr *)xaddr->a6;
715                 sin6->sin6_scope_id = 0;
716                 return 128;
717             }
718 #endif
719         }
720         return 0;
721 }
722
723 static struct sk_buff *__pfkey_xfrm_state2msg(const struct xfrm_state *x,
724                                               int add_keys, int hsc)
725 {
726         struct sk_buff *skb;
727         struct sadb_msg *hdr;
728         struct sadb_sa *sa;
729         struct sadb_lifetime *lifetime;
730         struct sadb_address *addr;
731         struct sadb_key *key;
732         struct sadb_x_sa2 *sa2;
733         struct sadb_x_sec_ctx *sec_ctx;
734         struct xfrm_sec_ctx *xfrm_ctx;
735         int ctx_size = 0;
736         int size;
737         int auth_key_size = 0;
738         int encrypt_key_size = 0;
739         int sockaddr_size;
740         struct xfrm_encap_tmpl *natt = NULL;
741         int mode;
742
743         /* address family check */
744         sockaddr_size = pfkey_sockaddr_size(x->props.family);
745         if (!sockaddr_size)
746                 return ERR_PTR(-EINVAL);
747
748         /* base, SA, (lifetime (HSC),) address(SD), (address(P),)
749            key(AE), (identity(SD),) (sensitivity)> */
750         size = sizeof(struct sadb_msg) +sizeof(struct sadb_sa) +
751                 sizeof(struct sadb_lifetime) +
752                 ((hsc & 1) ? sizeof(struct sadb_lifetime) : 0) +
753                 ((hsc & 2) ? sizeof(struct sadb_lifetime) : 0) +
754                         sizeof(struct sadb_address)*2 +
755                                 sockaddr_size*2 +
756                                         sizeof(struct sadb_x_sa2);
757
758         if ((xfrm_ctx = x->security)) {
759                 ctx_size = PFKEY_ALIGN8(xfrm_ctx->ctx_len);
760                 size += sizeof(struct sadb_x_sec_ctx) + ctx_size;
761         }
762
763         /* identity & sensitivity */
764         if (!xfrm_addr_equal(&x->sel.saddr, &x->props.saddr, x->props.family))
765                 size += sizeof(struct sadb_address) + sockaddr_size;
766
767         if (add_keys) {
768                 if (x->aalg && x->aalg->alg_key_len) {
769                         auth_key_size =
770                                 PFKEY_ALIGN8((x->aalg->alg_key_len + 7) / 8);
771                         size += sizeof(struct sadb_key) + auth_key_size;
772                 }
773                 if (x->ealg && x->ealg->alg_key_len) {
774                         encrypt_key_size =
775                                 PFKEY_ALIGN8((x->ealg->alg_key_len+7) / 8);
776                         size += sizeof(struct sadb_key) + encrypt_key_size;
777                 }
778         }
779         if (x->encap)
780                 natt = x->encap;
781
782         if (natt && natt->encap_type) {
783                 size += sizeof(struct sadb_x_nat_t_type);
784                 size += sizeof(struct sadb_x_nat_t_port);
785                 size += sizeof(struct sadb_x_nat_t_port);
786         }
787
788         skb =  alloc_skb(size + 16, GFP_ATOMIC);
789         if (skb == NULL)
790                 return ERR_PTR(-ENOBUFS);
791
792         /* call should fill header later */
793         hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
794         memset(hdr, 0, size);   /* XXX do we need this ? */
795         hdr->sadb_msg_len = size / sizeof(uint64_t);
796
797         /* sa */
798         sa = (struct sadb_sa *)  skb_put(skb, sizeof(struct sadb_sa));
799         sa->sadb_sa_len = sizeof(struct sadb_sa)/sizeof(uint64_t);
800         sa->sadb_sa_exttype = SADB_EXT_SA;
801         sa->sadb_sa_spi = x->id.spi;
802         sa->sadb_sa_replay = x->props.replay_window;
803         switch (x->km.state) {
804         case XFRM_STATE_VALID:
805                 sa->sadb_sa_state = x->km.dying ?
806                         SADB_SASTATE_DYING : SADB_SASTATE_MATURE;
807                 break;
808         case XFRM_STATE_ACQ:
809                 sa->sadb_sa_state = SADB_SASTATE_LARVAL;
810                 break;
811         default:
812                 sa->sadb_sa_state = SADB_SASTATE_DEAD;
813                 break;
814         }
815         sa->sadb_sa_auth = 0;
816         if (x->aalg) {
817                 struct xfrm_algo_desc *a = xfrm_aalg_get_byname(x->aalg->alg_name, 0);
818                 sa->sadb_sa_auth = (a && a->pfkey_supported) ?
819                                         a->desc.sadb_alg_id : 0;
820         }
821         sa->sadb_sa_encrypt = 0;
822         BUG_ON(x->ealg && x->calg);
823         if (x->ealg) {
824                 struct xfrm_algo_desc *a = xfrm_ealg_get_byname(x->ealg->alg_name, 0);
825                 sa->sadb_sa_encrypt = (a && a->pfkey_supported) ?
826                                         a->desc.sadb_alg_id : 0;
827         }
828         /* KAME compatible: sadb_sa_encrypt is overloaded with calg id */
829         if (x->calg) {
830                 struct xfrm_algo_desc *a = xfrm_calg_get_byname(x->calg->alg_name, 0);
831                 sa->sadb_sa_encrypt = (a && a->pfkey_supported) ?
832                                         a->desc.sadb_alg_id : 0;
833         }
834
835         sa->sadb_sa_flags = 0;
836         if (x->props.flags & XFRM_STATE_NOECN)
837                 sa->sadb_sa_flags |= SADB_SAFLAGS_NOECN;
838         if (x->props.flags & XFRM_STATE_DECAP_DSCP)
839                 sa->sadb_sa_flags |= SADB_SAFLAGS_DECAP_DSCP;
840         if (x->props.flags & XFRM_STATE_NOPMTUDISC)
841                 sa->sadb_sa_flags |= SADB_SAFLAGS_NOPMTUDISC;
842
843         /* hard time */
844         if (hsc & 2) {
845                 lifetime = (struct sadb_lifetime *)  skb_put(skb,
846                                                              sizeof(struct sadb_lifetime));
847                 lifetime->sadb_lifetime_len =
848                         sizeof(struct sadb_lifetime)/sizeof(uint64_t);
849                 lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
850                 lifetime->sadb_lifetime_allocations =  _X2KEY(x->lft.hard_packet_limit);
851                 lifetime->sadb_lifetime_bytes = _X2KEY(x->lft.hard_byte_limit);
852                 lifetime->sadb_lifetime_addtime = x->lft.hard_add_expires_seconds;
853                 lifetime->sadb_lifetime_usetime = x->lft.hard_use_expires_seconds;
854         }
855         /* soft time */
856         if (hsc & 1) {
857                 lifetime = (struct sadb_lifetime *)  skb_put(skb,
858                                                              sizeof(struct sadb_lifetime));
859                 lifetime->sadb_lifetime_len =
860                         sizeof(struct sadb_lifetime)/sizeof(uint64_t);
861                 lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
862                 lifetime->sadb_lifetime_allocations =  _X2KEY(x->lft.soft_packet_limit);
863                 lifetime->sadb_lifetime_bytes = _X2KEY(x->lft.soft_byte_limit);
864                 lifetime->sadb_lifetime_addtime = x->lft.soft_add_expires_seconds;
865                 lifetime->sadb_lifetime_usetime = x->lft.soft_use_expires_seconds;
866         }
867         /* current time */
868         lifetime = (struct sadb_lifetime *)  skb_put(skb,
869                                                      sizeof(struct sadb_lifetime));
870         lifetime->sadb_lifetime_len =
871                 sizeof(struct sadb_lifetime)/sizeof(uint64_t);
872         lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
873         lifetime->sadb_lifetime_allocations = x->curlft.packets;
874         lifetime->sadb_lifetime_bytes = x->curlft.bytes;
875         lifetime->sadb_lifetime_addtime = x->curlft.add_time;
876         lifetime->sadb_lifetime_usetime = x->curlft.use_time;
877         /* src address */
878         addr = (struct sadb_address*) skb_put(skb,
879                                               sizeof(struct sadb_address)+sockaddr_size);
880         addr->sadb_address_len =
881                 (sizeof(struct sadb_address)+sockaddr_size)/
882                         sizeof(uint64_t);
883         addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
884         /* "if the ports are non-zero, then the sadb_address_proto field,
885            normally zero, MUST be filled in with the transport
886            protocol's number." - RFC2367 */
887         addr->sadb_address_proto = 0;
888         addr->sadb_address_reserved = 0;
889
890         addr->sadb_address_prefixlen =
891                 pfkey_sockaddr_fill(&x->props.saddr, 0,
892                                     (struct sockaddr *) (addr + 1),
893                                     x->props.family);
894         if (!addr->sadb_address_prefixlen)
895                 BUG();
896
897         /* dst address */
898         addr = (struct sadb_address*) skb_put(skb,
899                                               sizeof(struct sadb_address)+sockaddr_size);
900         addr->sadb_address_len =
901                 (sizeof(struct sadb_address)+sockaddr_size)/
902                         sizeof(uint64_t);
903         addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
904         addr->sadb_address_proto = 0;
905         addr->sadb_address_reserved = 0;
906
907         addr->sadb_address_prefixlen =
908                 pfkey_sockaddr_fill(&x->id.daddr, 0,
909                                     (struct sockaddr *) (addr + 1),
910                                     x->props.family);
911         if (!addr->sadb_address_prefixlen)
912                 BUG();
913
914         if (!xfrm_addr_equal(&x->sel.saddr, &x->props.saddr,
915                              x->props.family)) {
916                 addr = (struct sadb_address*) skb_put(skb,
917                         sizeof(struct sadb_address)+sockaddr_size);
918                 addr->sadb_address_len =
919                         (sizeof(struct sadb_address)+sockaddr_size)/
920                         sizeof(uint64_t);
921                 addr->sadb_address_exttype = SADB_EXT_ADDRESS_PROXY;
922                 addr->sadb_address_proto =
923                         pfkey_proto_from_xfrm(x->sel.proto);
924                 addr->sadb_address_prefixlen = x->sel.prefixlen_s;
925                 addr->sadb_address_reserved = 0;
926
927                 pfkey_sockaddr_fill(&x->sel.saddr, x->sel.sport,
928                                     (struct sockaddr *) (addr + 1),
929                                     x->props.family);
930         }
931
932         /* auth key */
933         if (add_keys && auth_key_size) {
934                 key = (struct sadb_key *) skb_put(skb,
935                                                   sizeof(struct sadb_key)+auth_key_size);
936                 key->sadb_key_len = (sizeof(struct sadb_key) + auth_key_size) /
937                         sizeof(uint64_t);
938                 key->sadb_key_exttype = SADB_EXT_KEY_AUTH;
939                 key->sadb_key_bits = x->aalg->alg_key_len;
940                 key->sadb_key_reserved = 0;
941                 memcpy(key + 1, x->aalg->alg_key, (x->aalg->alg_key_len+7)/8);
942         }
943         /* encrypt key */
944         if (add_keys && encrypt_key_size) {
945                 key = (struct sadb_key *) skb_put(skb,
946                                                   sizeof(struct sadb_key)+encrypt_key_size);
947                 key->sadb_key_len = (sizeof(struct sadb_key) +
948                                      encrypt_key_size) / sizeof(uint64_t);
949                 key->sadb_key_exttype = SADB_EXT_KEY_ENCRYPT;
950                 key->sadb_key_bits = x->ealg->alg_key_len;
951                 key->sadb_key_reserved = 0;
952                 memcpy(key + 1, x->ealg->alg_key,
953                        (x->ealg->alg_key_len+7)/8);
954         }
955
956         /* sa */
957         sa2 = (struct sadb_x_sa2 *)  skb_put(skb, sizeof(struct sadb_x_sa2));
958         sa2->sadb_x_sa2_len = sizeof(struct sadb_x_sa2)/sizeof(uint64_t);
959         sa2->sadb_x_sa2_exttype = SADB_X_EXT_SA2;
960         if ((mode = pfkey_mode_from_xfrm(x->props.mode)) < 0) {
961                 kfree_skb(skb);
962                 return ERR_PTR(-EINVAL);
963         }
964         sa2->sadb_x_sa2_mode = mode;
965         sa2->sadb_x_sa2_reserved1 = 0;
966         sa2->sadb_x_sa2_reserved2 = 0;
967         sa2->sadb_x_sa2_sequence = 0;
968         sa2->sadb_x_sa2_reqid = x->props.reqid;
969
970         if (natt && natt->encap_type) {
971                 struct sadb_x_nat_t_type *n_type;
972                 struct sadb_x_nat_t_port *n_port;
973
974                 /* type */
975                 n_type = (struct sadb_x_nat_t_type*) skb_put(skb, sizeof(*n_type));
976                 n_type->sadb_x_nat_t_type_len = sizeof(*n_type)/sizeof(uint64_t);
977                 n_type->sadb_x_nat_t_type_exttype = SADB_X_EXT_NAT_T_TYPE;
978                 n_type->sadb_x_nat_t_type_type = natt->encap_type;
979                 n_type->sadb_x_nat_t_type_reserved[0] = 0;
980                 n_type->sadb_x_nat_t_type_reserved[1] = 0;
981                 n_type->sadb_x_nat_t_type_reserved[2] = 0;
982
983                 /* source port */
984                 n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port));
985                 n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t);
986                 n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_SPORT;
987                 n_port->sadb_x_nat_t_port_port = natt->encap_sport;
988                 n_port->sadb_x_nat_t_port_reserved = 0;
989
990                 /* dest port */
991                 n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port));
992                 n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t);
993                 n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_DPORT;
994                 n_port->sadb_x_nat_t_port_port = natt->encap_dport;
995                 n_port->sadb_x_nat_t_port_reserved = 0;
996         }
997
998         /* security context */
999         if (xfrm_ctx) {
1000                 sec_ctx = (struct sadb_x_sec_ctx *) skb_put(skb,
1001                                 sizeof(struct sadb_x_sec_ctx) + ctx_size);
1002                 sec_ctx->sadb_x_sec_len =
1003                   (sizeof(struct sadb_x_sec_ctx) + ctx_size) / sizeof(uint64_t);
1004                 sec_ctx->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX;
1005                 sec_ctx->sadb_x_ctx_doi = xfrm_ctx->ctx_doi;
1006                 sec_ctx->sadb_x_ctx_alg = xfrm_ctx->ctx_alg;
1007                 sec_ctx->sadb_x_ctx_len = xfrm_ctx->ctx_len;
1008                 memcpy(sec_ctx + 1, xfrm_ctx->ctx_str,
1009                        xfrm_ctx->ctx_len);
1010         }
1011
1012         return skb;
1013 }
1014
1015
1016 static inline struct sk_buff *pfkey_xfrm_state2msg(const struct xfrm_state *x)
1017 {
1018         struct sk_buff *skb;
1019
1020         skb = __pfkey_xfrm_state2msg(x, 1, 3);
1021
1022         return skb;
1023 }
1024
1025 static inline struct sk_buff *pfkey_xfrm_state2msg_expire(const struct xfrm_state *x,
1026                                                           int hsc)
1027 {
1028         return __pfkey_xfrm_state2msg(x, 0, hsc);
1029 }
1030
1031 static struct xfrm_state * pfkey_msg2xfrm_state(struct net *net,
1032                                                 const struct sadb_msg *hdr,
1033                                                 void * const *ext_hdrs)
1034 {
1035         struct xfrm_state *x;
1036         const struct sadb_lifetime *lifetime;
1037         const struct sadb_sa *sa;
1038         const struct sadb_key *key;
1039         const struct sadb_x_sec_ctx *sec_ctx;
1040         uint16_t proto;
1041         int err;
1042
1043
1044         sa = ext_hdrs[SADB_EXT_SA - 1];
1045         if (!sa ||
1046             !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
1047                                      ext_hdrs[SADB_EXT_ADDRESS_DST-1]))
1048                 return ERR_PTR(-EINVAL);
1049         if (hdr->sadb_msg_satype == SADB_SATYPE_ESP &&
1050             !ext_hdrs[SADB_EXT_KEY_ENCRYPT-1])
1051                 return ERR_PTR(-EINVAL);
1052         if (hdr->sadb_msg_satype == SADB_SATYPE_AH &&
1053             !ext_hdrs[SADB_EXT_KEY_AUTH-1])
1054                 return ERR_PTR(-EINVAL);
1055         if (!!ext_hdrs[SADB_EXT_LIFETIME_HARD-1] !=
1056             !!ext_hdrs[SADB_EXT_LIFETIME_SOFT-1])
1057                 return ERR_PTR(-EINVAL);
1058
1059         proto = pfkey_satype2proto(hdr->sadb_msg_satype);
1060         if (proto == 0)
1061                 return ERR_PTR(-EINVAL);
1062
1063         /* default error is no buffer space */
1064         err = -ENOBUFS;
1065
1066         /* RFC2367:
1067
1068    Only SADB_SASTATE_MATURE SAs may be submitted in an SADB_ADD message.
1069    SADB_SASTATE_LARVAL SAs are created by SADB_GETSPI and it is not
1070    sensible to add a new SA in the DYING or SADB_SASTATE_DEAD state.
1071    Therefore, the sadb_sa_state field of all submitted SAs MUST be
1072    SADB_SASTATE_MATURE and the kernel MUST return an error if this is
1073    not true.
1074
1075            However, KAME setkey always uses SADB_SASTATE_LARVAL.
1076            Hence, we have to _ignore_ sadb_sa_state, which is also reasonable.
1077          */
1078         if (sa->sadb_sa_auth > SADB_AALG_MAX ||
1079             (hdr->sadb_msg_satype == SADB_X_SATYPE_IPCOMP &&
1080              sa->sadb_sa_encrypt > SADB_X_CALG_MAX) ||
1081             sa->sadb_sa_encrypt > SADB_EALG_MAX)
1082                 return ERR_PTR(-EINVAL);
1083         key = ext_hdrs[SADB_EXT_KEY_AUTH - 1];
1084         if (key != NULL &&
1085             sa->sadb_sa_auth != SADB_X_AALG_NULL &&
1086             ((key->sadb_key_bits+7) / 8 == 0 ||
1087              (key->sadb_key_bits+7) / 8 > key->sadb_key_len * sizeof(uint64_t)))
1088                 return ERR_PTR(-EINVAL);
1089         key = ext_hdrs[SADB_EXT_KEY_ENCRYPT-1];
1090         if (key != NULL &&
1091             sa->sadb_sa_encrypt != SADB_EALG_NULL &&
1092             ((key->sadb_key_bits+7) / 8 == 0 ||
1093              (key->sadb_key_bits+7) / 8 > key->sadb_key_len * sizeof(uint64_t)))
1094                 return ERR_PTR(-EINVAL);
1095
1096         x = xfrm_state_alloc(net);
1097         if (x == NULL)
1098                 return ERR_PTR(-ENOBUFS);
1099
1100         x->id.proto = proto;
1101         x->id.spi = sa->sadb_sa_spi;
1102         x->props.replay_window = min_t(unsigned int, sa->sadb_sa_replay,
1103                                         (sizeof(x->replay.bitmap) * 8));
1104         if (sa->sadb_sa_flags & SADB_SAFLAGS_NOECN)
1105                 x->props.flags |= XFRM_STATE_NOECN;
1106         if (sa->sadb_sa_flags & SADB_SAFLAGS_DECAP_DSCP)
1107                 x->props.flags |= XFRM_STATE_DECAP_DSCP;
1108         if (sa->sadb_sa_flags & SADB_SAFLAGS_NOPMTUDISC)
1109                 x->props.flags |= XFRM_STATE_NOPMTUDISC;
1110
1111         lifetime = ext_hdrs[SADB_EXT_LIFETIME_HARD - 1];
1112         if (lifetime != NULL) {
1113                 x->lft.hard_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations);
1114                 x->lft.hard_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes);
1115                 x->lft.hard_add_expires_seconds = lifetime->sadb_lifetime_addtime;
1116                 x->lft.hard_use_expires_seconds = lifetime->sadb_lifetime_usetime;
1117         }
1118         lifetime = ext_hdrs[SADB_EXT_LIFETIME_SOFT - 1];
1119         if (lifetime != NULL) {
1120                 x->lft.soft_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations);
1121                 x->lft.soft_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes);
1122                 x->lft.soft_add_expires_seconds = lifetime->sadb_lifetime_addtime;
1123                 x->lft.soft_use_expires_seconds = lifetime->sadb_lifetime_usetime;
1124         }
1125
1126         sec_ctx = ext_hdrs[SADB_X_EXT_SEC_CTX - 1];
1127         if (sec_ctx != NULL) {
1128                 struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx, GFP_KERNEL);
1129
1130                 if (!uctx)
1131                         goto out;
1132
1133                 err = security_xfrm_state_alloc(x, uctx);
1134                 kfree(uctx);
1135
1136                 if (err)
1137                         goto out;
1138         }
1139
1140         key = ext_hdrs[SADB_EXT_KEY_AUTH - 1];
1141         if (sa->sadb_sa_auth) {
1142                 int keysize = 0;
1143                 struct xfrm_algo_desc *a = xfrm_aalg_get_byid(sa->sadb_sa_auth);
1144                 if (!a || !a->pfkey_supported) {
1145                         err = -ENOSYS;
1146                         goto out;
1147                 }
1148                 if (key)
1149                         keysize = (key->sadb_key_bits + 7) / 8;
1150                 x->aalg = kmalloc(sizeof(*x->aalg) + keysize, GFP_KERNEL);
1151                 if (!x->aalg)
1152                         goto out;
1153                 strcpy(x->aalg->alg_name, a->name);
1154                 x->aalg->alg_key_len = 0;
1155                 if (key) {
1156                         x->aalg->alg_key_len = key->sadb_key_bits;
1157                         memcpy(x->aalg->alg_key, key+1, keysize);
1158                 }
1159                 x->aalg->alg_trunc_len = a->uinfo.auth.icv_truncbits;
1160                 x->props.aalgo = sa->sadb_sa_auth;
1161                 /* x->algo.flags = sa->sadb_sa_flags; */
1162         }
1163         if (sa->sadb_sa_encrypt) {
1164                 if (hdr->sadb_msg_satype == SADB_X_SATYPE_IPCOMP) {
1165                         struct xfrm_algo_desc *a = xfrm_calg_get_byid(sa->sadb_sa_encrypt);
1166                         if (!a || !a->pfkey_supported) {
1167                                 err = -ENOSYS;
1168                                 goto out;
1169                         }
1170                         x->calg = kmalloc(sizeof(*x->calg), GFP_KERNEL);
1171                         if (!x->calg)
1172                                 goto out;
1173                         strcpy(x->calg->alg_name, a->name);
1174                         x->props.calgo = sa->sadb_sa_encrypt;
1175                 } else {
1176                         int keysize = 0;
1177                         struct xfrm_algo_desc *a = xfrm_ealg_get_byid(sa->sadb_sa_encrypt);
1178                         if (!a || !a->pfkey_supported) {
1179                                 err = -ENOSYS;
1180                                 goto out;
1181                         }
1182                         key = (struct sadb_key*) ext_hdrs[SADB_EXT_KEY_ENCRYPT-1];
1183                         if (key)
1184                                 keysize = (key->sadb_key_bits + 7) / 8;
1185                         x->ealg = kmalloc(sizeof(*x->ealg) + keysize, GFP_KERNEL);
1186                         if (!x->ealg)
1187                                 goto out;
1188                         strcpy(x->ealg->alg_name, a->name);
1189                         x->ealg->alg_key_len = 0;
1190                         if (key) {
1191                                 x->ealg->alg_key_len = key->sadb_key_bits;
1192                                 memcpy(x->ealg->alg_key, key+1, keysize);
1193                         }
1194                         x->props.ealgo = sa->sadb_sa_encrypt;
1195                 }
1196         }
1197         /* x->algo.flags = sa->sadb_sa_flags; */
1198
1199         x->props.family = pfkey_sadb_addr2xfrm_addr((struct sadb_address *) ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
1200                                                     &x->props.saddr);
1201         pfkey_sadb_addr2xfrm_addr((struct sadb_address *) ext_hdrs[SADB_EXT_ADDRESS_DST-1],
1202                                   &x->id.daddr);
1203
1204         if (ext_hdrs[SADB_X_EXT_SA2-1]) {
1205                 const struct sadb_x_sa2 *sa2 = ext_hdrs[SADB_X_EXT_SA2-1];
1206                 int mode = pfkey_mode_to_xfrm(sa2->sadb_x_sa2_mode);
1207                 if (mode < 0) {
1208                         err = -EINVAL;
1209                         goto out;
1210                 }
1211                 x->props.mode = mode;
1212                 x->props.reqid = sa2->sadb_x_sa2_reqid;
1213         }
1214
1215         if (ext_hdrs[SADB_EXT_ADDRESS_PROXY-1]) {
1216                 const struct sadb_address *addr = ext_hdrs[SADB_EXT_ADDRESS_PROXY-1];
1217
1218                 /* Nobody uses this, but we try. */
1219                 x->sel.family = pfkey_sadb_addr2xfrm_addr(addr, &x->sel.saddr);
1220                 x->sel.prefixlen_s = addr->sadb_address_prefixlen;
1221         }
1222
1223         if (!x->sel.family)
1224                 x->sel.family = x->props.family;
1225
1226         if (ext_hdrs[SADB_X_EXT_NAT_T_TYPE-1]) {
1227                 const struct sadb_x_nat_t_type* n_type;
1228                 struct xfrm_encap_tmpl *natt;
1229
1230                 x->encap = kmalloc(sizeof(*x->encap), GFP_KERNEL);
1231                 if (!x->encap)
1232                         goto out;
1233
1234                 natt = x->encap;
1235                 n_type = ext_hdrs[SADB_X_EXT_NAT_T_TYPE-1];
1236                 natt->encap_type = n_type->sadb_x_nat_t_type_type;
1237
1238                 if (ext_hdrs[SADB_X_EXT_NAT_T_SPORT-1]) {
1239                         const struct sadb_x_nat_t_port *n_port =
1240                                 ext_hdrs[SADB_X_EXT_NAT_T_SPORT-1];
1241                         natt->encap_sport = n_port->sadb_x_nat_t_port_port;
1242                 }
1243                 if (ext_hdrs[SADB_X_EXT_NAT_T_DPORT-1]) {
1244                         const struct sadb_x_nat_t_port *n_port =
1245                                 ext_hdrs[SADB_X_EXT_NAT_T_DPORT-1];
1246                         natt->encap_dport = n_port->sadb_x_nat_t_port_port;
1247                 }
1248                 memset(&natt->encap_oa, 0, sizeof(natt->encap_oa));
1249         }
1250
1251         err = xfrm_init_state(x);
1252         if (err)
1253                 goto out;
1254
1255         x->km.seq = hdr->sadb_msg_seq;
1256         return x;
1257
1258 out:
1259         x->km.state = XFRM_STATE_DEAD;
1260         xfrm_state_put(x);
1261         return ERR_PTR(err);
1262 }
1263
1264 static int pfkey_reserved(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
1265 {
1266         return -EOPNOTSUPP;
1267 }
1268
1269 static int pfkey_getspi(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
1270 {
1271         struct net *net = sock_net(sk);
1272         struct sk_buff *resp_skb;
1273         struct sadb_x_sa2 *sa2;
1274         struct sadb_address *saddr, *daddr;
1275         struct sadb_msg *out_hdr;
1276         struct sadb_spirange *range;
1277         struct xfrm_state *x = NULL;
1278         int mode;
1279         int err;
1280         u32 min_spi, max_spi;
1281         u32 reqid;
1282         u8 proto;
1283         unsigned short family;
1284         xfrm_address_t *xsaddr = NULL, *xdaddr = NULL;
1285
1286         if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
1287                                      ext_hdrs[SADB_EXT_ADDRESS_DST-1]))
1288                 return -EINVAL;
1289
1290         proto = pfkey_satype2proto(hdr->sadb_msg_satype);
1291         if (proto == 0)
1292                 return -EINVAL;
1293
1294         if ((sa2 = ext_hdrs[SADB_X_EXT_SA2-1]) != NULL) {
1295                 mode = pfkey_mode_to_xfrm(sa2->sadb_x_sa2_mode);
1296                 if (mode < 0)
1297                         return -EINVAL;
1298                 reqid = sa2->sadb_x_sa2_reqid;
1299         } else {
1300                 mode = 0;
1301                 reqid = 0;
1302         }
1303
1304         saddr = ext_hdrs[SADB_EXT_ADDRESS_SRC-1];
1305         daddr = ext_hdrs[SADB_EXT_ADDRESS_DST-1];
1306
1307         family = ((struct sockaddr *)(saddr + 1))->sa_family;
1308         switch (family) {
1309         case AF_INET:
1310                 xdaddr = (xfrm_address_t *)&((struct sockaddr_in *)(daddr + 1))->sin_addr.s_addr;
1311                 xsaddr = (xfrm_address_t *)&((struct sockaddr_in *)(saddr + 1))->sin_addr.s_addr;
1312                 break;
1313 #if IS_ENABLED(CONFIG_IPV6)
1314         case AF_INET6:
1315                 xdaddr = (xfrm_address_t *)&((struct sockaddr_in6 *)(daddr + 1))->sin6_addr;
1316                 xsaddr = (xfrm_address_t *)&((struct sockaddr_in6 *)(saddr + 1))->sin6_addr;
1317                 break;
1318 #endif
1319         }
1320
1321         if (hdr->sadb_msg_seq) {
1322                 x = xfrm_find_acq_byseq(net, DUMMY_MARK, hdr->sadb_msg_seq);
1323                 if (x && !xfrm_addr_equal(&x->id.daddr, xdaddr, family)) {
1324                         xfrm_state_put(x);
1325                         x = NULL;
1326                 }
1327         }
1328
1329         if (!x)
1330                 x = xfrm_find_acq(net, &dummy_mark, mode, reqid, proto, xdaddr, xsaddr, 1, family);
1331
1332         if (x == NULL)
1333                 return -ENOENT;
1334
1335         min_spi = 0x100;
1336         max_spi = 0x0fffffff;
1337
1338         range = ext_hdrs[SADB_EXT_SPIRANGE-1];
1339         if (range) {
1340                 min_spi = range->sadb_spirange_min;
1341                 max_spi = range->sadb_spirange_max;
1342         }
1343
1344         err = verify_spi_info(x->id.proto, min_spi, max_spi);
1345         if (err) {
1346                 xfrm_state_put(x);
1347                 return err;
1348         }
1349
1350         err = xfrm_alloc_spi(x, min_spi, max_spi);
1351         resp_skb = err ? ERR_PTR(err) : pfkey_xfrm_state2msg(x);
1352
1353         if (IS_ERR(resp_skb)) {
1354                 xfrm_state_put(x);
1355                 return  PTR_ERR(resp_skb);
1356         }
1357
1358         out_hdr = (struct sadb_msg *) resp_skb->data;
1359         out_hdr->sadb_msg_version = hdr->sadb_msg_version;
1360         out_hdr->sadb_msg_type = SADB_GETSPI;
1361         out_hdr->sadb_msg_satype = pfkey_proto2satype(proto);
1362         out_hdr->sadb_msg_errno = 0;
1363         out_hdr->sadb_msg_reserved = 0;
1364         out_hdr->sadb_msg_seq = hdr->sadb_msg_seq;
1365         out_hdr->sadb_msg_pid = hdr->sadb_msg_pid;
1366
1367         xfrm_state_put(x);
1368
1369         pfkey_broadcast(resp_skb, GFP_KERNEL, BROADCAST_ONE, sk, net);
1370
1371         return 0;
1372 }
1373
1374 static int pfkey_acquire(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
1375 {
1376         struct net *net = sock_net(sk);
1377         struct xfrm_state *x;
1378
1379         if (hdr->sadb_msg_len != sizeof(struct sadb_msg)/8)
1380                 return -EOPNOTSUPP;
1381
1382         if (hdr->sadb_msg_seq == 0 || hdr->sadb_msg_errno == 0)
1383                 return 0;
1384
1385         x = xfrm_find_acq_byseq(net, DUMMY_MARK, hdr->sadb_msg_seq);
1386         if (x == NULL)
1387                 return 0;
1388
1389         spin_lock_bh(&x->lock);
1390         if (x->km.state == XFRM_STATE_ACQ)
1391                 x->km.state = XFRM_STATE_ERROR;
1392
1393         spin_unlock_bh(&x->lock);
1394         xfrm_state_put(x);
1395         return 0;
1396 }
1397
1398 static inline int event2poltype(int event)
1399 {
1400         switch (event) {
1401         case XFRM_MSG_DELPOLICY:
1402                 return SADB_X_SPDDELETE;
1403         case XFRM_MSG_NEWPOLICY:
1404                 return SADB_X_SPDADD;
1405         case XFRM_MSG_UPDPOLICY:
1406                 return SADB_X_SPDUPDATE;
1407         case XFRM_MSG_POLEXPIRE:
1408         //      return SADB_X_SPDEXPIRE;
1409         default:
1410                 pr_err("pfkey: Unknown policy event %d\n", event);
1411                 break;
1412         }
1413
1414         return 0;
1415 }
1416
1417 static inline int event2keytype(int event)
1418 {
1419         switch (event) {
1420         case XFRM_MSG_DELSA:
1421                 return SADB_DELETE;
1422         case XFRM_MSG_NEWSA:
1423                 return SADB_ADD;
1424         case XFRM_MSG_UPDSA:
1425                 return SADB_UPDATE;
1426         case XFRM_MSG_EXPIRE:
1427                 return SADB_EXPIRE;
1428         default:
1429                 pr_err("pfkey: Unknown SA event %d\n", event);
1430                 break;
1431         }
1432
1433         return 0;
1434 }
1435
1436 /* ADD/UPD/DEL */
1437 static int key_notify_sa(struct xfrm_state *x, const struct km_event *c)
1438 {
1439         struct sk_buff *skb;
1440         struct sadb_msg *hdr;
1441
1442         skb = pfkey_xfrm_state2msg(x);
1443
1444         if (IS_ERR(skb))
1445                 return PTR_ERR(skb);
1446
1447         hdr = (struct sadb_msg *) skb->data;
1448         hdr->sadb_msg_version = PF_KEY_V2;
1449         hdr->sadb_msg_type = event2keytype(c->event);
1450         hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto);
1451         hdr->sadb_msg_errno = 0;
1452         hdr->sadb_msg_reserved = 0;
1453         hdr->sadb_msg_seq = c->seq;
1454         hdr->sadb_msg_pid = c->portid;
1455
1456         pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, xs_net(x));
1457
1458         return 0;
1459 }
1460
1461 static int pfkey_add(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
1462 {
1463         struct net *net = sock_net(sk);
1464         struct xfrm_state *x;
1465         int err;
1466         struct km_event c;
1467
1468         x = pfkey_msg2xfrm_state(net, hdr, ext_hdrs);
1469         if (IS_ERR(x))
1470                 return PTR_ERR(x);
1471
1472         xfrm_state_hold(x);
1473         if (hdr->sadb_msg_type == SADB_ADD)
1474                 err = xfrm_state_add(x);
1475         else
1476                 err = xfrm_state_update(x);
1477
1478         xfrm_audit_state_add(x, err ? 0 : 1,
1479                              audit_get_loginuid(current),
1480                              audit_get_sessionid(current), 0);
1481
1482         if (err < 0) {
1483                 x->km.state = XFRM_STATE_DEAD;
1484                 __xfrm_state_put(x);
1485                 goto out;
1486         }
1487
1488         if (hdr->sadb_msg_type == SADB_ADD)
1489                 c.event = XFRM_MSG_NEWSA;
1490         else
1491                 c.event = XFRM_MSG_UPDSA;
1492         c.seq = hdr->sadb_msg_seq;
1493         c.portid = hdr->sadb_msg_pid;
1494         km_state_notify(x, &c);
1495 out:
1496         xfrm_state_put(x);
1497         return err;
1498 }
1499
1500 static int pfkey_delete(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
1501 {
1502         struct net *net = sock_net(sk);
1503         struct xfrm_state *x;
1504         struct km_event c;
1505         int err;
1506
1507         if (!ext_hdrs[SADB_EXT_SA-1] ||
1508             !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
1509                                      ext_hdrs[SADB_EXT_ADDRESS_DST-1]))
1510                 return -EINVAL;
1511
1512         x = pfkey_xfrm_state_lookup(net, hdr, ext_hdrs);
1513         if (x == NULL)
1514                 return -ESRCH;
1515
1516         if ((err = security_xfrm_state_delete(x)))
1517                 goto out;
1518
1519         if (xfrm_state_kern(x)) {
1520                 err = -EPERM;
1521                 goto out;
1522         }
1523
1524         err = xfrm_state_delete(x);
1525
1526         if (err < 0)
1527                 goto out;
1528
1529         c.seq = hdr->sadb_msg_seq;
1530         c.portid = hdr->sadb_msg_pid;
1531         c.event = XFRM_MSG_DELSA;
1532         km_state_notify(x, &c);
1533 out:
1534         xfrm_audit_state_delete(x, err ? 0 : 1,
1535                                 audit_get_loginuid(current),
1536                                 audit_get_sessionid(current), 0);
1537         xfrm_state_put(x);
1538
1539         return err;
1540 }
1541
1542 static int pfkey_get(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
1543 {
1544         struct net *net = sock_net(sk);
1545         __u8 proto;
1546         struct sk_buff *out_skb;
1547         struct sadb_msg *out_hdr;
1548         struct xfrm_state *x;
1549
1550         if (!ext_hdrs[SADB_EXT_SA-1] ||
1551             !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
1552                                      ext_hdrs[SADB_EXT_ADDRESS_DST-1]))
1553                 return -EINVAL;
1554
1555         x = pfkey_xfrm_state_lookup(net, hdr, ext_hdrs);
1556         if (x == NULL)
1557                 return -ESRCH;
1558
1559         out_skb = pfkey_xfrm_state2msg(x);
1560         proto = x->id.proto;
1561         xfrm_state_put(x);
1562         if (IS_ERR(out_skb))
1563                 return  PTR_ERR(out_skb);
1564
1565         out_hdr = (struct sadb_msg *) out_skb->data;
1566         out_hdr->sadb_msg_version = hdr->sadb_msg_version;
1567         out_hdr->sadb_msg_type = SADB_GET;
1568         out_hdr->sadb_msg_satype = pfkey_proto2satype(proto);
1569         out_hdr->sadb_msg_errno = 0;
1570         out_hdr->sadb_msg_reserved = 0;
1571         out_hdr->sadb_msg_seq = hdr->sadb_msg_seq;
1572         out_hdr->sadb_msg_pid = hdr->sadb_msg_pid;
1573         pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ONE, sk, sock_net(sk));
1574
1575         return 0;
1576 }
1577
1578 static struct sk_buff *compose_sadb_supported(const struct sadb_msg *orig,
1579                                               gfp_t allocation)
1580 {
1581         struct sk_buff *skb;
1582         struct sadb_msg *hdr;
1583         int len, auth_len, enc_len, i;
1584
1585         auth_len = xfrm_count_pfkey_auth_supported();
1586         if (auth_len) {
1587                 auth_len *= sizeof(struct sadb_alg);
1588                 auth_len += sizeof(struct sadb_supported);
1589         }
1590
1591         enc_len = xfrm_count_pfkey_enc_supported();
1592         if (enc_len) {
1593                 enc_len *= sizeof(struct sadb_alg);
1594                 enc_len += sizeof(struct sadb_supported);
1595         }
1596
1597         len = enc_len + auth_len + sizeof(struct sadb_msg);
1598
1599         skb = alloc_skb(len + 16, allocation);
1600         if (!skb)
1601                 goto out_put_algs;
1602
1603         hdr = (struct sadb_msg *) skb_put(skb, sizeof(*hdr));
1604         pfkey_hdr_dup(hdr, orig);
1605         hdr->sadb_msg_errno = 0;
1606         hdr->sadb_msg_len = len / sizeof(uint64_t);
1607
1608         if (auth_len) {
1609                 struct sadb_supported *sp;
1610                 struct sadb_alg *ap;
1611
1612                 sp = (struct sadb_supported *) skb_put(skb, auth_len);
1613                 ap = (struct sadb_alg *) (sp + 1);
1614
1615                 sp->sadb_supported_len = auth_len / sizeof(uint64_t);
1616                 sp->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
1617
1618                 for (i = 0; ; i++) {
1619                         struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i);
1620                         if (!aalg)
1621                                 break;
1622                         if (!aalg->pfkey_supported)
1623                                 continue;
1624                         if (aalg->available)
1625                                 *ap++ = aalg->desc;
1626                 }
1627         }
1628
1629         if (enc_len) {
1630                 struct sadb_supported *sp;
1631                 struct sadb_alg *ap;
1632
1633                 sp = (struct sadb_supported *) skb_put(skb, enc_len);
1634                 ap = (struct sadb_alg *) (sp + 1);
1635
1636                 sp->sadb_supported_len = enc_len / sizeof(uint64_t);
1637                 sp->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
1638
1639                 for (i = 0; ; i++) {
1640                         struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i);
1641                         if (!ealg)
1642                                 break;
1643                         if (!ealg->pfkey_supported)
1644                                 continue;
1645                         if (ealg->available)
1646                                 *ap++ = ealg->desc;
1647                 }
1648         }
1649
1650 out_put_algs:
1651         return skb;
1652 }
1653
1654 static int pfkey_register(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
1655 {
1656         struct pfkey_sock *pfk = pfkey_sk(sk);
1657         struct sk_buff *supp_skb;
1658
1659         if (hdr->sadb_msg_satype > SADB_SATYPE_MAX)
1660                 return -EINVAL;
1661
1662         if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC) {
1663                 if (pfk->registered&(1<<hdr->sadb_msg_satype))
1664                         return -EEXIST;
1665                 pfk->registered |= (1<<hdr->sadb_msg_satype);
1666         }
1667
1668         xfrm_probe_algs();
1669
1670         supp_skb = compose_sadb_supported(hdr, GFP_KERNEL);
1671         if (!supp_skb) {
1672                 if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC)
1673                         pfk->registered &= ~(1<<hdr->sadb_msg_satype);
1674
1675                 return -ENOBUFS;
1676         }
1677
1678         pfkey_broadcast(supp_skb, GFP_KERNEL, BROADCAST_REGISTERED, sk, sock_net(sk));
1679
1680         return 0;
1681 }
1682
1683 static int unicast_flush_resp(struct sock *sk, const struct sadb_msg *ihdr)
1684 {
1685         struct sk_buff *skb;
1686         struct sadb_msg *hdr;
1687
1688         skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC);
1689         if (!skb)
1690                 return -ENOBUFS;
1691
1692         hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
1693         memcpy(hdr, ihdr, sizeof(struct sadb_msg));
1694         hdr->sadb_msg_errno = (uint8_t) 0;
1695         hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t));
1696
1697         return pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ONE, sk, sock_net(sk));
1698 }
1699
1700 static int key_notify_sa_flush(const struct km_event *c)
1701 {
1702         struct sk_buff *skb;
1703         struct sadb_msg *hdr;
1704
1705         skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC);
1706         if (!skb)
1707                 return -ENOBUFS;
1708         hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
1709         hdr->sadb_msg_satype = pfkey_proto2satype(c->data.proto);
1710         hdr->sadb_msg_type = SADB_FLUSH;
1711         hdr->sadb_msg_seq = c->seq;
1712         hdr->sadb_msg_pid = c->portid;
1713         hdr->sadb_msg_version = PF_KEY_V2;
1714         hdr->sadb_msg_errno = (uint8_t) 0;
1715         hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t));
1716         hdr->sadb_msg_reserved = 0;
1717
1718         pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net);
1719
1720         return 0;
1721 }
1722
1723 static int pfkey_flush(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
1724 {
1725         struct net *net = sock_net(sk);
1726         unsigned int proto;
1727         struct km_event c;
1728         struct xfrm_audit audit_info;
1729         int err, err2;
1730
1731         proto = pfkey_satype2proto(hdr->sadb_msg_satype);
1732         if (proto == 0)
1733                 return -EINVAL;
1734
1735         audit_info.loginuid = audit_get_loginuid(current);
1736         audit_info.sessionid = audit_get_sessionid(current);
1737         audit_info.secid = 0;
1738         err = xfrm_state_flush(net, proto, &audit_info);
1739         err2 = unicast_flush_resp(sk, hdr);
1740         if (err || err2) {
1741                 if (err == -ESRCH) /* empty table - go quietly */
1742                         err = 0;
1743                 return err ? err : err2;
1744         }
1745
1746         c.data.proto = proto;
1747         c.seq = hdr->sadb_msg_seq;
1748         c.portid = hdr->sadb_msg_pid;
1749         c.event = XFRM_MSG_FLUSHSA;
1750         c.net = net;
1751         km_state_notify(NULL, &c);
1752
1753         return 0;
1754 }
1755
1756 static int dump_sa(struct xfrm_state *x, int count, void *ptr)
1757 {
1758         struct pfkey_sock *pfk = ptr;
1759         struct sk_buff *out_skb;
1760         struct sadb_msg *out_hdr;
1761
1762         if (!pfkey_can_dump(&pfk->sk))
1763                 return -ENOBUFS;
1764
1765         out_skb = pfkey_xfrm_state2msg(x);
1766         if (IS_ERR(out_skb))
1767                 return PTR_ERR(out_skb);
1768
1769         out_hdr = (struct sadb_msg *) out_skb->data;
1770         out_hdr->sadb_msg_version = pfk->dump.msg_version;
1771         out_hdr->sadb_msg_type = SADB_DUMP;
1772         out_hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto);
1773         out_hdr->sadb_msg_errno = 0;
1774         out_hdr->sadb_msg_reserved = 0;
1775         out_hdr->sadb_msg_seq = count + 1;
1776         out_hdr->sadb_msg_pid = pfk->dump.msg_portid;
1777
1778         if (pfk->dump.skb)
1779                 pfkey_broadcast(pfk->dump.skb, GFP_ATOMIC, BROADCAST_ONE,
1780                                 &pfk->sk, sock_net(&pfk->sk));
1781         pfk->dump.skb = out_skb;
1782
1783         return 0;
1784 }
1785
1786 static int pfkey_dump_sa(struct pfkey_sock *pfk)
1787 {
1788         struct net *net = sock_net(&pfk->sk);
1789         return xfrm_state_walk(net, &pfk->dump.u.state, dump_sa, (void *) pfk);
1790 }
1791
1792 static void pfkey_dump_sa_done(struct pfkey_sock *pfk)
1793 {
1794         struct net *net = sock_net(&pfk->sk);
1795
1796         xfrm_state_walk_done(&pfk->dump.u.state, net);
1797 }
1798
1799 static int pfkey_dump(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
1800 {
1801         u8 proto;
1802         struct pfkey_sock *pfk = pfkey_sk(sk);
1803
1804         if (pfk->dump.dump != NULL)
1805                 return -EBUSY;
1806
1807         proto = pfkey_satype2proto(hdr->sadb_msg_satype);
1808         if (proto == 0)
1809                 return -EINVAL;
1810
1811         pfk->dump.msg_version = hdr->sadb_msg_version;
1812         pfk->dump.msg_portid = hdr->sadb_msg_pid;
1813         pfk->dump.dump = pfkey_dump_sa;
1814         pfk->dump.done = pfkey_dump_sa_done;
1815         xfrm_state_walk_init(&pfk->dump.u.state, proto);
1816
1817         return pfkey_do_dump(pfk);
1818 }
1819
1820 static int pfkey_promisc(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
1821 {
1822         struct pfkey_sock *pfk = pfkey_sk(sk);
1823         int satype = hdr->sadb_msg_satype;
1824         bool reset_errno = false;
1825
1826         if (hdr->sadb_msg_len == (sizeof(*hdr) / sizeof(uint64_t))) {
1827                 reset_errno = true;
1828                 if (satype != 0 && satype != 1)
1829                         return -EINVAL;
1830                 pfk->promisc = satype;
1831         }
1832         if (reset_errno && skb_cloned(skb))
1833                 skb = skb_copy(skb, GFP_KERNEL);
1834         else
1835                 skb = skb_clone(skb, GFP_KERNEL);
1836
1837         if (reset_errno && skb) {
1838                 struct sadb_msg *new_hdr = (struct sadb_msg *) skb->data;
1839                 new_hdr->sadb_msg_errno = 0;
1840         }
1841
1842         pfkey_broadcast(skb, GFP_KERNEL, BROADCAST_ALL, NULL, sock_net(sk));
1843         return 0;
1844 }
1845
1846 static int check_reqid(struct xfrm_policy *xp, int dir, int count, void *ptr)
1847 {
1848         int i;
1849         u32 reqid = *(u32*)ptr;
1850
1851         for (i=0; i<xp->xfrm_nr; i++) {
1852                 if (xp->xfrm_vec[i].reqid == reqid)
1853                         return -EEXIST;
1854         }
1855         return 0;
1856 }
1857
1858 static u32 gen_reqid(struct net *net)
1859 {
1860         struct xfrm_policy_walk walk;
1861         u32 start;
1862         int rc;
1863         static u32 reqid = IPSEC_MANUAL_REQID_MAX;
1864
1865         start = reqid;
1866         do {
1867                 ++reqid;
1868                 if (reqid == 0)
1869                         reqid = IPSEC_MANUAL_REQID_MAX+1;
1870                 xfrm_policy_walk_init(&walk, XFRM_POLICY_TYPE_MAIN);
1871                 rc = xfrm_policy_walk(net, &walk, check_reqid, (void*)&reqid);
1872                 xfrm_policy_walk_done(&walk, net);
1873                 if (rc != -EEXIST)
1874                         return reqid;
1875         } while (reqid != start);
1876         return 0;
1877 }
1878
1879 static int
1880 parse_ipsecrequest(struct xfrm_policy *xp, struct sadb_x_ipsecrequest *rq)
1881 {
1882         struct net *net = xp_net(xp);
1883         struct xfrm_tmpl *t = xp->xfrm_vec + xp->xfrm_nr;
1884         int mode;
1885
1886         if (xp->xfrm_nr >= XFRM_MAX_DEPTH)
1887                 return -ELOOP;
1888
1889         if (rq->sadb_x_ipsecrequest_mode == 0)
1890                 return -EINVAL;
1891
1892         t->id.proto = rq->sadb_x_ipsecrequest_proto; /* XXX check proto */
1893         if ((mode = pfkey_mode_to_xfrm(rq->sadb_x_ipsecrequest_mode)) < 0)
1894                 return -EINVAL;
1895         t->mode = mode;
1896         if (rq->sadb_x_ipsecrequest_level == IPSEC_LEVEL_USE)
1897                 t->optional = 1;
1898         else if (rq->sadb_x_ipsecrequest_level == IPSEC_LEVEL_UNIQUE) {
1899                 t->reqid = rq->sadb_x_ipsecrequest_reqid;
1900                 if (t->reqid > IPSEC_MANUAL_REQID_MAX)
1901                         t->reqid = 0;
1902                 if (!t->reqid && !(t->reqid = gen_reqid(net)))
1903                         return -ENOBUFS;
1904         }
1905
1906         /* addresses present only in tunnel mode */
1907         if (t->mode == XFRM_MODE_TUNNEL) {
1908                 u8 *sa = (u8 *) (rq + 1);
1909                 int family, socklen;
1910
1911                 family = pfkey_sockaddr_extract((struct sockaddr *)sa,
1912                                                 &t->saddr);
1913                 if (!family)
1914                         return -EINVAL;
1915
1916                 socklen = pfkey_sockaddr_len(family);
1917                 if (pfkey_sockaddr_extract((struct sockaddr *)(sa + socklen),
1918                                            &t->id.daddr) != family)
1919                         return -EINVAL;
1920                 t->encap_family = family;
1921         } else
1922                 t->encap_family = xp->family;
1923
1924         /* No way to set this via kame pfkey */
1925         t->allalgs = 1;
1926         xp->xfrm_nr++;
1927         return 0;
1928 }
1929
1930 static int
1931 parse_ipsecrequests(struct xfrm_policy *xp, struct sadb_x_policy *pol)
1932 {
1933         int err;
1934         int len = pol->sadb_x_policy_len*8 - sizeof(struct sadb_x_policy);
1935         struct sadb_x_ipsecrequest *rq = (void*)(pol+1);
1936
1937         if (pol->sadb_x_policy_len * 8 < sizeof(struct sadb_x_policy))
1938                 return -EINVAL;
1939
1940         while (len >= sizeof(struct sadb_x_ipsecrequest)) {
1941                 if ((err = parse_ipsecrequest(xp, rq)) < 0)
1942                         return err;
1943                 len -= rq->sadb_x_ipsecrequest_len;
1944                 rq = (void*)((u8*)rq + rq->sadb_x_ipsecrequest_len);
1945         }
1946         return 0;
1947 }
1948
1949 static inline int pfkey_xfrm_policy2sec_ctx_size(const struct xfrm_policy *xp)
1950 {
1951   struct xfrm_sec_ctx *xfrm_ctx = xp->security;
1952
1953         if (xfrm_ctx) {
1954                 int len = sizeof(struct sadb_x_sec_ctx);
1955                 len += xfrm_ctx->ctx_len;
1956                 return PFKEY_ALIGN8(len);
1957         }
1958         return 0;
1959 }
1960
1961 static int pfkey_xfrm_policy2msg_size(const struct xfrm_policy *xp)
1962 {
1963         const struct xfrm_tmpl *t;
1964         int sockaddr_size = pfkey_sockaddr_size(xp->family);
1965         int socklen = 0;
1966         int i;
1967
1968         for (i=0; i<xp->xfrm_nr; i++) {
1969                 t = xp->xfrm_vec + i;
1970                 socklen += pfkey_sockaddr_len(t->encap_family);
1971         }
1972
1973         return sizeof(struct sadb_msg) +
1974                 (sizeof(struct sadb_lifetime) * 3) +
1975                 (sizeof(struct sadb_address) * 2) +
1976                 (sockaddr_size * 2) +
1977                 sizeof(struct sadb_x_policy) +
1978                 (xp->xfrm_nr * sizeof(struct sadb_x_ipsecrequest)) +
1979                 (socklen * 2) +
1980                 pfkey_xfrm_policy2sec_ctx_size(xp);
1981 }
1982
1983 static struct sk_buff * pfkey_xfrm_policy2msg_prep(const struct xfrm_policy *xp)
1984 {
1985         struct sk_buff *skb;
1986         int size;
1987
1988         size = pfkey_xfrm_policy2msg_size(xp);
1989
1990         skb =  alloc_skb(size + 16, GFP_ATOMIC);
1991         if (skb == NULL)
1992                 return ERR_PTR(-ENOBUFS);
1993
1994         return skb;
1995 }
1996
1997 static int pfkey_xfrm_policy2msg(struct sk_buff *skb, const struct xfrm_policy *xp, int dir)
1998 {
1999         struct sadb_msg *hdr;
2000         struct sadb_address *addr;
2001         struct sadb_lifetime *lifetime;
2002         struct sadb_x_policy *pol;
2003         struct sadb_x_sec_ctx *sec_ctx;
2004         struct xfrm_sec_ctx *xfrm_ctx;
2005         int i;
2006         int size;
2007         int sockaddr_size = pfkey_sockaddr_size(xp->family);
2008         int socklen = pfkey_sockaddr_len(xp->family);
2009
2010         size = pfkey_xfrm_policy2msg_size(xp);
2011
2012         /* call should fill header later */
2013         hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
2014         memset(hdr, 0, size);   /* XXX do we need this ? */
2015
2016         /* src address */
2017         addr = (struct sadb_address*) skb_put(skb,
2018                                               sizeof(struct sadb_address)+sockaddr_size);
2019         addr->sadb_address_len =
2020                 (sizeof(struct sadb_address)+sockaddr_size)/
2021                         sizeof(uint64_t);
2022         addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
2023         addr->sadb_address_proto = pfkey_proto_from_xfrm(xp->selector.proto);
2024         addr->sadb_address_prefixlen = xp->selector.prefixlen_s;
2025         addr->sadb_address_reserved = 0;
2026         if (!pfkey_sockaddr_fill(&xp->selector.saddr,
2027                                  xp->selector.sport,
2028                                  (struct sockaddr *) (addr + 1),
2029                                  xp->family))
2030                 BUG();
2031
2032         /* dst address */
2033         addr = (struct sadb_address*) skb_put(skb,
2034                                               sizeof(struct sadb_address)+sockaddr_size);
2035         addr->sadb_address_len =
2036                 (sizeof(struct sadb_address)+sockaddr_size)/
2037                         sizeof(uint64_t);
2038         addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
2039         addr->sadb_address_proto = pfkey_proto_from_xfrm(xp->selector.proto);
2040         addr->sadb_address_prefixlen = xp->selector.prefixlen_d;
2041         addr->sadb_address_reserved = 0;
2042
2043         pfkey_sockaddr_fill(&xp->selector.daddr, xp->selector.dport,
2044                             (struct sockaddr *) (addr + 1),
2045                             xp->family);
2046
2047         /* hard time */
2048         lifetime = (struct sadb_lifetime *)  skb_put(skb,
2049                                                      sizeof(struct sadb_lifetime));
2050         lifetime->sadb_lifetime_len =
2051                 sizeof(struct sadb_lifetime)/sizeof(uint64_t);
2052         lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_HARD;
2053         lifetime->sadb_lifetime_allocations =  _X2KEY(xp->lft.hard_packet_limit);
2054         lifetime->sadb_lifetime_bytes = _X2KEY(xp->lft.hard_byte_limit);
2055         lifetime->sadb_lifetime_addtime = xp->lft.hard_add_expires_seconds;
2056         lifetime->sadb_lifetime_usetime = xp->lft.hard_use_expires_seconds;
2057         /* soft time */
2058         lifetime = (struct sadb_lifetime *)  skb_put(skb,
2059                                                      sizeof(struct sadb_lifetime));
2060         lifetime->sadb_lifetime_len =
2061                 sizeof(struct sadb_lifetime)/sizeof(uint64_t);
2062         lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_SOFT;
2063         lifetime->sadb_lifetime_allocations =  _X2KEY(xp->lft.soft_packet_limit);
2064         lifetime->sadb_lifetime_bytes = _X2KEY(xp->lft.soft_byte_limit);
2065         lifetime->sadb_lifetime_addtime = xp->lft.soft_add_expires_seconds;
2066         lifetime->sadb_lifetime_usetime = xp->lft.soft_use_expires_seconds;
2067         /* current time */
2068         lifetime = (struct sadb_lifetime *)  skb_put(skb,
2069                                                      sizeof(struct sadb_lifetime));
2070         lifetime->sadb_lifetime_len =
2071                 sizeof(struct sadb_lifetime)/sizeof(uint64_t);
2072         lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2073         lifetime->sadb_lifetime_allocations = xp->curlft.packets;
2074         lifetime->sadb_lifetime_bytes = xp->curlft.bytes;
2075         lifetime->sadb_lifetime_addtime = xp->curlft.add_time;
2076         lifetime->sadb_lifetime_usetime = xp->curlft.use_time;
2077
2078         pol = (struct sadb_x_policy *)  skb_put(skb, sizeof(struct sadb_x_policy));
2079         pol->sadb_x_policy_len = sizeof(struct sadb_x_policy)/sizeof(uint64_t);
2080         pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2081         pol->sadb_x_policy_type = IPSEC_POLICY_DISCARD;
2082         if (xp->action == XFRM_POLICY_ALLOW) {
2083                 if (xp->xfrm_nr)
2084                         pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
2085                 else
2086                         pol->sadb_x_policy_type = IPSEC_POLICY_NONE;
2087         }
2088         pol->sadb_x_policy_dir = dir+1;
2089         pol->sadb_x_policy_reserved = 0;
2090         pol->sadb_x_policy_id = xp->index;
2091         pol->sadb_x_policy_priority = xp->priority;
2092
2093         for (i=0; i<xp->xfrm_nr; i++) {
2094                 const struct xfrm_tmpl *t = xp->xfrm_vec + i;
2095                 struct sadb_x_ipsecrequest *rq;
2096                 int req_size;
2097                 int mode;
2098
2099                 req_size = sizeof(struct sadb_x_ipsecrequest);
2100                 if (t->mode == XFRM_MODE_TUNNEL) {
2101                         socklen = pfkey_sockaddr_len(t->encap_family);
2102                         req_size += socklen * 2;
2103                 } else {
2104                         size -= 2*socklen;
2105                 }
2106                 rq = (void*)skb_put(skb, req_size);
2107                 pol->sadb_x_policy_len += req_size/8;
2108                 memset(rq, 0, sizeof(*rq));
2109                 rq->sadb_x_ipsecrequest_len = req_size;
2110                 rq->sadb_x_ipsecrequest_proto = t->id.proto;
2111                 if ((mode = pfkey_mode_from_xfrm(t->mode)) < 0)
2112                         return -EINVAL;
2113                 rq->sadb_x_ipsecrequest_mode = mode;
2114                 rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_REQUIRE;
2115                 if (t->reqid)
2116                         rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_UNIQUE;
2117                 if (t->optional)
2118                         rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_USE;
2119                 rq->sadb_x_ipsecrequest_reqid = t->reqid;
2120
2121                 if (t->mode == XFRM_MODE_TUNNEL) {
2122                         u8 *sa = (void *)(rq + 1);
2123                         pfkey_sockaddr_fill(&t->saddr, 0,
2124                                             (struct sockaddr *)sa,
2125                                             t->encap_family);
2126                         pfkey_sockaddr_fill(&t->id.daddr, 0,
2127                                             (struct sockaddr *) (sa + socklen),
2128                                             t->encap_family);
2129                 }
2130         }
2131
2132         /* security context */
2133         if ((xfrm_ctx = xp->security)) {
2134                 int ctx_size = pfkey_xfrm_policy2sec_ctx_size(xp);
2135
2136                 sec_ctx = (struct sadb_x_sec_ctx *) skb_put(skb, ctx_size);
2137                 sec_ctx->sadb_x_sec_len = ctx_size / sizeof(uint64_t);
2138                 sec_ctx->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX;
2139                 sec_ctx->sadb_x_ctx_doi = xfrm_ctx->ctx_doi;
2140                 sec_ctx->sadb_x_ctx_alg = xfrm_ctx->ctx_alg;
2141                 sec_ctx->sadb_x_ctx_len = xfrm_ctx->ctx_len;
2142                 memcpy(sec_ctx + 1, xfrm_ctx->ctx_str,
2143                        xfrm_ctx->ctx_len);
2144         }
2145
2146         hdr->sadb_msg_len = size / sizeof(uint64_t);
2147         hdr->sadb_msg_reserved = atomic_read(&xp->refcnt);
2148
2149         return 0;
2150 }
2151
2152 static int key_notify_policy(struct xfrm_policy *xp, int dir, const struct km_event *c)
2153 {
2154         struct sk_buff *out_skb;
2155         struct sadb_msg *out_hdr;
2156         int err;
2157
2158         out_skb = pfkey_xfrm_policy2msg_prep(xp);
2159         if (IS_ERR(out_skb))
2160                 return PTR_ERR(out_skb);
2161
2162         err = pfkey_xfrm_policy2msg(out_skb, xp, dir);
2163         if (err < 0)
2164                 return err;
2165
2166         out_hdr = (struct sadb_msg *) out_skb->data;
2167         out_hdr->sadb_msg_version = PF_KEY_V2;
2168
2169         if (c->data.byid && c->event == XFRM_MSG_DELPOLICY)
2170                 out_hdr->sadb_msg_type = SADB_X_SPDDELETE2;
2171         else
2172                 out_hdr->sadb_msg_type = event2poltype(c->event);
2173         out_hdr->sadb_msg_errno = 0;
2174         out_hdr->sadb_msg_seq = c->seq;
2175         out_hdr->sadb_msg_pid = c->portid;
2176         pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ALL, NULL, xp_net(xp));
2177         return 0;
2178
2179 }
2180
2181 static int pfkey_spdadd(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
2182 {
2183         struct net *net = sock_net(sk);
2184         int err = 0;
2185         struct sadb_lifetime *lifetime;
2186         struct sadb_address *sa;
2187         struct sadb_x_policy *pol;
2188         struct xfrm_policy *xp;
2189         struct km_event c;
2190         struct sadb_x_sec_ctx *sec_ctx;
2191
2192         if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
2193                                      ext_hdrs[SADB_EXT_ADDRESS_DST-1]) ||
2194             !ext_hdrs[SADB_X_EXT_POLICY-1])
2195                 return -EINVAL;
2196
2197         pol = ext_hdrs[SADB_X_EXT_POLICY-1];
2198         if (pol->sadb_x_policy_type > IPSEC_POLICY_IPSEC)
2199                 return -EINVAL;
2200         if (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir >= IPSEC_DIR_MAX)
2201                 return -EINVAL;
2202
2203         xp = xfrm_policy_alloc(net, GFP_KERNEL);
2204         if (xp == NULL)
2205                 return -ENOBUFS;
2206
2207         xp->action = (pol->sadb_x_policy_type == IPSEC_POLICY_DISCARD ?
2208                       XFRM_POLICY_BLOCK : XFRM_POLICY_ALLOW);
2209         xp->priority = pol->sadb_x_policy_priority;
2210
2211         sa = ext_hdrs[SADB_EXT_ADDRESS_SRC-1];
2212         xp->family = pfkey_sadb_addr2xfrm_addr(sa, &xp->selector.saddr);
2213         xp->selector.family = xp->family;
2214         xp->selector.prefixlen_s = sa->sadb_address_prefixlen;
2215         xp->selector.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
2216         xp->selector.sport = ((struct sockaddr_in *)(sa+1))->sin_port;
2217         if (xp->selector.sport)
2218                 xp->selector.sport_mask = htons(0xffff);
2219
2220         sa = ext_hdrs[SADB_EXT_ADDRESS_DST-1];
2221         pfkey_sadb_addr2xfrm_addr(sa, &xp->selector.daddr);
2222         xp->selector.prefixlen_d = sa->sadb_address_prefixlen;
2223
2224         /* Amusing, we set this twice.  KAME apps appear to set same value
2225          * in both addresses.
2226          */
2227         xp->selector.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
2228
2229         xp->selector.dport = ((struct sockaddr_in *)(sa+1))->sin_port;
2230         if (xp->selector.dport)
2231                 xp->selector.dport_mask = htons(0xffff);
2232
2233         sec_ctx = ext_hdrs[SADB_X_EXT_SEC_CTX - 1];
2234         if (sec_ctx != NULL) {
2235                 struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx, GFP_KERNEL);
2236
2237                 if (!uctx) {
2238                         err = -ENOBUFS;
2239                         goto out;
2240                 }
2241
2242                 err = security_xfrm_policy_alloc(&xp->security, uctx, GFP_KERNEL);
2243                 kfree(uctx);
2244
2245                 if (err)
2246                         goto out;
2247         }
2248
2249         xp->lft.soft_byte_limit = XFRM_INF;
2250         xp->lft.hard_byte_limit = XFRM_INF;
2251         xp->lft.soft_packet_limit = XFRM_INF;
2252         xp->lft.hard_packet_limit = XFRM_INF;
2253         if ((lifetime = ext_hdrs[SADB_EXT_LIFETIME_HARD-1]) != NULL) {
2254                 xp->lft.hard_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations);
2255                 xp->lft.hard_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes);
2256                 xp->lft.hard_add_expires_seconds = lifetime->sadb_lifetime_addtime;
2257                 xp->lft.hard_use_expires_seconds = lifetime->sadb_lifetime_usetime;
2258         }
2259         if ((lifetime = ext_hdrs[SADB_EXT_LIFETIME_SOFT-1]) != NULL) {
2260                 xp->lft.soft_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations);
2261                 xp->lft.soft_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes);
2262                 xp->lft.soft_add_expires_seconds = lifetime->sadb_lifetime_addtime;
2263                 xp->lft.soft_use_expires_seconds = lifetime->sadb_lifetime_usetime;
2264         }
2265         xp->xfrm_nr = 0;
2266         if (pol->sadb_x_policy_type == IPSEC_POLICY_IPSEC &&
2267             (err = parse_ipsecrequests(xp, pol)) < 0)
2268                 goto out;
2269
2270         err = xfrm_policy_insert(pol->sadb_x_policy_dir-1, xp,
2271                                  hdr->sadb_msg_type != SADB_X_SPDUPDATE);
2272
2273         xfrm_audit_policy_add(xp, err ? 0 : 1,
2274                               audit_get_loginuid(current),
2275                               audit_get_sessionid(current), 0);
2276
2277         if (err)
2278                 goto out;
2279
2280         if (hdr->sadb_msg_type == SADB_X_SPDUPDATE)
2281                 c.event = XFRM_MSG_UPDPOLICY;
2282         else
2283                 c.event = XFRM_MSG_NEWPOLICY;
2284
2285         c.seq = hdr->sadb_msg_seq;
2286         c.portid = hdr->sadb_msg_pid;
2287
2288         km_policy_notify(xp, pol->sadb_x_policy_dir-1, &c);
2289         xfrm_pol_put(xp);
2290         return 0;
2291
2292 out:
2293         xp->walk.dead = 1;
2294         xfrm_policy_destroy(xp);
2295         return err;
2296 }
2297
2298 static int pfkey_spddelete(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
2299 {
2300         struct net *net = sock_net(sk);
2301         int err;
2302         struct sadb_address *sa;
2303         struct sadb_x_policy *pol;
2304         struct xfrm_policy *xp;
2305         struct xfrm_selector sel;
2306         struct km_event c;
2307         struct sadb_x_sec_ctx *sec_ctx;
2308         struct xfrm_sec_ctx *pol_ctx = NULL;
2309
2310         if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
2311                                      ext_hdrs[SADB_EXT_ADDRESS_DST-1]) ||
2312             !ext_hdrs[SADB_X_EXT_POLICY-1])
2313                 return -EINVAL;
2314
2315         pol = ext_hdrs[SADB_X_EXT_POLICY-1];
2316         if (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir >= IPSEC_DIR_MAX)
2317                 return -EINVAL;
2318
2319         memset(&sel, 0, sizeof(sel));
2320
2321         sa = ext_hdrs[SADB_EXT_ADDRESS_SRC-1];
2322         sel.family = pfkey_sadb_addr2xfrm_addr(sa, &sel.saddr);
2323         sel.prefixlen_s = sa->sadb_address_prefixlen;
2324         sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
2325         sel.sport = ((struct sockaddr_in *)(sa+1))->sin_port;
2326         if (sel.sport)
2327                 sel.sport_mask = htons(0xffff);
2328
2329         sa = ext_hdrs[SADB_EXT_ADDRESS_DST-1];
2330         pfkey_sadb_addr2xfrm_addr(sa, &sel.daddr);
2331         sel.prefixlen_d = sa->sadb_address_prefixlen;
2332         sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
2333         sel.dport = ((struct sockaddr_in *)(sa+1))->sin_port;
2334         if (sel.dport)
2335                 sel.dport_mask = htons(0xffff);
2336
2337         sec_ctx = ext_hdrs[SADB_X_EXT_SEC_CTX - 1];
2338         if (sec_ctx != NULL) {
2339                 struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx, GFP_KERNEL);
2340
2341                 if (!uctx)
2342                         return -ENOMEM;
2343
2344                 err = security_xfrm_policy_alloc(&pol_ctx, uctx, GFP_KERNEL);
2345                 kfree(uctx);
2346                 if (err)
2347                         return err;
2348         }
2349
2350         xp = xfrm_policy_bysel_ctx(net, DUMMY_MARK, XFRM_POLICY_TYPE_MAIN,
2351                                    pol->sadb_x_policy_dir - 1, &sel, pol_ctx,
2352                                    1, &err);
2353         security_xfrm_policy_free(pol_ctx);
2354         if (xp == NULL)
2355                 return -ENOENT;
2356
2357         xfrm_audit_policy_delete(xp, err ? 0 : 1,
2358                                  audit_get_loginuid(current),
2359                                  audit_get_sessionid(current), 0);
2360
2361         if (err)
2362                 goto out;
2363
2364         c.seq = hdr->sadb_msg_seq;
2365         c.portid = hdr->sadb_msg_pid;
2366         c.data.byid = 0;
2367         c.event = XFRM_MSG_DELPOLICY;
2368         km_policy_notify(xp, pol->sadb_x_policy_dir-1, &c);
2369
2370 out:
2371         xfrm_pol_put(xp);
2372         if (err == 0)
2373                 xfrm_garbage_collect(net);
2374         return err;
2375 }
2376
2377 static int key_pol_get_resp(struct sock *sk, struct xfrm_policy *xp, const struct sadb_msg *hdr, int dir)
2378 {
2379         int err;
2380         struct sk_buff *out_skb;
2381         struct sadb_msg *out_hdr;
2382         err = 0;
2383
2384         out_skb = pfkey_xfrm_policy2msg_prep(xp);
2385         if (IS_ERR(out_skb)) {
2386                 err =  PTR_ERR(out_skb);
2387                 goto out;
2388         }
2389         err = pfkey_xfrm_policy2msg(out_skb, xp, dir);
2390         if (err < 0)
2391                 goto out;
2392
2393         out_hdr = (struct sadb_msg *) out_skb->data;
2394         out_hdr->sadb_msg_version = hdr->sadb_msg_version;
2395         out_hdr->sadb_msg_type = hdr->sadb_msg_type;
2396         out_hdr->sadb_msg_satype = 0;
2397         out_hdr->sadb_msg_errno = 0;
2398         out_hdr->sadb_msg_seq = hdr->sadb_msg_seq;
2399         out_hdr->sadb_msg_pid = hdr->sadb_msg_pid;
2400         pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ONE, sk, xp_net(xp));
2401         err = 0;
2402
2403 out:
2404         return err;
2405 }
2406
2407 #ifdef CONFIG_NET_KEY_MIGRATE
2408 static int pfkey_sockaddr_pair_size(sa_family_t family)
2409 {
2410         return PFKEY_ALIGN8(pfkey_sockaddr_len(family) * 2);
2411 }
2412
2413 static int parse_sockaddr_pair(struct sockaddr *sa, int ext_len,
2414                                xfrm_address_t *saddr, xfrm_address_t *daddr,
2415                                u16 *family)
2416 {
2417         int af, socklen;
2418
2419         if (ext_len < pfkey_sockaddr_pair_size(sa->sa_family))
2420                 return -EINVAL;
2421
2422         af = pfkey_sockaddr_extract(sa, saddr);
2423         if (!af)
2424                 return -EINVAL;
2425
2426         socklen = pfkey_sockaddr_len(af);
2427         if (pfkey_sockaddr_extract((struct sockaddr *) (((u8 *)sa) + socklen),
2428                                    daddr) != af)
2429                 return -EINVAL;
2430
2431         *family = af;
2432         return 0;
2433 }
2434
2435 static int ipsecrequests_to_migrate(struct sadb_x_ipsecrequest *rq1, int len,
2436                                     struct xfrm_migrate *m)
2437 {
2438         int err;
2439         struct sadb_x_ipsecrequest *rq2;
2440         int mode;
2441
2442         if (len <= sizeof(struct sadb_x_ipsecrequest) ||
2443             len < rq1->sadb_x_ipsecrequest_len)
2444                 return -EINVAL;
2445
2446         /* old endoints */
2447         err = parse_sockaddr_pair((struct sockaddr *)(rq1 + 1),
2448                                   rq1->sadb_x_ipsecrequest_len,
2449                                   &m->old_saddr, &m->old_daddr,
2450                                   &m->old_family);
2451         if (err)
2452                 return err;
2453
2454         rq2 = (struct sadb_x_ipsecrequest *)((u8 *)rq1 + rq1->sadb_x_ipsecrequest_len);
2455         len -= rq1->sadb_x_ipsecrequest_len;
2456
2457         if (len <= sizeof(struct sadb_x_ipsecrequest) ||
2458             len < rq2->sadb_x_ipsecrequest_len)
2459                 return -EINVAL;
2460
2461         /* new endpoints */
2462         err = parse_sockaddr_pair((struct sockaddr *)(rq2 + 1),
2463                                   rq2->sadb_x_ipsecrequest_len,
2464                                   &m->new_saddr, &m->new_daddr,
2465                                   &m->new_family);
2466         if (err)
2467                 return err;
2468
2469         if (rq1->sadb_x_ipsecrequest_proto != rq2->sadb_x_ipsecrequest_proto ||
2470             rq1->sadb_x_ipsecrequest_mode != rq2->sadb_x_ipsecrequest_mode ||
2471             rq1->sadb_x_ipsecrequest_reqid != rq2->sadb_x_ipsecrequest_reqid)
2472                 return -EINVAL;
2473
2474         m->proto = rq1->sadb_x_ipsecrequest_proto;
2475         if ((mode = pfkey_mode_to_xfrm(rq1->sadb_x_ipsecrequest_mode)) < 0)
2476                 return -EINVAL;
2477         m->mode = mode;
2478         m->reqid = rq1->sadb_x_ipsecrequest_reqid;
2479
2480         return ((int)(rq1->sadb_x_ipsecrequest_len +
2481                       rq2->sadb_x_ipsecrequest_len));
2482 }
2483
2484 static int pfkey_migrate(struct sock *sk, struct sk_buff *skb,
2485                          const struct sadb_msg *hdr, void * const *ext_hdrs)
2486 {
2487         int i, len, ret, err = -EINVAL;
2488         u8 dir;
2489         struct sadb_address *sa;
2490         struct sadb_x_kmaddress *kma;
2491         struct sadb_x_policy *pol;
2492         struct sadb_x_ipsecrequest *rq;
2493         struct xfrm_selector sel;
2494         struct xfrm_migrate m[XFRM_MAX_DEPTH];
2495         struct xfrm_kmaddress k;
2496         struct net *net = sock_net(sk);
2497
2498         if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC - 1],
2499                                      ext_hdrs[SADB_EXT_ADDRESS_DST - 1]) ||
2500             !ext_hdrs[SADB_X_EXT_POLICY - 1]) {
2501                 err = -EINVAL;
2502                 goto out;
2503         }
2504
2505         kma = ext_hdrs[SADB_X_EXT_KMADDRESS - 1];
2506         pol = ext_hdrs[SADB_X_EXT_POLICY - 1];
2507
2508         if (pol->sadb_x_policy_dir >= IPSEC_DIR_MAX) {
2509                 err = -EINVAL;
2510                 goto out;
2511         }
2512
2513         if (kma) {
2514                 /* convert sadb_x_kmaddress to xfrm_kmaddress */
2515                 k.reserved = kma->sadb_x_kmaddress_reserved;
2516                 ret = parse_sockaddr_pair((struct sockaddr *)(kma + 1),
2517                                           8*(kma->sadb_x_kmaddress_len) - sizeof(*kma),
2518                                           &k.local, &k.remote, &k.family);
2519                 if (ret < 0) {
2520                         err = ret;
2521                         goto out;
2522                 }
2523         }
2524
2525         dir = pol->sadb_x_policy_dir - 1;
2526         memset(&sel, 0, sizeof(sel));
2527
2528         /* set source address info of selector */
2529         sa = ext_hdrs[SADB_EXT_ADDRESS_SRC - 1];
2530         sel.family = pfkey_sadb_addr2xfrm_addr(sa, &sel.saddr);
2531         sel.prefixlen_s = sa->sadb_address_prefixlen;
2532         sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
2533         sel.sport = ((struct sockaddr_in *)(sa + 1))->sin_port;
2534         if (sel.sport)
2535                 sel.sport_mask = htons(0xffff);
2536
2537         /* set destination address info of selector */
2538         sa = ext_hdrs[SADB_EXT_ADDRESS_DST - 1],
2539         pfkey_sadb_addr2xfrm_addr(sa, &sel.daddr);
2540         sel.prefixlen_d = sa->sadb_address_prefixlen;
2541         sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
2542         sel.dport = ((struct sockaddr_in *)(sa + 1))->sin_port;
2543         if (sel.dport)
2544                 sel.dport_mask = htons(0xffff);
2545
2546         rq = (struct sadb_x_ipsecrequest *)(pol + 1);
2547
2548         /* extract ipsecrequests */
2549         i = 0;
2550         len = pol->sadb_x_policy_len * 8 - sizeof(struct sadb_x_policy);
2551
2552         while (len > 0 && i < XFRM_MAX_DEPTH) {
2553                 ret = ipsecrequests_to_migrate(rq, len, &m[i]);
2554                 if (ret < 0) {
2555                         err = ret;
2556                         goto out;
2557                 } else {
2558                         rq = (struct sadb_x_ipsecrequest *)((u8 *)rq + ret);
2559                         len -= ret;
2560                         i++;
2561                 }
2562         }
2563
2564         if (!i || len > 0) {
2565                 err = -EINVAL;
2566                 goto out;
2567         }
2568
2569         return xfrm_migrate(&sel, dir, XFRM_POLICY_TYPE_MAIN, m, i,
2570                             kma ? &k : NULL, net);
2571
2572  out:
2573         return err;
2574 }
2575 #else
2576 static int pfkey_migrate(struct sock *sk, struct sk_buff *skb,
2577                          const struct sadb_msg *hdr, void * const *ext_hdrs)
2578 {
2579         return -ENOPROTOOPT;
2580 }
2581 #endif
2582
2583
2584 static int pfkey_spdget(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
2585 {
2586         struct net *net = sock_net(sk);
2587         unsigned int dir;
2588         int err = 0, delete;
2589         struct sadb_x_policy *pol;
2590         struct xfrm_policy *xp;
2591         struct km_event c;
2592
2593         if ((pol = ext_hdrs[SADB_X_EXT_POLICY-1]) == NULL)
2594                 return -EINVAL;
2595
2596         dir = xfrm_policy_id2dir(pol->sadb_x_policy_id);
2597         if (dir >= XFRM_POLICY_MAX)
2598                 return -EINVAL;
2599
2600         delete = (hdr->sadb_msg_type == SADB_X_SPDDELETE2);
2601         xp = xfrm_policy_byid(net, DUMMY_MARK, XFRM_POLICY_TYPE_MAIN,
2602                               dir, pol->sadb_x_policy_id, delete, &err);
2603         if (xp == NULL)
2604                 return -ENOENT;
2605
2606         if (delete) {
2607                 xfrm_audit_policy_delete(xp, err ? 0 : 1,
2608                                 audit_get_loginuid(current),
2609                                 audit_get_sessionid(current), 0);
2610
2611                 if (err)
2612                         goto out;
2613                 c.seq = hdr->sadb_msg_seq;
2614                 c.portid = hdr->sadb_msg_pid;
2615                 c.data.byid = 1;
2616                 c.event = XFRM_MSG_DELPOLICY;
2617                 km_policy_notify(xp, dir, &c);
2618         } else {
2619                 err = key_pol_get_resp(sk, xp, hdr, dir);
2620         }
2621
2622 out:
2623         xfrm_pol_put(xp);
2624         if (delete && err == 0)
2625                 xfrm_garbage_collect(net);
2626         return err;
2627 }
2628
2629 static int dump_sp(struct xfrm_policy *xp, int dir, int count, void *ptr)
2630 {
2631         struct pfkey_sock *pfk = ptr;
2632         struct sk_buff *out_skb;
2633         struct sadb_msg *out_hdr;
2634         int err;
2635
2636         if (!pfkey_can_dump(&pfk->sk))
2637                 return -ENOBUFS;
2638
2639         out_skb = pfkey_xfrm_policy2msg_prep(xp);
2640         if (IS_ERR(out_skb))
2641                 return PTR_ERR(out_skb);
2642
2643         err = pfkey_xfrm_policy2msg(out_skb, xp, dir);
2644         if (err < 0)
2645                 return err;
2646
2647         out_hdr = (struct sadb_msg *) out_skb->data;
2648         out_hdr->sadb_msg_version = pfk->dump.msg_version;
2649         out_hdr->sadb_msg_type = SADB_X_SPDDUMP;
2650         out_hdr->sadb_msg_satype = SADB_SATYPE_UNSPEC;
2651         out_hdr->sadb_msg_errno = 0;
2652         out_hdr->sadb_msg_seq = count + 1;
2653         out_hdr->sadb_msg_pid = pfk->dump.msg_portid;
2654
2655         if (pfk->dump.skb)
2656                 pfkey_broadcast(pfk->dump.skb, GFP_ATOMIC, BROADCAST_ONE,
2657                                 &pfk->sk, sock_net(&pfk->sk));
2658         pfk->dump.skb = out_skb;
2659
2660         return 0;
2661 }
2662
2663 static int pfkey_dump_sp(struct pfkey_sock *pfk)
2664 {
2665         struct net *net = sock_net(&pfk->sk);
2666         return xfrm_policy_walk(net, &pfk->dump.u.policy, dump_sp, (void *) pfk);
2667 }
2668
2669 static void pfkey_dump_sp_done(struct pfkey_sock *pfk)
2670 {
2671         struct net *net = sock_net((struct sock *)pfk);
2672
2673         xfrm_policy_walk_done(&pfk->dump.u.policy, net);
2674 }
2675
2676 static int pfkey_spddump(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
2677 {
2678         struct pfkey_sock *pfk = pfkey_sk(sk);
2679
2680         if (pfk->dump.dump != NULL)
2681                 return -EBUSY;
2682
2683         pfk->dump.msg_version = hdr->sadb_msg_version;
2684         pfk->dump.msg_portid = hdr->sadb_msg_pid;
2685         pfk->dump.dump = pfkey_dump_sp;
2686         pfk->dump.done = pfkey_dump_sp_done;
2687         xfrm_policy_walk_init(&pfk->dump.u.policy, XFRM_POLICY_TYPE_MAIN);
2688
2689         return pfkey_do_dump(pfk);
2690 }
2691
2692 static int key_notify_policy_flush(const struct km_event *c)
2693 {
2694         struct sk_buff *skb_out;
2695         struct sadb_msg *hdr;
2696
2697         skb_out = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC);
2698         if (!skb_out)
2699                 return -ENOBUFS;
2700         hdr = (struct sadb_msg *) skb_put(skb_out, sizeof(struct sadb_msg));
2701         hdr->sadb_msg_type = SADB_X_SPDFLUSH;
2702         hdr->sadb_msg_seq = c->seq;
2703         hdr->sadb_msg_pid = c->portid;
2704         hdr->sadb_msg_version = PF_KEY_V2;
2705         hdr->sadb_msg_errno = (uint8_t) 0;
2706         hdr->sadb_msg_satype = SADB_SATYPE_UNSPEC;
2707         hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t));
2708         hdr->sadb_msg_reserved = 0;
2709         pfkey_broadcast(skb_out, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net);
2710         return 0;
2711
2712 }
2713
2714 static int pfkey_spdflush(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
2715 {
2716         struct net *net = sock_net(sk);
2717         struct km_event c;
2718         struct xfrm_audit audit_info;
2719         int err, err2;
2720
2721         audit_info.loginuid = audit_get_loginuid(current);
2722         audit_info.sessionid = audit_get_sessionid(current);
2723         audit_info.secid = 0;
2724         err = xfrm_policy_flush(net, XFRM_POLICY_TYPE_MAIN, &audit_info);
2725         err2 = unicast_flush_resp(sk, hdr);
2726         if (err || err2) {
2727                 if (err == -ESRCH) /* empty table - old silent behavior */
2728                         return 0;
2729                 return err;
2730         }
2731
2732         c.data.type = XFRM_POLICY_TYPE_MAIN;
2733         c.event = XFRM_MSG_FLUSHPOLICY;
2734         c.portid = hdr->sadb_msg_pid;
2735         c.seq = hdr->sadb_msg_seq;
2736         c.net = net;
2737         km_policy_notify(NULL, 0, &c);
2738
2739         return 0;
2740 }
2741
2742 typedef int (*pfkey_handler)(struct sock *sk, struct sk_buff *skb,
2743                              const struct sadb_msg *hdr, void * const *ext_hdrs);
2744 static const pfkey_handler pfkey_funcs[SADB_MAX + 1] = {
2745         [SADB_RESERVED]         = pfkey_reserved,
2746         [SADB_GETSPI]           = pfkey_getspi,
2747         [SADB_UPDATE]           = pfkey_add,
2748         [SADB_ADD]              = pfkey_add,
2749         [SADB_DELETE]           = pfkey_delete,
2750         [SADB_GET]              = pfkey_get,
2751         [SADB_ACQUIRE]          = pfkey_acquire,
2752         [SADB_REGISTER]         = pfkey_register,
2753         [SADB_EXPIRE]           = NULL,
2754         [SADB_FLUSH]            = pfkey_flush,
2755         [SADB_DUMP]             = pfkey_dump,
2756         [SADB_X_PROMISC]        = pfkey_promisc,
2757         [SADB_X_PCHANGE]        = NULL,
2758         [SADB_X_SPDUPDATE]      = pfkey_spdadd,
2759         [SADB_X_SPDADD]         = pfkey_spdadd,
2760         [SADB_X_SPDDELETE]      = pfkey_spddelete,
2761         [SADB_X_SPDGET]         = pfkey_spdget,
2762         [SADB_X_SPDACQUIRE]     = NULL,
2763         [SADB_X_SPDDUMP]        = pfkey_spddump,
2764         [SADB_X_SPDFLUSH]       = pfkey_spdflush,
2765         [SADB_X_SPDSETIDX]      = pfkey_spdadd,
2766         [SADB_X_SPDDELETE2]     = pfkey_spdget,
2767         [SADB_X_MIGRATE]        = pfkey_migrate,
2768 };
2769
2770 static int pfkey_process(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr)
2771 {
2772         void *ext_hdrs[SADB_EXT_MAX];
2773         int err;
2774
2775         pfkey_broadcast(skb_clone(skb, GFP_KERNEL), GFP_KERNEL,
2776                         BROADCAST_PROMISC_ONLY, NULL, sock_net(sk));
2777
2778         memset(ext_hdrs, 0, sizeof(ext_hdrs));
2779         err = parse_exthdrs(skb, hdr, ext_hdrs);
2780         if (!err) {
2781                 err = -EOPNOTSUPP;
2782                 if (pfkey_funcs[hdr->sadb_msg_type])
2783                         err = pfkey_funcs[hdr->sadb_msg_type](sk, skb, hdr, ext_hdrs);
2784         }
2785         return err;
2786 }
2787
2788 static struct sadb_msg *pfkey_get_base_msg(struct sk_buff *skb, int *errp)
2789 {
2790         struct sadb_msg *hdr = NULL;
2791
2792         if (skb->len < sizeof(*hdr)) {
2793                 *errp = -EMSGSIZE;
2794         } else {
2795                 hdr = (struct sadb_msg *) skb->data;
2796                 if (hdr->sadb_msg_version != PF_KEY_V2 ||
2797                     hdr->sadb_msg_reserved != 0 ||
2798                     (hdr->sadb_msg_type <= SADB_RESERVED ||
2799                      hdr->sadb_msg_type > SADB_MAX)) {
2800                         hdr = NULL;
2801                         *errp = -EINVAL;
2802                 } else if (hdr->sadb_msg_len != (skb->len /
2803                                                  sizeof(uint64_t)) ||
2804                            hdr->sadb_msg_len < (sizeof(struct sadb_msg) /
2805                                                 sizeof(uint64_t))) {
2806                         hdr = NULL;
2807                         *errp = -EMSGSIZE;
2808                 } else {
2809                         *errp = 0;
2810                 }
2811         }
2812         return hdr;
2813 }
2814
2815 static inline int aalg_tmpl_set(const struct xfrm_tmpl *t,
2816                                 const struct xfrm_algo_desc *d)
2817 {
2818         unsigned int id = d->desc.sadb_alg_id;
2819
2820         if (id >= sizeof(t->aalgos) * 8)
2821                 return 0;
2822
2823         return (t->aalgos >> id) & 1;
2824 }
2825
2826 static inline int ealg_tmpl_set(const struct xfrm_tmpl *t,
2827                                 const struct xfrm_algo_desc *d)
2828 {
2829         unsigned int id = d->desc.sadb_alg_id;
2830
2831         if (id >= sizeof(t->ealgos) * 8)
2832                 return 0;
2833
2834         return (t->ealgos >> id) & 1;
2835 }
2836
2837 static int count_ah_combs(const struct xfrm_tmpl *t)
2838 {
2839         int i, sz = 0;
2840
2841         for (i = 0; ; i++) {
2842                 const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i);
2843                 if (!aalg)
2844                         break;
2845                 if (!aalg->pfkey_supported)
2846                         continue;
2847                 if (aalg_tmpl_set(t, aalg) && aalg->available)
2848                         sz += sizeof(struct sadb_comb);
2849         }
2850         return sz + sizeof(struct sadb_prop);
2851 }
2852
2853 static int count_esp_combs(const struct xfrm_tmpl *t)
2854 {
2855         int i, k, sz = 0;
2856
2857         for (i = 0; ; i++) {
2858                 const struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i);
2859                 if (!ealg)
2860                         break;
2861
2862                 if (!ealg->pfkey_supported)
2863                         continue;
2864
2865                 if (!(ealg_tmpl_set(t, ealg) && ealg->available))
2866                         continue;
2867
2868                 for (k = 1; ; k++) {
2869                         const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(k);
2870                         if (!aalg)
2871                                 break;
2872
2873                         if (!aalg->pfkey_supported)
2874                                 continue;
2875
2876                         if (aalg_tmpl_set(t, aalg) && aalg->available)
2877                                 sz += sizeof(struct sadb_comb);
2878                 }
2879         }
2880         return sz + sizeof(struct sadb_prop);
2881 }
2882
2883 static void dump_ah_combs(struct sk_buff *skb, const struct xfrm_tmpl *t)
2884 {
2885         struct sadb_prop *p;
2886         int i;
2887
2888         p = (struct sadb_prop*)skb_put(skb, sizeof(struct sadb_prop));
2889         p->sadb_prop_len = sizeof(struct sadb_prop)/8;
2890         p->sadb_prop_exttype = SADB_EXT_PROPOSAL;
2891         p->sadb_prop_replay = 32;
2892         memset(p->sadb_prop_reserved, 0, sizeof(p->sadb_prop_reserved));
2893
2894         for (i = 0; ; i++) {
2895                 const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i);
2896                 if (!aalg)
2897                         break;
2898
2899                 if (!aalg->pfkey_supported)
2900                         continue;
2901
2902                 if (aalg_tmpl_set(t, aalg) && aalg->available) {
2903                         struct sadb_comb *c;
2904                         c = (struct sadb_comb*)skb_put(skb, sizeof(struct sadb_comb));
2905                         memset(c, 0, sizeof(*c));
2906                         p->sadb_prop_len += sizeof(struct sadb_comb)/8;
2907                         c->sadb_comb_auth = aalg->desc.sadb_alg_id;
2908                         c->sadb_comb_auth_minbits = aalg->desc.sadb_alg_minbits;
2909                         c->sadb_comb_auth_maxbits = aalg->desc.sadb_alg_maxbits;
2910                         c->sadb_comb_hard_addtime = 24*60*60;
2911                         c->sadb_comb_soft_addtime = 20*60*60;
2912                         c->sadb_comb_hard_usetime = 8*60*60;
2913                         c->sadb_comb_soft_usetime = 7*60*60;
2914                 }
2915         }
2916 }
2917
2918 static void dump_esp_combs(struct sk_buff *skb, const struct xfrm_tmpl *t)
2919 {
2920         struct sadb_prop *p;
2921         int i, k;
2922
2923         p = (struct sadb_prop*)skb_put(skb, sizeof(struct sadb_prop));
2924         p->sadb_prop_len = sizeof(struct sadb_prop)/8;
2925         p->sadb_prop_exttype = SADB_EXT_PROPOSAL;
2926         p->sadb_prop_replay = 32;
2927         memset(p->sadb_prop_reserved, 0, sizeof(p->sadb_prop_reserved));
2928
2929         for (i=0; ; i++) {
2930                 const struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i);
2931                 if (!ealg)
2932                         break;
2933
2934                 if (!ealg->pfkey_supported)
2935                         continue;
2936
2937                 if (!(ealg_tmpl_set(t, ealg) && ealg->available))
2938                         continue;
2939
2940                 for (k = 1; ; k++) {
2941                         struct sadb_comb *c;
2942                         const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(k);
2943                         if (!aalg)
2944                                 break;
2945                         if (!aalg->pfkey_supported)
2946                                 continue;
2947                         if (!(aalg_tmpl_set(t, aalg) && aalg->available))
2948                                 continue;
2949                         c = (struct sadb_comb*)skb_put(skb, sizeof(struct sadb_comb));
2950                         memset(c, 0, sizeof(*c));
2951                         p->sadb_prop_len += sizeof(struct sadb_comb)/8;
2952                         c->sadb_comb_auth = aalg->desc.sadb_alg_id;
2953                         c->sadb_comb_auth_minbits = aalg->desc.sadb_alg_minbits;
2954                         c->sadb_comb_auth_maxbits = aalg->desc.sadb_alg_maxbits;
2955                         c->sadb_comb_encrypt = ealg->desc.sadb_alg_id;
2956                         c->sadb_comb_encrypt_minbits = ealg->desc.sadb_alg_minbits;
2957                         c->sadb_comb_encrypt_maxbits = ealg->desc.sadb_alg_maxbits;
2958                         c->sadb_comb_hard_addtime = 24*60*60;
2959                         c->sadb_comb_soft_addtime = 20*60*60;
2960                         c->sadb_comb_hard_usetime = 8*60*60;
2961                         c->sadb_comb_soft_usetime = 7*60*60;
2962                 }
2963         }
2964 }
2965
2966 static int key_notify_policy_expire(struct xfrm_policy *xp, const struct km_event *c)
2967 {
2968         return 0;
2969 }
2970
2971 static int key_notify_sa_expire(struct xfrm_state *x, const struct km_event *c)
2972 {
2973         struct sk_buff *out_skb;
2974         struct sadb_msg *out_hdr;
2975         int hard;
2976         int hsc;
2977
2978         hard = c->data.hard;
2979         if (hard)
2980                 hsc = 2;
2981         else
2982                 hsc = 1;
2983
2984         out_skb = pfkey_xfrm_state2msg_expire(x, hsc);
2985         if (IS_ERR(out_skb))
2986                 return PTR_ERR(out_skb);
2987
2988         out_hdr = (struct sadb_msg *) out_skb->data;
2989         out_hdr->sadb_msg_version = PF_KEY_V2;
2990         out_hdr->sadb_msg_type = SADB_EXPIRE;
2991         out_hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto);
2992         out_hdr->sadb_msg_errno = 0;
2993         out_hdr->sadb_msg_reserved = 0;
2994         out_hdr->sadb_msg_seq = 0;
2995         out_hdr->sadb_msg_pid = 0;
2996
2997         pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL, xs_net(x));
2998         return 0;
2999 }
3000
3001 static int pfkey_send_notify(struct xfrm_state *x, const struct km_event *c)
3002 {
3003         struct net *net = x ? xs_net(x) : c->net;
3004         struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id);
3005
3006         if (atomic_read(&net_pfkey->socks_nr) == 0)
3007                 return 0;
3008
3009         switch (c->event) {
3010         case XFRM_MSG_EXPIRE:
3011                 return key_notify_sa_expire(x, c);
3012         case XFRM_MSG_DELSA:
3013         case XFRM_MSG_NEWSA:
3014         case XFRM_MSG_UPDSA:
3015                 return key_notify_sa(x, c);
3016         case XFRM_MSG_FLUSHSA:
3017                 return key_notify_sa_flush(c);
3018         case XFRM_MSG_NEWAE: /* not yet supported */
3019                 break;
3020         default:
3021                 pr_err("pfkey: Unknown SA event %d\n", c->event);
3022                 break;
3023         }
3024
3025         return 0;
3026 }
3027
3028 static int pfkey_send_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c)
3029 {
3030         if (xp && xp->type != XFRM_POLICY_TYPE_MAIN)
3031                 return 0;
3032
3033         switch (c->event) {
3034         case XFRM_MSG_POLEXPIRE:
3035                 return key_notify_policy_expire(xp, c);
3036         case XFRM_MSG_DELPOLICY:
3037         case XFRM_MSG_NEWPOLICY:
3038         case XFRM_MSG_UPDPOLICY:
3039                 return key_notify_policy(xp, dir, c);
3040         case XFRM_MSG_FLUSHPOLICY:
3041                 if (c->data.type != XFRM_POLICY_TYPE_MAIN)
3042                         break;
3043                 return key_notify_policy_flush(c);
3044         default:
3045                 pr_err("pfkey: Unknown policy event %d\n", c->event);
3046                 break;
3047         }
3048
3049         return 0;
3050 }
3051
3052 static u32 get_acqseq(void)
3053 {
3054         u32 res;
3055         static atomic_t acqseq;
3056
3057         do {
3058                 res = atomic_inc_return(&acqseq);
3059         } while (!res);
3060         return res;
3061 }
3062
3063 static int pfkey_send_acquire(struct xfrm_state *x, struct xfrm_tmpl *t, struct xfrm_policy *xp)
3064 {
3065         struct sk_buff *skb;
3066         struct sadb_msg *hdr;
3067         struct sadb_address *addr;
3068         struct sadb_x_policy *pol;
3069         int sockaddr_size;
3070         int size;
3071         struct sadb_x_sec_ctx *sec_ctx;
3072         struct xfrm_sec_ctx *xfrm_ctx;
3073         int ctx_size = 0;
3074
3075         sockaddr_size = pfkey_sockaddr_size(x->props.family);
3076         if (!sockaddr_size)
3077                 return -EINVAL;
3078
3079         size = sizeof(struct sadb_msg) +
3080                 (sizeof(struct sadb_address) * 2) +
3081                 (sockaddr_size * 2) +
3082                 sizeof(struct sadb_x_policy);
3083
3084         if (x->id.proto == IPPROTO_AH)
3085                 size += count_ah_combs(t);
3086         else if (x->id.proto == IPPROTO_ESP)
3087                 size += count_esp_combs(t);
3088
3089         if ((xfrm_ctx = x->security)) {
3090                 ctx_size = PFKEY_ALIGN8(xfrm_ctx->ctx_len);
3091                 size +=  sizeof(struct sadb_x_sec_ctx) + ctx_size;
3092         }
3093
3094         skb =  alloc_skb(size + 16, GFP_ATOMIC);
3095         if (skb == NULL)
3096                 return -ENOMEM;
3097
3098         hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
3099         hdr->sadb_msg_version = PF_KEY_V2;
3100         hdr->sadb_msg_type = SADB_ACQUIRE;
3101         hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto);
3102         hdr->sadb_msg_len = size / sizeof(uint64_t);
3103         hdr->sadb_msg_errno = 0;
3104         hdr->sadb_msg_reserved = 0;
3105         hdr->sadb_msg_seq = x->km.seq = get_acqseq();
3106         hdr->sadb_msg_pid = 0;
3107
3108         /* src address */
3109         addr = (struct sadb_address*) skb_put(skb,
3110                                               sizeof(struct sadb_address)+sockaddr_size);
3111         addr->sadb_address_len =
3112                 (sizeof(struct sadb_address)+sockaddr_size)/
3113                         sizeof(uint64_t);
3114         addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
3115         addr->sadb_address_proto = 0;
3116         addr->sadb_address_reserved = 0;
3117         addr->sadb_address_prefixlen =
3118                 pfkey_sockaddr_fill(&x->props.saddr, 0,
3119                                     (struct sockaddr *) (addr + 1),
3120                                     x->props.family);
3121         if (!addr->sadb_address_prefixlen)
3122                 BUG();
3123
3124         /* dst address */
3125         addr = (struct sadb_address*) skb_put(skb,
3126                                               sizeof(struct sadb_address)+sockaddr_size);
3127         addr->sadb_address_len =
3128                 (sizeof(struct sadb_address)+sockaddr_size)/
3129                         sizeof(uint64_t);
3130         addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
3131         addr->sadb_address_proto = 0;
3132         addr->sadb_address_reserved = 0;
3133         addr->sadb_address_prefixlen =
3134                 pfkey_sockaddr_fill(&x->id.daddr, 0,
3135                                     (struct sockaddr *) (addr + 1),
3136                                     x->props.family);
3137         if (!addr->sadb_address_prefixlen)
3138                 BUG();
3139
3140         pol = (struct sadb_x_policy *)  skb_put(skb, sizeof(struct sadb_x_policy));
3141         pol->sadb_x_policy_len = sizeof(struct sadb_x_policy)/sizeof(uint64_t);
3142         pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3143         pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
3144         pol->sadb_x_policy_dir = XFRM_POLICY_OUT + 1;
3145         pol->sadb_x_policy_reserved = 0;
3146         pol->sadb_x_policy_id = xp->index;
3147         pol->sadb_x_policy_priority = xp->priority;
3148
3149         /* Set sadb_comb's. */
3150         if (x->id.proto == IPPROTO_AH)
3151                 dump_ah_combs(skb, t);
3152         else if (x->id.proto == IPPROTO_ESP)
3153                 dump_esp_combs(skb, t);
3154
3155         /* security context */
3156         if (xfrm_ctx) {
3157                 sec_ctx = (struct sadb_x_sec_ctx *) skb_put(skb,
3158                                 sizeof(struct sadb_x_sec_ctx) + ctx_size);
3159                 sec_ctx->sadb_x_sec_len =
3160                   (sizeof(struct sadb_x_sec_ctx) + ctx_size) / sizeof(uint64_t);
3161                 sec_ctx->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX;
3162                 sec_ctx->sadb_x_ctx_doi = xfrm_ctx->ctx_doi;
3163                 sec_ctx->sadb_x_ctx_alg = xfrm_ctx->ctx_alg;
3164                 sec_ctx->sadb_x_ctx_len = xfrm_ctx->ctx_len;
3165                 memcpy(sec_ctx + 1, xfrm_ctx->ctx_str,
3166                        xfrm_ctx->ctx_len);
3167         }
3168
3169         return pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL, xs_net(x));
3170 }
3171
3172 static struct xfrm_policy *pfkey_compile_policy(struct sock *sk, int opt,
3173                                                 u8 *data, int len, int *dir)
3174 {
3175         struct net *net = sock_net(sk);
3176         struct xfrm_policy *xp;
3177         struct sadb_x_policy *pol = (struct sadb_x_policy*)data;
3178         struct sadb_x_sec_ctx *sec_ctx;
3179
3180         switch (sk->sk_family) {
3181         case AF_INET:
3182                 if (opt != IP_IPSEC_POLICY) {
3183                         *dir = -EOPNOTSUPP;
3184                         return NULL;
3185                 }
3186                 break;
3187 #if IS_ENABLED(CONFIG_IPV6)
3188         case AF_INET6:
3189                 if (opt != IPV6_IPSEC_POLICY) {
3190                         *dir = -EOPNOTSUPP;
3191                         return NULL;
3192                 }
3193                 break;
3194 #endif
3195         default:
3196                 *dir = -EINVAL;
3197                 return NULL;
3198         }
3199
3200         *dir = -EINVAL;
3201
3202         if (len < sizeof(struct sadb_x_policy) ||
3203             pol->sadb_x_policy_len*8 > len ||
3204             pol->sadb_x_policy_type > IPSEC_POLICY_BYPASS ||
3205             (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir > IPSEC_DIR_OUTBOUND))
3206                 return NULL;
3207
3208         xp = xfrm_policy_alloc(net, GFP_ATOMIC);
3209         if (xp == NULL) {
3210                 *dir = -ENOBUFS;
3211                 return NULL;
3212         }
3213
3214         xp->action = (pol->sadb_x_policy_type == IPSEC_POLICY_DISCARD ?
3215                       XFRM_POLICY_BLOCK : XFRM_POLICY_ALLOW);
3216
3217         xp->lft.soft_byte_limit = XFRM_INF;
3218         xp->lft.hard_byte_limit = XFRM_INF;
3219         xp->lft.soft_packet_limit = XFRM_INF;
3220         xp->lft.hard_packet_limit = XFRM_INF;
3221         xp->family = sk->sk_family;
3222
3223         xp->xfrm_nr = 0;
3224         if (pol->sadb_x_policy_type == IPSEC_POLICY_IPSEC &&
3225             (*dir = parse_ipsecrequests(xp, pol)) < 0)
3226                 goto out;
3227
3228         /* security context too */
3229         if (len >= (pol->sadb_x_policy_len*8 +
3230             sizeof(struct sadb_x_sec_ctx))) {
3231                 char *p = (char *)pol;
3232                 struct xfrm_user_sec_ctx *uctx;
3233
3234                 p += pol->sadb_x_policy_len*8;
3235                 sec_ctx = (struct sadb_x_sec_ctx *)p;
3236                 if (len < pol->sadb_x_policy_len*8 +
3237                     sec_ctx->sadb_x_sec_len) {
3238                         *dir = -EINVAL;
3239                         goto out;
3240                 }
3241                 if ((*dir = verify_sec_ctx_len(p)))
3242                         goto out;
3243                 uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx, GFP_ATOMIC);
3244                 *dir = security_xfrm_policy_alloc(&xp->security, uctx, GFP_ATOMIC);
3245                 kfree(uctx);
3246
3247                 if (*dir)
3248                         goto out;
3249         }
3250
3251         *dir = pol->sadb_x_policy_dir-1;
3252         return xp;
3253
3254 out:
3255         xp->walk.dead = 1;
3256         xfrm_policy_destroy(xp);
3257         return NULL;
3258 }
3259
3260 static int pfkey_send_new_mapping(struct xfrm_state *x, xfrm_address_t *ipaddr, __be16 sport)
3261 {
3262         struct sk_buff *skb;
3263         struct sadb_msg *hdr;
3264         struct sadb_sa *sa;
3265         struct sadb_address *addr;
3266         struct sadb_x_nat_t_port *n_port;
3267         int sockaddr_size;
3268         int size;
3269         __u8 satype = (x->id.proto == IPPROTO_ESP ? SADB_SATYPE_ESP : 0);
3270         struct xfrm_encap_tmpl *natt = NULL;
3271
3272         sockaddr_size = pfkey_sockaddr_size(x->props.family);
3273         if (!sockaddr_size)
3274                 return -EINVAL;
3275
3276         if (!satype)
3277                 return -EINVAL;
3278
3279         if (!x->encap)
3280                 return -EINVAL;
3281
3282         natt = x->encap;
3283
3284         /* Build an SADB_X_NAT_T_NEW_MAPPING message:
3285          *
3286          * HDR | SA | ADDRESS_SRC (old addr) | NAT_T_SPORT (old port) |
3287          * ADDRESS_DST (new addr) | NAT_T_DPORT (new port)
3288          */
3289
3290         size = sizeof(struct sadb_msg) +
3291                 sizeof(struct sadb_sa) +
3292                 (sizeof(struct sadb_address) * 2) +
3293                 (sockaddr_size * 2) +
3294                 (sizeof(struct sadb_x_nat_t_port) * 2);
3295
3296         skb =  alloc_skb(size + 16, GFP_ATOMIC);
3297         if (skb == NULL)
3298                 return -ENOMEM;
3299
3300         hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
3301         hdr->sadb_msg_version = PF_KEY_V2;
3302         hdr->sadb_msg_type = SADB_X_NAT_T_NEW_MAPPING;
3303         hdr->sadb_msg_satype = satype;
3304         hdr->sadb_msg_len = size / sizeof(uint64_t);
3305         hdr->sadb_msg_errno = 0;
3306         hdr->sadb_msg_reserved = 0;
3307         hdr->sadb_msg_seq = x->km.seq = get_acqseq();
3308         hdr->sadb_msg_pid = 0;
3309
3310         /* SA */
3311         sa = (struct sadb_sa *) skb_put(skb, sizeof(struct sadb_sa));
3312         sa->sadb_sa_len = sizeof(struct sadb_sa)/sizeof(uint64_t);
3313         sa->sadb_sa_exttype = SADB_EXT_SA;
3314         sa->sadb_sa_spi = x->id.spi;
3315         sa->sadb_sa_replay = 0;
3316         sa->sadb_sa_state = 0;
3317         sa->sadb_sa_auth = 0;
3318         sa->sadb_sa_encrypt = 0;
3319         sa->sadb_sa_flags = 0;
3320
3321         /* ADDRESS_SRC (old addr) */
3322         addr = (struct sadb_address*)
3323                 skb_put(skb, sizeof(struct sadb_address)+sockaddr_size);
3324         addr->sadb_address_len =
3325                 (sizeof(struct sadb_address)+sockaddr_size)/
3326                         sizeof(uint64_t);
3327         addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
3328         addr->sadb_address_proto = 0;
3329         addr->sadb_address_reserved = 0;
3330         addr->sadb_address_prefixlen =
3331                 pfkey_sockaddr_fill(&x->props.saddr, 0,
3332                                     (struct sockaddr *) (addr + 1),
3333                                     x->props.family);
3334         if (!addr->sadb_address_prefixlen)
3335                 BUG();
3336
3337         /* NAT_T_SPORT (old port) */
3338         n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port));
3339         n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t);
3340         n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_SPORT;
3341         n_port->sadb_x_nat_t_port_port = natt->encap_sport;
3342         n_port->sadb_x_nat_t_port_reserved = 0;
3343
3344         /* ADDRESS_DST (new addr) */
3345         addr = (struct sadb_address*)
3346                 skb_put(skb, sizeof(struct sadb_address)+sockaddr_size);
3347         addr->sadb_address_len =
3348                 (sizeof(struct sadb_address)+sockaddr_size)/
3349                         sizeof(uint64_t);
3350         addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
3351         addr->sadb_address_proto = 0;
3352         addr->sadb_address_reserved = 0;
3353         addr->sadb_address_prefixlen =
3354                 pfkey_sockaddr_fill(ipaddr, 0,
3355                                     (struct sockaddr *) (addr + 1),
3356                                     x->props.family);
3357         if (!addr->sadb_address_prefixlen)
3358                 BUG();
3359
3360         /* NAT_T_DPORT (new port) */
3361         n_port = (struct sadb_x_nat_t_port*) skb_put(skb, sizeof (*n_port));
3362         n_port->sadb_x_nat_t_port_len = sizeof(*n_port)/sizeof(uint64_t);
3363         n_port->sadb_x_nat_t_port_exttype = SADB_X_EXT_NAT_T_DPORT;
3364         n_port->sadb_x_nat_t_port_port = sport;
3365         n_port->sadb_x_nat_t_port_reserved = 0;
3366
3367         return pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL, xs_net(x));
3368 }
3369
3370 #ifdef CONFIG_NET_KEY_MIGRATE
3371 static int set_sadb_address(struct sk_buff *skb, int sasize, int type,
3372                             const struct xfrm_selector *sel)
3373 {
3374         struct sadb_address *addr;
3375         addr = (struct sadb_address *)skb_put(skb, sizeof(struct sadb_address) + sasize);
3376         addr->sadb_address_len = (sizeof(struct sadb_address) + sasize)/8;
3377         addr->sadb_address_exttype = type;
3378         addr->sadb_address_proto = sel->proto;
3379         addr->sadb_address_reserved = 0;
3380
3381         switch (type) {
3382         case SADB_EXT_ADDRESS_SRC:
3383                 addr->sadb_address_prefixlen = sel->prefixlen_s;
3384                 pfkey_sockaddr_fill(&sel->saddr, 0,
3385                                     (struct sockaddr *)(addr + 1),
3386                                     sel->family);
3387                 break;
3388         case SADB_EXT_ADDRESS_DST:
3389                 addr->sadb_address_prefixlen = sel->prefixlen_d;
3390                 pfkey_sockaddr_fill(&sel->daddr, 0,
3391                                     (struct sockaddr *)(addr + 1),
3392                                     sel->family);
3393                 break;
3394         default:
3395                 return -EINVAL;
3396         }
3397
3398         return 0;
3399 }
3400
3401
3402 static int set_sadb_kmaddress(struct sk_buff *skb, const struct xfrm_kmaddress *k)
3403 {
3404         struct sadb_x_kmaddress *kma;
3405         u8 *sa;
3406         int family = k->family;
3407         int socklen = pfkey_sockaddr_len(family);
3408         int size_req;
3409
3410         size_req = (sizeof(struct sadb_x_kmaddress) +
3411                     pfkey_sockaddr_pair_size(family));
3412
3413         kma = (struct sadb_x_kmaddress *)skb_put(skb, size_req);
3414         memset(kma, 0, size_req);
3415         kma->sadb_x_kmaddress_len = size_req / 8;
3416         kma->sadb_x_kmaddress_exttype = SADB_X_EXT_KMADDRESS;
3417         kma->sadb_x_kmaddress_reserved = k->reserved;
3418
3419         sa = (u8 *)(kma + 1);
3420         if (!pfkey_sockaddr_fill(&k->local, 0, (struct sockaddr *)sa, family) ||
3421             !pfkey_sockaddr_fill(&k->remote, 0, (struct sockaddr *)(sa+socklen), family))
3422                 return -EINVAL;
3423
3424         return 0;
3425 }
3426
3427 static int set_ipsecrequest(struct sk_buff *skb,
3428                             uint8_t proto, uint8_t mode, int level,
3429                             uint32_t reqid, uint8_t family,
3430                             const xfrm_address_t *src, const xfrm_address_t *dst)
3431 {
3432         struct sadb_x_ipsecrequest *rq;
3433         u8 *sa;
3434         int socklen = pfkey_sockaddr_len(family);
3435         int size_req;
3436
3437         size_req = sizeof(struct sadb_x_ipsecrequest) +
3438                    pfkey_sockaddr_pair_size(family);
3439
3440         rq = (struct sadb_x_ipsecrequest *)skb_put(skb, size_req);
3441         memset(rq, 0, size_req);
3442         rq->sadb_x_ipsecrequest_len = size_req;
3443         rq->sadb_x_ipsecrequest_proto = proto;
3444         rq->sadb_x_ipsecrequest_mode = mode;
3445         rq->sadb_x_ipsecrequest_level = level;
3446         rq->sadb_x_ipsecrequest_reqid = reqid;
3447
3448         sa = (u8 *) (rq + 1);
3449         if (!pfkey_sockaddr_fill(src, 0, (struct sockaddr *)sa, family) ||
3450             !pfkey_sockaddr_fill(dst, 0, (struct sockaddr *)(sa + socklen), family))
3451                 return -EINVAL;
3452
3453         return 0;
3454 }
3455 #endif
3456
3457 #ifdef CONFIG_NET_KEY_MIGRATE
3458 static int pfkey_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
3459                               const struct xfrm_migrate *m, int num_bundles,
3460                               const struct xfrm_kmaddress *k)
3461 {
3462         int i;
3463         int sasize_sel;
3464         int size = 0;
3465         int size_pol = 0;
3466         struct sk_buff *skb;
3467         struct sadb_msg *hdr;
3468         struct sadb_x_policy *pol;
3469         const struct xfrm_migrate *mp;
3470
3471         if (type != XFRM_POLICY_TYPE_MAIN)
3472                 return 0;
3473
3474         if (num_bundles <= 0 || num_bundles > XFRM_MAX_DEPTH)
3475                 return -EINVAL;
3476
3477         if (k != NULL) {
3478                 /* addresses for KM */
3479                 size += PFKEY_ALIGN8(sizeof(struct sadb_x_kmaddress) +
3480                                      pfkey_sockaddr_pair_size(k->family));
3481         }
3482
3483         /* selector */
3484         sasize_sel = pfkey_sockaddr_size(sel->family);
3485         if (!sasize_sel)
3486                 return -EINVAL;
3487         size += (sizeof(struct sadb_address) + sasize_sel) * 2;
3488
3489         /* policy info */
3490         size_pol += sizeof(struct sadb_x_policy);
3491
3492         /* ipsecrequests */
3493         for (i = 0, mp = m; i < num_bundles; i++, mp++) {
3494                 /* old locator pair */
3495                 size_pol += sizeof(struct sadb_x_ipsecrequest) +
3496                             pfkey_sockaddr_pair_size(mp->old_family);
3497                 /* new locator pair */
3498                 size_pol += sizeof(struct sadb_x_ipsecrequest) +
3499                             pfkey_sockaddr_pair_size(mp->new_family);
3500         }
3501
3502         size += sizeof(struct sadb_msg) + size_pol;
3503
3504         /* alloc buffer */
3505         skb = alloc_skb(size, GFP_ATOMIC);
3506         if (skb == NULL)
3507                 return -ENOMEM;
3508
3509         hdr = (struct sadb_msg *)skb_put(skb, sizeof(struct sadb_msg));
3510         hdr->sadb_msg_version = PF_KEY_V2;
3511         hdr->sadb_msg_type = SADB_X_MIGRATE;
3512         hdr->sadb_msg_satype = pfkey_proto2satype(m->proto);
3513         hdr->sadb_msg_len = size / 8;
3514         hdr->sadb_msg_errno = 0;
3515         hdr->sadb_msg_reserved = 0;
3516         hdr->sadb_msg_seq = 0;
3517         hdr->sadb_msg_pid = 0;
3518
3519         /* Addresses to be used by KM for negotiation, if ext is available */
3520         if (k != NULL && (set_sadb_kmaddress(skb, k) < 0))
3521                 goto err;
3522
3523         /* selector src */
3524         set_sadb_address(skb, sasize_sel, SADB_EXT_ADDRESS_SRC, sel);
3525
3526         /* selector dst */
3527         set_sadb_address(skb, sasize_sel, SADB_EXT_ADDRESS_DST, sel);
3528
3529         /* policy information */
3530         pol = (struct sadb_x_policy *)skb_put(skb, sizeof(struct sadb_x_policy));
3531         pol->sadb_x_policy_len = size_pol / 8;
3532         pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3533         pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
3534         pol->sadb_x_policy_dir = dir + 1;
3535         pol->sadb_x_policy_reserved = 0;
3536         pol->sadb_x_policy_id = 0;
3537         pol->sadb_x_policy_priority = 0;
3538
3539         for (i = 0, mp = m; i < num_bundles; i++, mp++) {
3540                 /* old ipsecrequest */
3541                 int mode = pfkey_mode_from_xfrm(mp->mode);
3542                 if (mode < 0)
3543                         goto err;
3544                 if (set_ipsecrequest(skb, mp->proto, mode,
3545                                      (mp->reqid ?  IPSEC_LEVEL_UNIQUE : IPSEC_LEVEL_REQUIRE),
3546                                      mp->reqid, mp->old_family,
3547                                      &mp->old_saddr, &mp->old_daddr) < 0)
3548                         goto err;
3549
3550                 /* new ipsecrequest */
3551                 if (set_ipsecrequest(skb, mp->proto, mode,
3552                                      (mp->reqid ? IPSEC_LEVEL_UNIQUE : IPSEC_LEVEL_REQUIRE),
3553                                      mp->reqid, mp->new_family,
3554                                      &mp->new_saddr, &mp->new_daddr) < 0)
3555                         goto err;
3556         }
3557
3558         /* broadcast migrate message to sockets */
3559         pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, &init_net);
3560
3561         return 0;
3562
3563 err:
3564         kfree_skb(skb);
3565         return -EINVAL;
3566 }
3567 #else
3568 static int pfkey_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,
3569                               const struct xfrm_migrate *m, int num_bundles,
3570                               const struct xfrm_kmaddress *k)
3571 {
3572         return -ENOPROTOOPT;
3573 }
3574 #endif
3575
3576 static int pfkey_sendmsg(struct kiocb *kiocb,
3577                          struct socket *sock, struct msghdr *msg, size_t len)
3578 {
3579         struct sock *sk = sock->sk;
3580         struct sk_buff *skb = NULL;
3581         struct sadb_msg *hdr = NULL;
3582         int err;
3583         struct net *net = sock_net(sk);
3584
3585         err = -EOPNOTSUPP;
3586         if (msg->msg_flags & MSG_OOB)
3587                 goto out;
3588
3589         err = -EMSGSIZE;
3590         if ((unsigned int)len > sk->sk_sndbuf - 32)
3591                 goto out;
3592
3593         err = -ENOBUFS;
3594         skb = alloc_skb(len, GFP_KERNEL);
3595         if (skb == NULL)
3596                 goto out;
3597
3598         err = -EFAULT;
3599         if (memcpy_fromiovec(skb_put(skb,len), msg->msg_iov, len))
3600                 goto out;
3601
3602         hdr = pfkey_get_base_msg(skb, &err);
3603         if (!hdr)
3604                 goto out;
3605
3606         mutex_lock(&net->xfrm.xfrm_cfg_mutex);
3607         err = pfkey_process(sk, skb, hdr);
3608         mutex_unlock(&net->xfrm.xfrm_cfg_mutex);
3609
3610 out:
3611         if (err && hdr && pfkey_error(hdr, err, sk) == 0)
3612                 err = 0;
3613         kfree_skb(skb);
3614
3615         return err ? : len;
3616 }
3617
3618 static int pfkey_recvmsg(struct kiocb *kiocb,
3619                          struct socket *sock, struct msghdr *msg, size_t len,
3620                          int flags)
3621 {
3622         struct sock *sk = sock->sk;
3623         struct pfkey_sock *pfk = pfkey_sk(sk);
3624         struct sk_buff *skb;
3625         int copied, err;
3626
3627         err = -EINVAL;
3628         if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT))
3629                 goto out;
3630
3631         skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);
3632         if (skb == NULL)
3633                 goto out;
3634
3635         copied = skb->len;
3636         if (copied > len) {
3637                 msg->msg_flags |= MSG_TRUNC;
3638                 copied = len;
3639         }
3640
3641         skb_reset_transport_header(skb);
3642         err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
3643         if (err)
3644                 goto out_free;
3645
3646         sock_recv_ts_and_drops(msg, sk, skb);
3647
3648         err = (flags & MSG_TRUNC) ? skb->len : copied;
3649
3650         if (pfk->dump.dump != NULL &&
3651             3 * atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf)
3652                 pfkey_do_dump(pfk);
3653
3654 out_free:
3655         skb_free_datagram(sk, skb);
3656 out:
3657         return err;
3658 }
3659
3660 static const struct proto_ops pfkey_ops = {
3661         .family         =       PF_KEY,
3662         .owner          =       THIS_MODULE,
3663         /* Operations that make no sense on pfkey sockets. */
3664         .bind           =       sock_no_bind,
3665         .connect        =       sock_no_connect,
3666         .socketpair     =       sock_no_socketpair,
3667         .accept         =       sock_no_accept,
3668         .getname        =       sock_no_getname,
3669         .ioctl          =       sock_no_ioctl,
3670         .listen         =       sock_no_listen,
3671         .shutdown       =       sock_no_shutdown,
3672         .setsockopt     =       sock_no_setsockopt,
3673         .getsockopt     =       sock_no_getsockopt,
3674         .mmap           =       sock_no_mmap,
3675         .sendpage       =       sock_no_sendpage,
3676
3677         /* Now the operations that really occur. */
3678         .release        =       pfkey_release,
3679         .poll           =       datagram_poll,
3680         .sendmsg        =       pfkey_sendmsg,
3681         .recvmsg        =       pfkey_recvmsg,
3682 };
3683
3684 static const struct net_proto_family pfkey_family_ops = {
3685         .family =       PF_KEY,
3686         .create =       pfkey_create,
3687         .owner  =       THIS_MODULE,
3688 };
3689
3690 #ifdef CONFIG_PROC_FS
3691 static int pfkey_seq_show(struct seq_file *f, void *v)
3692 {
3693         struct sock *s = sk_entry(v);
3694
3695         if (v == SEQ_START_TOKEN)
3696                 seq_printf(f ,"sk       RefCnt Rmem   Wmem   User   Inode\n");
3697         else
3698                 seq_printf(f, "%pK %-6d %-6u %-6u %-6u %-6lu\n",
3699                                s,
3700                                atomic_read(&s->sk_refcnt),
3701                                sk_rmem_alloc_get(s),
3702                                sk_wmem_alloc_get(s),
3703                                from_kuid_munged(seq_user_ns(f), sock_i_uid(s)),
3704                                sock_i_ino(s)
3705                                );
3706         return 0;
3707 }
3708
3709 static void *pfkey_seq_start(struct seq_file *f, loff_t *ppos)
3710         __acquires(rcu)
3711 {
3712         struct net *net = seq_file_net(f);
3713         struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id);
3714
3715         rcu_read_lock();
3716         return seq_hlist_start_head_rcu(&net_pfkey->table, *ppos);
3717 }
3718
3719 static void *pfkey_seq_next(struct seq_file *f, void *v, loff_t *ppos)
3720 {
3721         struct net *net = seq_file_net(f);
3722         struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id);
3723
3724         return seq_hlist_next_rcu(v, &net_pfkey->table, ppos);
3725 }
3726
3727 static void pfkey_seq_stop(struct seq_file *f, void *v)
3728         __releases(rcu)
3729 {
3730         rcu_read_unlock();
3731 }
3732
3733 static const struct seq_operations pfkey_seq_ops = {
3734         .start  = pfkey_seq_start,
3735         .next   = pfkey_seq_next,
3736         .stop   = pfkey_seq_stop,
3737         .show   = pfkey_seq_show,
3738 };
3739
3740 static int pfkey_seq_open(struct inode *inode, struct file *file)
3741 {
3742         return seq_open_net(inode, file, &pfkey_seq_ops,
3743                             sizeof(struct seq_net_private));
3744 }
3745
3746 static const struct file_operations pfkey_proc_ops = {
3747         .open    = pfkey_seq_open,
3748         .read    = seq_read,
3749         .llseek  = seq_lseek,
3750         .release = seq_release_net,
3751 };
3752
3753 static int __net_init pfkey_init_proc(struct net *net)
3754 {
3755         struct proc_dir_entry *e;
3756
3757         e = proc_create("pfkey", 0, net->proc_net, &pfkey_proc_ops);
3758         if (e == NULL)
3759                 return -ENOMEM;
3760
3761         return 0;
3762 }
3763
3764 static void __net_exit pfkey_exit_proc(struct net *net)
3765 {
3766         remove_proc_entry("pfkey", net->proc_net);
3767 }
3768 #else
3769 static inline int pfkey_init_proc(struct net *net)
3770 {
3771         return 0;
3772 }
3773
3774 static inline void pfkey_exit_proc(struct net *net)
3775 {
3776 }
3777 #endif
3778
3779 static struct xfrm_mgr pfkeyv2_mgr =
3780 {
3781         .id             = "pfkeyv2",
3782         .notify         = pfkey_send_notify,
3783         .acquire        = pfkey_send_acquire,
3784         .compile_policy = pfkey_compile_policy,
3785         .new_mapping    = pfkey_send_new_mapping,
3786         .notify_policy  = pfkey_send_policy_notify,
3787         .migrate        = pfkey_send_migrate,
3788 };
3789
3790 static int __net_init pfkey_net_init(struct net *net)
3791 {
3792         struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id);
3793         int rv;
3794
3795         INIT_HLIST_HEAD(&net_pfkey->table);
3796         atomic_set(&net_pfkey->socks_nr, 0);
3797
3798         rv = pfkey_init_proc(net);
3799
3800         return rv;
3801 }
3802
3803 static void __net_exit pfkey_net_exit(struct net *net)
3804 {
3805         struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id);
3806
3807         pfkey_exit_proc(net);
3808         BUG_ON(!hlist_empty(&net_pfkey->table));
3809 }
3810
3811 static struct pernet_operations pfkey_net_ops = {
3812         .init = pfkey_net_init,
3813         .exit = pfkey_net_exit,
3814         .id   = &pfkey_net_id,
3815         .size = sizeof(struct netns_pfkey),
3816 };
3817
3818 static void __exit ipsec_pfkey_exit(void)
3819 {
3820         xfrm_unregister_km(&pfkeyv2_mgr);
3821         sock_unregister(PF_KEY);
3822         unregister_pernet_subsys(&pfkey_net_ops);
3823         proto_unregister(&key_proto);
3824 }
3825
3826 static int __init ipsec_pfkey_init(void)
3827 {
3828         int err = proto_register(&key_proto, 0);
3829
3830         if (err != 0)
3831                 goto out;
3832
3833         err = register_pernet_subsys(&pfkey_net_ops);
3834         if (err != 0)
3835                 goto out_unregister_key_proto;
3836         err = sock_register(&pfkey_family_ops);
3837         if (err != 0)
3838                 goto out_unregister_pernet;
3839         err = xfrm_register_km(&pfkeyv2_mgr);
3840         if (err != 0)
3841                 goto out_sock_unregister;
3842 out:
3843         return err;
3844
3845 out_sock_unregister:
3846         sock_unregister(PF_KEY);
3847 out_unregister_pernet:
3848         unregister_pernet_subsys(&pfkey_net_ops);
3849 out_unregister_key_proto:
3850         proto_unregister(&key_proto);
3851         goto out;
3852 }
3853
3854 module_init(ipsec_pfkey_init);
3855 module_exit(ipsec_pfkey_exit);
3856 MODULE_LICENSE("GPL");
3857 MODULE_ALIAS_NETPROTO(PF_KEY);