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