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