VBoxNetLwipNAT.cpp revision 5eb4b75eda15627221295b5a3edf2d0622b4da28
1N/A/* $Id$ */
1N/A/** @file
1N/A * VBoxNetNAT - NAT Service for connecting to IntNet.
1N/A */
1N/A
1N/A/*
1N/A * Copyright (C) 2009 Oracle Corporation
1N/A *
1N/A * This file is part of VirtualBox Open Source Edition (OSE), as
1N/A * available from http://www.virtualbox.org. This file is free software;
1N/A * you can redistribute it and/or modify it under the terms of the GNU
1N/A * General Public License (GPL) as published by the Free Software
1N/A * Foundation, in version 2 as it comes in the "COPYING" file of the
1N/A * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
1N/A * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
1N/A */
1N/A
1N/A#include "winutils.h"
1N/A
1N/A#include <VBox/com/assert.h>
1N/A#include <VBox/com/com.h>
1N/A#include <VBox/com/listeners.h>
1N/A#include <VBox/com/string.h>
1N/A#include <VBox/com/Guid.h>
1N/A#include <VBox/com/array.h>
1N/A#include <VBox/com/ErrorInfo.h>
1N/A#include <VBox/com/errorprint.h>
1N/A#include <VBox/com/VirtualBox.h>
1N/A
1N/A#include <iprt/net.h>
1N/A#include <iprt/initterm.h>
1N/A#include <iprt/alloca.h>
1N/A#ifndef RT_OS_WINDOWS
1N/A# include <arpa/inet.h>
1N/A#endif
1N/A#include <iprt/err.h>
1N/A#include <iprt/time.h>
1N/A#include <iprt/timer.h>
1N/A#include <iprt/thread.h>
1N/A#include <iprt/stream.h>
1N/A#include <iprt/path.h>
1N/A#include <iprt/param.h>
1N/A#include <iprt/pipe.h>
1N/A#include <iprt/getopt.h>
1N/A#include <iprt/string.h>
1N/A#include <iprt/mem.h>
1N/A#include <iprt/message.h>
1N/A#include <iprt/req.h>
1N/A#include <iprt/file.h>
1N/A#include <iprt/semaphore.h>
1N/A#include <iprt/cpp/utils.h>
1N/A#define LOG_GROUP LOG_GROUP_NAT_SERVICE
1N/A#include <VBox/log.h>
1N/A
1N/A#include <VBox/sup.h>
1N/A#include <VBox/intnet.h>
1N/A#include <VBox/intnetinline.h>
1N/A#include <VBox/vmm/pdmnetinline.h>
1N/A#include <VBox/vmm/vmm.h>
1N/A#include <VBox/version.h>
1N/A
1N/A#ifndef RT_OS_WINDOWS
1N/A# include <sys/poll.h>
1N/A# include <sys/socket.h>
1N/A# include <netinet/in.h>
1N/A# ifdef RT_OS_LINUX
1N/A# include <linux/icmp.h> /* ICMP_FILTER */
1N/A# endif
1N/A# include <netinet/icmp6.h>
1N/A#endif
1N/A
1N/A#include <map>
1N/A#include <vector>
1N/A#include <string>
1N/A
1N/A#include "../NetLib/VBoxNetLib.h"
1N/A#include "../NetLib/VBoxNetBaseService.h"
1N/A#include "../NetLib/utils.h"
1N/A#include "VBoxLwipCore.h"
1N/A
1N/Aextern "C"
1N/A{
1N/A/* bunch of LWIP headers */
1N/A#include "lwip/opt.h"
1N/A#ifdef LWIP_SOCKET
1N/A# undef LWIP_SOCKET
1N/A# define LWIP_SOCKET 0
1N/A#endif
1N/A#include "lwip/sys.h"
1N/A#include "lwip/pbuf.h"
1N/A#include "lwip/netif.h"
1N/A#include "lwip/ethip6.h"
1N/A#include "lwip/nd6.h" // for proxy_na_hook
1N/A#include "lwip/mld6.h"
1N/A#include "lwip/tcpip.h"
1N/A#include "netif/etharp.h"
1N/A
1N/A#include "proxy.h"
1N/A#include "pxremap.h"
1N/A#include "portfwd.h"
1N/A}
1N/A
1N/A
1N/A#if defined(VBOX_RAWSOCK_DEBUG_HELPER) \
1N/A && (defined(VBOX_WITH_HARDENING) \
1N/A || defined(RT_OS_WINDOWS) \
1N/A || defined(RT_OS_DARWIN))
1N/A# error Have you forgotten to turn off VBOX_RAWSOCK_DEBUG_HELPER?
1N/A#endif
1N/A
1N/A#ifdef VBOX_RAWSOCK_DEBUG_HELPER
1N/Aextern "C" int getrawsock(int type);
1N/A#endif
1N/A
1N/A#include "../NetLib/VBoxPortForwardString.h"
1N/A
1N/Astatic RTGETOPTDEF g_aGetOptDef[] =
1N/A{
1N/A { "--port-forward4", 'p', RTGETOPT_REQ_STRING },
1N/A { "--port-forward6", 'P', RTGETOPT_REQ_STRING }
1N/A};
1N/A
1N/Atypedef struct NATSEVICEPORTFORWARDRULE
1N/A{
1N/A PORTFORWARDRULE Pfr;
1N/A fwspec FWSpec;
1N/A} NATSEVICEPORTFORWARDRULE, *PNATSEVICEPORTFORWARDRULE;
1N/A
1N/Atypedef std::vector<NATSEVICEPORTFORWARDRULE> VECNATSERVICEPF;
1N/Atypedef VECNATSERVICEPF::iterator ITERATORNATSERVICEPF;
1N/Atypedef VECNATSERVICEPF::const_iterator CITERATORNATSERVICEPF;
1N/A
1N/Astatic int fetchNatPortForwardRules(const ComNatPtr&, bool, VECNATSERVICEPF&);
1N/A
1N/A
1N/Aclass VBoxNetLwipNAT: public VBoxNetBaseService, public NATNetworkEventAdapter
1N/A{
1N/A friend class NATNetworkListener;
1N/A public:
1N/A VBoxNetLwipNAT(SOCKET icmpsock4, SOCKET icmpsock6);
1N/A virtual ~VBoxNetLwipNAT();
1N/A void usage(){ /* @todo: should be implemented */ };
1N/A int run();
1N/A virtual int init(void);
1N/A virtual int parseOpt(int rc, const RTGETOPTUNION& getOptVal);
1N/A /* VBoxNetNAT always needs Main */
1N/A virtual bool isMainNeeded() const { return true; }
1N/A virtual int processFrame(void *, size_t);
1N/A virtual int processGSO(PCPDMNETWORKGSO, size_t);
1N/A virtual int processUDP(void *, size_t) { return VERR_IGNORED; }
1N/A
1N/A private:
1N/A struct proxy_options m_ProxyOptions;
1N/A struct sockaddr_in m_src4;
1N/A struct sockaddr_in6 m_src6;
1N/A /**
1N/A * place for registered local interfaces.
1N/A */
1N/A ip4_lomap m_lo2off[10];
1N/A ip4_lomap_desc m_loOptDescriptor;
1N/A
1N/A uint16_t m_u16Mtu;
1N/A netif m_LwipNetIf;
1N/A
1N/A /* Our NAT network descriptor in Main */
1N/A ComPtr<INATNetwork> m_net;
1N/A ComNatListenerPtr m_listener;
1N/A
1N/A ComPtr<IHost> m_host;
1N/A ComNatListenerPtr m_vboxListener;
1N/A static INTNETSEG aXmitSeg[64];
1N/A
1N/A HRESULT HandleEvent(VBoxEventType_T aEventType, IEvent *pEvent);
1N/A
1N/A const char **getHostNameservers();
1N/A
1N/A /* Only for debug needs, by default NAT service should load rules from SVC
1N/A * on startup, and then on sync them on events.
1N/A */
1N/A bool fDontLoadRulesOnStartup;
1N/A static void onLwipTcpIpInit(void *arg);
1N/A static void onLwipTcpIpFini(void *arg);
1N/A static err_t netifInit(netif *pNetif);
1N/A static err_t netifLinkoutput(netif *pNetif, pbuf *pBuf);
1N/A static int intNetThreadRecv(RTTHREAD, void *);
1N/A
1N/A VECNATSERVICEPF m_vecPortForwardRule4;
1N/A VECNATSERVICEPF m_vecPortForwardRule6;
1N/A
1N/A static int natServicePfRegister(NATSEVICEPORTFORWARDRULE& natServicePf);
1N/A static int natServiceProcessRegisteredPf(VECNATSERVICEPF& vecPf);
1N/A};
1N/A
1N/A
1N/Astatic VBoxNetLwipNAT *g_pLwipNat;
1N/AINTNETSEG VBoxNetLwipNAT::aXmitSeg[64];
1N/A
1N/A/**
1N/A * @note: this work on Event thread.
1N/A */
1N/AHRESULT VBoxNetLwipNAT::HandleEvent(VBoxEventType_T aEventType,
1N/A IEvent *pEvent)
1N/A{
1N/A HRESULT hrc = S_OK;
1N/A switch (aEventType)
1N/A {
1N/A case VBoxEventType_OnNATNetworkSetting:
1N/A {
1N/A ComPtr<INATNetworkSettingEvent> evSettings(pEvent);
1N/A // XXX: only handle IPv6 default route for now
1N/A
1N/A if (!m_ProxyOptions.ipv6_enabled)
1N/A {
1N/A break;
1N/A }
1N/A
1N/A BOOL fIPv6DefaultRoute = FALSE;
1N/A hrc = evSettings->COMGETTER(AdvertiseDefaultIPv6RouteEnabled)(&fIPv6DefaultRoute);
1N/A AssertReturn(SUCCEEDED(hrc), hrc);
1N/A
1N/A if (m_ProxyOptions.ipv6_defroute == fIPv6DefaultRoute)
1N/A {
1N/A break;
1N/A }
1N/A
1N/A m_ProxyOptions.ipv6_defroute = fIPv6DefaultRoute;
1N/A tcpip_callback_with_block(proxy_rtadvd_do_quick, &m_LwipNetIf, 0);
1N/A
1N/A break;
1N/A }
1N/A
1N/A case VBoxEventType_OnNATNetworkPortForward:
1N/A {
1N/A com::Bstr name, strHostAddr, strGuestAddr;
1N/A LONG lHostPort, lGuestPort;
1N/A BOOL fCreateFW, fIPv6FW;
1N/A NATProtocol_T proto = NATProtocol_TCP;
1N/A
1N/A
1N/A ComPtr<INATNetworkPortForwardEvent> pfEvt = pEvent;
1N/A
1N/A hrc = pfEvt->COMGETTER(Name)(name.asOutParam());
1N/A AssertReturn(SUCCEEDED(hrc), hrc);
1N/A
1N/A hrc = pfEvt->COMGETTER(Proto)(&proto);
1N/A AssertReturn(SUCCEEDED(hrc), hrc);
1N/A
1N/A hrc = pfEvt->COMGETTER(HostIp)(strHostAddr.asOutParam());
1N/A AssertReturn(SUCCEEDED(hrc), hrc);
1N/A
1N/A hrc = pfEvt->COMGETTER(HostPort)(&lHostPort);
1N/A AssertReturn(SUCCEEDED(hrc), hrc);
1N/A
1N/A hrc = pfEvt->COMGETTER(GuestIp)(strGuestAddr.asOutParam());
1N/A AssertReturn(SUCCEEDED(hrc), hrc);
1N/A
1N/A hrc = pfEvt->COMGETTER(GuestPort)(&lGuestPort);
1N/A AssertReturn(SUCCEEDED(hrc), hrc);
1N/A
1N/A hrc = pfEvt->COMGETTER(Create)(&fCreateFW);
1N/A AssertReturn(SUCCEEDED(hrc), hrc);
1N/A
1N/A hrc = pfEvt->COMGETTER(Ipv6)(&fIPv6FW);
1N/A AssertReturn(SUCCEEDED(hrc), hrc);
1N/A
1N/A VECNATSERVICEPF& rules = (fIPv6FW ?
1N/A m_vecPortForwardRule6 :
1N/A m_vecPortForwardRule4);
1N/A
1N/A NATSEVICEPORTFORWARDRULE r;
1N/A
1N/A RT_ZERO(r);
1N/A
1N/A if (name.length() > sizeof(r.Pfr.szPfrName))
1N/A {
1N/A hrc = E_INVALIDARG;
1N/A goto port_forward_done;
1N/A }
1N/A
1N/A r.Pfr.fPfrIPv6 = fIPv6FW;
1N/A
1N/A switch (proto)
1N/A {
1N/A case NATProtocol_TCP:
1N/A r.Pfr.iPfrProto = IPPROTO_TCP;
1N/A break;
1N/A case NATProtocol_UDP:
1N/A r.Pfr.iPfrProto = IPPROTO_UDP;
1N/A break;
1N/A default:
1N/A goto port_forward_done;
1N/A }
1N/A
1N/A
1N/A RTStrPrintf(r.Pfr.szPfrName, sizeof(r.Pfr.szPfrName),
1N/A "%s", com::Utf8Str(name).c_str());
1N/A
1N/A RTStrPrintf(r.Pfr.szPfrHostAddr, sizeof(r.Pfr.szPfrHostAddr),
1N/A "%s", com::Utf8Str(strHostAddr).c_str());
1N/A
1N/A /* XXX: limits should be checked */
1N/A r.Pfr.u16PfrHostPort = (uint16_t)lHostPort;
1N/A
1N/A RTStrPrintf(r.Pfr.szPfrGuestAddr, sizeof(r.Pfr.szPfrGuestAddr),
1N/A "%s", com::Utf8Str(strGuestAddr).c_str());
1N/A
1N/A /* XXX: limits should be checked */
1N/A r.Pfr.u16PfrGuestPort = (uint16_t)lGuestPort;
1N/A
1N/A if (fCreateFW) /* Addition */
1N/A {
1N/A rules.push_back(r);
1N/A
1N/A natServicePfRegister(rules.back());
1N/A }
1N/A else /* Deletion */
1N/A {
1N/A ITERATORNATSERVICEPF it;
1N/A for (it = rules.begin(); it != rules.end(); ++it)
1N/A {
1N/A /* compare */
1N/A NATSEVICEPORTFORWARDRULE& natFw = *it;
1N/A if ( natFw.Pfr.iPfrProto == r.Pfr.iPfrProto
1N/A && natFw.Pfr.u16PfrHostPort == r.Pfr.u16PfrHostPort
1N/A && (strncmp(natFw.Pfr.szPfrHostAddr, r.Pfr.szPfrHostAddr, INET6_ADDRSTRLEN) == 0)
1N/A && natFw.Pfr.u16PfrGuestPort == r.Pfr.u16PfrGuestPort
1N/A && (strncmp(natFw.Pfr.szPfrGuestAddr, r.Pfr.szPfrGuestAddr, INET6_ADDRSTRLEN) == 0))
1N/A {
1N/A fwspec *pFwCopy = (fwspec *)RTMemAllocZ(sizeof(fwspec));
1N/A if (!pFwCopy)
1N/A {
1N/A break;
1N/A }
1N/A memcpy(pFwCopy, &natFw.FWSpec, sizeof(fwspec));
1N/A
1N/A /* We shouldn't care about pFwCopy this memory will be freed when
1N/A * will message will arrive to the destination.
1N/A */
1N/A portfwd_rule_del(pFwCopy);
1N/A
1N/A rules.erase(it);
1N/A break;
1N/A }
1N/A } /* loop over vector elements */
1N/A } /* condition add or delete */
1N/A port_forward_done:
1N/A /* clean up strings */
1N/A name.setNull();
1N/A strHostAddr.setNull();
1N/A strGuestAddr.setNull();
1N/A break;
1N/A }
1N/A
1N/A case VBoxEventType_OnHostNameResolutionConfigurationChange:
1N/A {
1N/A const char **ppcszNameServers = getHostNameservers();
1N/A err_t error;
1N/A
1N/A error = tcpip_callback_with_block(pxdns_set_nameservers,
1N/A ppcszNameServers,
1N/A /* :block */ 0);
1N/A if (error != ERR_OK && ppcszNameServers != NULL)
1N/A {
1N/A RTMemFree(ppcszNameServers);
1N/A }
1N/A break;
1N/A }
1N/A }
1N/A return hrc;
1N/A}
1N/A
1N/A
1N/Avoid VBoxNetLwipNAT::onLwipTcpIpInit(void* arg)
1N/A{
1N/A AssertPtrReturnVoid(arg);
1N/A VBoxNetLwipNAT *pNat = static_cast<VBoxNetLwipNAT *>(arg);
1N/A
1N/A HRESULT hrc = com::Initialize();
1N/A Assert(!FAILED(hrc));
1N/A
1N/A proxy_arp_hook = pxremap_proxy_arp;
1N/A proxy_ip4_divert_hook = pxremap_ip4_divert;
1N/A
1N/A proxy_na_hook = pxremap_proxy_na;
1N/A proxy_ip6_divert_hook = pxremap_ip6_divert;
1N/A
1N/A /* lwip thread */
1N/A RTNETADDRIPV4 network;
1N/A RTNETADDRIPV4 address = g_pLwipNat->getIpv4Address();
1N/A RTNETADDRIPV4 netmask = g_pLwipNat->getIpv4Netmask();
1N/A network.u = address.u & netmask.u;
1N/A
1N/A ip_addr LwipIpAddr, LwipIpNetMask, LwipIpNetwork;
1N/A
1N/A memcpy(&LwipIpAddr, &address, sizeof(ip_addr));
1N/A memcpy(&LwipIpNetMask, &netmask, sizeof(ip_addr));
1N/A memcpy(&LwipIpNetwork, &network, sizeof(ip_addr));
1N/A
1N/A netif *pNetif = netif_add(&g_pLwipNat->m_LwipNetIf /* Lwip Interface */,
1N/A &LwipIpAddr /* IP address*/,
1N/A &LwipIpNetMask /* Network mask */,
1N/A &LwipIpAddr /* gateway address, @todo: is self IP acceptable? */,
1N/A g_pLwipNat /* state */,
1N/A VBoxNetLwipNAT::netifInit /* netif_init_fn */,
1N/A lwip_tcpip_input /* netif_input_fn */);
1N/A
1N/A AssertPtrReturnVoid(pNetif);
1N/A
1N/A netif_set_up(pNetif);
1N/A netif_set_link_up(pNetif);
1N/A
1N/A if (pNat->m_ProxyOptions.ipv6_enabled) {
1N/A /*
1N/A * XXX: lwIP currently only ever calls mld6_joingroup() in
1N/A * nd6_tmr() for fresh tentative addresses, which is a wrong place
1N/A * to do it - but I'm not keen on fixing this properly for now
1N/A * (with correct handling of interface up and down transitions,
1N/A * etc). So stick it here as a kludge.
1N/A */
1N/A for (int i = 0; i <= 1; ++i) {
1N/A ip6_addr_t *paddr = netif_ip6_addr(pNetif, i);
1N/A
1N/A ip6_addr_t solicited_node_multicast_address;
1N/A ip6_addr_set_solicitednode(&solicited_node_multicast_address,
1N/A paddr->addr[3]);
1N/A mld6_joingroup(paddr, &solicited_node_multicast_address);
1N/A }
1N/A
1N/A /*
1N/A * XXX: We must join the solicited-node multicast for the
1N/A * addresses we do IPv6 NA-proxy for. We map IPv6 loopback to
1N/A * proxy address + 1. We only need the low 24 bits, and those are
1N/A * fixed.
1N/A */
1N/A {
1N/A ip6_addr_t solicited_node_multicast_address;
1N/A
1N/A ip6_addr_set_solicitednode(&solicited_node_multicast_address,
1N/A /* last 24 bits of the address */
1N/A PP_HTONL(0x00000002));
1N/A mld6_netif_joingroup(pNetif, &solicited_node_multicast_address);
1N/A }
1N/A }
1N/A
1N/A proxy_init(&g_pLwipNat->m_LwipNetIf, &g_pLwipNat->m_ProxyOptions);
1N/A
1N/A natServiceProcessRegisteredPf(g_pLwipNat->m_vecPortForwardRule4);
1N/A natServiceProcessRegisteredPf(g_pLwipNat->m_vecPortForwardRule6);
1N/A}
1N/A
1N/A
1N/Avoid VBoxNetLwipNAT::onLwipTcpIpFini(void* arg)
1N/A{
1N/A AssertPtrReturnVoid(arg);
1N/A VBoxNetLwipNAT *pThis = (VBoxNetLwipNAT *)arg;
1N/A
1N/A /* XXX: proxy finalization */
1N/A netif_set_link_down(&g_pLwipNat->m_LwipNetIf);
1N/A netif_set_down(&g_pLwipNat->m_LwipNetIf);
1N/A netif_remove(&g_pLwipNat->m_LwipNetIf);
1N/A
1N/A}
1N/A
1N/A/*
1N/A * Callback for netif_add() to initialize the interface.
1N/A */
1N/Aerr_t VBoxNetLwipNAT::netifInit(netif *pNetif)
1N/A{
1N/A err_t rcLwip = ERR_OK;
1N/A
1N/A AssertPtrReturn(pNetif, ERR_ARG);
1N/A
1N/A VBoxNetLwipNAT *pNat = static_cast<VBoxNetLwipNAT *>(pNetif->state);
1N/A AssertPtrReturn(pNat, ERR_ARG);
1N/A
1N/A LogFlowFunc(("ENTER: pNetif[%c%c%d]\n", pNetif->name[0], pNetif->name[1], pNetif->num));
1N/A /* validity */
1N/A AssertReturn( pNetif->name[0] == 'N'
1N/A && pNetif->name[1] == 'T', ERR_ARG);
1N/A
1N/A
1N/A pNetif->hwaddr_len = sizeof(RTMAC);
1N/A RTMAC mac = g_pLwipNat->getMacAddress();
1N/A memcpy(pNetif->hwaddr, &mac, sizeof(RTMAC));
1N/A
1N/A pNat->m_u16Mtu = 1500; // XXX: FIXME
1N/A pNetif->mtu = pNat->m_u16Mtu;
1N/A
1N/A pNetif->flags = NETIF_FLAG_BROADCAST
1N/A | NETIF_FLAG_ETHARP /* Don't bother driver with ARP and let Lwip resolve ARP handling */
1N/A | NETIF_FLAG_ETHERNET; /* Lwip works with ethernet too */
1N/A
1N/A pNetif->linkoutput = netifLinkoutput; /* ether-level-pipe */
1N/A pNetif->output = lwip_etharp_output; /* ip-pipe */
1N/A
1N/A if (pNat->m_ProxyOptions.ipv6_enabled) {
1N/A pNetif->output_ip6 = ethip6_output;
1N/A
1N/A /* IPv6 link-local address in slot 0 */
1N/A netif_create_ip6_linklocal_address(pNetif, /* :from_mac_48bit */ 1);
1N/A netif_ip6_addr_set_state(pNetif, 0, IP6_ADDR_PREFERRED); // skip DAD
1N/A
1N/A /*
1N/A * RFC 4193 Locally Assigned Global ID (ULA) in slot 1
1N/A * [fd17:625c:f037:XXXX::1] where XXXX, 16 bit Subnet ID, are two
1N/A * bytes from the middle of the IPv4 address, e.g. :dead: for
1N/A * 10.222.173.1
1N/A */
1N/A u8_t nethi = ip4_addr2(&pNetif->ip_addr);
1N/A u8_t netlo = ip4_addr3(&pNetif->ip_addr);
1N/A
1N/A ip6_addr_t *paddr = netif_ip6_addr(pNetif, 1);
1N/A IP6_ADDR(paddr, 0, 0xFD, 0x17, 0x62, 0x5C);
1N/A IP6_ADDR(paddr, 1, 0xF0, 0x37, nethi, netlo);
1N/A IP6_ADDR(paddr, 2, 0x00, 0x00, 0x00, 0x00);
1N/A IP6_ADDR(paddr, 3, 0x00, 0x00, 0x00, 0x01);
1N/A netif_ip6_addr_set_state(pNetif, 1, IP6_ADDR_PREFERRED);
1N/A
1N/A#if LWIP_IPV6_SEND_ROUTER_SOLICIT
1N/A pNetif->rs_count = 0;
1N/A#endif
1N/A }
LogFlowFunc(("LEAVE: %d\n", rcLwip));
return rcLwip;
}
err_t VBoxNetLwipNAT::netifLinkoutput(netif *pNetif, pbuf *pPBuf)
{
AssertPtrReturn(pNetif, ERR_ARG);
AssertPtrReturn(pPBuf, ERR_ARG);
AssertReturn((void *)g_pLwipNat == pNetif->state, ERR_ARG);
LogFlowFunc(("ENTER: pNetif[%c%c%d], pPbuf:%p\n",
pNetif->name[0],
pNetif->name[1],
pNetif->num,
pPBuf));
RT_ZERO(VBoxNetLwipNAT::aXmitSeg);
unsigned idx = 0;
for( struct pbuf *pPBufPtr = pPBuf;
pPBufPtr;
pPBufPtr = pPBufPtr->next, ++idx)
{
AssertReturn(idx < RT_ELEMENTS(VBoxNetLwipNAT::aXmitSeg), ERR_MEM);
VBoxNetLwipNAT::aXmitSeg[idx].pv = pPBufPtr->payload;
VBoxNetLwipNAT::aXmitSeg[idx].cb = pPBufPtr->len;
}
int rc = g_pLwipNat->sendBufferOnWire(VBoxNetLwipNAT::aXmitSeg, idx, pPBuf->tot_len);
AssertRCReturn(rc, ERR_IF);
g_pLwipNat->flushWire();
LogFlowFunc(("LEAVE: %d\n", ERR_OK));
return ERR_OK;
}
VBoxNetLwipNAT::VBoxNetLwipNAT(SOCKET icmpsock4, SOCKET icmpsock6) : VBoxNetBaseService("VBoxNetNAT", "nat-network")
{
LogFlowFuncEnter();
m_ProxyOptions.ipv6_enabled = 0;
m_ProxyOptions.ipv6_defroute = 0;
m_ProxyOptions.icmpsock4 = icmpsock4;
m_ProxyOptions.icmpsock6 = icmpsock6;
m_ProxyOptions.tftp_root = NULL;
m_ProxyOptions.src4 = NULL;
m_ProxyOptions.src6 = NULL;
memset(&m_src4, 0, sizeof(m_src4));
memset(&m_src6, 0, sizeof(m_src6));
m_src4.sin_family = AF_INET;
m_src6.sin6_family = AF_INET6;
#if HAVE_SA_LEN
m_src4.sin_len = sizeof(m_src4);
m_src6.sin6_len = sizeof(m_src6);
#endif
m_ProxyOptions.nameservers = NULL;
m_LwipNetIf.name[0] = 'N';
m_LwipNetIf.name[1] = 'T';
RTMAC mac;
mac.au8[0] = 0x52;
mac.au8[1] = 0x54;
mac.au8[2] = 0;
mac.au8[3] = 0x12;
mac.au8[4] = 0x35;
mac.au8[5] = 0;
setMacAddress(mac);
RTNETADDRIPV4 address;
address.u = RT_MAKE_U32_FROM_U8( 10, 0, 2, 2); // NB: big-endian
setIpv4Address(address);
address.u = RT_H2N_U32_C(0xffffff00);
setIpv4Netmask(address);
fDontLoadRulesOnStartup = false;
for(unsigned int i = 0; i < RT_ELEMENTS(g_aGetOptDef); ++i)
addCommandLineOption(&g_aGetOptDef[i]);
LogFlowFuncLeave();
}
VBoxNetLwipNAT::~VBoxNetLwipNAT()
{
if (m_ProxyOptions.tftp_root != NULL)
{
RTStrFree((char *)m_ProxyOptions.tftp_root);
}
}
int VBoxNetLwipNAT::natServicePfRegister(NATSEVICEPORTFORWARDRULE& natPf)
{
int lrc = 0;
int rc = VINF_SUCCESS;
int socketSpec = SOCK_STREAM;
char *pszHostAddr;
int sockFamily = (natPf.Pfr.fPfrIPv6 ? PF_INET6 : PF_INET);
switch(natPf.Pfr.iPfrProto)
{
case IPPROTO_TCP:
socketSpec = SOCK_STREAM;
break;
case IPPROTO_UDP:
socketSpec = SOCK_DGRAM;
break;
default:
return VERR_IGNORED; /* Ah, just ignore the garbage */
}
pszHostAddr = natPf.Pfr.szPfrHostAddr;
/* XXX: workaround for inet_pton and an empty ipv4 address
* in rule declaration.
*/
if ( sockFamily == PF_INET
&& pszHostAddr[0] == 0)
pszHostAddr = (char *)"0.0.0.0"; /* XXX: fix it! without type cast */
lrc = fwspec_set(&natPf.FWSpec,
sockFamily,
socketSpec,
pszHostAddr,
natPf.Pfr.u16PfrHostPort,
natPf.Pfr.szPfrGuestAddr,
natPf.Pfr.u16PfrGuestPort);
AssertReturn(!lrc, VERR_IGNORED);
fwspec *pFwCopy = (fwspec *)RTMemAllocZ(sizeof(fwspec));
AssertPtrReturn(pFwCopy, VERR_IGNORED);
/*
* We need pass the copy, because we can't be sure
* how much this pointer will be valid in LWIP environment.
*/
memcpy(pFwCopy, &natPf.FWSpec, sizeof(fwspec));
lrc = portfwd_rule_add(pFwCopy);
AssertReturn(!lrc, VERR_IGNORED);
return VINF_SUCCESS;
}
int VBoxNetLwipNAT::natServiceProcessRegisteredPf(VECNATSERVICEPF& vecRules){
ITERATORNATSERVICEPF it;
for (it = vecRules.begin();
it != vecRules.end(); ++it)
{
int rc = natServicePfRegister((*it));
if (RT_FAILURE(rc))
{
LogRel(("PF: %s is ignored\n", (*it).Pfr.szPfrName));
continue;
}
}
return VINF_SUCCESS;
}
/** This method executed on main thread, only at the end threr're one threads started explcitly (LWIP and later in ::run()
* RECV)
*/
int VBoxNetLwipNAT::init()
{
LogFlowFuncEnter();
/* virtualbox initialized in super class */
int rc = ::VBoxNetBaseService::init();
AssertRCReturn(rc, rc);
std::string networkName = getNetwork();
rc = findNatNetwork(virtualbox, networkName, m_net);
AssertRCReturn(rc, rc);
ComEventTypeArray aNetEvents;
aNetEvents.push_back(VBoxEventType_OnNATNetworkPortForward);
aNetEvents.push_back(VBoxEventType_OnNATNetworkSetting);
rc = createNatListener(m_listener, virtualbox, this, aNetEvents);
AssertRCReturn(rc, rc);
// resolver changes are reported on vbox but are retrieved from
// host so stash a pointer for future lookups
HRESULT hrc = virtualbox->COMGETTER(Host)(m_host.asOutParam());
AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
ComEventTypeArray aVBoxEvents;
aVBoxEvents.push_back(VBoxEventType_OnHostNameResolutionConfigurationChange);
rc = createNatListener(m_vboxListener, virtualbox, this, aVBoxEvents);
AssertRCReturn(rc, rc);
BOOL fIPv6Enabled = FALSE;
hrc = m_net->COMGETTER(IPv6Enabled)(&fIPv6Enabled);
AssertComRCReturn(hrc, VERR_NOT_FOUND);
BOOL fIPv6DefaultRoute = FALSE;
if (fIPv6Enabled)
{
hrc = m_net->COMGETTER(AdvertiseDefaultIPv6RouteEnabled)(&fIPv6DefaultRoute);
AssertComRCReturn(hrc, VERR_NOT_FOUND);
}
m_ProxyOptions.ipv6_enabled = fIPv6Enabled;
m_ProxyOptions.ipv6_defroute = fIPv6DefaultRoute;
com::Bstr bstrSourceIp4Key = com::BstrFmt("NAT/%s/SourceIp4", networkName.c_str());
com::Bstr bstrSourceIpX;
hrc = virtualbox->GetExtraData(bstrSourceIp4Key.raw(), bstrSourceIpX.asOutParam());
if (SUCCEEDED(hrc))
{
RTNETADDRIPV4 addr;
rc = RTNetStrToIPv4Addr(com::Utf8Str(bstrSourceIpX).c_str(), &addr);
if (RT_SUCCESS(rc))
{
RT_ZERO(m_src4);
m_src4.sin_addr.s_addr = addr.u;
m_ProxyOptions.src4 = &m_src4;
bstrSourceIpX.setNull();
}
}
if (!fDontLoadRulesOnStartup)
{
fetchNatPortForwardRules(m_net, false, m_vecPortForwardRule4);
fetchNatPortForwardRules(m_net, true, m_vecPortForwardRule6);
} /* if (!fDontLoadRulesOnStartup) */
AddressToOffsetMapping tmp;
rc = localMappings(m_net, tmp);
if (RT_SUCCESS(rc) && tmp.size() != 0)
{
unsigned long i = 0;
for (AddressToOffsetMapping::iterator it = tmp.begin();
it != tmp.end() && i < RT_ELEMENTS(m_lo2off);
++it, ++i)
{
ip4_addr_set_u32(&m_lo2off[i].loaddr, it->first.u);
m_lo2off[i].off = it->second;
}
m_loOptDescriptor.lomap = m_lo2off;
m_loOptDescriptor.num_lomap = i;
m_ProxyOptions.lomap_desc = &m_loOptDescriptor;
}
com::Bstr bstr;
hrc = virtualbox->COMGETTER(HomeFolder)(bstr.asOutParam());
AssertComRCReturn(hrc, VERR_NOT_FOUND);
if (!bstr.isEmpty())
{
com::Utf8Str strTftpRoot(com::Utf8StrFmt("%ls%c%s",
bstr.raw(), RTPATH_DELIMITER, "TFTP"));
char *pszStrTemp; // avoid const char ** vs char **
rc = RTStrUtf8ToCurrentCP(&pszStrTemp, strTftpRoot.c_str());
AssertRC(rc);
m_ProxyOptions.tftp_root = pszStrTemp;
}
m_ProxyOptions.nameservers = getHostNameservers();
/* end of COM initialization */
rc = g_pLwipNat->tryGoOnline();
if (RT_FAILURE(rc))
{
return rc;
}
/* this starts LWIP thread */
vboxLwipCoreInitialize(VBoxNetLwipNAT::onLwipTcpIpInit, this);
LogFlowFuncLeaveRC(rc);
return rc;
}
const char **VBoxNetLwipNAT::getHostNameservers()
{
HRESULT hrc;
if (m_host.isNull())
{
return NULL;
}
com::SafeArray<BSTR> aNameServers;
hrc = m_host->COMGETTER(NameServers)(ComSafeArrayAsOutParam(aNameServers));
if (FAILED(hrc))
{
return NULL;
}
const size_t cNameServers = aNameServers.size();
if (cNameServers == 0)
{
return NULL;
}
const char **ppcszNameServers =
(const char **)RTMemAllocZ(sizeof(char *) * (cNameServers + 1));
if (ppcszNameServers == NULL)
{
return NULL;
}
size_t idxLast = 0;
for (size_t i = 0; i < cNameServers; ++i)
{
com::Utf8Str strNameServer(aNameServers[i]);
ppcszNameServers[idxLast] = RTStrDup(strNameServer.c_str());
if (ppcszNameServers[idxLast] != NULL)
{
++idxLast;
}
}
if (idxLast == 0)
{
RTMemFree(ppcszNameServers);
return NULL;
}
return ppcszNameServers;
}
int VBoxNetLwipNAT::parseOpt(int rc, const RTGETOPTUNION& Val)
{
switch (rc)
{
case 'p':
case 'P':
{
NATSEVICEPORTFORWARDRULE Rule;
VECNATSERVICEPF& rules = (rc == 'P'?
m_vecPortForwardRule6
: m_vecPortForwardRule4);
fDontLoadRulesOnStartup = true;
RT_ZERO(Rule);
int irc = netPfStrToPf(Val.psz, (rc == 'P'), &Rule.Pfr);
rules.push_back(Rule);
return VINF_SUCCESS;
}
default:;
}
return VERR_NOT_FOUND;
}
int VBoxNetLwipNAT::processFrame(void *pvFrame, size_t cbFrame)
{
AssertReturn(pvFrame && cbFrame, VERR_INVALID_PARAMETER);
struct pbuf *pPbufHdr, *pPbuf;
pPbufHdr = pPbuf = pbuf_alloc(PBUF_RAW, cbFrame, PBUF_POOL);
AssertMsgReturn(pPbuf, ("NAT: Can't allocate send buffer cbFrame=%u\n", cbFrame), VERR_INTERNAL_ERROR);
AssertReturn(pPbufHdr->tot_len == cbFrame, VERR_INTERNAL_ERROR);
uint8_t *pu8Frame = (uint8_t *)pvFrame;
while(pPbuf)
{
memcpy(pPbuf->payload, pu8Frame, pPbuf->len);
pu8Frame += pPbuf->len;
pPbuf = pPbuf->next;
}
m_LwipNetIf.input(pPbufHdr, &m_LwipNetIf);
return VINF_SUCCESS;
}
int VBoxNetLwipNAT::processGSO(PCPDMNETWORKGSO pGso, size_t cbFrame)
{
if (!PDMNetGsoIsValid(pGso, cbFrame,
cbFrame - sizeof(PDMNETWORKGSO)))
return VERR_INVALID_PARAMETER;
cbFrame -= sizeof(PDMNETWORKGSO);
uint8_t abHdrScratch[256];
uint32_t const cSegs = PDMNetGsoCalcSegmentCount(pGso,
cbFrame);
for (size_t iSeg = 0; iSeg < cSegs; iSeg++)
{
uint32_t cbSegFrame;
void *pvSegFrame =
PDMNetGsoCarveSegmentQD(pGso,
(uint8_t *)(pGso + 1),
cbFrame,
abHdrScratch,
iSeg,
cSegs,
&cbSegFrame);
struct pbuf *pPbuf = pbuf_alloc(PBUF_RAW, cbSegFrame, PBUF_POOL);
AssertMsgReturn(pPbuf, ("NAT: Can't allocate send buffer cbFrame=%u\n", cbSegFrame), VERR_INTERNAL_ERROR);
AssertReturn(!pPbuf->next && pPbuf->len == cbSegFrame, VERR_INTERNAL_ERROR);
memcpy(pPbuf->payload, pvSegFrame, cbSegFrame);
m_LwipNetIf.input(pPbuf, &g_pLwipNat->m_LwipNetIf);
}
return VINF_SUCCESS;
}
int VBoxNetLwipNAT::run()
{
/* Father starts receiving thread and enter event loop. */
VBoxNetBaseService::run();
vboxLwipCoreFinalize(VBoxNetLwipNAT::onLwipTcpIpFini, this);
m_vecPortForwardRule4.clear();
m_vecPortForwardRule6.clear();
return VINF_SUCCESS;
}
/**
* Entry point.
*/
extern "C" DECLEXPORT(int) TrustedMain(int argc, char **argv, char **envp)
{
LogFlowFuncEnter();
NOREF(envp);
#ifdef RT_OS_WINDOWS
WSADATA wsaData;
int err;
err = WSAStartup(MAKEWORD(2,2), &wsaData);
if (err)
{
fprintf(stderr, "wsastartup: failed (%d)\n", err);
return 1;
}
#endif
SOCKET icmpsock4 = INVALID_SOCKET;
SOCKET icmpsock6 = INVALID_SOCKET;
#ifndef RT_OS_DARWIN
const int icmpstype = SOCK_RAW;
#else
/* on OS X it's not privileged */
const int icmpstype = SOCK_DGRAM;
#endif
icmpsock4 = socket(AF_INET, icmpstype, IPPROTO_ICMP);
if (icmpsock4 == INVALID_SOCKET)
{
perror("IPPROTO_ICMP");
#ifdef VBOX_RAWSOCK_DEBUG_HELPER
icmpsock4 = getrawsock(AF_INET);
#endif
}
if (icmpsock4 != INVALID_SOCKET)
{
#ifdef ICMP_FILTER // Linux specific
struct icmp_filter flt = {
~(uint32_t)(
(1U << ICMP_ECHOREPLY)
| (1U << ICMP_DEST_UNREACH)
| (1U << ICMP_TIME_EXCEEDED)
)
};
int status = setsockopt(icmpsock4, SOL_RAW, ICMP_FILTER,
&flt, sizeof(flt));
if (status < 0)
{
perror("ICMP_FILTER");
}
#endif
}
icmpsock6 = socket(AF_INET6, icmpstype, IPPROTO_ICMPV6);
if (icmpsock6 == INVALID_SOCKET)
{
perror("IPPROTO_ICMPV6");
#ifdef VBOX_RAWSOCK_DEBUG_HELPER
icmpsock6 = getrawsock(AF_INET6);
#endif
}
if (icmpsock6 != INVALID_SOCKET)
{
#ifdef ICMP6_FILTER // Windows doesn't support RFC 3542 API
/*
* XXX: We do this here for now, not in pxping.c, to avoid
* name clashes between lwIP and system headers.
*/
struct icmp6_filter flt;
ICMP6_FILTER_SETBLOCKALL(&flt);
ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &flt);
ICMP6_FILTER_SETPASS(ICMP6_DST_UNREACH, &flt);
ICMP6_FILTER_SETPASS(ICMP6_PACKET_TOO_BIG, &flt);
ICMP6_FILTER_SETPASS(ICMP6_TIME_EXCEEDED, &flt);
ICMP6_FILTER_SETPASS(ICMP6_PARAM_PROB, &flt);
int status = setsockopt(icmpsock6, IPPROTO_ICMPV6, ICMP6_FILTER,
&flt, sizeof(flt));
if (status < 0)
{
perror("ICMP6_FILTER");
}
#endif
}
HRESULT hrc = com::Initialize();
#ifdef VBOX_WITH_XPCOM
if (hrc == NS_ERROR_FILE_ACCESS_DENIED)
{
char szHome[RTPATH_MAX] = "";
com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome));
return RTMsgErrorExit(RTEXITCODE_FAILURE,
"Failed to initialize COM because the global settings directory '%s' is not accessible!", szHome);
}
#endif
if (FAILED(hrc))
return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to initialize COM!");
g_pLwipNat = new VBoxNetLwipNAT(icmpsock4, icmpsock6);
Log2(("NAT: initialization\n"));
int rc = g_pLwipNat->parseArgs(argc - 1, argv + 1);
rc = (rc == 0) ? VINF_SUCCESS : VERR_GENERAL_FAILURE; /* XXX: FIXME */
if (RT_SUCCESS(rc))
{
rc = g_pLwipNat->init();
}
if (RT_SUCCESS(rc))
{
g_pLwipNat->run();
}
delete g_pLwipNat;
return 0;
}
static int fetchNatPortForwardRules(const ComNatPtr& nat, bool fIsIPv6, VECNATSERVICEPF& vec)
{
HRESULT hrc;
com::SafeArray<BSTR> rules;
if (fIsIPv6)
hrc = nat->COMGETTER(PortForwardRules6)(ComSafeArrayAsOutParam(rules));
else
hrc = nat->COMGETTER(PortForwardRules4)(ComSafeArrayAsOutParam(rules));
AssertReturn(SUCCEEDED(hrc), VERR_INTERNAL_ERROR);
NATSEVICEPORTFORWARDRULE Rule;
for (size_t idxRules = 0; idxRules < rules.size(); ++idxRules)
{
Log(("%d-%s rule: %ls\n", idxRules, (fIsIPv6 ? "IPv6" : "IPv4"), rules[idxRules]));
RT_ZERO(Rule);
int rc = netPfStrToPf(com::Utf8Str(rules[idxRules]).c_str(), 0, &Rule.Pfr);
if (RT_FAILURE(rc))
continue;
vec.push_back(Rule);
}
return VINF_SUCCESS;
}
#ifndef VBOX_WITH_HARDENING
int main(int argc, char **argv, char **envp)
{
int rc = RTR3InitExe(argc, &argv, RTR3INIT_FLAGS_SUPLIB);
if (RT_FAILURE(rc))
return RTMsgInitFailure(rc);
return TrustedMain(argc, argv, envp);
}
# if defined(RT_OS_WINDOWS)
static LRESULT CALLBACK WindowProc(HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam
)
{
if(uMsg == WM_DESTROY)
{
PostQuitMessage(0);
return 0;
}
return DefWindowProc (hwnd, uMsg, wParam, lParam);
}
static LPCWSTR g_WndClassName = L"VBoxNetNatLwipClass";
static DWORD WINAPI MsgThreadProc(__in LPVOID lpParameter)
{
HWND hwnd = 0;
HINSTANCE hInstance = (HINSTANCE)GetModuleHandle (NULL);
bool bExit = false;
/* Register the Window Class. */
WNDCLASS wc;
wc.style = 0;
wc.lpfnWndProc = WindowProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = sizeof(void *);
wc.hInstance = hInstance;
wc.hIcon = NULL;
wc.hCursor = NULL;
wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1);
wc.lpszMenuName = NULL;
wc.lpszClassName = g_WndClassName;
ATOM atomWindowClass = RegisterClass(&wc);
if (atomWindowClass != 0)
{
/* Create the window. */
hwnd = CreateWindowEx (WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_TOPMOST,
g_WndClassName, g_WndClassName,
WS_POPUPWINDOW,
-200, -200, 100, 100, NULL, NULL, hInstance, NULL);
if (hwnd)
{
SetWindowPos(hwnd, HWND_TOPMOST, -200, -200, 0, 0,
SWP_NOACTIVATE | SWP_HIDEWINDOW | SWP_NOCOPYBITS | SWP_NOREDRAW | SWP_NOSIZE);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
DestroyWindow (hwnd);
bExit = true;
}
UnregisterClass (g_WndClassName, hInstance);
}
if(bExit)
{
/* no need any accuracy here, in anyway the DHCP server usually gets terminated with TerminateProcess */
exit(0);
}
return 0;
}
/** (We don't want a console usually.) */
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
#if 0
NOREF(hInstance); NOREF(hPrevInstance); NOREF(lpCmdLine); NOREF(nCmdShow);
HANDLE hThread = CreateThread(
NULL, /*__in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes, */
0, /*__in SIZE_T dwStackSize, */
MsgThreadProc, /*__in LPTHREAD_START_ROUTINE lpStartAddress,*/
NULL, /*__in_opt LPVOID lpParameter,*/
0, /*__in DWORD dwCreationFlags,*/
NULL /*__out_opt LPDWORD lpThreadId*/
);
if(hThread != NULL)
CloseHandle(hThread);
#endif
return main(__argc, __argv, environ);
}
# endif /* RT_OS_WINDOWS */
#endif /* !VBOX_WITH_HARDENING */