Allow controller to set MAC address to use in ARP responses for SNAT IPs.
[sliver-openvswitch.git] / datapath / nx_act_snat.c
1 #ifdef SUPPORT_SNAT
2 /*
3  * Distributed under the terms of the GNU GPL version 2.
4  * Copyright (c) 2008 Nicira Networks
5  */
6
7 #include <linux/etherdevice.h>
8 #include <linux/netdevice.h>
9 #include <linux/netfilter.h>
10 #include <linux/netfilter_ipv4.h>
11 #include <linux/in.h>
12 #include <net/ip.h>
13 #include <linux/icmp.h>
14 #include <linux/if_ether.h>
15 #include <net/arp.h>
16 #include <net/route.h>
17
18 #include "forward.h"
19 #include "dp_act.h"
20 #include "nx_act_snat.h"
21
22
23 /* We need these fake structures to make netfilter happy --
24  * lots of places assume that skb->dst != NULL, which isn't
25  * all that unreasonable.
26  *
27  * Currently, we fill in the PMTU entry because netfilter
28  * refragmentation needs it, and the rt_flags entry because
29  * ipt_REJECT needs it.  Future netfilter modules might
30  * require us to fill additional fields. */
31 static struct net_device __fake_net_device = {
32         .hard_header_len        = ETH_HLEN
33 };
34
35 static struct rtable __fake_rtable = {
36         .u = {
37                 .dst = {
38                         .__refcnt          = ATOMIC_INIT(1),
39                         .dev                    = &__fake_net_device,
40                         .path              = &__fake_rtable.u.dst,
41                         .metrics                = {[RTAX_MTU - 1] = 1500},
42                         .flags            = DST_NOXFRM,
43                 }
44         },
45         .rt_flags   = 0,
46 };
47
48 /* Define ARP for IP since the Linux headers don't do it cleanly. */
49 struct ip_arphdr {
50         uint16_t ar_hrd;
51         uint16_t ar_pro;
52         uint8_t ar_hln;
53         uint8_t ar_pln;
54         uint16_t ar_op;
55         uint8_t ar_sha[ETH_ALEN];
56         uint32_t ar_sip;
57         uint8_t ar_tha[ETH_ALEN];
58         uint32_t ar_tip;
59 } __attribute__((packed));
60 OFP_ASSERT(sizeof(struct ip_arphdr) == 28);
61
62
63 /* Push the Ethernet header back on and tranmit the packet. */
64 static int
65 dp_xmit_skb_push(struct sk_buff *skb)
66 {
67         skb_push(skb, ETH_HLEN);
68         return dp_xmit_skb(skb);
69 }
70
71 /* Perform maintainence related to a SNAT'd interface.  Currently, this only 
72  * checks whether MAC->IP bindings have expired.
73  *
74  * Called with the RCU read lock */
75 void
76 snat_maint(struct net_bridge_port *p)
77 {
78         struct snat_conf *sc;
79         struct snat_mapping *m, *n;
80         unsigned long flags;
81         unsigned long timeout;
82
83         spin_lock_irqsave(&p->lock, flags);
84         sc = p->snat;
85         if (!sc)
86                 goto done;
87
88         timeout = sc->mac_timeout * HZ;
89
90         list_for_each_entry_safe (m, n, &sc->mappings, node) {
91                 if (time_after(jiffies, m->used + timeout)) {
92                         list_del(&m->node);
93                         kfree(m);
94                 }
95         }
96
97 done:
98         spin_unlock_irqrestore(&p->lock, flags);
99 }
100
101 /* When the packet is bound for a local interface, strip off the fake
102  * routing table.
103  */
104 void snat_local_in(struct sk_buff *skb)
105 {
106         if (skb->dst == (struct dst_entry *)&__fake_rtable) {
107                 dst_release(skb->dst);
108                 skb->dst = NULL;
109         }
110 }
111
112 /* Check whether destination IP's address is in the IP->MAC mappings.
113  * If it is, then overwrite the destination MAC with the value from the
114  * cache.
115  *
116  * Returns -1 if there is a problem, otherwise 0. */
117 static int
118 dnat_mac(struct net_bridge_port *p, struct sk_buff *skb)
119 {
120         struct snat_conf *sc = p->snat;
121         struct iphdr *iph = ip_hdr(skb);
122         struct ethhdr *eh = eth_hdr(skb);
123         struct snat_mapping *m;
124
125         if (skb->protocol != htons(ETH_P_IP)) 
126                 return 0;
127
128         list_for_each_entry (m, &sc->mappings, node) {
129                 if (m->ip_addr == iph->daddr){
130                         /* Found it! */
131                         if (!make_writable(&skb)) {
132                                 if (net_ratelimit())
133                                         printk("make_writable failed\n");
134                                 return -EINVAL;
135                         }
136                         m->used = jiffies;
137                         memcpy(eh->h_dest, m->hw_addr, ETH_ALEN);
138                         break;
139                 }
140         }
141
142         return 0;
143 }
144
145 static int
146 __snat_this_address(struct snat_conf *sc, u32 ip_addr)
147 {
148         if (sc) {
149                 u32 h_ip_addr = ntohl(ip_addr);
150                 return (h_ip_addr >= sc->ip_addr_start &&
151                         h_ip_addr <= sc->ip_addr_end);
152         }
153         return 0;
154 }
155
156 static int
157 snat_this_address(struct net_bridge_port *p, u32 ip_addr)
158 {
159         unsigned long int flags;
160         int retval;
161
162         spin_lock_irqsave(&p->lock, flags);
163         retval = __snat_this_address(p->snat, ip_addr);
164         spin_unlock_irqrestore(&p->lock, flags);
165
166         return retval;
167 }
168
169 /* Must hold RCU lock. */
170 static struct net_bridge_port *
171 get_nbp_by_ip_addr(struct datapath *dp, u32 ip_addr)
172 {
173         struct net_bridge_port *p;
174
175         list_for_each_entry_rcu (p, &dp->port_list, node)
176                 if (snat_this_address(p, ip_addr))
177                         return p;
178
179         return NULL;
180 }
181
182 static int
183 snat_pre_route_finish(struct sk_buff *skb)
184 {
185         struct net_bridge_port *p = skb->dev->br_port;
186         struct snat_conf *sc;
187         struct iphdr *iph = ip_hdr(skb);
188         unsigned long flags;
189
190         skb->dst = (struct dst_entry *)&__fake_rtable;
191         dst_hold(skb->dst);
192
193         /* Don't process packets that were not translated due to NAT */
194         spin_lock_irqsave(&p->lock, flags);
195         sc = p->snat;
196         if (!__snat_this_address(sc, iph->daddr)) {
197                 /* If SNAT is configured for this input device, check the
198                  * IP->MAC mappings to see if we should update the destination
199                  * MAC. */
200                 if (sc)
201                         dnat_mac(skb->dev->br_port, skb);
202
203         }
204         spin_unlock_irqrestore(&p->lock, flags);
205
206         /* Pass the translated packet as input to the OpenFlow stack, which
207          * consumes it. */
208         skb_push(skb, ETH_HLEN);
209         skb_reset_mac_header(skb);
210         fwd_port_input(p->dp->chain, skb, p);
211
212         return 0;
213 }
214
215 /* Checks whether 'skb' is an ARP request for an SNAT'd interface.  If
216  * so, it will generate a response.  
217  *
218  * Returns 0 if the packet was not handled.  Otherwise, -1 is returned
219  * and the caller is responsible for freeing 'skb'. */
220 static int 
221 handle_arp_snat(struct sk_buff *skb)
222 {
223         struct net_bridge_port *s_nbp = skb->dev->br_port;
224         struct net_bridge_port *nat_nbp;
225         struct ip_arphdr *ah;
226         uint8_t mac_addr[ETH_ALEN];
227
228         if (!pskb_may_pull(skb, sizeof *ah))
229                 return 0;
230
231         ah = (struct ip_arphdr *)arp_hdr(skb);
232         if ((ah->ar_op != htons(ARPOP_REQUEST)) 
233                         || ah->ar_hln != ETH_ALEN
234                         || ah->ar_pro != htons(ETH_P_IP)
235                         || ah->ar_pln != 4)
236                 return 0;
237
238         rcu_read_lock();
239         nat_nbp = get_nbp_by_ip_addr(s_nbp->dp, ah->ar_tip);
240         if (!nat_nbp) {
241                 rcu_read_unlock();
242                 return 0;
243         }
244         if (s_nbp == nat_nbp) 
245                 memcpy(mac_addr, s_nbp->dp->netdev->dev_addr, sizeof(mac_addr));
246         else if (!is_zero_ether_addr(nat_nbp->snat->mac_addr)) 
247                 memcpy(mac_addr, nat_nbp->snat->mac_addr, sizeof(mac_addr));
248         else {
249                 rcu_read_unlock();
250                 return 0;
251         }
252         rcu_read_unlock();
253
254         arp_send(ARPOP_REPLY, ETH_P_ARP, ah->ar_sip, skb->dev, ah->ar_tip, 
255                          ah->ar_sha, mac_addr, ah->ar_sha);
256
257         return -1;
258 }
259
260 /* Checks whether 'skb' is a ping request for an SNAT'd interface.  If
261  * so, it will generate a response.  
262  *
263  * Returns 0 if the packet was not handled.  Otherwise, -1 is returned
264  * and the caller is responsible for freeing 'skb'. */
265 static int 
266 handle_icmp_snat(struct sk_buff *skb)
267 {
268         struct net_bridge_port *p = skb->dev->br_port;
269         struct ethhdr *eh;
270         struct iphdr *iph;
271         struct icmphdr *icmph;
272         uint8_t tmp_eth[ETH_ALEN];
273         uint32_t tmp_ip;
274         struct sk_buff *nskb;
275
276         /* We're only interested in addresses we rewrite. */
277         iph = ip_hdr(skb);
278         if (!snat_this_address(p, iph->daddr)) {
279                 return 0;
280         }
281
282         /* Drop fragments and packets not long enough to hold the ICMP
283          * header. */
284         if ((ntohs(iph->frag_off) & IP_OFFSET) != 0 ||
285             !pskb_may_pull(skb, skb_transport_offset(skb) + 4))
286                 return 0;
287
288         /* We only respond to echo requests to our address.  Continue 
289          * processing replies and other ICMP messages since they may be 
290          * intended for NAT'd hosts. */
291         icmph = icmp_hdr(skb);
292         if (icmph->type != ICMP_ECHO)
293                 return 0;
294
295         /* Send an echo reply in response */
296         nskb = skb_copy(skb, GFP_ATOMIC);
297         if (!nskb) {
298                 if (net_ratelimit())
299                         printk("skb copy failed for icmp reply\n");
300                 return -1;
301         }
302
303         /* Update Ethernet header. */
304         eh = eth_hdr(nskb);
305         memcpy(tmp_eth, eh->h_dest, ETH_ALEN);
306         memcpy(eh->h_dest, eh->h_source, ETH_ALEN);
307         memcpy(eh->h_source, tmp_eth, ETH_ALEN);
308
309         /* Update IP header.
310          * This is kind of busted, at least in that it doesn't check that the
311          * echoed IP options make sense. */
312         iph = ip_hdr(nskb);
313         iph->id = 0;
314         iph->frag_off = 0;
315         iph->ttl = IPDEFTTL;
316         iph->check = 0;
317         tmp_ip = iph->daddr;
318         iph->daddr = iph->saddr;
319         iph->saddr = tmp_ip;
320         iph->check = ip_fast_csum(iph, iph->ihl);
321
322         /* Update ICMP header. */
323         icmph = icmp_hdr(nskb);
324         icmph->type = ICMP_ECHOREPLY;
325         icmph->checksum = 0;
326         icmph->checksum = ip_compute_csum(icmph,
327                                           nskb->tail - nskb->transport_header);
328
329         dp_xmit_skb_push(nskb);
330
331         return -1;
332 }
333
334 /* Check if any SNAT maintenance needs to be done on 'skb' before it's 
335  * checked against the datapath's tables.  This includes DNAT
336  * modification based on prior SNAT action and responding to ARP and
337  * echo requests for the SNAT interface. 
338  *
339  * Returns -1 if the packet was handled and consumed, 0 if the caller
340  * should continue to process 'skb'.
341  */
342 int
343 snat_pre_route(struct sk_buff *skb)
344 {
345         struct iphdr *iph;
346         int len;
347
348         WARN_ON_ONCE(skb_network_offset(skb));
349         if (skb->protocol == htons(ETH_P_ARP)) {
350                 if (handle_arp_snat(skb))
351                         goto consume;
352                 return 0;
353         }
354         else if (skb->protocol != htons(ETH_P_IP)) 
355                 return 0;
356
357         if (!pskb_may_pull(skb, sizeof *iph))
358                 goto consume;
359
360         iph = ip_hdr(skb);
361         if (iph->ihl < 5 || iph->version != 4)
362                 goto consume;
363
364         if (!pskb_may_pull(skb, ip_hdrlen(skb)))
365                 goto consume;
366         skb_set_transport_header(skb, ip_hdrlen(skb));
367
368         /* Check if we need to echo reply for this address */
369         iph = ip_hdr(skb);
370         if ((iph->protocol == IPPROTO_ICMP) && (handle_icmp_snat(skb))) 
371                 goto consume;
372
373         iph = ip_hdr(skb);
374         if (unlikely(ip_fast_csum(iph, iph->ihl)))
375                 goto consume;
376
377         len = ntohs(iph->tot_len);
378         if ((skb->len < len) || len < (iph->ihl*4))
379                 goto consume;
380
381         if (pskb_trim_rcsum(skb, len))
382                 goto consume;
383
384         NF_HOOK(PF_INET, NF_INET_PRE_ROUTING, skb, skb->dev, NULL,
385                 snat_pre_route_finish);
386         return -1;
387
388 consume:
389         kfree_skb(skb);
390         return -1;
391 }
392
393
394 static int 
395 snat_skb_finish(struct sk_buff *skb)
396 {
397         NF_HOOK(PF_INET, NF_INET_POST_ROUTING, skb, NULL, skb->dev, 
398                         dp_xmit_skb_push);
399
400         return 0;
401 }
402
403 /* Update the MAC->IP mappings for the private side of the SNAT'd
404  * interface. */
405 static void
406 update_mapping(struct net_bridge_port *p, const struct sk_buff *skb)
407 {
408         unsigned long flags;
409         struct snat_conf *sc;
410         const struct iphdr *iph = ip_hdr(skb);
411         const struct ethhdr *eh = eth_hdr(skb);
412         struct snat_mapping *m;
413
414         spin_lock_irqsave(&p->lock, flags);
415         sc = p->snat;
416         if (!sc) 
417                 goto done;
418         
419         list_for_each_entry (m, &sc->mappings, node) {
420                 if (m->ip_addr == iph->saddr){
421                         memcpy(m->hw_addr, eh->h_source, ETH_ALEN);
422                         m->used = jiffies;
423                         goto done;
424                 }
425         }
426
427         m = kmalloc(sizeof *m, GFP_ATOMIC);
428         if (!m)
429                 goto done;
430         m->ip_addr = iph->saddr;
431         memcpy(m->hw_addr, eh->h_source, ETH_ALEN);
432         m->used = jiffies;
433
434         list_add(&m->node, &sc->mappings);
435
436 done:
437         spin_unlock_irqrestore(&p->lock, flags);
438 }
439
440 /* Perform SNAT modification on 'skb' and send out 'out_port'.  If the 
441  * port was not configured for SNAT, it will be sent through the interface 
442  * unmodified.  'skb' is not consumed, so caller will need to free it.
443  */
444 void 
445 snat_skb(struct datapath *dp, const struct sk_buff *skb, int out_port)
446 {
447         struct net_bridge_port *p = dp->ports[out_port];
448         struct sk_buff *nskb;
449
450         if (!p)
451                 return;
452
453         /* FIXME: Expensive.  Just need to skb_clone() here?
454          * (However, the skb_copy() does linearize and ensure that the headers
455          * are accessible.) */
456         nskb = skb_copy(skb, GFP_ATOMIC);
457         if (!nskb)
458                 return;
459
460         nskb->dev = p->dev;
461
462         /* We only SNAT IP, so just send it on its way if not */
463         if (skb->protocol != htons(ETH_P_IP)) {
464                 dp_xmit_skb(nskb);
465                 return;
466         }
467
468         /* Set the source MAC to the OF interface */
469         memcpy(eth_hdr(nskb)->h_source, dp->netdev->dev_addr, ETH_ALEN);
470
471         update_mapping(p, skb);
472
473         /* Take the Ethernet header back off for netfilter hooks. */
474         skb_pull(nskb, ETH_HLEN);
475
476         NF_HOOK(PF_INET, NF_INET_FORWARD, nskb, skb->dev, nskb->dev, 
477                         snat_skb_finish);
478 }
479
480 /* Remove SNAT configuration on port 'p'.  
481  *
482  * NB: The caller must hold the port's spinlock. */
483 int
484 snat_free_conf(struct net_bridge_port *p)
485 {
486         struct snat_conf *sc = p->snat;
487
488         if (!sc) 
489                 return -EINVAL;
490
491         /* Free existing mapping entries */
492         while (!list_empty(&sc->mappings)) {
493                 struct snat_mapping *m = list_entry(sc->mappings.next, 
494                                 struct snat_mapping, node);
495                 list_del(&m->node);
496                 kfree(m);
497         }
498
499         kfree(p->snat);
500         p->snat = NULL;
501
502         return 0;
503 }
504
505 /* Remove SNAT configuration from an interface. */
506 static int 
507 snat_del_port(struct datapath *dp, const struct nx_snat_config *nsc)
508 {
509         unsigned long flags;
510         uint16_t port = ntohs(nsc->port);
511         struct net_bridge_port *p = dp->ports[port];
512
513         if (!p) {
514                 if (net_ratelimit()) 
515                         printk("Attempt to remove snat on non-existent port: %d\n", port);
516                 return -EINVAL;
517         }
518
519         spin_lock_irqsave(&p->lock, flags);
520         if (snat_free_conf(p)) {
521                 /* SNAT not configured on this port */
522                 spin_unlock_irqrestore(&p->lock, flags);
523                 if (net_ratelimit()) 
524                         printk("Attempt to remove snat on non-snat port: %d\n", port);
525                 return -EINVAL;
526         }
527
528         spin_unlock_irqrestore(&p->lock, flags);
529
530         return 0;
531 }
532
533 /* Add SNAT configuration to an interface.  */
534 static int 
535 snat_add_port(struct datapath *dp, const struct nx_snat_config *nsc)
536 {
537         unsigned long flags;
538         uint16_t port = ntohs(nsc->port);
539         struct net_bridge_port *p = dp->ports[port];
540         uint16_t mac_timeout = ntohs(nsc->mac_timeout);
541         struct snat_conf *sc;
542         
543         if (mac_timeout == 0)
544                 mac_timeout = MAC_TIMEOUT_DEFAULT;
545
546         if (!p) {
547                 if (net_ratelimit()) 
548                         printk("Attempt to add snat on non-existent port: %d\n", port);
549                 return -EINVAL;
550         }
551         
552         /* If SNAT is already configured on the port, check whether the same
553          * IP addresses are used.  If so, just update the mac timeout
554          * configuration. Otherwise, drop all SNAT configuration and
555          * reconfigure it. */
556         spin_lock_irqsave(&p->lock, flags);
557         if (p->snat) {
558                 if ((p->snat->ip_addr_start == ntohl(nsc->ip_addr_start)) 
559                                 && (p->snat->ip_addr_end == ntohl(nsc->ip_addr_end))) {
560                         p->snat->mac_timeout = mac_timeout;
561                         spin_unlock_irqrestore(&p->lock, flags);
562                         return 0;
563                 }
564
565                 /* Free the existing configuration and mappings. */
566                 snat_free_conf(p);
567         }
568
569         sc = kzalloc(sizeof *sc, GFP_ATOMIC);
570         if (!sc) {
571                 spin_unlock_irqrestore(&p->lock, flags);
572                 return -ENOMEM;
573         }
574
575         sc->ip_addr_start = ntohl(nsc->ip_addr_start);
576         sc->ip_addr_end = ntohl(nsc->ip_addr_end);
577         sc->mac_timeout = mac_timeout;
578         memcpy(sc->mac_addr, nsc->mac_addr, sizeof(sc->mac_addr));
579         INIT_LIST_HEAD(&sc->mappings);
580
581         p->snat = sc;
582         spin_unlock_irqrestore(&p->lock, flags);
583
584         return 0;
585 }
586
587 /* Handle a SNAT configuration message. 
588  *
589  * Returns 0 if no problems are found.  Otherwise, a negative errno. */
590 int 
591 snat_mod_config(struct datapath *dp, const struct nx_act_config *nac)
592 {
593         int n_entries = (ntohs(nac->header.header.length) - sizeof *nac)
594                         / sizeof (struct nx_snat_config);
595         int ret = 0;
596         int i;
597
598         for (i=0; i<n_entries; i++) {
599                 const struct nx_snat_config *nsc = &nac->snat[i];
600                 int r = 0;
601
602                 if (nsc->command == NXSC_ADD)
603                         r = snat_add_port(dp, nsc);
604                 else 
605                         r = snat_del_port(dp, nsc);
606
607                 if (r)
608                         ret = r;
609         }
610
611         return ret;
612 }
613 #endif