af_key: do not use GFP_KERNEL in atomic contexts
[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, gfp_t allocation,
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, allocation, 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, GFP_ATOMIC, 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, GFP_KERNEL, 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         err = -ENOBUFS;
1156         key = ext_hdrs[SADB_EXT_KEY_AUTH - 1];
1157         if (sa->sadb_sa_auth) {
1158                 int keysize = 0;
1159                 struct xfrm_algo_desc *a = xfrm_aalg_get_byid(sa->sadb_sa_auth);
1160                 if (!a) {
1161                         err = -ENOSYS;
1162                         goto out;
1163                 }
1164                 if (key)
1165                         keysize = (key->sadb_key_bits + 7) / 8;
1166                 x->aalg = kmalloc(sizeof(*x->aalg) + keysize, GFP_KERNEL);
1167                 if (!x->aalg) {
1168                         err = -ENOMEM;
1169                         goto out;
1170                 }
1171                 strcpy(x->aalg->alg_name, a->name);
1172                 x->aalg->alg_key_len = 0;
1173                 if (key) {
1174                         x->aalg->alg_key_len = key->sadb_key_bits;
1175                         memcpy(x->aalg->alg_key, key+1, keysize);
1176                 }
1177                 x->aalg->alg_trunc_len = a->uinfo.auth.icv_truncbits;
1178                 x->props.aalgo = sa->sadb_sa_auth;
1179                 /* x->algo.flags = sa->sadb_sa_flags; */
1180         }
1181         if (sa->sadb_sa_encrypt) {
1182                 if (hdr->sadb_msg_satype == SADB_X_SATYPE_IPCOMP) {
1183                         struct xfrm_algo_desc *a = xfrm_calg_get_byid(sa->sadb_sa_encrypt);
1184                         if (!a) {
1185                                 err = -ENOSYS;
1186                                 goto out;
1187                         }
1188                         x->calg = kmalloc(sizeof(*x->calg), GFP_KERNEL);
1189                         if (!x->calg) {
1190                                 err = -ENOMEM;
1191                                 goto out;
1192                         }
1193                         strcpy(x->calg->alg_name, a->name);
1194                         x->props.calgo = sa->sadb_sa_encrypt;
1195                 } else {
1196                         int keysize = 0;
1197                         struct xfrm_algo_desc *a = xfrm_ealg_get_byid(sa->sadb_sa_encrypt);
1198                         if (!a) {
1199                                 err = -ENOSYS;
1200                                 goto out;
1201                         }
1202                         key = (struct sadb_key*) ext_hdrs[SADB_EXT_KEY_ENCRYPT-1];
1203                         if (key)
1204                                 keysize = (key->sadb_key_bits + 7) / 8;
1205                         x->ealg = kmalloc(sizeof(*x->ealg) + keysize, GFP_KERNEL);
1206                         if (!x->ealg) {
1207                                 err = -ENOMEM;
1208                                 goto out;
1209                         }
1210                         strcpy(x->ealg->alg_name, a->name);
1211                         x->ealg->alg_key_len = 0;
1212                         if (key) {
1213                                 x->ealg->alg_key_len = key->sadb_key_bits;
1214                                 memcpy(x->ealg->alg_key, key+1, keysize);
1215                         }
1216                         x->props.ealgo = sa->sadb_sa_encrypt;
1217                 }
1218         }
1219         /* x->algo.flags = sa->sadb_sa_flags; */
1220
1221         x->props.family = pfkey_sadb_addr2xfrm_addr((struct sadb_address *) ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
1222                                                     &x->props.saddr);
1223         if (!x->props.family) {
1224                 err = -EAFNOSUPPORT;
1225                 goto out;
1226         }
1227         pfkey_sadb_addr2xfrm_addr((struct sadb_address *) ext_hdrs[SADB_EXT_ADDRESS_DST-1],
1228                                   &x->id.daddr);
1229
1230         if (ext_hdrs[SADB_X_EXT_SA2-1]) {
1231                 const struct sadb_x_sa2 *sa2 = ext_hdrs[SADB_X_EXT_SA2-1];
1232                 int mode = pfkey_mode_to_xfrm(sa2->sadb_x_sa2_mode);
1233                 if (mode < 0) {
1234                         err = -EINVAL;
1235                         goto out;
1236                 }
1237                 x->props.mode = mode;
1238                 x->props.reqid = sa2->sadb_x_sa2_reqid;
1239         }
1240
1241         if (ext_hdrs[SADB_EXT_ADDRESS_PROXY-1]) {
1242                 const struct sadb_address *addr = ext_hdrs[SADB_EXT_ADDRESS_PROXY-1];
1243
1244                 /* Nobody uses this, but we try. */
1245                 x->sel.family = pfkey_sadb_addr2xfrm_addr(addr, &x->sel.saddr);
1246                 x->sel.prefixlen_s = addr->sadb_address_prefixlen;
1247         }
1248
1249         if (!x->sel.family)
1250                 x->sel.family = x->props.family;
1251
1252         if (ext_hdrs[SADB_X_EXT_NAT_T_TYPE-1]) {
1253                 const struct sadb_x_nat_t_type* n_type;
1254                 struct xfrm_encap_tmpl *natt;
1255
1256                 x->encap = kmalloc(sizeof(*x->encap), GFP_KERNEL);
1257                 if (!x->encap) {
1258                         err = -ENOMEM;
1259                         goto out;
1260                 }
1261
1262                 natt = x->encap;
1263                 n_type = ext_hdrs[SADB_X_EXT_NAT_T_TYPE-1];
1264                 natt->encap_type = n_type->sadb_x_nat_t_type_type;
1265
1266                 if (ext_hdrs[SADB_X_EXT_NAT_T_SPORT-1]) {
1267                         const struct sadb_x_nat_t_port *n_port =
1268                                 ext_hdrs[SADB_X_EXT_NAT_T_SPORT-1];
1269                         natt->encap_sport = n_port->sadb_x_nat_t_port_port;
1270                 }
1271                 if (ext_hdrs[SADB_X_EXT_NAT_T_DPORT-1]) {
1272                         const struct sadb_x_nat_t_port *n_port =
1273                                 ext_hdrs[SADB_X_EXT_NAT_T_DPORT-1];
1274                         natt->encap_dport = n_port->sadb_x_nat_t_port_port;
1275                 }
1276                 memset(&natt->encap_oa, 0, sizeof(natt->encap_oa));
1277         }
1278
1279         err = xfrm_init_state(x);
1280         if (err)
1281                 goto out;
1282
1283         x->km.seq = hdr->sadb_msg_seq;
1284         return x;
1285
1286 out:
1287         x->km.state = XFRM_STATE_DEAD;
1288         xfrm_state_put(x);
1289         return ERR_PTR(err);
1290 }
1291
1292 static int pfkey_reserved(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
1293 {
1294         return -EOPNOTSUPP;
1295 }
1296
1297 static int pfkey_getspi(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
1298 {
1299         struct net *net = sock_net(sk);
1300         struct sk_buff *resp_skb;
1301         struct sadb_x_sa2 *sa2;
1302         struct sadb_address *saddr, *daddr;
1303         struct sadb_msg *out_hdr;
1304         struct sadb_spirange *range;
1305         struct xfrm_state *x = NULL;
1306         int mode;
1307         int err;
1308         u32 min_spi, max_spi;
1309         u32 reqid;
1310         u8 proto;
1311         unsigned short family;
1312         xfrm_address_t *xsaddr = NULL, *xdaddr = NULL;
1313
1314         if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
1315                                      ext_hdrs[SADB_EXT_ADDRESS_DST-1]))
1316                 return -EINVAL;
1317
1318         proto = pfkey_satype2proto(hdr->sadb_msg_satype);
1319         if (proto == 0)
1320                 return -EINVAL;
1321
1322         if ((sa2 = ext_hdrs[SADB_X_EXT_SA2-1]) != NULL) {
1323                 mode = pfkey_mode_to_xfrm(sa2->sadb_x_sa2_mode);
1324                 if (mode < 0)
1325                         return -EINVAL;
1326                 reqid = sa2->sadb_x_sa2_reqid;
1327         } else {
1328                 mode = 0;
1329                 reqid = 0;
1330         }
1331
1332         saddr = ext_hdrs[SADB_EXT_ADDRESS_SRC-1];
1333         daddr = ext_hdrs[SADB_EXT_ADDRESS_DST-1];
1334
1335         family = ((struct sockaddr *)(saddr + 1))->sa_family;
1336         switch (family) {
1337         case AF_INET:
1338                 xdaddr = (xfrm_address_t *)&((struct sockaddr_in *)(daddr + 1))->sin_addr.s_addr;
1339                 xsaddr = (xfrm_address_t *)&((struct sockaddr_in *)(saddr + 1))->sin_addr.s_addr;
1340                 break;
1341 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
1342         case AF_INET6:
1343                 xdaddr = (xfrm_address_t *)&((struct sockaddr_in6 *)(daddr + 1))->sin6_addr;
1344                 xsaddr = (xfrm_address_t *)&((struct sockaddr_in6 *)(saddr + 1))->sin6_addr;
1345                 break;
1346 #endif
1347         }
1348
1349         if (hdr->sadb_msg_seq) {
1350                 x = xfrm_find_acq_byseq(net, DUMMY_MARK, hdr->sadb_msg_seq);
1351                 if (x && xfrm_addr_cmp(&x->id.daddr, xdaddr, family)) {
1352                         xfrm_state_put(x);
1353                         x = NULL;
1354                 }
1355         }
1356
1357         if (!x)
1358                 x = xfrm_find_acq(net, &dummy_mark, mode, reqid, proto, xdaddr, xsaddr, 1, family);
1359
1360         if (x == NULL)
1361                 return -ENOENT;
1362
1363         min_spi = 0x100;
1364         max_spi = 0x0fffffff;
1365
1366         range = ext_hdrs[SADB_EXT_SPIRANGE-1];
1367         if (range) {
1368                 min_spi = range->sadb_spirange_min;
1369                 max_spi = range->sadb_spirange_max;
1370         }
1371
1372         err = xfrm_alloc_spi(x, min_spi, max_spi);
1373         resp_skb = err ? ERR_PTR(err) : pfkey_xfrm_state2msg(x);
1374
1375         if (IS_ERR(resp_skb)) {
1376                 xfrm_state_put(x);
1377                 return  PTR_ERR(resp_skb);
1378         }
1379
1380         out_hdr = (struct sadb_msg *) resp_skb->data;
1381         out_hdr->sadb_msg_version = hdr->sadb_msg_version;
1382         out_hdr->sadb_msg_type = SADB_GETSPI;
1383         out_hdr->sadb_msg_satype = pfkey_proto2satype(proto);
1384         out_hdr->sadb_msg_errno = 0;
1385         out_hdr->sadb_msg_reserved = 0;
1386         out_hdr->sadb_msg_seq = hdr->sadb_msg_seq;
1387         out_hdr->sadb_msg_pid = hdr->sadb_msg_pid;
1388
1389         xfrm_state_put(x);
1390
1391         pfkey_broadcast(resp_skb, GFP_KERNEL, BROADCAST_ONE, sk, net);
1392
1393         return 0;
1394 }
1395
1396 static int pfkey_acquire(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
1397 {
1398         struct net *net = sock_net(sk);
1399         struct xfrm_state *x;
1400
1401         if (hdr->sadb_msg_len != sizeof(struct sadb_msg)/8)
1402                 return -EOPNOTSUPP;
1403
1404         if (hdr->sadb_msg_seq == 0 || hdr->sadb_msg_errno == 0)
1405                 return 0;
1406
1407         x = xfrm_find_acq_byseq(net, DUMMY_MARK, hdr->sadb_msg_seq);
1408         if (x == NULL)
1409                 return 0;
1410
1411         spin_lock_bh(&x->lock);
1412         if (x->km.state == XFRM_STATE_ACQ) {
1413                 x->km.state = XFRM_STATE_ERROR;
1414                 wake_up(&net->xfrm.km_waitq);
1415         }
1416         spin_unlock_bh(&x->lock);
1417         xfrm_state_put(x);
1418         return 0;
1419 }
1420
1421 static inline int event2poltype(int event)
1422 {
1423         switch (event) {
1424         case XFRM_MSG_DELPOLICY:
1425                 return SADB_X_SPDDELETE;
1426         case XFRM_MSG_NEWPOLICY:
1427                 return SADB_X_SPDADD;
1428         case XFRM_MSG_UPDPOLICY:
1429                 return SADB_X_SPDUPDATE;
1430         case XFRM_MSG_POLEXPIRE:
1431         //      return SADB_X_SPDEXPIRE;
1432         default:
1433                 pr_err("pfkey: Unknown policy event %d\n", event);
1434                 break;
1435         }
1436
1437         return 0;
1438 }
1439
1440 static inline int event2keytype(int event)
1441 {
1442         switch (event) {
1443         case XFRM_MSG_DELSA:
1444                 return SADB_DELETE;
1445         case XFRM_MSG_NEWSA:
1446                 return SADB_ADD;
1447         case XFRM_MSG_UPDSA:
1448                 return SADB_UPDATE;
1449         case XFRM_MSG_EXPIRE:
1450                 return SADB_EXPIRE;
1451         default:
1452                 pr_err("pfkey: Unknown SA event %d\n", event);
1453                 break;
1454         }
1455
1456         return 0;
1457 }
1458
1459 /* ADD/UPD/DEL */
1460 static int key_notify_sa(struct xfrm_state *x, const struct km_event *c)
1461 {
1462         struct sk_buff *skb;
1463         struct sadb_msg *hdr;
1464
1465         skb = pfkey_xfrm_state2msg(x);
1466
1467         if (IS_ERR(skb))
1468                 return PTR_ERR(skb);
1469
1470         hdr = (struct sadb_msg *) skb->data;
1471         hdr->sadb_msg_version = PF_KEY_V2;
1472         hdr->sadb_msg_type = event2keytype(c->event);
1473         hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto);
1474         hdr->sadb_msg_errno = 0;
1475         hdr->sadb_msg_reserved = 0;
1476         hdr->sadb_msg_seq = c->seq;
1477         hdr->sadb_msg_pid = c->pid;
1478
1479         pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, xs_net(x));
1480
1481         return 0;
1482 }
1483
1484 static int pfkey_add(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
1485 {
1486         struct net *net = sock_net(sk);
1487         struct xfrm_state *x;
1488         int err;
1489         struct km_event c;
1490
1491         x = pfkey_msg2xfrm_state(net, hdr, ext_hdrs);
1492         if (IS_ERR(x))
1493                 return PTR_ERR(x);
1494
1495         xfrm_state_hold(x);
1496         if (hdr->sadb_msg_type == SADB_ADD)
1497                 err = xfrm_state_add(x);
1498         else
1499                 err = xfrm_state_update(x);
1500
1501         xfrm_audit_state_add(x, err ? 0 : 1,
1502                              audit_get_loginuid(current),
1503                              audit_get_sessionid(current), 0);
1504
1505         if (err < 0) {
1506                 x->km.state = XFRM_STATE_DEAD;
1507                 __xfrm_state_put(x);
1508                 goto out;
1509         }
1510
1511         if (hdr->sadb_msg_type == SADB_ADD)
1512                 c.event = XFRM_MSG_NEWSA;
1513         else
1514                 c.event = XFRM_MSG_UPDSA;
1515         c.seq = hdr->sadb_msg_seq;
1516         c.pid = hdr->sadb_msg_pid;
1517         km_state_notify(x, &c);
1518 out:
1519         xfrm_state_put(x);
1520         return err;
1521 }
1522
1523 static int pfkey_delete(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
1524 {
1525         struct net *net = sock_net(sk);
1526         struct xfrm_state *x;
1527         struct km_event c;
1528         int err;
1529
1530         if (!ext_hdrs[SADB_EXT_SA-1] ||
1531             !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
1532                                      ext_hdrs[SADB_EXT_ADDRESS_DST-1]))
1533                 return -EINVAL;
1534
1535         x = pfkey_xfrm_state_lookup(net, hdr, ext_hdrs);
1536         if (x == NULL)
1537                 return -ESRCH;
1538
1539         if ((err = security_xfrm_state_delete(x)))
1540                 goto out;
1541
1542         if (xfrm_state_kern(x)) {
1543                 err = -EPERM;
1544                 goto out;
1545         }
1546
1547         err = xfrm_state_delete(x);
1548
1549         if (err < 0)
1550                 goto out;
1551
1552         c.seq = hdr->sadb_msg_seq;
1553         c.pid = hdr->sadb_msg_pid;
1554         c.event = XFRM_MSG_DELSA;
1555         km_state_notify(x, &c);
1556 out:
1557         xfrm_audit_state_delete(x, err ? 0 : 1,
1558                                 audit_get_loginuid(current),
1559                                 audit_get_sessionid(current), 0);
1560         xfrm_state_put(x);
1561
1562         return err;
1563 }
1564
1565 static int pfkey_get(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
1566 {
1567         struct net *net = sock_net(sk);
1568         __u8 proto;
1569         struct sk_buff *out_skb;
1570         struct sadb_msg *out_hdr;
1571         struct xfrm_state *x;
1572
1573         if (!ext_hdrs[SADB_EXT_SA-1] ||
1574             !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
1575                                      ext_hdrs[SADB_EXT_ADDRESS_DST-1]))
1576                 return -EINVAL;
1577
1578         x = pfkey_xfrm_state_lookup(net, hdr, ext_hdrs);
1579         if (x == NULL)
1580                 return -ESRCH;
1581
1582         out_skb = pfkey_xfrm_state2msg(x);
1583         proto = x->id.proto;
1584         xfrm_state_put(x);
1585         if (IS_ERR(out_skb))
1586                 return  PTR_ERR(out_skb);
1587
1588         out_hdr = (struct sadb_msg *) out_skb->data;
1589         out_hdr->sadb_msg_version = hdr->sadb_msg_version;
1590         out_hdr->sadb_msg_type = SADB_GET;
1591         out_hdr->sadb_msg_satype = pfkey_proto2satype(proto);
1592         out_hdr->sadb_msg_errno = 0;
1593         out_hdr->sadb_msg_reserved = 0;
1594         out_hdr->sadb_msg_seq = hdr->sadb_msg_seq;
1595         out_hdr->sadb_msg_pid = hdr->sadb_msg_pid;
1596         pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ONE, sk, sock_net(sk));
1597
1598         return 0;
1599 }
1600
1601 static struct sk_buff *compose_sadb_supported(const struct sadb_msg *orig,
1602                                               gfp_t allocation)
1603 {
1604         struct sk_buff *skb;
1605         struct sadb_msg *hdr;
1606         int len, auth_len, enc_len, i;
1607
1608         auth_len = xfrm_count_auth_supported();
1609         if (auth_len) {
1610                 auth_len *= sizeof(struct sadb_alg);
1611                 auth_len += sizeof(struct sadb_supported);
1612         }
1613
1614         enc_len = xfrm_count_enc_supported();
1615         if (enc_len) {
1616                 enc_len *= sizeof(struct sadb_alg);
1617                 enc_len += sizeof(struct sadb_supported);
1618         }
1619
1620         len = enc_len + auth_len + sizeof(struct sadb_msg);
1621
1622         skb = alloc_skb(len + 16, allocation);
1623         if (!skb)
1624                 goto out_put_algs;
1625
1626         hdr = (struct sadb_msg *) skb_put(skb, sizeof(*hdr));
1627         pfkey_hdr_dup(hdr, orig);
1628         hdr->sadb_msg_errno = 0;
1629         hdr->sadb_msg_len = len / sizeof(uint64_t);
1630
1631         if (auth_len) {
1632                 struct sadb_supported *sp;
1633                 struct sadb_alg *ap;
1634
1635                 sp = (struct sadb_supported *) skb_put(skb, auth_len);
1636                 ap = (struct sadb_alg *) (sp + 1);
1637
1638                 sp->sadb_supported_len = auth_len / sizeof(uint64_t);
1639                 sp->sadb_supported_exttype = SADB_EXT_SUPPORTED_AUTH;
1640
1641                 for (i = 0; ; i++) {
1642                         struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i);
1643                         if (!aalg)
1644                                 break;
1645                         if (aalg->available)
1646                                 *ap++ = aalg->desc;
1647                 }
1648         }
1649
1650         if (enc_len) {
1651                 struct sadb_supported *sp;
1652                 struct sadb_alg *ap;
1653
1654                 sp = (struct sadb_supported *) skb_put(skb, enc_len);
1655                 ap = (struct sadb_alg *) (sp + 1);
1656
1657                 sp->sadb_supported_len = enc_len / sizeof(uint64_t);
1658                 sp->sadb_supported_exttype = SADB_EXT_SUPPORTED_ENCRYPT;
1659
1660                 for (i = 0; ; i++) {
1661                         struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i);
1662                         if (!ealg)
1663                                 break;
1664                         if (ealg->available)
1665                                 *ap++ = ealg->desc;
1666                 }
1667         }
1668
1669 out_put_algs:
1670         return skb;
1671 }
1672
1673 static int pfkey_register(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
1674 {
1675         struct pfkey_sock *pfk = pfkey_sk(sk);
1676         struct sk_buff *supp_skb;
1677
1678         if (hdr->sadb_msg_satype > SADB_SATYPE_MAX)
1679                 return -EINVAL;
1680
1681         if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC) {
1682                 if (pfk->registered&(1<<hdr->sadb_msg_satype))
1683                         return -EEXIST;
1684                 pfk->registered |= (1<<hdr->sadb_msg_satype);
1685         }
1686
1687         xfrm_probe_algs();
1688
1689         supp_skb = compose_sadb_supported(hdr, GFP_KERNEL);
1690         if (!supp_skb) {
1691                 if (hdr->sadb_msg_satype != SADB_SATYPE_UNSPEC)
1692                         pfk->registered &= ~(1<<hdr->sadb_msg_satype);
1693
1694                 return -ENOBUFS;
1695         }
1696
1697         pfkey_broadcast(supp_skb, GFP_KERNEL, BROADCAST_REGISTERED, sk,
1698                         sock_net(sk));
1699         return 0;
1700 }
1701
1702 static int unicast_flush_resp(struct sock *sk, const struct sadb_msg *ihdr)
1703 {
1704         struct sk_buff *skb;
1705         struct sadb_msg *hdr;
1706
1707         skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC);
1708         if (!skb)
1709                 return -ENOBUFS;
1710
1711         hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
1712         memcpy(hdr, ihdr, sizeof(struct sadb_msg));
1713         hdr->sadb_msg_errno = (uint8_t) 0;
1714         hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t));
1715
1716         return pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ONE, sk,
1717                                sock_net(sk));
1718 }
1719
1720 static int key_notify_sa_flush(const struct km_event *c)
1721 {
1722         struct sk_buff *skb;
1723         struct sadb_msg *hdr;
1724
1725         skb = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC);
1726         if (!skb)
1727                 return -ENOBUFS;
1728         hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
1729         hdr->sadb_msg_satype = pfkey_proto2satype(c->data.proto);
1730         hdr->sadb_msg_type = SADB_FLUSH;
1731         hdr->sadb_msg_seq = c->seq;
1732         hdr->sadb_msg_pid = c->pid;
1733         hdr->sadb_msg_version = PF_KEY_V2;
1734         hdr->sadb_msg_errno = (uint8_t) 0;
1735         hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t));
1736         hdr->sadb_msg_reserved = 0;
1737
1738         pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net);
1739
1740         return 0;
1741 }
1742
1743 static int pfkey_flush(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
1744 {
1745         struct net *net = sock_net(sk);
1746         unsigned proto;
1747         struct km_event c;
1748         struct xfrm_audit audit_info;
1749         int err, err2;
1750
1751         proto = pfkey_satype2proto(hdr->sadb_msg_satype);
1752         if (proto == 0)
1753                 return -EINVAL;
1754
1755         audit_info.loginuid = audit_get_loginuid(current);
1756         audit_info.sessionid = audit_get_sessionid(current);
1757         audit_info.secid = 0;
1758         err = xfrm_state_flush(net, proto, &audit_info);
1759         err2 = unicast_flush_resp(sk, hdr);
1760         if (err || err2) {
1761                 if (err == -ESRCH) /* empty table - go quietly */
1762                         err = 0;
1763                 return err ? err : err2;
1764         }
1765
1766         c.data.proto = proto;
1767         c.seq = hdr->sadb_msg_seq;
1768         c.pid = hdr->sadb_msg_pid;
1769         c.event = XFRM_MSG_FLUSHSA;
1770         c.net = net;
1771         km_state_notify(NULL, &c);
1772
1773         return 0;
1774 }
1775
1776 static int dump_sa(struct xfrm_state *x, int count, void *ptr)
1777 {
1778         struct pfkey_sock *pfk = ptr;
1779         struct sk_buff *out_skb;
1780         struct sadb_msg *out_hdr;
1781
1782         if (!pfkey_can_dump(&pfk->sk))
1783                 return -ENOBUFS;
1784
1785         out_skb = pfkey_xfrm_state2msg(x);
1786         if (IS_ERR(out_skb))
1787                 return PTR_ERR(out_skb);
1788
1789         out_hdr = (struct sadb_msg *) out_skb->data;
1790         out_hdr->sadb_msg_version = pfk->dump.msg_version;
1791         out_hdr->sadb_msg_type = SADB_DUMP;
1792         out_hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto);
1793         out_hdr->sadb_msg_errno = 0;
1794         out_hdr->sadb_msg_reserved = 0;
1795         out_hdr->sadb_msg_seq = count + 1;
1796         out_hdr->sadb_msg_pid = pfk->dump.msg_pid;
1797
1798         if (pfk->dump.skb)
1799                 pfkey_broadcast(pfk->dump.skb, GFP_ATOMIC, BROADCAST_ONE,
1800                                 &pfk->sk, sock_net(&pfk->sk));
1801         pfk->dump.skb = out_skb;
1802
1803         return 0;
1804 }
1805
1806 static int pfkey_dump_sa(struct pfkey_sock *pfk)
1807 {
1808         struct net *net = sock_net(&pfk->sk);
1809         return xfrm_state_walk(net, &pfk->dump.u.state, dump_sa, (void *) pfk);
1810 }
1811
1812 static void pfkey_dump_sa_done(struct pfkey_sock *pfk)
1813 {
1814         xfrm_state_walk_done(&pfk->dump.u.state);
1815 }
1816
1817 static int pfkey_dump(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
1818 {
1819         u8 proto;
1820         struct pfkey_sock *pfk = pfkey_sk(sk);
1821
1822         mutex_lock(&pfk->dump_lock);
1823         if (pfk->dump.dump != NULL) {
1824                 mutex_unlock(&pfk->dump_lock);
1825                 return -EBUSY;
1826         }
1827
1828         proto = pfkey_satype2proto(hdr->sadb_msg_satype);
1829         if (proto == 0) {
1830                 mutex_unlock(&pfk->dump_lock);
1831                 return -EINVAL;
1832         }
1833
1834         pfk->dump.msg_version = hdr->sadb_msg_version;
1835         pfk->dump.msg_pid = hdr->sadb_msg_pid;
1836         pfk->dump.dump = pfkey_dump_sa;
1837         pfk->dump.done = pfkey_dump_sa_done;
1838         xfrm_state_walk_init(&pfk->dump.u.state, proto);
1839         mutex_unlock(&pfk->dump_lock);
1840
1841         return pfkey_do_dump(pfk);
1842 }
1843
1844 static int pfkey_promisc(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
1845 {
1846         struct pfkey_sock *pfk = pfkey_sk(sk);
1847         int satype = hdr->sadb_msg_satype;
1848         bool reset_errno = false;
1849
1850         if (hdr->sadb_msg_len == (sizeof(*hdr) / sizeof(uint64_t))) {
1851                 reset_errno = true;
1852                 if (satype != 0 && satype != 1)
1853                         return -EINVAL;
1854                 pfk->promisc = satype;
1855         }
1856         if (reset_errno && skb_cloned(skb))
1857                 skb = skb_copy(skb, GFP_KERNEL);
1858         else
1859                 skb = skb_clone(skb, GFP_KERNEL);
1860
1861         if (reset_errno && skb) {
1862                 struct sadb_msg *new_hdr = (struct sadb_msg *) skb->data;
1863                 new_hdr->sadb_msg_errno = 0;
1864         }
1865
1866         pfkey_broadcast(skb, GFP_KERNEL, BROADCAST_ALL, NULL, sock_net(sk));
1867         return 0;
1868 }
1869
1870 static int check_reqid(struct xfrm_policy *xp, int dir, int count, void *ptr)
1871 {
1872         int i;
1873         u32 reqid = *(u32*)ptr;
1874
1875         for (i=0; i<xp->xfrm_nr; i++) {
1876                 if (xp->xfrm_vec[i].reqid == reqid)
1877                         return -EEXIST;
1878         }
1879         return 0;
1880 }
1881
1882 static u32 gen_reqid(struct net *net)
1883 {
1884         struct xfrm_policy_walk walk;
1885         u32 start;
1886         int rc;
1887         static u32 reqid = IPSEC_MANUAL_REQID_MAX;
1888
1889         start = reqid;
1890         do {
1891                 ++reqid;
1892                 if (reqid == 0)
1893                         reqid = IPSEC_MANUAL_REQID_MAX+1;
1894                 xfrm_policy_walk_init(&walk, XFRM_POLICY_TYPE_MAIN);
1895                 rc = xfrm_policy_walk(net, &walk, check_reqid, (void*)&reqid);
1896                 xfrm_policy_walk_done(&walk);
1897                 if (rc != -EEXIST)
1898                         return reqid;
1899         } while (reqid != start);
1900         return 0;
1901 }
1902
1903 static int
1904 parse_ipsecrequest(struct xfrm_policy *xp, struct sadb_x_ipsecrequest *rq)
1905 {
1906         struct net *net = xp_net(xp);
1907         struct xfrm_tmpl *t = xp->xfrm_vec + xp->xfrm_nr;
1908         int mode;
1909
1910         if (xp->xfrm_nr >= XFRM_MAX_DEPTH)
1911                 return -ELOOP;
1912
1913         if (rq->sadb_x_ipsecrequest_mode == 0)
1914                 return -EINVAL;
1915
1916         t->id.proto = rq->sadb_x_ipsecrequest_proto; /* XXX check proto */
1917         if ((mode = pfkey_mode_to_xfrm(rq->sadb_x_ipsecrequest_mode)) < 0)
1918                 return -EINVAL;
1919         t->mode = mode;
1920         if (rq->sadb_x_ipsecrequest_level == IPSEC_LEVEL_USE)
1921                 t->optional = 1;
1922         else if (rq->sadb_x_ipsecrequest_level == IPSEC_LEVEL_UNIQUE) {
1923                 t->reqid = rq->sadb_x_ipsecrequest_reqid;
1924                 if (t->reqid > IPSEC_MANUAL_REQID_MAX)
1925                         t->reqid = 0;
1926                 if (!t->reqid && !(t->reqid = gen_reqid(net)))
1927                         return -ENOBUFS;
1928         }
1929
1930         /* addresses present only in tunnel mode */
1931         if (t->mode == XFRM_MODE_TUNNEL) {
1932                 u8 *sa = (u8 *) (rq + 1);
1933                 int family, socklen;
1934
1935                 family = pfkey_sockaddr_extract((struct sockaddr *)sa,
1936                                                 &t->saddr);
1937                 if (!family)
1938                         return -EINVAL;
1939
1940                 socklen = pfkey_sockaddr_len(family);
1941                 if (pfkey_sockaddr_extract((struct sockaddr *)(sa + socklen),
1942                                            &t->id.daddr) != family)
1943                         return -EINVAL;
1944                 t->encap_family = family;
1945         } else
1946                 t->encap_family = xp->family;
1947
1948         /* No way to set this via kame pfkey */
1949         t->allalgs = 1;
1950         xp->xfrm_nr++;
1951         return 0;
1952 }
1953
1954 static int
1955 parse_ipsecrequests(struct xfrm_policy *xp, struct sadb_x_policy *pol)
1956 {
1957         int err;
1958         int len = pol->sadb_x_policy_len*8 - sizeof(struct sadb_x_policy);
1959         struct sadb_x_ipsecrequest *rq = (void*)(pol+1);
1960
1961         while (len >= sizeof(struct sadb_x_ipsecrequest)) {
1962                 if ((err = parse_ipsecrequest(xp, rq)) < 0)
1963                         return err;
1964                 len -= rq->sadb_x_ipsecrequest_len;
1965                 rq = (void*)((u8*)rq + rq->sadb_x_ipsecrequest_len);
1966         }
1967         return 0;
1968 }
1969
1970 static inline int pfkey_xfrm_policy2sec_ctx_size(const struct xfrm_policy *xp)
1971 {
1972   struct xfrm_sec_ctx *xfrm_ctx = xp->security;
1973
1974         if (xfrm_ctx) {
1975                 int len = sizeof(struct sadb_x_sec_ctx);
1976                 len += xfrm_ctx->ctx_len;
1977                 return PFKEY_ALIGN8(len);
1978         }
1979         return 0;
1980 }
1981
1982 static int pfkey_xfrm_policy2msg_size(const struct xfrm_policy *xp)
1983 {
1984         const struct xfrm_tmpl *t;
1985         int sockaddr_size = pfkey_sockaddr_size(xp->family);
1986         int socklen = 0;
1987         int i;
1988
1989         for (i=0; i<xp->xfrm_nr; i++) {
1990                 t = xp->xfrm_vec + i;
1991                 socklen += pfkey_sockaddr_len(t->encap_family);
1992         }
1993
1994         return sizeof(struct sadb_msg) +
1995                 (sizeof(struct sadb_lifetime) * 3) +
1996                 (sizeof(struct sadb_address) * 2) +
1997                 (sockaddr_size * 2) +
1998                 sizeof(struct sadb_x_policy) +
1999                 (xp->xfrm_nr * sizeof(struct sadb_x_ipsecrequest)) +
2000                 (socklen * 2) +
2001                 pfkey_xfrm_policy2sec_ctx_size(xp);
2002 }
2003
2004 static struct sk_buff * pfkey_xfrm_policy2msg_prep(const struct xfrm_policy *xp)
2005 {
2006         struct sk_buff *skb;
2007         int size;
2008
2009         size = pfkey_xfrm_policy2msg_size(xp);
2010
2011         skb =  alloc_skb(size + 16, GFP_ATOMIC);
2012         if (skb == NULL)
2013                 return ERR_PTR(-ENOBUFS);
2014
2015         return skb;
2016 }
2017
2018 static int pfkey_xfrm_policy2msg(struct sk_buff *skb, const struct xfrm_policy *xp, int dir)
2019 {
2020         struct sadb_msg *hdr;
2021         struct sadb_address *addr;
2022         struct sadb_lifetime *lifetime;
2023         struct sadb_x_policy *pol;
2024         struct sadb_x_sec_ctx *sec_ctx;
2025         struct xfrm_sec_ctx *xfrm_ctx;
2026         int i;
2027         int size;
2028         int sockaddr_size = pfkey_sockaddr_size(xp->family);
2029         int socklen = pfkey_sockaddr_len(xp->family);
2030
2031         size = pfkey_xfrm_policy2msg_size(xp);
2032
2033         /* call should fill header later */
2034         hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
2035         memset(hdr, 0, size);   /* XXX do we need this ? */
2036
2037         /* src address */
2038         addr = (struct sadb_address*) skb_put(skb,
2039                                               sizeof(struct sadb_address)+sockaddr_size);
2040         addr->sadb_address_len =
2041                 (sizeof(struct sadb_address)+sockaddr_size)/
2042                         sizeof(uint64_t);
2043         addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
2044         addr->sadb_address_proto = pfkey_proto_from_xfrm(xp->selector.proto);
2045         addr->sadb_address_prefixlen = xp->selector.prefixlen_s;
2046         addr->sadb_address_reserved = 0;
2047         if (!pfkey_sockaddr_fill(&xp->selector.saddr,
2048                                  xp->selector.sport,
2049                                  (struct sockaddr *) (addr + 1),
2050                                  xp->family))
2051                 BUG();
2052
2053         /* dst address */
2054         addr = (struct sadb_address*) skb_put(skb,
2055                                               sizeof(struct sadb_address)+sockaddr_size);
2056         addr->sadb_address_len =
2057                 (sizeof(struct sadb_address)+sockaddr_size)/
2058                         sizeof(uint64_t);
2059         addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
2060         addr->sadb_address_proto = pfkey_proto_from_xfrm(xp->selector.proto);
2061         addr->sadb_address_prefixlen = xp->selector.prefixlen_d;
2062         addr->sadb_address_reserved = 0;
2063
2064         pfkey_sockaddr_fill(&xp->selector.daddr, xp->selector.dport,
2065                             (struct sockaddr *) (addr + 1),
2066                             xp->family);
2067
2068         /* hard 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_HARD;
2074         lifetime->sadb_lifetime_allocations =  _X2KEY(xp->lft.hard_packet_limit);
2075         lifetime->sadb_lifetime_bytes = _X2KEY(xp->lft.hard_byte_limit);
2076         lifetime->sadb_lifetime_addtime = xp->lft.hard_add_expires_seconds;
2077         lifetime->sadb_lifetime_usetime = xp->lft.hard_use_expires_seconds;
2078         /* soft 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_SOFT;
2084         lifetime->sadb_lifetime_allocations =  _X2KEY(xp->lft.soft_packet_limit);
2085         lifetime->sadb_lifetime_bytes = _X2KEY(xp->lft.soft_byte_limit);
2086         lifetime->sadb_lifetime_addtime = xp->lft.soft_add_expires_seconds;
2087         lifetime->sadb_lifetime_usetime = xp->lft.soft_use_expires_seconds;
2088         /* current time */
2089         lifetime = (struct sadb_lifetime *)  skb_put(skb,
2090                                                      sizeof(struct sadb_lifetime));
2091         lifetime->sadb_lifetime_len =
2092                 sizeof(struct sadb_lifetime)/sizeof(uint64_t);
2093         lifetime->sadb_lifetime_exttype = SADB_EXT_LIFETIME_CURRENT;
2094         lifetime->sadb_lifetime_allocations = xp->curlft.packets;
2095         lifetime->sadb_lifetime_bytes = xp->curlft.bytes;
2096         lifetime->sadb_lifetime_addtime = xp->curlft.add_time;
2097         lifetime->sadb_lifetime_usetime = xp->curlft.use_time;
2098
2099         pol = (struct sadb_x_policy *)  skb_put(skb, sizeof(struct sadb_x_policy));
2100         pol->sadb_x_policy_len = sizeof(struct sadb_x_policy)/sizeof(uint64_t);
2101         pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
2102         pol->sadb_x_policy_type = IPSEC_POLICY_DISCARD;
2103         if (xp->action == XFRM_POLICY_ALLOW) {
2104                 if (xp->xfrm_nr)
2105                         pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
2106                 else
2107                         pol->sadb_x_policy_type = IPSEC_POLICY_NONE;
2108         }
2109         pol->sadb_x_policy_dir = dir+1;
2110         pol->sadb_x_policy_reserved = 0;
2111         pol->sadb_x_policy_id = xp->index;
2112         pol->sadb_x_policy_priority = xp->priority;
2113
2114         for (i=0; i<xp->xfrm_nr; i++) {
2115                 const struct xfrm_tmpl *t = xp->xfrm_vec + i;
2116                 struct sadb_x_ipsecrequest *rq;
2117                 int req_size;
2118                 int mode;
2119
2120                 req_size = sizeof(struct sadb_x_ipsecrequest);
2121                 if (t->mode == XFRM_MODE_TUNNEL) {
2122                         socklen = pfkey_sockaddr_len(t->encap_family);
2123                         req_size += socklen * 2;
2124                 } else {
2125                         size -= 2*socklen;
2126                 }
2127                 rq = (void*)skb_put(skb, req_size);
2128                 pol->sadb_x_policy_len += req_size/8;
2129                 memset(rq, 0, sizeof(*rq));
2130                 rq->sadb_x_ipsecrequest_len = req_size;
2131                 rq->sadb_x_ipsecrequest_proto = t->id.proto;
2132                 if ((mode = pfkey_mode_from_xfrm(t->mode)) < 0)
2133                         return -EINVAL;
2134                 rq->sadb_x_ipsecrequest_mode = mode;
2135                 rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_REQUIRE;
2136                 if (t->reqid)
2137                         rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_UNIQUE;
2138                 if (t->optional)
2139                         rq->sadb_x_ipsecrequest_level = IPSEC_LEVEL_USE;
2140                 rq->sadb_x_ipsecrequest_reqid = t->reqid;
2141
2142                 if (t->mode == XFRM_MODE_TUNNEL) {
2143                         u8 *sa = (void *)(rq + 1);
2144                         pfkey_sockaddr_fill(&t->saddr, 0,
2145                                             (struct sockaddr *)sa,
2146                                             t->encap_family);
2147                         pfkey_sockaddr_fill(&t->id.daddr, 0,
2148                                             (struct sockaddr *) (sa + socklen),
2149                                             t->encap_family);
2150                 }
2151         }
2152
2153         /* security context */
2154         if ((xfrm_ctx = xp->security)) {
2155                 int ctx_size = pfkey_xfrm_policy2sec_ctx_size(xp);
2156
2157                 sec_ctx = (struct sadb_x_sec_ctx *) skb_put(skb, ctx_size);
2158                 sec_ctx->sadb_x_sec_len = ctx_size / sizeof(uint64_t);
2159                 sec_ctx->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX;
2160                 sec_ctx->sadb_x_ctx_doi = xfrm_ctx->ctx_doi;
2161                 sec_ctx->sadb_x_ctx_alg = xfrm_ctx->ctx_alg;
2162                 sec_ctx->sadb_x_ctx_len = xfrm_ctx->ctx_len;
2163                 memcpy(sec_ctx + 1, xfrm_ctx->ctx_str,
2164                        xfrm_ctx->ctx_len);
2165         }
2166
2167         hdr->sadb_msg_len = size / sizeof(uint64_t);
2168         hdr->sadb_msg_reserved = atomic_read(&xp->refcnt);
2169
2170         return 0;
2171 }
2172
2173 static int key_notify_policy(struct xfrm_policy *xp, int dir, const struct km_event *c)
2174 {
2175         struct sk_buff *out_skb;
2176         struct sadb_msg *out_hdr;
2177         int err;
2178
2179         out_skb = pfkey_xfrm_policy2msg_prep(xp);
2180         if (IS_ERR(out_skb))
2181                 return PTR_ERR(out_skb);
2182
2183         err = pfkey_xfrm_policy2msg(out_skb, xp, dir);
2184         if (err < 0)
2185                 return err;
2186
2187         out_hdr = (struct sadb_msg *) out_skb->data;
2188         out_hdr->sadb_msg_version = PF_KEY_V2;
2189
2190         if (c->data.byid && c->event == XFRM_MSG_DELPOLICY)
2191                 out_hdr->sadb_msg_type = SADB_X_SPDDELETE2;
2192         else
2193                 out_hdr->sadb_msg_type = event2poltype(c->event);
2194         out_hdr->sadb_msg_errno = 0;
2195         out_hdr->sadb_msg_seq = c->seq;
2196         out_hdr->sadb_msg_pid = c->pid;
2197         pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ALL, NULL, xp_net(xp));
2198         return 0;
2199
2200 }
2201
2202 static int pfkey_spdadd(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
2203 {
2204         struct net *net = sock_net(sk);
2205         int err = 0;
2206         struct sadb_lifetime *lifetime;
2207         struct sadb_address *sa;
2208         struct sadb_x_policy *pol;
2209         struct xfrm_policy *xp;
2210         struct km_event c;
2211         struct sadb_x_sec_ctx *sec_ctx;
2212
2213         if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
2214                                      ext_hdrs[SADB_EXT_ADDRESS_DST-1]) ||
2215             !ext_hdrs[SADB_X_EXT_POLICY-1])
2216                 return -EINVAL;
2217
2218         pol = ext_hdrs[SADB_X_EXT_POLICY-1];
2219         if (pol->sadb_x_policy_type > IPSEC_POLICY_IPSEC)
2220                 return -EINVAL;
2221         if (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir >= IPSEC_DIR_MAX)
2222                 return -EINVAL;
2223
2224         xp = xfrm_policy_alloc(net, GFP_KERNEL);
2225         if (xp == NULL)
2226                 return -ENOBUFS;
2227
2228         xp->action = (pol->sadb_x_policy_type == IPSEC_POLICY_DISCARD ?
2229                       XFRM_POLICY_BLOCK : XFRM_POLICY_ALLOW);
2230         xp->priority = pol->sadb_x_policy_priority;
2231
2232         sa = ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
2233         xp->family = pfkey_sadb_addr2xfrm_addr(sa, &xp->selector.saddr);
2234         if (!xp->family) {
2235                 err = -EINVAL;
2236                 goto out;
2237         }
2238         xp->selector.family = xp->family;
2239         xp->selector.prefixlen_s = sa->sadb_address_prefixlen;
2240         xp->selector.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
2241         xp->selector.sport = ((struct sockaddr_in *)(sa+1))->sin_port;
2242         if (xp->selector.sport)
2243                 xp->selector.sport_mask = htons(0xffff);
2244
2245         sa = ext_hdrs[SADB_EXT_ADDRESS_DST-1],
2246         pfkey_sadb_addr2xfrm_addr(sa, &xp->selector.daddr);
2247         xp->selector.prefixlen_d = sa->sadb_address_prefixlen;
2248
2249         /* Amusing, we set this twice.  KAME apps appear to set same value
2250          * in both addresses.
2251          */
2252         xp->selector.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
2253
2254         xp->selector.dport = ((struct sockaddr_in *)(sa+1))->sin_port;
2255         if (xp->selector.dport)
2256                 xp->selector.dport_mask = htons(0xffff);
2257
2258         sec_ctx = ext_hdrs[SADB_X_EXT_SEC_CTX - 1];
2259         if (sec_ctx != NULL) {
2260                 struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx);
2261
2262                 if (!uctx) {
2263                         err = -ENOBUFS;
2264                         goto out;
2265                 }
2266
2267                 err = security_xfrm_policy_alloc(&xp->security, uctx);
2268                 kfree(uctx);
2269
2270                 if (err)
2271                         goto out;
2272         }
2273
2274         xp->lft.soft_byte_limit = XFRM_INF;
2275         xp->lft.hard_byte_limit = XFRM_INF;
2276         xp->lft.soft_packet_limit = XFRM_INF;
2277         xp->lft.hard_packet_limit = XFRM_INF;
2278         if ((lifetime = ext_hdrs[SADB_EXT_LIFETIME_HARD-1]) != NULL) {
2279                 xp->lft.hard_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations);
2280                 xp->lft.hard_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes);
2281                 xp->lft.hard_add_expires_seconds = lifetime->sadb_lifetime_addtime;
2282                 xp->lft.hard_use_expires_seconds = lifetime->sadb_lifetime_usetime;
2283         }
2284         if ((lifetime = ext_hdrs[SADB_EXT_LIFETIME_SOFT-1]) != NULL) {
2285                 xp->lft.soft_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations);
2286                 xp->lft.soft_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes);
2287                 xp->lft.soft_add_expires_seconds = lifetime->sadb_lifetime_addtime;
2288                 xp->lft.soft_use_expires_seconds = lifetime->sadb_lifetime_usetime;
2289         }
2290         xp->xfrm_nr = 0;
2291         if (pol->sadb_x_policy_type == IPSEC_POLICY_IPSEC &&
2292             (err = parse_ipsecrequests(xp, pol)) < 0)
2293                 goto out;
2294
2295         err = xfrm_policy_insert(pol->sadb_x_policy_dir-1, xp,
2296                                  hdr->sadb_msg_type != SADB_X_SPDUPDATE);
2297
2298         xfrm_audit_policy_add(xp, err ? 0 : 1,
2299                               audit_get_loginuid(current),
2300                               audit_get_sessionid(current), 0);
2301
2302         if (err)
2303                 goto out;
2304
2305         if (hdr->sadb_msg_type == SADB_X_SPDUPDATE)
2306                 c.event = XFRM_MSG_UPDPOLICY;
2307         else
2308                 c.event = XFRM_MSG_NEWPOLICY;
2309
2310         c.seq = hdr->sadb_msg_seq;
2311         c.pid = hdr->sadb_msg_pid;
2312
2313         km_policy_notify(xp, pol->sadb_x_policy_dir-1, &c);
2314         xfrm_pol_put(xp);
2315         return 0;
2316
2317 out:
2318         xp->walk.dead = 1;
2319         xfrm_policy_destroy(xp);
2320         return err;
2321 }
2322
2323 static int pfkey_spddelete(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
2324 {
2325         struct net *net = sock_net(sk);
2326         int err;
2327         struct sadb_address *sa;
2328         struct sadb_x_policy *pol;
2329         struct xfrm_policy *xp;
2330         struct xfrm_selector sel;
2331         struct km_event c;
2332         struct sadb_x_sec_ctx *sec_ctx;
2333         struct xfrm_sec_ctx *pol_ctx = NULL;
2334
2335         if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
2336                                      ext_hdrs[SADB_EXT_ADDRESS_DST-1]) ||
2337             !ext_hdrs[SADB_X_EXT_POLICY-1])
2338                 return -EINVAL;
2339
2340         pol = ext_hdrs[SADB_X_EXT_POLICY-1];
2341         if (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir >= IPSEC_DIR_MAX)
2342                 return -EINVAL;
2343
2344         memset(&sel, 0, sizeof(sel));
2345
2346         sa = ext_hdrs[SADB_EXT_ADDRESS_SRC-1],
2347         sel.family = pfkey_sadb_addr2xfrm_addr(sa, &sel.saddr);
2348         sel.prefixlen_s = sa->sadb_address_prefixlen;
2349         sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
2350         sel.sport = ((struct sockaddr_in *)(sa+1))->sin_port;
2351         if (sel.sport)
2352                 sel.sport_mask = htons(0xffff);
2353
2354         sa = ext_hdrs[SADB_EXT_ADDRESS_DST-1],
2355         pfkey_sadb_addr2xfrm_addr(sa, &sel.daddr);
2356         sel.prefixlen_d = sa->sadb_address_prefixlen;
2357         sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
2358         sel.dport = ((struct sockaddr_in *)(sa+1))->sin_port;
2359         if (sel.dport)
2360                 sel.dport_mask = htons(0xffff);
2361
2362         sec_ctx = ext_hdrs[SADB_X_EXT_SEC_CTX - 1];
2363         if (sec_ctx != NULL) {
2364                 struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx);
2365
2366                 if (!uctx)
2367                         return -ENOMEM;
2368
2369                 err = security_xfrm_policy_alloc(&pol_ctx, uctx);
2370                 kfree(uctx);
2371                 if (err)
2372                         return err;
2373         }
2374
2375         xp = xfrm_policy_bysel_ctx(net, DUMMY_MARK, XFRM_POLICY_TYPE_MAIN,
2376                                    pol->sadb_x_policy_dir - 1, &sel, pol_ctx,
2377                                    1, &err);
2378         security_xfrm_policy_free(pol_ctx);
2379         if (xp == NULL)
2380                 return -ENOENT;
2381
2382         xfrm_audit_policy_delete(xp, err ? 0 : 1,
2383                                  audit_get_loginuid(current),
2384                                  audit_get_sessionid(current), 0);
2385
2386         if (err)
2387                 goto out;
2388
2389         c.seq = hdr->sadb_msg_seq;
2390         c.pid = hdr->sadb_msg_pid;
2391         c.data.byid = 0;
2392         c.event = XFRM_MSG_DELPOLICY;
2393         km_policy_notify(xp, pol->sadb_x_policy_dir-1, &c);
2394
2395 out:
2396         xfrm_pol_put(xp);
2397         return err;
2398 }
2399
2400 static int key_pol_get_resp(struct sock *sk, struct xfrm_policy *xp, const struct sadb_msg *hdr, int dir)
2401 {
2402         int err;
2403         struct sk_buff *out_skb;
2404         struct sadb_msg *out_hdr;
2405         err = 0;
2406
2407         out_skb = pfkey_xfrm_policy2msg_prep(xp);
2408         if (IS_ERR(out_skb)) {
2409                 err =  PTR_ERR(out_skb);
2410                 goto out;
2411         }
2412         err = pfkey_xfrm_policy2msg(out_skb, xp, dir);
2413         if (err < 0)
2414                 goto out;
2415
2416         out_hdr = (struct sadb_msg *) out_skb->data;
2417         out_hdr->sadb_msg_version = hdr->sadb_msg_version;
2418         out_hdr->sadb_msg_type = hdr->sadb_msg_type;
2419         out_hdr->sadb_msg_satype = 0;
2420         out_hdr->sadb_msg_errno = 0;
2421         out_hdr->sadb_msg_seq = hdr->sadb_msg_seq;
2422         out_hdr->sadb_msg_pid = hdr->sadb_msg_pid;
2423         pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_ONE, sk, xp_net(xp));
2424         err = 0;
2425
2426 out:
2427         return err;
2428 }
2429
2430 #ifdef CONFIG_NET_KEY_MIGRATE
2431 static int pfkey_sockaddr_pair_size(sa_family_t family)
2432 {
2433         return PFKEY_ALIGN8(pfkey_sockaddr_len(family) * 2);
2434 }
2435
2436 static int parse_sockaddr_pair(struct sockaddr *sa, int ext_len,
2437                                xfrm_address_t *saddr, xfrm_address_t *daddr,
2438                                u16 *family)
2439 {
2440         int af, socklen;
2441
2442         if (ext_len < pfkey_sockaddr_pair_size(sa->sa_family))
2443                 return -EINVAL;
2444
2445         af = pfkey_sockaddr_extract(sa, saddr);
2446         if (!af)
2447                 return -EINVAL;
2448
2449         socklen = pfkey_sockaddr_len(af);
2450         if (pfkey_sockaddr_extract((struct sockaddr *) (((u8 *)sa) + socklen),
2451                                    daddr) != af)
2452                 return -EINVAL;
2453
2454         *family = af;
2455         return 0;
2456 }
2457
2458 static int ipsecrequests_to_migrate(struct sadb_x_ipsecrequest *rq1, int len,
2459                                     struct xfrm_migrate *m)
2460 {
2461         int err;
2462         struct sadb_x_ipsecrequest *rq2;
2463         int mode;
2464
2465         if (len <= sizeof(struct sadb_x_ipsecrequest) ||
2466             len < rq1->sadb_x_ipsecrequest_len)
2467                 return -EINVAL;
2468
2469         /* old endoints */
2470         err = parse_sockaddr_pair((struct sockaddr *)(rq1 + 1),
2471                                   rq1->sadb_x_ipsecrequest_len,
2472                                   &m->old_saddr, &m->old_daddr,
2473                                   &m->old_family);
2474         if (err)
2475                 return err;
2476
2477         rq2 = (struct sadb_x_ipsecrequest *)((u8 *)rq1 + rq1->sadb_x_ipsecrequest_len);
2478         len -= rq1->sadb_x_ipsecrequest_len;
2479
2480         if (len <= sizeof(struct sadb_x_ipsecrequest) ||
2481             len < rq2->sadb_x_ipsecrequest_len)
2482                 return -EINVAL;
2483
2484         /* new endpoints */
2485         err = parse_sockaddr_pair((struct sockaddr *)(rq2 + 1),
2486                                   rq2->sadb_x_ipsecrequest_len,
2487                                   &m->new_saddr, &m->new_daddr,
2488                                   &m->new_family);
2489         if (err)
2490                 return err;
2491
2492         if (rq1->sadb_x_ipsecrequest_proto != rq2->sadb_x_ipsecrequest_proto ||
2493             rq1->sadb_x_ipsecrequest_mode != rq2->sadb_x_ipsecrequest_mode ||
2494             rq1->sadb_x_ipsecrequest_reqid != rq2->sadb_x_ipsecrequest_reqid)
2495                 return -EINVAL;
2496
2497         m->proto = rq1->sadb_x_ipsecrequest_proto;
2498         if ((mode = pfkey_mode_to_xfrm(rq1->sadb_x_ipsecrequest_mode)) < 0)
2499                 return -EINVAL;
2500         m->mode = mode;
2501         m->reqid = rq1->sadb_x_ipsecrequest_reqid;
2502
2503         return ((int)(rq1->sadb_x_ipsecrequest_len +
2504                       rq2->sadb_x_ipsecrequest_len));
2505 }
2506
2507 static int pfkey_migrate(struct sock *sk, struct sk_buff *skb,
2508                          const struct sadb_msg *hdr, void * const *ext_hdrs)
2509 {
2510         int i, len, ret, err = -EINVAL;
2511         u8 dir;
2512         struct sadb_address *sa;
2513         struct sadb_x_kmaddress *kma;
2514         struct sadb_x_policy *pol;
2515         struct sadb_x_ipsecrequest *rq;
2516         struct xfrm_selector sel;
2517         struct xfrm_migrate m[XFRM_MAX_DEPTH];
2518         struct xfrm_kmaddress k;
2519
2520         if (!present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC - 1],
2521                                      ext_hdrs[SADB_EXT_ADDRESS_DST - 1]) ||
2522             !ext_hdrs[SADB_X_EXT_POLICY - 1]) {
2523                 err = -EINVAL;
2524                 goto out;
2525         }
2526
2527         kma = ext_hdrs[SADB_X_EXT_KMADDRESS - 1];
2528         pol = ext_hdrs[SADB_X_EXT_POLICY - 1];
2529
2530         if (pol->sadb_x_policy_dir >= IPSEC_DIR_MAX) {
2531                 err = -EINVAL;
2532                 goto out;
2533         }
2534
2535         if (kma) {
2536                 /* convert sadb_x_kmaddress to xfrm_kmaddress */
2537                 k.reserved = kma->sadb_x_kmaddress_reserved;
2538                 ret = parse_sockaddr_pair((struct sockaddr *)(kma + 1),
2539                                           8*(kma->sadb_x_kmaddress_len) - sizeof(*kma),
2540                                           &k.local, &k.remote, &k.family);
2541                 if (ret < 0) {
2542                         err = ret;
2543                         goto out;
2544                 }
2545         }
2546
2547         dir = pol->sadb_x_policy_dir - 1;
2548         memset(&sel, 0, sizeof(sel));
2549
2550         /* set source address info of selector */
2551         sa = ext_hdrs[SADB_EXT_ADDRESS_SRC - 1];
2552         sel.family = pfkey_sadb_addr2xfrm_addr(sa, &sel.saddr);
2553         sel.prefixlen_s = sa->sadb_address_prefixlen;
2554         sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
2555         sel.sport = ((struct sockaddr_in *)(sa + 1))->sin_port;
2556         if (sel.sport)
2557                 sel.sport_mask = htons(0xffff);
2558
2559         /* set destination address info of selector */
2560         sa = ext_hdrs[SADB_EXT_ADDRESS_DST - 1],
2561         pfkey_sadb_addr2xfrm_addr(sa, &sel.daddr);
2562         sel.prefixlen_d = sa->sadb_address_prefixlen;
2563         sel.proto = pfkey_proto_to_xfrm(sa->sadb_address_proto);
2564         sel.dport = ((struct sockaddr_in *)(sa + 1))->sin_port;
2565         if (sel.dport)
2566                 sel.dport_mask = htons(0xffff);
2567
2568         rq = (struct sadb_x_ipsecrequest *)(pol + 1);
2569
2570         /* extract ipsecrequests */
2571         i = 0;
2572         len = pol->sadb_x_policy_len * 8 - sizeof(struct sadb_x_policy);
2573
2574         while (len > 0 && i < XFRM_MAX_DEPTH) {
2575                 ret = ipsecrequests_to_migrate(rq, len, &m[i]);
2576                 if (ret < 0) {
2577                         err = ret;
2578                         goto out;
2579                 } else {
2580                         rq = (struct sadb_x_ipsecrequest *)((u8 *)rq + ret);
2581                         len -= ret;
2582                         i++;
2583                 }
2584         }
2585
2586         if (!i || len > 0) {
2587                 err = -EINVAL;
2588                 goto out;
2589         }
2590
2591         return xfrm_migrate(&sel, dir, XFRM_POLICY_TYPE_MAIN, m, i,
2592                             kma ? &k : NULL);
2593
2594  out:
2595         return err;
2596 }
2597 #else
2598 static int pfkey_migrate(struct sock *sk, struct sk_buff *skb,
2599                          const struct sadb_msg *hdr, void * const *ext_hdrs)
2600 {
2601         return -ENOPROTOOPT;
2602 }
2603 #endif
2604
2605
2606 static int pfkey_spdget(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
2607 {
2608         struct net *net = sock_net(sk);
2609         unsigned int dir;
2610         int err = 0, delete;
2611         struct sadb_x_policy *pol;
2612         struct xfrm_policy *xp;
2613         struct km_event c;
2614
2615         if ((pol = ext_hdrs[SADB_X_EXT_POLICY-1]) == NULL)
2616                 return -EINVAL;
2617
2618         dir = xfrm_policy_id2dir(pol->sadb_x_policy_id);
2619         if (dir >= XFRM_POLICY_MAX)
2620                 return -EINVAL;
2621
2622         delete = (hdr->sadb_msg_type == SADB_X_SPDDELETE2);
2623         xp = xfrm_policy_byid(net, DUMMY_MARK, XFRM_POLICY_TYPE_MAIN,
2624                               dir, pol->sadb_x_policy_id, delete, &err);
2625         if (xp == NULL)
2626                 return -ENOENT;
2627
2628         if (delete) {
2629                 xfrm_audit_policy_delete(xp, err ? 0 : 1,
2630                                 audit_get_loginuid(current),
2631                                 audit_get_sessionid(current), 0);
2632
2633                 if (err)
2634                         goto out;
2635                 c.seq = hdr->sadb_msg_seq;
2636                 c.pid = hdr->sadb_msg_pid;
2637                 c.data.byid = 1;
2638                 c.event = XFRM_MSG_DELPOLICY;
2639                 km_policy_notify(xp, dir, &c);
2640         } else {
2641                 err = key_pol_get_resp(sk, xp, hdr, dir);
2642         }
2643
2644 out:
2645         xfrm_pol_put(xp);
2646         return err;
2647 }
2648
2649 static int dump_sp(struct xfrm_policy *xp, int dir, int count, void *ptr)
2650 {
2651         struct pfkey_sock *pfk = ptr;
2652         struct sk_buff *out_skb;
2653         struct sadb_msg *out_hdr;
2654         int err;
2655
2656         if (!pfkey_can_dump(&pfk->sk))
2657                 return -ENOBUFS;
2658
2659         out_skb = pfkey_xfrm_policy2msg_prep(xp);
2660         if (IS_ERR(out_skb))
2661                 return PTR_ERR(out_skb);
2662
2663         err = pfkey_xfrm_policy2msg(out_skb, xp, dir);
2664         if (err < 0)
2665                 return err;
2666
2667         out_hdr = (struct sadb_msg *) out_skb->data;
2668         out_hdr->sadb_msg_version = pfk->dump.msg_version;
2669         out_hdr->sadb_msg_type = SADB_X_SPDDUMP;
2670         out_hdr->sadb_msg_satype = SADB_SATYPE_UNSPEC;
2671         out_hdr->sadb_msg_errno = 0;
2672         out_hdr->sadb_msg_seq = count + 1;
2673         out_hdr->sadb_msg_pid = pfk->dump.msg_pid;
2674
2675         if (pfk->dump.skb)
2676                 pfkey_broadcast(pfk->dump.skb, GFP_ATOMIC, BROADCAST_ONE,
2677                                 &pfk->sk, sock_net(&pfk->sk));
2678         pfk->dump.skb = out_skb;
2679
2680         return 0;
2681 }
2682
2683 static int pfkey_dump_sp(struct pfkey_sock *pfk)
2684 {
2685         struct net *net = sock_net(&pfk->sk);
2686         return xfrm_policy_walk(net, &pfk->dump.u.policy, dump_sp, (void *) pfk);
2687 }
2688
2689 static void pfkey_dump_sp_done(struct pfkey_sock *pfk)
2690 {
2691         xfrm_policy_walk_done(&pfk->dump.u.policy);
2692 }
2693
2694 static int pfkey_spddump(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
2695 {
2696         struct pfkey_sock *pfk = pfkey_sk(sk);
2697
2698         mutex_lock(&pfk->dump_lock);
2699         if (pfk->dump.dump != NULL) {
2700                 mutex_unlock(&pfk->dump_lock);
2701                 return -EBUSY;
2702         }
2703
2704         pfk->dump.msg_version = hdr->sadb_msg_version;
2705         pfk->dump.msg_pid = hdr->sadb_msg_pid;
2706         pfk->dump.dump = pfkey_dump_sp;
2707         pfk->dump.done = pfkey_dump_sp_done;
2708         xfrm_policy_walk_init(&pfk->dump.u.policy, XFRM_POLICY_TYPE_MAIN);
2709         mutex_unlock(&pfk->dump_lock);
2710
2711         return pfkey_do_dump(pfk);
2712 }
2713
2714 static int key_notify_policy_flush(const struct km_event *c)
2715 {
2716         struct sk_buff *skb_out;
2717         struct sadb_msg *hdr;
2718
2719         skb_out = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC);
2720         if (!skb_out)
2721                 return -ENOBUFS;
2722         hdr = (struct sadb_msg *) skb_put(skb_out, sizeof(struct sadb_msg));
2723         hdr->sadb_msg_type = SADB_X_SPDFLUSH;
2724         hdr->sadb_msg_seq = c->seq;
2725         hdr->sadb_msg_pid = c->pid;
2726         hdr->sadb_msg_version = PF_KEY_V2;
2727         hdr->sadb_msg_errno = (uint8_t) 0;
2728         hdr->sadb_msg_satype = SADB_SATYPE_UNSPEC;
2729         hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t));
2730         hdr->sadb_msg_reserved = 0;
2731         pfkey_broadcast(skb_out, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net);
2732         return 0;
2733
2734 }
2735
2736 static int pfkey_spdflush(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr, void * const *ext_hdrs)
2737 {
2738         struct net *net = sock_net(sk);
2739         struct km_event c;
2740         struct xfrm_audit audit_info;
2741         int err, err2;
2742
2743         audit_info.loginuid = audit_get_loginuid(current);
2744         audit_info.sessionid = audit_get_sessionid(current);
2745         audit_info.secid = 0;
2746         err = xfrm_policy_flush(net, XFRM_POLICY_TYPE_MAIN, &audit_info);
2747         err2 = unicast_flush_resp(sk, hdr);
2748         if (err || err2) {
2749                 if (err == -ESRCH) /* empty table - old silent behavior */
2750                         return 0;
2751                 return err;
2752         }
2753
2754         c.data.type = XFRM_POLICY_TYPE_MAIN;
2755         c.event = XFRM_MSG_FLUSHPOLICY;
2756         c.pid = hdr->sadb_msg_pid;
2757         c.seq = hdr->sadb_msg_seq;
2758         c.net = net;
2759         km_policy_notify(NULL, 0, &c);
2760
2761         return 0;
2762 }
2763
2764 typedef int (*pfkey_handler)(struct sock *sk, struct sk_buff *skb,
2765                              const struct sadb_msg *hdr, void * const *ext_hdrs);
2766 static pfkey_handler pfkey_funcs[SADB_MAX + 1] = {
2767         [SADB_RESERVED]         = pfkey_reserved,
2768         [SADB_GETSPI]           = pfkey_getspi,
2769         [SADB_UPDATE]           = pfkey_add,
2770         [SADB_ADD]              = pfkey_add,
2771         [SADB_DELETE]           = pfkey_delete,
2772         [SADB_GET]              = pfkey_get,
2773         [SADB_ACQUIRE]          = pfkey_acquire,
2774         [SADB_REGISTER]         = pfkey_register,
2775         [SADB_EXPIRE]           = NULL,
2776         [SADB_FLUSH]            = pfkey_flush,
2777         [SADB_DUMP]             = pfkey_dump,
2778         [SADB_X_PROMISC]        = pfkey_promisc,
2779         [SADB_X_PCHANGE]        = NULL,
2780         [SADB_X_SPDUPDATE]      = pfkey_spdadd,
2781         [SADB_X_SPDADD]         = pfkey_spdadd,
2782         [SADB_X_SPDDELETE]      = pfkey_spddelete,
2783         [SADB_X_SPDGET]         = pfkey_spdget,
2784         [SADB_X_SPDACQUIRE]     = NULL,
2785         [SADB_X_SPDDUMP]        = pfkey_spddump,
2786         [SADB_X_SPDFLUSH]       = pfkey_spdflush,
2787         [SADB_X_SPDSETIDX]      = pfkey_spdadd,
2788         [SADB_X_SPDDELETE2]     = pfkey_spdget,
2789         [SADB_X_MIGRATE]        = pfkey_migrate,
2790 };
2791
2792 static int pfkey_process(struct sock *sk, struct sk_buff *skb, const struct sadb_msg *hdr)
2793 {
2794         void *ext_hdrs[SADB_EXT_MAX];
2795         int err;
2796
2797         pfkey_broadcast(skb_clone(skb, GFP_KERNEL), GFP_KERNEL,
2798                         BROADCAST_PROMISC_ONLY, NULL, sock_net(sk));
2799
2800         memset(ext_hdrs, 0, sizeof(ext_hdrs));
2801         err = parse_exthdrs(skb, hdr, ext_hdrs);
2802         if (!err) {
2803                 err = -EOPNOTSUPP;
2804                 if (pfkey_funcs[hdr->sadb_msg_type])
2805                         err = pfkey_funcs[hdr->sadb_msg_type](sk, skb, hdr, ext_hdrs);
2806         }
2807         return err;
2808 }
2809
2810 static struct sadb_msg *pfkey_get_base_msg(struct sk_buff *skb, int *errp)
2811 {
2812         struct sadb_msg *hdr = NULL;
2813
2814         if (skb->len < sizeof(*hdr)) {
2815                 *errp = -EMSGSIZE;
2816         } else {
2817                 hdr = (struct sadb_msg *) skb->data;
2818                 if (hdr->sadb_msg_version != PF_KEY_V2 ||
2819                     hdr->sadb_msg_reserved != 0 ||
2820                     (hdr->sadb_msg_type <= SADB_RESERVED ||
2821                      hdr->sadb_msg_type > SADB_MAX)) {
2822                         hdr = NULL;
2823                         *errp = -EINVAL;
2824                 } else if (hdr->sadb_msg_len != (skb->len /
2825                                                  sizeof(uint64_t)) ||
2826                            hdr->sadb_msg_len < (sizeof(struct sadb_msg) /
2827                                                 sizeof(uint64_t))) {
2828                         hdr = NULL;
2829                         *errp = -EMSGSIZE;
2830                 } else {
2831                         *errp = 0;
2832                 }
2833         }
2834         return hdr;
2835 }
2836
2837 static inline int aalg_tmpl_set(const struct xfrm_tmpl *t,
2838                                 const struct xfrm_algo_desc *d)
2839 {
2840         unsigned int id = d->desc.sadb_alg_id;
2841
2842         if (id >= sizeof(t->aalgos) * 8)
2843                 return 0;
2844
2845         return (t->aalgos >> id) & 1;
2846 }
2847
2848 static inline int ealg_tmpl_set(const struct xfrm_tmpl *t,
2849                                 const struct xfrm_algo_desc *d)
2850 {
2851         unsigned int id = d->desc.sadb_alg_id;
2852
2853         if (id >= sizeof(t->ealgos) * 8)
2854                 return 0;
2855
2856         return (t->ealgos >> id) & 1;
2857 }
2858
2859 static int count_ah_combs(const struct xfrm_tmpl *t)
2860 {
2861         int i, sz = 0;
2862
2863         for (i = 0; ; i++) {
2864                 const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i);
2865                 if (!aalg)
2866                         break;
2867                 if (aalg_tmpl_set(t, aalg) && aalg->available)
2868                         sz += sizeof(struct sadb_comb);
2869         }
2870         return sz + sizeof(struct sadb_prop);
2871 }
2872
2873 static int count_esp_combs(const struct xfrm_tmpl *t)
2874 {
2875         int i, k, sz = 0;
2876
2877         for (i = 0; ; i++) {
2878                 const struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i);
2879                 if (!ealg)
2880                         break;
2881
2882                 if (!(ealg_tmpl_set(t, ealg) && ealg->available))
2883                         continue;
2884
2885                 for (k = 1; ; k++) {
2886                         const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(k);
2887                         if (!aalg)
2888                                 break;
2889
2890                         if (aalg_tmpl_set(t, aalg) && aalg->available)
2891                                 sz += sizeof(struct sadb_comb);
2892                 }
2893         }
2894         return sz + sizeof(struct sadb_prop);
2895 }
2896
2897 static void dump_ah_combs(struct sk_buff *skb, const struct xfrm_tmpl *t)
2898 {
2899         struct sadb_prop *p;
2900         int i;
2901
2902         p = (struct sadb_prop*)skb_put(skb, sizeof(struct sadb_prop));
2903         p->sadb_prop_len = sizeof(struct sadb_prop)/8;
2904         p->sadb_prop_exttype = SADB_EXT_PROPOSAL;
2905         p->sadb_prop_replay = 32;
2906         memset(p->sadb_prop_reserved, 0, sizeof(p->sadb_prop_reserved));
2907
2908         for (i = 0; ; i++) {
2909                 const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(i);
2910                 if (!aalg)
2911                         break;
2912
2913                 if (aalg_tmpl_set(t, aalg) && aalg->available) {
2914                         struct sadb_comb *c;
2915                         c = (struct sadb_comb*)skb_put(skb, sizeof(struct sadb_comb));
2916                         memset(c, 0, sizeof(*c));
2917                         p->sadb_prop_len += sizeof(struct sadb_comb)/8;
2918                         c->sadb_comb_auth = aalg->desc.sadb_alg_id;
2919                         c->sadb_comb_auth_minbits = aalg->desc.sadb_alg_minbits;
2920                         c->sadb_comb_auth_maxbits = aalg->desc.sadb_alg_maxbits;
2921                         c->sadb_comb_hard_addtime = 24*60*60;
2922                         c->sadb_comb_soft_addtime = 20*60*60;
2923                         c->sadb_comb_hard_usetime = 8*60*60;
2924                         c->sadb_comb_soft_usetime = 7*60*60;
2925                 }
2926         }
2927 }
2928
2929 static void dump_esp_combs(struct sk_buff *skb, const struct xfrm_tmpl *t)
2930 {
2931         struct sadb_prop *p;
2932         int i, k;
2933
2934         p = (struct sadb_prop*)skb_put(skb, sizeof(struct sadb_prop));
2935         p->sadb_prop_len = sizeof(struct sadb_prop)/8;
2936         p->sadb_prop_exttype = SADB_EXT_PROPOSAL;
2937         p->sadb_prop_replay = 32;
2938         memset(p->sadb_prop_reserved, 0, sizeof(p->sadb_prop_reserved));
2939
2940         for (i=0; ; i++) {
2941                 const struct xfrm_algo_desc *ealg = xfrm_ealg_get_byidx(i);
2942                 if (!ealg)
2943                         break;
2944
2945                 if (!(ealg_tmpl_set(t, ealg) && ealg->available))
2946                         continue;
2947
2948                 for (k = 1; ; k++) {
2949                         struct sadb_comb *c;
2950                         const struct xfrm_algo_desc *aalg = xfrm_aalg_get_byidx(k);
2951                         if (!aalg)
2952                                 break;
2953                         if (!(aalg_tmpl_set(t, aalg) && aalg->available))
2954                                 continue;
2955                         c = (struct sadb_comb*)skb_put(skb, sizeof(struct sadb_comb));
2956                         memset(c, 0, sizeof(*c));
2957                         p->sadb_prop_len += sizeof(struct sadb_comb)/8;
2958                         c->sadb_comb_auth = aalg->desc.sadb_alg_id;
2959                         c->sadb_comb_auth_minbits = aalg->desc.sadb_alg_minbits;
2960                         c->sadb_comb_auth_maxbits = aalg->desc.sadb_alg_maxbits;
2961                         c->sadb_comb_encrypt = ealg->desc.sadb_alg_id;
2962                         c->sadb_comb_encrypt_minbits = ealg->desc.sadb_alg_minbits;
2963                         c->sadb_comb_encrypt_maxbits = ealg->desc.sadb_alg_maxbits;
2964                         c->sadb_comb_hard_addtime = 24*60*60;
2965                         c->sadb_comb_soft_addtime = 20*60*60;
2966                         c->sadb_comb_hard_usetime = 8*60*60;
2967                         c->sadb_comb_soft_usetime = 7*60*60;
2968                 }
2969         }
2970 }
2971
2972 static int key_notify_policy_expire(struct xfrm_policy *xp, const struct km_event *c)
2973 {
2974         return 0;
2975 }
2976
2977 static int key_notify_sa_expire(struct xfrm_state *x, const struct km_event *c)
2978 {
2979         struct sk_buff *out_skb;
2980         struct sadb_msg *out_hdr;
2981         int hard;
2982         int hsc;
2983
2984         hard = c->data.hard;
2985         if (hard)
2986                 hsc = 2;
2987         else
2988                 hsc = 1;
2989
2990         out_skb = pfkey_xfrm_state2msg_expire(x, hsc);
2991         if (IS_ERR(out_skb))
2992                 return PTR_ERR(out_skb);
2993
2994         out_hdr = (struct sadb_msg *) out_skb->data;
2995         out_hdr->sadb_msg_version = PF_KEY_V2;
2996         out_hdr->sadb_msg_type = SADB_EXPIRE;
2997         out_hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto);
2998         out_hdr->sadb_msg_errno = 0;
2999         out_hdr->sadb_msg_reserved = 0;
3000         out_hdr->sadb_msg_seq = 0;
3001         out_hdr->sadb_msg_pid = 0;
3002
3003         pfkey_broadcast(out_skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL,
3004                         xs_net(x));
3005         return 0;
3006 }
3007
3008 static int pfkey_send_notify(struct xfrm_state *x, const struct km_event *c)
3009 {
3010         struct net *net = x ? xs_net(x) : c->net;
3011         struct netns_pfkey *net_pfkey = net_generic(net, pfkey_net_id);
3012
3013         if (atomic_read(&net_pfkey->socks_nr) == 0)
3014                 return 0;
3015
3016         switch (c->event) {
3017         case XFRM_MSG_EXPIRE:
3018                 return key_notify_sa_expire(x, c);
3019         case XFRM_MSG_DELSA:
3020         case XFRM_MSG_NEWSA:
3021         case XFRM_MSG_UPDSA:
3022                 return key_notify_sa(x, c);
3023         case XFRM_MSG_FLUSHSA:
3024                 return key_notify_sa_flush(c);
3025         case XFRM_MSG_NEWAE: /* not yet supported */
3026                 break;
3027         default:
3028                 pr_err("pfkey: Unknown SA event %d\n", c->event);
3029                 break;
3030         }
3031
3032         return 0;
3033 }
3034
3035 static int pfkey_send_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c)
3036 {
3037         if (xp && xp->type != XFRM_POLICY_TYPE_MAIN)
3038                 return 0;
3039
3040         switch (c->event) {
3041         case XFRM_MSG_POLEXPIRE:
3042                 return key_notify_policy_expire(xp, c);
3043         case XFRM_MSG_DELPOLICY:
3044         case XFRM_MSG_NEWPOLICY:
3045         case XFRM_MSG_UPDPOLICY:
3046                 return key_notify_policy(xp, dir, c);
3047         case XFRM_MSG_FLUSHPOLICY:
3048                 if (c->data.type != XFRM_POLICY_TYPE_MAIN)
3049                         break;
3050                 return key_notify_policy_flush(c);
3051         default:
3052                 pr_err("pfkey: Unknown policy event %d\n", c->event);
3053                 break;
3054         }
3055
3056         return 0;
3057 }
3058
3059 static u32 get_acqseq(void)
3060 {
3061         u32 res;
3062         static atomic_t acqseq;
3063
3064         do {
3065                 res = atomic_inc_return(&acqseq);
3066         } while (!res);
3067         return res;
3068 }
3069
3070 static int pfkey_send_acquire(struct xfrm_state *x, struct xfrm_tmpl *t, struct xfrm_policy *xp, int dir)
3071 {
3072         struct sk_buff *skb;
3073         struct sadb_msg *hdr;
3074         struct sadb_address *addr;
3075         struct sadb_x_policy *pol;
3076         int sockaddr_size;
3077         int size;
3078         struct sadb_x_sec_ctx *sec_ctx;
3079         struct xfrm_sec_ctx *xfrm_ctx;
3080         int ctx_size = 0;
3081
3082         sockaddr_size = pfkey_sockaddr_size(x->props.family);
3083         if (!sockaddr_size)
3084                 return -EINVAL;
3085
3086         size = sizeof(struct sadb_msg) +
3087                 (sizeof(struct sadb_address) * 2) +
3088                 (sockaddr_size * 2) +
3089                 sizeof(struct sadb_x_policy);
3090
3091         if (x->id.proto == IPPROTO_AH)
3092                 size += count_ah_combs(t);
3093         else if (x->id.proto == IPPROTO_ESP)
3094                 size += count_esp_combs(t);
3095
3096         if ((xfrm_ctx = x->security)) {
3097                 ctx_size = PFKEY_ALIGN8(xfrm_ctx->ctx_len);
3098                 size +=  sizeof(struct sadb_x_sec_ctx) + ctx_size;
3099         }
3100
3101         skb =  alloc_skb(size + 16, GFP_ATOMIC);
3102         if (skb == NULL)
3103                 return -ENOMEM;
3104
3105         hdr = (struct sadb_msg *) skb_put(skb, sizeof(struct sadb_msg));
3106         hdr->sadb_msg_version = PF_KEY_V2;
3107         hdr->sadb_msg_type = SADB_ACQUIRE;
3108         hdr->sadb_msg_satype = pfkey_proto2satype(x->id.proto);
3109         hdr->sadb_msg_len = size / sizeof(uint64_t);
3110         hdr->sadb_msg_errno = 0;
3111         hdr->sadb_msg_reserved = 0;
3112         hdr->sadb_msg_seq = x->km.seq = get_acqseq();
3113         hdr->sadb_msg_pid = 0;
3114
3115         /* src address */
3116         addr = (struct sadb_address*) skb_put(skb,
3117                                               sizeof(struct sadb_address)+sockaddr_size);
3118         addr->sadb_address_len =
3119                 (sizeof(struct sadb_address)+sockaddr_size)/
3120                         sizeof(uint64_t);
3121         addr->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
3122         addr->sadb_address_proto = 0;
3123         addr->sadb_address_reserved = 0;
3124         addr->sadb_address_prefixlen =
3125                 pfkey_sockaddr_fill(&x->props.saddr, 0,
3126                                     (struct sockaddr *) (addr + 1),
3127                                     x->props.family);
3128         if (!addr->sadb_address_prefixlen)
3129                 BUG();
3130
3131         /* dst address */
3132         addr = (struct sadb_address*) skb_put(skb,
3133                                               sizeof(struct sadb_address)+sockaddr_size);
3134         addr->sadb_address_len =
3135                 (sizeof(struct sadb_address)+sockaddr_size)/
3136                         sizeof(uint64_t);
3137         addr->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
3138         addr->sadb_address_proto = 0;
3139         addr->sadb_address_reserved = 0;
3140         addr->sadb_address_prefixlen =
3141                 pfkey_sockaddr_fill(&x->id.daddr, 0,
3142                                     (struct sockaddr *) (addr + 1),
3143                                     x->props.family);
3144         if (!addr->sadb_address_prefixlen)
3145                 BUG();
3146
3147         pol = (struct sadb_x_policy *)  skb_put(skb, sizeof(struct sadb_x_policy));
3148         pol->sadb_x_policy_len = sizeof(struct sadb_x_policy)/sizeof(uint64_t);
3149         pol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;
3150         pol->sadb_x_policy_type = IPSEC_POLICY_IPSEC;
3151         pol->sadb_x_policy_dir = dir+1;
3152         pol->sadb_x_policy_reserved = 0;
3153         pol->sadb_x_policy_id = xp->index;
3154         pol->sadb_x_policy_priority = xp->priority;
3155
3156         /* Set sadb_comb's. */
3157         if (x->id.proto == IPPROTO_AH)
3158                 dump_ah_combs(skb, t);
3159         else if (x->id.proto == IPPROTO_ESP)
3160                 dump_esp_combs(skb, t);
3161
3162         /* security context */
3163         if (xfrm_ctx) {
3164                 sec_ctx = (struct sadb_x_sec_ctx *) skb_put(skb,
3165                                 sizeof(struct sadb_x_sec_ctx) + ctx_size);
3166                 sec_ctx->sadb_x_sec_len =
3167                   (sizeof(struct sadb_x_sec_ctx) + ctx_size) / sizeof(uint64_t);
3168                 sec_ctx->sadb_x_sec_exttype = SADB_X_EXT_SEC_CTX;
3169                 sec_ctx->sadb_x_ctx_doi = xfrm_ctx->ctx_doi;
3170                 sec_ctx->sadb_x_ctx_alg = xfrm_ctx->ctx_alg;
3171                 sec_ctx->sadb_x_ctx_len = xfrm_ctx->ctx_len;
3172                 memcpy(sec_ctx + 1, xfrm_ctx->ctx_str,
3173                        xfrm_ctx->ctx_len);
3174         }
3175
3176         return pfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_REGISTERED, NULL,
3177                                xs_net(x));
3178 }
3179
3180 static struct xfrm_policy *pfkey_compile_policy(struct sock *sk, int opt,
3181                                                 u8 *data, int len, int *dir)
3182 {
3183         struct net *net = sock_net(sk);
3184         struct xfrm_policy *xp;
3185         struct sadb_x_policy *pol = (struct sadb_x_policy*)data;
3186         struct sadb_x_sec_ctx *sec_ctx;
3187
3188         switch (sk->sk_family) {
3189         case AF_INET:
3190                 if (opt != IP_IPSEC_POLICY) {
3191                         *dir = -EOPNOTSUPP;
3192                         return NULL;
3193                 }
3194                 break;
3195 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
3196         case AF_INET6:
3197                 if (opt != IPV6_IPSEC_POLICY) {
3198                         *dir = -EOPNOTSUPP;
3199                         return NULL;
3200                 }
3201                 break;
3202 #endif
3203         default:
3204                 *dir = -EINVAL;
3205                 return NULL;
3206         }
3207
3208         *dir = -EINVAL;
3209
3210         if (len < sizeof(struct sadb_x_policy) ||
3211             pol->sadb_x_policy_len*8 > len ||
3212             pol->sadb_x_policy_type > IPSEC_POLICY_BYPASS ||
3213             (!pol->sadb_x_policy_dir || pol->sadb_x_policy_dir > IPSEC_DIR_OUTBOUND))
3214                 return NULL;
3215
3216         xp = xfrm_policy_alloc(net, GFP_ATOMIC);
3217         if (xp == NULL) {
3218                 *dir = -ENOBUFS;
3219                 return NULL;