OSDN Git Service

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