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