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