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