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