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