Merge commit '86cc97e55fe346502462284d2e636a2b3708163e' as 'Sources/OpenVPN3'

This commit is contained in:
Sergey Abramchuk
2020-02-24 14:43:11 +03:00
655 changed files with 146468 additions and 0 deletions
@@ -0,0 +1,379 @@
// OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012-2017 OpenVPN Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License Version 3
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
// Client tun interface for Mac OS X
#ifndef OPENVPN_TUN_MAC_CLIENT_TUNCLI_H
#define OPENVPN_TUN_MAC_CLIENT_TUNCLI_H
#include <string>
#include <sstream>
#include <memory>
#include <openvpn/common/to_string.hpp>
#include <openvpn/asio/scoped_asio_stream.hpp>
#include <openvpn/common/cleanup.hpp>
#include <openvpn/tun/client/tunbase.hpp>
#include <openvpn/tun/client/tunprop.hpp>
#include <openvpn/tun/persist/tunpersist.hpp>
#include <openvpn/tun/persist/tunwrapasio.hpp>
#include <openvpn/tun/tunio.hpp>
#include <openvpn/tun/mac/client/tunsetup.hpp>
#ifdef TEST_EER // test emulated exclude routes
#include <openvpn/client/cliemuexr.hpp>
#endif
namespace openvpn {
namespace TunMac {
OPENVPN_EXCEPTION(tun_mac_error);
// struct used to pass received tun packets
struct PacketFrom
{
typedef std::unique_ptr<PacketFrom> SPtr;
BufferAllocated buf;
};
// tun interface wrapper for Mac OS X
template <typename ReadHandler, typename TunPersist>
class Tun : public TunIO<ReadHandler, PacketFrom, TunWrapAsioStream<TunPersist> >
{
typedef TunIO<ReadHandler, PacketFrom, TunWrapAsioStream<TunPersist> > Base;
public:
typedef RCPtr<Tun> Ptr;
Tun(const typename TunPersist::Ptr& tun_persist,
const std::string& name,
const bool retain_stream,
const bool tun_prefix,
ReadHandler read_handler,
const Frame::Ptr& frame,
const SessionStats::Ptr& stats)
: Base(read_handler, frame, stats)
{
Base::name_ = name;
Base::retain_stream = retain_stream;
Base::tun_prefix = tun_prefix;
Base::stream = new TunWrapAsioStream<TunPersist>(tun_persist);
}
};
// These types manage the underlying tun driver fd
typedef openvpn_io::posix::stream_descriptor TUNStream;
typedef ScopedAsioStream<TUNStream> ScopedTUNStream;
typedef TunPersistTemplate<ScopedTUNStream> TunPersist;
class Client;
class ClientConfig : public TunClientFactory
{
public:
typedef RCPtr<ClientConfig> Ptr;
TunProp::Config tun_prop;
int n_parallel = 8; // number of parallel async reads on tun socket
Frame::Ptr frame;
SessionStats::Ptr stats;
TunPersist::Ptr tun_persist;
Stop* stop = nullptr;
TunBuilderSetup::Factory::Ptr tun_setup_factory;
TunBuilderSetup::Base::Ptr new_setup_obj()
{
if (tun_setup_factory)
return tun_setup_factory->new_setup_obj();
else
return new TunMac::Setup();
}
static Ptr new_obj()
{
return new ClientConfig;
}
virtual TunClient::Ptr new_tun_client_obj(openvpn_io::io_context& io_context,
TunClientParent& parent,
TransportClient* transcli);
// return true if layer 2 tunnels are supported
virtual bool layer_2_supported() const
{
# if defined(MAC_TUNTAP_FALLBACK)
return false; // change to true after TAP support is added
# else
return false; // utun device doesn't support TAP
# endif
}
// called just prior to transmission of Disconnect event
virtual void finalize(const bool disconnected)
{
if (disconnected)
tun_persist.reset();
}
};
class Client : public TunClient
{
friend class ClientConfig; // calls constructor
friend class TunIO<Client*, PacketFrom, TunWrapAsioStream<TunPersist> >; // calls tun_read_handler
typedef Tun<Client*, TunPersist> TunImpl;
public:
virtual void tun_start(const OptionList& opt, TransportClient& transcli, CryptoDCSettings&) override
{
if (!impl)
{
halt = false;
if (config->tun_persist)
{
OPENVPN_LOG("TunPersist: long-term session scope");
tun_persist = config->tun_persist;
}
else
{
OPENVPN_LOG("TunPersist: short-term connection scope");
tun_persist.reset(new TunPersist(false, false, NULL));
}
try {
const IP::Addr server_addr = transcli.server_endpoint_addr();
// Check if persisted tun session matches properties of to-be-created session
if (tun_persist->use_persisted_tun(server_addr, config->tun_prop, opt))
{
state = tun_persist->state();
OPENVPN_LOG("TunPersist: reused tun context");
}
else
{
OPENVPN_LOG("TunPersist: new tun context");
// notify parent
parent.tun_pre_tun_config();
// close old tun handle if persisted
tun_persist->close();
// emulated exclude routes
EmulateExcludeRouteFactory::Ptr eer_factory;
#ifdef TEST_EER
eer_factory.reset(new EmulateExcludeRouteFactoryImpl(true));
#endif
// parse pushed options
TunBuilderCapture::Ptr po(new TunBuilderCapture());
TunProp::configure_builder(po.get(),
state.get(),
config->stats.get(),
server_addr,
config->tun_prop,
opt,
eer_factory.get(),
false);
// handle MTU default
if (!po->mtu)
po->mtu = 1500;
OPENVPN_LOG("CAPTURED OPTIONS:" << std::endl << po->to_string());
// create new tun setup object
tun_setup = config->new_setup_obj();
// create config object for tun setup layer
Setup::Config tsconf;
tsconf.iface_name = state->iface_name;
tsconf.layer = config->tun_prop.layer;
// open/config tun
int fd = -1;
{
std::ostringstream os;
auto os_print = Cleanup([&os](){ OPENVPN_LOG_STRING(os.str()); });
fd = tun_setup->establish(*po, &tsconf, config->stop, os);
}
// create ASIO wrapper for tun fd
TUNStream* ts = new TUNStream(io_context, fd);
// persist tun settings state
state->iface_name = tsconf.iface_name;
state->tun_prefix = tsconf.tun_prefix;
if (tun_persist->persist_tun_state(ts, state))
OPENVPN_LOG("TunPersist: saving tun context:" << std::endl << tun_persist->options());
// enable tun_setup destructor
tun_persist->add_destructor(tun_setup);
}
// configure tun interface packet forwarding
impl.reset(new TunImpl(tun_persist,
state->iface_name,
true,
state->tun_prefix,
this,
config->frame,
config->stats
));
impl->start(config->n_parallel);
// signal that we are connected
parent.tun_connected();
}
catch (const std::exception& e)
{
if (tun_persist)
tun_persist->close();
stop();
Error::Type err = Error::TUN_SETUP_FAILED;
const ExceptionCode *ec = dynamic_cast<const ExceptionCode *>(&e);
if (ec && ec->code_defined())
err = ec->code();
parent.tun_error(err, e.what());
}
}
}
virtual bool tun_send(BufferAllocated& buf) override
{
return send(buf);
}
virtual std::string tun_name() const override
{
if (impl)
return impl->name();
else
return "UNDEF_TUN";
}
virtual std::string vpn_ip4() const override
{
if (state->vpn_ip4_addr.specified())
return state->vpn_ip4_addr.to_string();
else
return "";
}
virtual std::string vpn_ip6() const override
{
if (state->vpn_ip6_addr.specified())
return state->vpn_ip6_addr.to_string();
else
return "";
}
virtual std::string vpn_gw4() const override
{
if (state->vpn_ip4_gw.specified())
return state->vpn_ip4_gw.to_string();
else
return "";
}
virtual std::string vpn_gw6() const override
{
if (state->vpn_ip6_gw.specified())
return state->vpn_ip6_gw.to_string();
else
return "";
}
virtual void set_disconnect() override
{
}
virtual void stop() override { stop_(); }
virtual ~Client() { stop_(); }
private:
Client(openvpn_io::io_context& io_context_arg,
ClientConfig* config_arg,
TunClientParent& parent_arg)
: io_context(io_context_arg),
config(config_arg),
parent(parent_arg),
halt(false),
state(new TunProp::State())
{
}
bool send(Buffer& buf)
{
if (impl)
return impl->write(buf);
else
return false;
}
void tun_read_handler(PacketFrom::SPtr& pfp) // called by TunImpl
{
parent.tun_recv(pfp->buf);
}
void tun_error_handler(const Error::Type errtype, // called by TunImpl
const openvpn_io::error_code* error)
{
parent.tun_error(Error::TUN_ERROR, "TUN I/O error");
}
void stop_()
{
if (!halt)
{
halt = true;
// stop tun
if (impl)
impl->stop();
tun_persist.reset();
}
}
openvpn_io::io_context& io_context;
TunPersist::Ptr tun_persist; // contains the tun device fd
ClientConfig::Ptr config;
TunClientParent& parent;
TunImpl::Ptr impl;
bool halt;
TunProp::State::Ptr state;
TunBuilderSetup::Base::Ptr tun_setup;
};
inline TunClient::Ptr ClientConfig::new_tun_client_obj(openvpn_io::io_context& io_context,
TunClientParent& parent,
TransportClient* transcli)
{
return TunClient::Ptr(new Client(io_context, this, parent));
}
}
} // namespace openvpn
#endif
@@ -0,0 +1,507 @@
// OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012-2017 OpenVPN Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License Version 3
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
// Client tun setup for Mac
#ifndef OPENVPN_TUN_MAC_CLIENT_TUNSETUP_H
#define OPENVPN_TUN_MAC_CLIENT_TUNSETUP_H
#include <string>
#include <sstream>
#include <ostream>
#include <openvpn/common/exception.hpp>
#include <openvpn/common/rc.hpp>
#include <openvpn/common/size.hpp>
#include <openvpn/common/arraysize.hpp>
#include <openvpn/common/action.hpp>
#include <openvpn/common/process.hpp>
#include <openvpn/common/jsonlib.hpp>
#include <openvpn/error/excode.hpp>
#include <openvpn/tun/layer.hpp>
#include <openvpn/tun/mac/tunutil.hpp>
#include <openvpn/tun/mac/utun.hpp>
#include <openvpn/tun/mac/macgw.hpp>
#include <openvpn/tun/mac/macdns_watchdog.hpp>
#include <openvpn/tun/proxy.hpp>
#include <openvpn/tun/mac/macproxy.hpp>
#include <openvpn/tun/builder/rgwflags.hpp>
#include <openvpn/tun/builder/setup.hpp>
#ifdef HAVE_JSON
#include <openvpn/common/jsonhelper.hpp>
#endif
namespace openvpn {
namespace TunMac {
class Setup : public TunBuilderSetup::Base
{
public:
typedef RCPtr<Setup> Ptr;
OPENVPN_EXCEPTION(tun_mac_setup);
struct Config : public TunBuilderSetup::Config
{
std::string iface_name;
Layer layer; // OSI layer
bool tun_prefix = false;
bool add_bypass_routes_on_establish = false;
#ifdef HAVE_JSON
virtual Json::Value to_json() override
{
Json::Value root(Json::objectValue);
root["iface_name"] = Json::Value(iface_name);
root["layer"] = Json::Value(layer.str());
root["tun_prefix"] = Json::Value(tun_prefix);
return root;
};
virtual void from_json(const Json::Value& root, const std::string& title) override
{
json::assert_dict(root, title);
json::to_string(root, iface_name, "iface_name", title);
layer = Layer::from_str(json::get_string(root, "layer", title));
json::to_bool(root, tun_prefix, "tun_prefix", title);
}
#endif
};
bool add_bypass_route(const std::string& address,
bool ipv6,
std::ostream& os)
{
// not yet implemented
return true;
}
virtual int establish(const TunBuilderCapture& pull, // defined by TunBuilderSetup::Base
TunBuilderSetup::Config* config,
Stop* stop,
std::ostream& os) override
{
// get configuration
Config *conf = dynamic_cast<Config *>(config);
if (!conf)
throw tun_mac_setup("missing config");
// close out old remove cmds, if they exist
destroy(os);
// Open tun device. Try Mac OS X integrated utun device first
// (layer 3 only). If utun fails and MAC_TUNTAP_FALLBACK is defined,
// then fall back to TunTap third-party device.
// If successful, conf->iface_name will be set to tun iface name.
int fd = -1;
conf->tun_prefix = false;
try {
# if defined(MAC_TUNTAP_FALLBACK)
# if !defined(ASIO_DISABLE_KQUEUE)
# error Mac OS X TunTap adapter is incompatible with kqueue; rebuild with ASIO_DISABLE_KQUEUE
# endif
if (conf->layer() == Layer::OSI_LAYER_3)
{
try {
fd = UTun::utun_open(conf->iface_name);
conf->tun_prefix = true;
}
catch (const std::exception& e)
{
os << e.what() << std::endl;
}
}
if (fd == -1)
fd = Util::tuntap_open(conf->layer, conf->iface_name);
# else
fd = UTun::utun_open(conf->iface_name);
conf->tun_prefix = true;
# endif
}
catch (const std::exception& e)
{
throw ErrorCode(Error::TUN_IFACE_CREATE, true, e.what());
}
// create ActionLists for setting up and removing adapter properties
ActionList::Ptr add_cmds(new ActionList());
remove_cmds.reset(new ActionList());
// populate add/remove lists with actions
tun_config(conf->iface_name, pull, *add_cmds, *remove_cmds, os);
// execute the add actions
add_cmds->execute(os);
// now that the add actions have succeeded,
// enable the remove actions
remove_cmds->enable_destroy(true);
os << "open " << conf->iface_name << " SUCCEEDED" << std::endl;
return fd;
}
virtual void destroy(std::ostream& os) override // defined by DestructorBase
{
if (remove_cmds)
{
remove_cmds->destroy(os);
remove_cmds.reset();
}
}
virtual ~Setup()
{
std::ostringstream os;
destroy(os);
}
private:
enum { // add_del_route flags
R_IPv6=(1<<0),
R_IFACE=(1<<1),
R_IFACE_HINT=(1<<2),
R_ONLINK=(1<<3),
R_REJECT=(1<<4),
R_BLACKHOLE=(1<<5),
};
static void add_del_route(const std::string& addr_str,
const int prefix_len,
const std::string& gateway_str,
const std::string& iface,
const unsigned int flags,
Action::Ptr& create,
Action::Ptr& destroy)
{
if (flags & R_IPv6)
{
const IPv6::Addr addr = IPv6::Addr::from_string(addr_str);
const IPv6::Addr netmask = IPv6::Addr::netmask_from_prefix_len(prefix_len);
const IPv6::Addr net = addr & netmask;
Command::Ptr add(new Command);
add->argv.push_back("/sbin/route");
add->argv.push_back("add");
add->argv.push_back("-net");
add->argv.push_back("-inet6");
add->argv.push_back(net.to_string());
add->argv.push_back("-prefixlen");
add->argv.push_back(to_string(prefix_len));
if (flags & R_REJECT)
add->argv.push_back("-reject");
if (flags & R_BLACKHOLE)
add->argv.push_back("-blackhole");
if (!iface.empty())
{
if (flags & R_IFACE)
{
add->argv.push_back("-iface");
add->argv.push_back(iface);
}
}
if (!gateway_str.empty() && !(flags & R_IFACE))
{
std::string g = gateway_str;
if (flags & R_IFACE_HINT)
g += '%' + iface;
add->argv.push_back(g);
}
create = add;
// for the destroy command, copy the add command but replace "add" with "delete"
Command::Ptr del(add->copy());
del->argv[1] = "delete";
destroy = del;
}
else
{
const IPv4::Addr addr = IPv4::Addr::from_string(addr_str);
const IPv4::Addr netmask = IPv4::Addr::netmask_from_prefix_len(prefix_len);
const IPv4::Addr net = addr & netmask;
Command::Ptr add(new Command);
add->argv.push_back("/sbin/route");
add->argv.push_back("add");
if (flags & R_ONLINK)
{
add->argv.push_back("-cloning");
add->argv.push_back("-net");
add->argv.push_back(net.to_string());
add->argv.push_back("-netmask");
add->argv.push_back(netmask.to_string());
add->argv.push_back("-interface");
add->argv.push_back(iface);
}
else
{
add->argv.push_back("-net");
add->argv.push_back(net.to_string());
add->argv.push_back("-netmask");
add->argv.push_back(netmask.to_string());
if (flags & R_REJECT)
add->argv.push_back("-reject");
if (flags & R_BLACKHOLE)
add->argv.push_back("-blackhole");
if (!iface.empty())
{
if (flags & R_IFACE)
{
add->argv.push_back("-iface");
add->argv.push_back(iface);
}
}
add->argv.push_back(gateway_str);
}
create = add;
// for the destroy command, copy the add command but replace "add" with "delete"
Command::Ptr del(add->copy());
del->argv[1] = "delete";
destroy = del;
}
}
static void add_del_route(const std::string& addr_str,
const int prefix_len,
const std::string& gateway_str,
const std::string& iface,
const unsigned int flags,
ActionList& create,
ActionList& destroy)
{
Action::Ptr c, d;
add_del_route(addr_str, prefix_len, gateway_str, iface, flags, c, d);
create.add(c);
destroy.add(d);
}
static void tun_config(const std::string& iface_name,
const TunBuilderCapture& pull,
ActionList& create,
ActionList& destroy,
std::ostream& os)
{
// get default gateway
MacGWInfo gw;
// set local4 and local6 to point to IPv4/6 route configurations
const TunBuilderCapture::RouteAddress* local4 = nullptr;
const TunBuilderCapture::RouteAddress* local6 = nullptr;
if (pull.tunnel_address_index_ipv4 >= 0)
local4 = &pull.tunnel_addresses[pull.tunnel_address_index_ipv4];
if (pull.tunnel_address_index_ipv6 >= 0)
local6 = &pull.tunnel_addresses[pull.tunnel_address_index_ipv6];
// Interface down
Command::Ptr iface_down(new Command);
iface_down->argv.push_back("/sbin/ifconfig");
iface_down->argv.push_back(iface_name);
iface_down->argv.push_back("down");
create.add(iface_down);
// Set IPv4 Interface
if (local4)
{
// Process ifconfig
const IPv4::Addr netmask = IPv4::Addr::netmask_from_prefix_len(local4->prefix_length);
{
Command::Ptr cmd(new Command);
cmd->argv.push_back("/sbin/ifconfig");
cmd->argv.push_back(iface_name);
cmd->argv.push_back(local4->address);
cmd->argv.push_back(local4->gateway);
cmd->argv.push_back("netmask");
cmd->argv.push_back(netmask.to_string());
cmd->argv.push_back("mtu");
cmd->argv.push_back(to_string(pull.mtu));
cmd->argv.push_back("up");
create.add(cmd);
}
add_del_route(local4->address, local4->prefix_length, local4->address, iface_name, 0, create, destroy);
}
// Set IPv6 Interface
if (local6 && !pull.block_ipv6)
{
{
Command::Ptr cmd(new Command);
cmd->argv.push_back("/sbin/ifconfig");
cmd->argv.push_back(iface_name);
cmd->argv.push_back("inet6");
cmd->argv.push_back(local6->address + '/' + to_string(local6->prefix_length));
cmd->argv.push_back("up");
create.add(cmd);
}
add_del_route(local6->address, local6->prefix_length, "", iface_name, R_IPv6|R_IFACE, create, destroy);
}
// Process Routes
{
for (std::vector<TunBuilderCapture::Route>::const_iterator i = pull.add_routes.begin(); i != pull.add_routes.end(); ++i)
{
const TunBuilderCapture::Route& route = *i;
if (route.ipv6)
{
if (!pull.block_ipv6)
add_del_route(route.address, route.prefix_length, local6->gateway, iface_name, R_IPv6|R_IFACE, create, destroy);
}
else
{
if (local4 && !local4->gateway.empty())
add_del_route(route.address, route.prefix_length, local4->gateway, iface_name, 0, create, destroy);
else
os << "ERROR: IPv4 route pushed without IPv4 ifconfig and/or route-gateway" << std::endl;
}
}
}
// Process exclude routes
if (!pull.exclude_routes.empty())
{
for (std::vector<TunBuilderCapture::Route>::const_iterator i = pull.exclude_routes.begin(); i != pull.exclude_routes.end(); ++i)
{
const TunBuilderCapture::Route& route = *i;
if (route.ipv6)
{
if (!pull.block_ipv6)
{
if (gw.v6.defined())
add_del_route(route.address, route.prefix_length, gw.v6.router.to_string(), gw.v6.iface, R_IPv6|R_IFACE_HINT, create, destroy);
else
os << "NOTE: cannot determine gateway for exclude IPv6 routes" << std::endl;
}
}
else
{
if (gw.v4.defined())
add_del_route(route.address, route.prefix_length, gw.v4.router.to_string(), gw.v4.iface, 0, create, destroy);
else
os << "NOTE: cannot determine gateway for exclude IPv4 routes" << std::endl;
}
}
}
// Process IPv4 redirect-gateway
if (pull.reroute_gw.ipv4)
{
// add server bypass route
if (gw.v4.defined())
{
if (!pull.remote_address.ipv6 && !(pull.reroute_gw.flags & RedirectGatewayFlags::RG_LOCAL))
{
Action::Ptr c, d;
add_del_route(pull.remote_address.address, 32, gw.v4.router.to_string(), gw.v4.iface, 0, c, d);
create.add(c);
destroy.add(d);
//add_del_route(gw.v4.router.to_string(), 32, "", gw.v4.iface, R_ONLINK, create, destroy); // fixme -- needed for block-local
}
}
else
os << "ERROR: cannot detect IPv4 default gateway" << std::endl;
if (!(pull.reroute_gw.flags & RGWFlags::EmulateExcludeRoutes))
{
add_del_route("0.0.0.0", 1, local4->gateway, iface_name, 0, create, destroy);
add_del_route("128.0.0.0", 1, local4->gateway, iface_name, 0, create, destroy);
}
}
// Process IPv6 redirect-gateway
if (pull.reroute_gw.ipv6 && !pull.block_ipv6)
{
// add server bypass route
if (gw.v6.defined())
{
if (pull.remote_address.ipv6 && !(pull.reroute_gw.flags & RedirectGatewayFlags::RG_LOCAL))
{
Action::Ptr c, d;
add_del_route(pull.remote_address.address, 128, gw.v6.router.to_string(), gw.v6.iface, R_IPv6|R_IFACE_HINT, c, d);
create.add(c);
destroy.add(d);
//add_del_route(gw.v6.router.to_string(), 128, "", gw.v6.iface, R_IPv6|R_ONLINK, create, destroy); // fixme -- needed for block-local
}
}
else
os << "ERROR: cannot detect IPv6 default gateway" << std::endl;
if (!(pull.reroute_gw.flags & RGWFlags::EmulateExcludeRoutes))
{
add_del_route("0000::", 1, local6->gateway, iface_name, R_IPv6|R_IFACE, create, destroy);
add_del_route("8000::", 1, local6->gateway, iface_name, R_IPv6|R_IFACE, create, destroy);
}
}
// Process block-ipv6
if (pull.block_ipv6)
{
add_del_route("2000::", 4, "::1", "lo0", R_IPv6|R_REJECT|R_IFACE_HINT, create, destroy);
add_del_route("3000::", 4, "::1", "lo0", R_IPv6|R_REJECT|R_IFACE_HINT, create, destroy);
add_del_route("fc00::", 7, "::1", "lo0", R_IPv6|R_REJECT|R_IFACE_HINT, create, destroy);
}
// Interface down
destroy.add(iface_down);
// configure DNS
{
MacDNS::Config::Ptr dns(new MacDNS::Config(pull));
MacDNSWatchdog::add_actions(dns,
MacDNSWatchdog::FLUSH_RECONFIG
#ifdef ENABLE_DNS_WATCHDOG
| MacDNSWatchdog::SYNCHRONOUS
| MacDNSWatchdog::ENABLE_WATCHDOG
#endif
,
create,
destroy);
}
if (pull.proxy_auto_config_url.defined())
ProxySettings::add_actions<MacProxySettings>(pull, create, destroy);
}
ActionList::Ptr remove_cmds;
public:
static void add_bypass_route(const std::string& route,
bool ipv6,
ActionList& add_cmds,
ActionList& remove_cmds_bypass_gw)
{
MacGWInfo gw;
if (!ipv6)
{
if (gw.v4.defined())
add_del_route(route, 32, gw.v4.router.to_string(), gw.v4.iface, 0, add_cmds, remove_cmds_bypass_gw);
}
else
{
if (gw.v6.defined())
add_del_route(route, 128, gw.v6.router.to_string(), gw.v6.iface, R_IPv6|R_IFACE_HINT, add_cmds, remove_cmds_bypass_gw);
}
}
};
}
}
#endif
+184
View File
@@ -0,0 +1,184 @@
// OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012-2018 OpenVPN Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License Version 3
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
#pragma once
namespace openvpn {
class DSDict {
public:
OPENVPN_EXCEPTION(dsdict_error);
DSDict(CF::DynamicStore& sc_arg, const std::string& sname_arg, const std::string& dskey_arg)
: sc(sc_arg),
sname(sname_arg),
dskey(dskey_arg),
dict(CF::DynamicStoreCopyDict(sc_arg, dskey)) { }
bool dirty() const
{
return mod.defined() ? !CFEqual(dict(), mod()) : false;
}
bool push_to_store()
{
if (dirty())
{
const CF::String keystr = CF::string(dskey);
if (SCDynamicStoreSetValue(sc(), keystr(), mod()))
{
OPENVPN_LOG("DSDict: updated " << dskey);
return true;
}
else
OPENVPN_LOG("DSDict: ERROR updating " << dskey);
}
return false;
}
bool remove_from_store()
{
if (dirty())
throw dsdict_error("internal error: remove_from_store called on modified dict");
const CF::String keystr = CF::string(dskey);
if (SCDynamicStoreRemoveValue(sc(), keystr()))
{
OPENVPN_LOG("DSDict: removed " << dskey);
return true;
}
else
{
OPENVPN_LOG("DSDict: ERROR removing " << dskey);
return false;
}
}
void will_modify()
{
if (!mod.defined())
mod = CF::mutable_dict_copy(dict);
}
void mod_reset()
{
mod = CF::mutable_dict();
}
void backup_orig(const std::string& key, const bool wipe_orig=true)
{
const CF::String k = CF::string(key);
const CF::String orig = orig_key(key);
if (!CFDictionaryContainsKey(dict(), orig()))
{
const CF::String delval = delete_value();
CFTypeRef v = CFDictionaryGetValue(dict(), k());
if (!v)
v = delval();
will_modify();
CFDictionarySetValue(mod(), orig(), v);
}
if (wipe_orig)
{
will_modify();
CFDictionaryRemoveValue(mod(), k());
}
}
void restore_orig()
{
const CFIndex size = CFDictionaryGetCount(dict());
std::unique_ptr<const void *[]> keys(new const void *[size]);
std::unique_ptr<const void *[]> values(new const void *[size]);
CFDictionaryGetKeysAndValues(dict(), keys.get(), values.get());
const CF::String orig_prefix = orig_key("");
const CFIndex orig_prefix_len = CFStringGetLength(orig_prefix());
const CF::String delval = delete_value();
for (CFIndex i = 0; i < size; ++i)
{
const CF::String key = CF::string_cast(keys[i]);
if (CFStringHasPrefix(key(), orig_prefix()))
{
const CFIndex key_len = CFStringGetLength(key());
if (key_len > orig_prefix_len)
{
const CFRange r = CFRangeMake(orig_prefix_len, key_len - orig_prefix_len);
const CF::String k(CFStringCreateWithSubstring(kCFAllocatorDefault, key(), r));
const CFTypeRef v = values[i];
const CF::String vstr = CF::string_cast(v);
will_modify();
if (vstr.defined() && CFStringCompare(vstr(), delval(), 0) == kCFCompareEqualTo)
CFDictionaryRemoveValue(mod(), k());
else
CFDictionaryReplaceValue(mod(), k(), v);
CFDictionaryRemoveValue(mod(), key());
}
}
}
}
std::string to_string() const
{
std::ostringstream os;
os << "*** DSDict " << dskey << std::endl;
std::string orig = CF::description(dict());
string::trim_crlf(orig);
os << "ORIG " << orig << std::endl;
if (dirty())
{
std::string modstr = CF::description(mod());
string::trim_crlf(modstr);
os << "MODIFIED " << modstr << std::endl;
}
return os.str();
}
static CF::DynamicStore ds_create(const std::string& sname)
{
CF::String sn = CF::string(sname);
return CF::DynamicStore(SCDynamicStoreCreate(kCFAllocatorDefault, sn(), nullptr, nullptr));
}
static bool signal_network_reconfiguration(const std::string& sname)
{
const char *key = "Setup:/Network/Global/IPv4";
CF::DynamicStore sc = ds_create(sname);
const CF::String cfkey = CF::string(key);
OPENVPN_LOG("DSDict: SCDynamicStoreNotifyValue " << key);
return bool(SCDynamicStoreNotifyValue(sc(), cfkey()));
}
CF::DynamicStore sc;
const std::string sname;
const std::string dskey;
const CF::Dict dict;
CF::MutableDict mod;
private:
CF::String orig_key(const std::string& key) const
{
return CF::string(sname + "Orig" + key);
}
CF::String delete_value() const
{
return CF::string(sname + "DeleteValue");
}
};
}
+282
View File
@@ -0,0 +1,282 @@
// OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012-2017 OpenVPN Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License Version 3
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
// Get IPv4 gateway info on Mac OS X.
#ifndef OPENVPN_TUN_MAC_GWV4_H
#define OPENVPN_TUN_MAC_GWV4_H
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/route.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <cstring>
#include <string>
#include <sstream>
#include <algorithm> // for std::max
#include <cstdint> // for std::uint32_t
#include <memory>
#include <openvpn/common/exception.hpp>
#include <openvpn/common/hexstr.hpp>
#include <openvpn/common/scoped_fd.hpp>
#include <openvpn/common/socktypes.hpp>
#include <openvpn/common/string.hpp>
#include <openvpn/addr/ip.hpp>
#include <openvpn/addr/addrpair.hpp>
#include <openvpn/addr/macaddr.hpp>
namespace openvpn {
class MacGatewayInfoV4
{
struct rtmsg {
struct rt_msghdr m_rtm;
char m_space[512];
};
# define OPENVPN_ROUNDUP(a) \
((a) > 0 ? (1 + (((a) - 1) | (sizeof(std::uint32_t) - 1))) : sizeof(std::uint32_t))
# define OPENVPN_NEXTADDR(w, u) \
if (rtm_addrs & (w)) { \
l = OPENVPN_ROUNDUP(u.sa_len); \
std::memmove(cp, &(u), l); \
cp += l; \
}
# define OPENVPN_ADVANCE(x, n) \
(x += OPENVPN_ROUNDUP((n)->sa_len))
public:
OPENVPN_EXCEPTION(route_gateway_error);
enum {
ADDR_DEFINED = (1<<0), /* set if gateway.addr defined */
NETMASK_DEFINED = (1<<1), /* set if gateway.netmask defined */
HWADDR_DEFINED = (1<<2), /* set if hwaddr is defined */
IFACE_DEFINED = (1<<3), /* set if iface is defined */
};
MacGatewayInfoV4()
: flags_(0)
{
struct rtmsg m_rtmsg;
ScopedFD sockfd;
int seq, l, pid, rtm_addrs, i;
struct sockaddr so_dst, so_mask;
char *cp = m_rtmsg.m_space;
struct sockaddr *gate = nullptr, *ifp = nullptr, *sa;
struct rt_msghdr *rtm_aux;
/* setup data to send to routing socket */
pid = ::getpid();
seq = 0;
rtm_addrs = RTA_DST | RTA_NETMASK | RTA_IFP;
std::memset(&m_rtmsg, 0, sizeof(m_rtmsg));
std::memset(&so_dst, 0, sizeof(so_dst));
std::memset(&so_mask, 0, sizeof(so_mask));
std::memset(&m_rtmsg.m_rtm, 0, sizeof(struct rt_msghdr));
m_rtmsg.m_rtm.rtm_type = RTM_GET;
m_rtmsg.m_rtm.rtm_flags = RTF_UP | RTF_GATEWAY;
m_rtmsg.m_rtm.rtm_version = RTM_VERSION;
m_rtmsg.m_rtm.rtm_seq = ++seq;
m_rtmsg.m_rtm.rtm_addrs = rtm_addrs;
so_dst.sa_family = AF_INET;
so_dst.sa_len = sizeof(struct sockaddr_in);
so_mask.sa_family = AF_INET;
so_mask.sa_len = sizeof(struct sockaddr_in);
OPENVPN_NEXTADDR(RTA_DST, so_dst);
OPENVPN_NEXTADDR(RTA_NETMASK, so_mask);
m_rtmsg.m_rtm.rtm_msglen = l = cp - (char *)&m_rtmsg;
/* transact with routing socket */
sockfd.reset(socket(PF_ROUTE, SOCK_RAW, 0));
if (!sockfd.defined())
throw route_gateway_error("GDG: socket #1 failed");
if (::write(sockfd(), (char *)&m_rtmsg, l) < 0)
throw route_gateway_error("GDG: problem writing to routing socket");
do {
l = ::read(sockfd(), (char *)&m_rtmsg, sizeof(m_rtmsg));
} while (l > 0 && (m_rtmsg.m_rtm.rtm_seq != seq || m_rtmsg.m_rtm.rtm_pid != pid));
sockfd.close();
/* extract return data from routing socket */
rtm_aux = &m_rtmsg.m_rtm;
cp = ((char *)(rtm_aux + 1));
if (rtm_aux->rtm_addrs)
{
for (i = 1; i; i <<= 1)
{
if (i & rtm_aux->rtm_addrs)
{
sa = (struct sockaddr *)cp;
if (i == RTA_GATEWAY )
gate = sa;
else if (i == RTA_IFP)
ifp = sa;
OPENVPN_ADVANCE(cp, sa);
}
}
}
else
return;
/* get gateway addr and interface name */
if (gate != nullptr )
{
/* get default gateway addr */
gateway_.addr.reset_ipv4_from_uint32(ntohl(((struct sockaddr_in *)gate)->sin_addr.s_addr));
if (!gateway_.addr.unspecified())
flags_ |= ADDR_DEFINED;
if (ifp)
{
/* get interface name */
const struct sockaddr_dl *adl = (struct sockaddr_dl *) ifp;
const size_t len = adl->sdl_nlen;
if (len && len < sizeof(iface_))
{
std::memcpy (iface_, adl->sdl_data, len);
iface_[len] = '\0';
flags_ |= IFACE_DEFINED;
}
}
}
/* get netmask of interface that owns default gateway */
if (flags_ & IFACE_DEFINED) {
struct ifreq ifr;
sockfd.reset(socket(AF_INET, SOCK_DGRAM, 0));
if (!sockfd.defined())
throw route_gateway_error("GDG: socket #2 failed");
std::memset(&ifr, 0, sizeof(ifr));
ifr.ifr_addr.sa_family = AF_INET;
string::strncpynt(ifr.ifr_name, iface_, IFNAMSIZ);
if (::ioctl(sockfd(), SIOCGIFNETMASK, (char *)&ifr) < 0)
throw route_gateway_error("GDG: ioctl #1 failed");
sockfd.close();
gateway_.netmask.reset_ipv4_from_uint32(ntohl(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr.s_addr));
flags_ |= NETMASK_DEFINED;
}
/* try to read MAC addr associated with interface that owns default gateway */
if (flags_ & IFACE_DEFINED)
{
struct ifconf ifc;
struct ifreq *ifr;
const int bufsize = 4096;
std::unique_ptr<char[]> buffer(new char[bufsize]);
std::memset(buffer.get(), 0, bufsize);
sockfd.reset(socket(AF_INET, SOCK_DGRAM, 0));
if (!sockfd.defined())
throw route_gateway_error("GDG: socket #3 failed");
ifc.ifc_len = bufsize;
ifc.ifc_buf = buffer.get();
if (::ioctl(sockfd(), SIOCGIFCONF, (char *)&ifc) < 0)
throw route_gateway_error("GDG: ioctl #2 failed");
sockfd.close();
for (cp = buffer.get(); cp <= buffer.get() + ifc.ifc_len - sizeof(struct ifreq); )
{
ifr = (struct ifreq *)cp;
const size_t len = sizeof(ifr->ifr_name) + std::max(sizeof(ifr->ifr_addr), size_t(ifr->ifr_addr.sa_len));
if (!ifr->ifr_addr.sa_family)
break;
if (!::strncmp(ifr->ifr_name, iface_, IFNAMSIZ))
{
if (ifr->ifr_addr.sa_family == AF_LINK)
{
struct sockaddr_dl *sdl = (struct sockaddr_dl *)&ifr->ifr_addr;
hwaddr_.reset((const unsigned char *)LLADDR(sdl));
flags_ |= HWADDR_DEFINED;
}
}
cp += len;
}
}
}
# undef OPENVPN_ROUNDUP
# undef OPENVPN_NEXTADDR
# undef OPENVPN_ADVANCE
std::string info() const
{
std::ostringstream os;
os << "GATEWAY";
if (flags_ & ADDR_DEFINED)
{
os << " ADDR=" << gateway_.addr;
if (flags_ & NETMASK_DEFINED)
{
os << '/' << gateway_.netmask;
}
}
if (flags_ & IFACE_DEFINED)
os << " IFACE=" << iface_;
if (flags_ & HWADDR_DEFINED)
os << " HWADDR=" << hwaddr_;
return os.str();
}
unsigned int flags() const { return flags_; }
const IP::Addr& gateway_addr() const { return gateway_.addr; }
std::string gateway_addr_str() const { return gateway_addr().to_string(); }
const IP::Addr& gateway_netmask() const { return gateway_.netmask; }
std::string gateway_netmask_str() const { return gateway_netmask().to_string(); }
std::string iface() const { return iface_; }
const MACAddr& hwaddr() const { return hwaddr_; }
bool iface_addr_defined() const
{
return (flags_ & (ADDR_DEFINED|IFACE_DEFINED)) == (ADDR_DEFINED|IFACE_DEFINED);
}
bool hwaddr_defined() const
{
return flags_ & HWADDR_DEFINED;
}
private:
unsigned int flags_;
IP::AddrMaskPair gateway_;
char iface_[16];
MACAddr hwaddr_;
};
}
#endif
+374
View File
@@ -0,0 +1,374 @@
// OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012-2017 OpenVPN Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License Version 3
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
// DNS utilities for Mac OS X.
#ifndef OPENVPN_TUN_MAC_MACDNS_H
#define OPENVPN_TUN_MAC_MACDNS_H
#include <string>
#include <sstream>
#include <memory>
#include <openvpn/common/size.hpp>
#include <openvpn/common/exception.hpp>
#include <openvpn/common/string.hpp>
#include <openvpn/common/process.hpp>
#include <openvpn/apple/macver.hpp>
#include <openvpn/apple/scdynstore.hpp>
#include <openvpn/apple/cf/cfhelper.hpp>
#include <openvpn/tun/builder/capture.hpp>
#include <openvpn/tun/mac/dsdict.hpp>
namespace openvpn {
class MacDNS : public RC<thread_unsafe_refcount>
{
class Info;
public:
typedef RCPtr<MacDNS> Ptr;
OPENVPN_EXCEPTION(macdns_error);
class Config : public RC<thread_safe_refcount>
{
public:
typedef RCPtr<Config> Ptr;
Config()
{
}
Config(const TunBuilderCapture& settings)
: dns_servers(get_dns_servers(settings)),
search_domains(get_search_domains(settings)),
adapter_domain_suffix(settings.adapter_domain_suffix)
{
// We redirect DNS if either of the following is true:
// 1. redirect-gateway (IPv4) is pushed, or
// 2. DNS servers are pushed but no search domains are pushed
redirect_dns = settings.reroute_gw.ipv4 || (CF::array_len(dns_servers) && !CF::array_len(search_domains));
}
std::string to_string() const
{
std::ostringstream os;
os << "RD=" << redirect_dns;
os << " SO=" << search_order;
os << " DNS=" << CF::array_to_string(dns_servers);
os << " DOM=" << CF::array_to_string(search_domains);
os << " ADS=" << adapter_domain_suffix;
return os.str();
}
bool redirect_dns = false;
int search_order = 5000;
CF::Array dns_servers;
CF::Array search_domains;
std::string adapter_domain_suffix;
private:
static CF::Array get_dns_servers(const TunBuilderCapture& settings)
{
CF::MutableArray ret(CF::mutable_array());
for (std::vector<TunBuilderCapture::DNSServer>::const_iterator i = settings.dns_servers.begin();
i != settings.dns_servers.end(); ++i)
{
const TunBuilderCapture::DNSServer& ds = *i;
CF::array_append_str(ret, ds.address);
}
return CF::const_array(ret);
}
static CF::Array get_search_domains(const TunBuilderCapture& settings)
{
CF::MutableArray ret(CF::mutable_array());
for (std::vector<TunBuilderCapture::SearchDomain>::const_iterator i = settings.search_domains.begin();
i != settings.search_domains.end(); ++i)
{
const TunBuilderCapture::SearchDomain& sd = *i;
CF::array_append_str(ret, sd.domain);
}
return CF::const_array(ret);
}
};
MacDNS(const std::string& sname_arg)
: sname(sname_arg)
{
}
void flush_cache()
{
const int v = ver.major();
if (v < Mac::Version::OSX_10_6)
OPENVPN_LOG("MacDNS: Error: No support for Mac OS X versions earlier than 10.6");
if (v == Mac::Version::OSX_10_6 || v >= Mac::Version::OSX_10_9)
{
Argv args;
args.push_back("/usr/bin/dscacheutil");
args.push_back("-flushcache");
OPENVPN_LOG(args.to_string());
system_cmd(args);
}
if (v >= Mac::Version::OSX_10_7)
{
Argv args;
args.push_back("/usr/bin/killall");
args.push_back("-HUP");
args.push_back("mDNSResponder");
OPENVPN_LOG(args.to_string());
system_cmd(args);
}
}
bool signal_network_reconfiguration()
{
return DSDict::signal_network_reconfiguration(sname);
}
bool setdns(const Config& config)
{
bool mod = false;
try {
CF::DynamicStore sc = ds_create();
Info::Ptr info(new Info(sc, sname));
// cleanup settings applied to previous interface
interface_change_cleanup(info.get());
if (config.redirect_dns)
{
// redirect all DNS
info->dns.will_modify();
// set DNS servers
if (CF::array_len(config.dns_servers))
{
info->dns.backup_orig("ServerAddresses");
CF::dict_set_obj(info->dns.mod, "ServerAddresses", config.dns_servers());
}
// set search domains
info->dns.backup_orig("SearchDomains");
CF::MutableArray search_domains(CF::mutable_array());
// add adapter_domain_suffix to SearchDomains for domain autocompletion
if (config.adapter_domain_suffix.length() > 0)
CF::array_append_str(search_domains, config.adapter_domain_suffix);
if (CF::array_len(search_domains))
CF::dict_set_obj(info->dns.mod, "SearchDomains", search_domains());
// set search order
info->dns.backup_orig("SearchOrder");
CF::dict_set_int(info->dns.mod, "SearchOrder", config.search_order);
// push it
mod |= info->dns.push_to_store();
}
else
{
// split-DNS - resolve only specific domains
info->ovpn.mod_reset();
if (CF::array_len(config.dns_servers) && CF::array_len(config.search_domains))
{
// set DNS servers
CF::dict_set_obj(info->ovpn.mod, "ServerAddresses", config.dns_servers());
// DNS will be used only for those domains
CF::dict_set_obj(info->ovpn.mod, "SupplementalMatchDomains", config.search_domains());
// do not use those domains in autocompletion
CF::dict_set_int(info->ovpn.mod, "SupplementalMatchDomainsNoSearch", 1);
}
// in case of split-DNS macOS uses domain suffix of network adapter,
// not the one provided by VPN (which we put to SearchDomains)
// push it
mod |= info->ovpn.push_to_store();
}
if (mod)
{
// As a backup, save PrimaryService in private dict (if network goes down while
// we are set, we can lose info about PrimaryService in State:/Network/Global/IPv4
// and be unable to reset ourselves).
const CFTypeRef ps = CF::dict_get_obj(info->ipv4.dict, "PrimaryService");
if (ps)
{
info->info.mod_reset();
CF::dict_set_obj(info->info.mod, "PrimaryService", ps);
info->info.push_to_store();
}
}
prev = info;
if (mod)
OPENVPN_LOG("MacDNS: SETDNS " << ver.to_string() << std::endl << info->to_string());
}
catch (const std::exception& e)
{
OPENVPN_LOG("MacDNS: setdns exception: " << e.what());
}
return mod;
}
bool resetdns()
{
bool mod = false;
try {
CF::DynamicStore sc = ds_create();
Info::Ptr info(new Info(sc, sname));
// cleanup settings applied to previous interface
interface_change_cleanup(info.get());
// undo primary dns changes
mod |= reset_primary_dns(info.get());
// undo non-redirect-gateway changes
if (CF::dict_len(info->ovpn.dict))
mod |= info->ovpn.remove_from_store();
// remove private info dict
if (CF::dict_len(info->info.dict))
mod |= info->info.remove_from_store();
if (mod)
OPENVPN_LOG("MacDNS: RESETDNS " << ver.to_string() << std::endl << info->to_string());
}
catch (const std::exception& e)
{
OPENVPN_LOG("MacDNS: resetdns exception: " << e.what());
}
return mod;
}
std::string to_string() const
{
CF::DynamicStore sc = ds_create();
Info::Ptr info(new Info(sc, sname));
return info->to_string();
}
CF::Array dskey_array() const
{
CF::DynamicStore sc = ds_create();
Info::Ptr info(new Info(sc, sname));
CF::MutableArray ret(CF::mutable_array());
CF::array_append_str(ret, info->ipv4.dskey);
CF::array_append_str(ret, info->info.dskey);
CF::array_append_str(ret, info->ovpn.dskey);
CF::array_append_str(ret, info->dns.dskey);
return CF::const_array(ret);
}
private:
void interface_change_cleanup(Info* info)
{
if (info->interface_change(prev.get()))
{
reset_primary_dns(prev.get());
prev.reset();
}
}
bool reset_primary_dns(Info* info)
{
bool mod = false;
if (info)
{
#if 1
// Restore previous DNS settings.
// Recommended for production.
info->dns.will_modify();
info->dns.restore_orig();
mod |= info->dns.push_to_store();
#else
// Wipe DNS settings without restore.
// This can potentially wipe static IP/DNS settings.
info->dns.mod_reset();
mod |= info->dns.push_to_store();
#endif
}
return mod;
}
class Info : public RC<thread_unsafe_refcount>
{
public:
typedef RCPtr<Info> Ptr;
Info(CF::DynamicStore& sc, const std::string& sname)
: ipv4(sc, sname, "State:/Network/Global/IPv4"),
info(sc, sname, "State:/Network/Service/" + sname + "/Info"),
ovpn(sc, sname, "State:/Network/Service/" + sname + "/DNS"),
dns(sc, sname, primary_dns(ipv4.dict, info.dict))
{
}
std::string to_string() const
{
std::ostringstream os;
os << ipv4.to_string();
os << info.to_string();
os << ovpn.to_string();
os << dns.to_string();
return os.str();
}
bool interface_change(Info* other) const
{
return other && dns.dskey != other->dns.dskey;
}
DSDict ipv4;
DSDict info; // we may modify
DSDict ovpn; // we may modify
DSDict dns; // we may modify
private:
static std::string primary_dns(const CF::Dict& ipv4, const CF::Dict& info)
{
std::string serv = CF::dict_get_str(ipv4, "PrimaryService");
if (serv.empty())
serv = CF::dict_get_str(info, "PrimaryService");
if (serv.empty())
throw macdns_error("no primary service");
return "Setup:/Network/Service/" + serv + "/DNS";
}
};
CF::DynamicStore ds_create() const
{
return DSDict::ds_create(sname);
}
const std::string sname;
Mac::Version ver;
Info::Ptr prev;
};
}
#endif
@@ -0,0 +1,291 @@
// OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012-2017 OpenVPN Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License Version 3
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
// DNS utilities for Mac
#ifndef OPENVPN_TUN_MAC_MACDNS_WATCHDOG_H
#define OPENVPN_TUN_MAC_MACDNS_WATCHDOG_H
#include <thread>
#include <mutex>
#include <openvpn/log/logthread.hpp>
#include <openvpn/common/action.hpp>
#include <openvpn/apple/cf/cftimer.hpp>
#include <openvpn/apple/cf/cfrunloop.hpp>
#include <openvpn/tun/mac/macdns.hpp>
namespace openvpn {
OPENVPN_EXCEPTION(macdns_watchdog_error);
class MacDNSWatchdog : public RC<thread_unsafe_refcount>
{
public:
typedef RCPtr<MacDNSWatchdog> Ptr;
// flags
enum {
ENABLE_WATCHDOG = (1<<0),
SYNCHRONOUS = (1<<1),
FLUSH_RECONFIG = (1<<2),
};
class DNSAction : public Action
{
public:
typedef RCPtr<DNSAction> Ptr;
DNSAction(const MacDNSWatchdog::Ptr& parent_arg,
const MacDNS::Config::Ptr& config_arg,
const unsigned int flags_arg)
: parent(parent_arg),
config(config_arg),
flags(flags_arg)
{
}
virtual void execute(std::ostream& os)
{
os << to_string() << std::endl;
if (parent)
parent->setdns(config, flags);
}
virtual std::string to_string() const
{
std::ostringstream os;
os << "MacDNSAction: FLAGS=";
if (flags & ENABLE_WATCHDOG)
os << 'E';
if (flags & SYNCHRONOUS)
os << 'S';
if (flags & FLUSH_RECONFIG)
os << 'F';
if (config)
os << ' ' << config->to_string();
return os.str();
}
private:
const MacDNSWatchdog::Ptr parent;
const MacDNS::Config::Ptr config;
const unsigned int flags;
};
MacDNSWatchdog()
: macdns(new MacDNS("OpenVPNConnect")),
thread(nullptr)
{
}
virtual ~MacDNSWatchdog()
{
stop_thread();
}
static void add_actions(const MacDNS::Config::Ptr& dns,
const unsigned int flags,
ActionList& create,
ActionList& destroy)
{
MacDNSWatchdog::Ptr watchdog(new MacDNSWatchdog);
MacDNS::Config::Ptr dns_remove;
DNSAction::Ptr create_action(new DNSAction(watchdog, dns, flags));
DNSAction::Ptr destroy_action(new DNSAction(watchdog, dns_remove, flags));
create.add(create_action);
destroy.add(destroy_action);
}
private:
bool setdns(const MacDNS::Config::Ptr& config, const unsigned int flags)
{
bool mod = false;
if (config)
{
if ((flags & SYNCHRONOUS) || !(flags & ENABLE_WATCHDOG))
stop_thread();
config_ = config;
if (flags & ENABLE_WATCHDOG)
{
if (!thread)
{
mod = macdns->setdns(*config_);
thread = new std::thread(&MacDNSWatchdog::thread_func, this);
}
else
{
if (runloop.defined())
schedule_push_timer(0);
else
OPENVPN_LOG("MacDNSWatchdog::setdns: runloop undefined");
}
}
else
{
mod = macdns->setdns(*config_);
}
}
else
{
stop_thread();
config_.reset();
mod = macdns->resetdns();
}
if (mod && (flags & FLUSH_RECONFIG))
{
macdns->flush_cache();
macdns->signal_network_reconfiguration();
}
return mod;
}
std::string to_string() const
{
const MacDNS::Config::Ptr config(config_);
if (config)
return config->to_string();
else
return std::string("UNDEF");
}
void stop_thread()
{
if (thread)
{
if (runloop.defined())
CFRunLoopStop(runloop());
thread->join();
delete thread;
thread = nullptr;
}
}
// All methods below this point called in the context of watchdog thread
// except for schedule_push_timer which may be called from parent thread
// as well.
void thread_func()
{
runloop.reset(CFRunLoopGetCurrent(), CF::GET);
Log::Context logctx(logwrap);
try {
SCDynamicStoreContext context = {0, this, nullptr, nullptr, nullptr};
CF::DynamicStore ds(SCDynamicStoreCreate(kCFAllocatorDefault,
CFSTR("OpenVPN_MacDNSWatchdog"),
callback_static,
&context));
if (!ds.defined())
throw macdns_watchdog_error("SCDynamicStoreCreate");
const CF::Array watched_keys(macdns->dskey_array());
if (!watched_keys.defined())
throw macdns_watchdog_error("watched_keys is undefined");
if (!SCDynamicStoreSetNotificationKeys(ds(),
watched_keys(),
nullptr))
throw macdns_watchdog_error("SCDynamicStoreSetNotificationKeys failed");
CF::RunLoopSource rls(SCDynamicStoreCreateRunLoopSource(kCFAllocatorDefault, ds(), 0));
if (!rls.defined())
throw macdns_watchdog_error("SCDynamicStoreCreateRunLoopSource failed");
CFRunLoopAddSource(CFRunLoopGetCurrent(), rls(), kCFRunLoopDefaultMode);
// process event loop until CFRunLoopStop is called from parent thread
CFRunLoopRun();
}
catch (const std::exception& e)
{
OPENVPN_LOG("MacDNSWatchdog::thread_func exception: " << e.what());
}
cancel_push_timer();
}
static void callback_static(SCDynamicStoreRef store, CFArrayRef changedKeys, void *arg)
{
MacDNSWatchdog *self = (MacDNSWatchdog *)arg;
self->callback(store, changedKeys);
}
void callback(SCDynamicStoreRef store, CFArrayRef changedKeys)
{
// DNS Watchdog delay from the time that change is detected
// to when we forcibly revert it (seconds).
schedule_push_timer(1);
}
void schedule_push_timer(const int seconds)
{
std::lock_guard<std::mutex> lock(push_timer_lock);
CFRunLoopTimerContext context = { 0, this, nullptr, nullptr, nullptr };
cancel_push_timer_nolock();
push_timer.reset(CFRunLoopTimerCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + seconds, 0, 0, 0, push_timer_callback_static, &context));
if (push_timer.defined())
CFRunLoopAddTimer(runloop(), push_timer(), kCFRunLoopCommonModes);
else
OPENVPN_LOG("MacDNSWatchdog::schedule_push_timer: failed to create timer");
}
void cancel_push_timer_nolock()
{
if (push_timer.defined())
{
CFRunLoopTimerInvalidate(push_timer());
push_timer.reset(nullptr);
}
}
void cancel_push_timer()
{
std::lock_guard<std::mutex> lock(push_timer_lock);
cancel_push_timer_nolock();
}
static void push_timer_callback_static(CFRunLoopTimerRef timer, void *info)
{
MacDNSWatchdog* self = (MacDNSWatchdog*)info;
self->push_timer_callback(timer);
}
void push_timer_callback(CFRunLoopTimerRef timer)
{
try {
// reset DNS settings after watcher detected modifications by third party
const MacDNS::Config::Ptr config(config_);
if (macdns->setdns(*config))
OPENVPN_LOG("MacDNSWatchdog: updated DNS settings");
}
catch (const std::exception& e)
{
OPENVPN_LOG("MacDNSWatchdog::push_timer_callback exception: " << e.what());
}
}
MacDNS::Config::Ptr config_;
MacDNS::Ptr macdns;
std::thread* thread; // watcher thread
CF::RunLoop runloop; // run loop in watcher thread
CF::Timer push_timer; // watcher thread timer
std::mutex push_timer_lock;
Log::Context::Wrapper logwrap; // used to carry forward the log context from parent thread
};
}
#endif
@@ -0,0 +1,88 @@
// OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012-2017 OpenVPN Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License Version 3
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
#ifndef OPENVPN_TUN_MAC_MACGW_H
#define OPENVPN_TUN_MAC_MACGW_H
#include <string>
#include <openvpn/common/size.hpp>
#include <openvpn/common/exception.hpp>
#include <openvpn/addr/ip.hpp>
#include <openvpn/apple/scdynstore.hpp>
#include <openvpn/apple/cf/cfhelper.hpp>
namespace openvpn {
struct MacGWInfo
{
struct Variant
{
friend struct MacGWInfo;
public:
bool defined() const {
return !iface.empty() && router.defined();
}
std::string to_string() const
{
return iface + '/' + router.to_string();
}
std::string iface;
IP::Addr router;
private:
Variant() {}
Variant(const IP::Addr::Version v, const CF::DynamicStore& dstore)
{
const std::string key = std::string("State:/Network/Global/IP") + IP::Addr::version_string_static(v);
const CF::Dict d(CF::DynamicStoreCopyDict(dstore, key));
iface = CF::dict_get_str(d, "PrimaryInterface");
const std::string addr = CF::dict_get_str(d, "Router");
if (!addr.empty())
router = IP::Addr::from_string(addr, "MacGWInfo::Variant", v);
else
router.reset();
}
};
MacGWInfo()
{
const CF::DynamicStore ds(SCDynamicStoreCreate(kCFAllocatorDefault,
CFSTR("MacGWInfo"),
nullptr,
nullptr));
v4 = Variant(IP::Addr::V4, ds);
v6 = Variant(IP::Addr::V6, ds);
}
std::string to_string() const
{
return "IPv4=" + v4.to_string() + " IPv6=" + v6.to_string();
}
Variant v4;
Variant v6;
};
}
#endif
@@ -0,0 +1,99 @@
// OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012-2018 OpenVPN Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License Version 3
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
#pragma once
#include <openvpn/tun/proxy.hpp>
#include <openvpn/tun/mac/dsdict.hpp>
namespace openvpn {
class MacProxySettings : public ProxySettings
{
public:
OPENVPN_EXCEPTION(macproxy_error);
typedef RCPtr<MacProxySettings> Ptr;
class Info : public RC<thread_unsafe_refcount>
{
public:
typedef RCPtr<Info> Ptr;
Info(CF::DynamicStore& sc, const std::string& sname)
: ipv4(sc, sname, "State:/Network/Global/IPv4"),
info(sc, sname, "State:/Network/Service/" + sname + "/Info"),
proxy(sc, sname, proxies(ipv4.dict, info.dict)) { }
std::string to_string() const
{
std::ostringstream os;
os << ipv4.to_string();
os << info.to_string();
os << proxy.to_string();
return os.str();
}
DSDict ipv4;
DSDict info;
DSDict proxy;
private:
static std::string proxies(const CF::Dict& ipv4, const CF::Dict& info)
{
std::string serv = CF::dict_get_str(ipv4, "PrimaryService");
if (serv.empty())
serv = CF::dict_get_str(info, "PrimaryService");
if (serv.empty())
throw macproxy_error("no primary service");
return "Setup:/Network/Service/" + serv + "/Proxies";
}
};
MacProxySettings(const TunBuilderCapture::ProxyAutoConfigURL& config_arg)
: ProxySettings(config_arg) { }
void set_proxy(bool del) override
{
if (!config.defined())
return;
CF::DynamicStore sc = DSDict::ds_create(sname);
Info::Ptr info(new Info(sc, sname));
info->proxy.will_modify();
if (!del)
{
info->proxy.backup_orig("ProxyAutoConfigEnable");
CF::dict_set_int(info->proxy.mod, "ProxyAutoConfigEnable", 1);
info->proxy.backup_orig("ProxyAutoConfigURLString");
CF::dict_set_str(info->proxy.mod, "ProxyAutoConfigURLString", config.to_string());
}
else
info->proxy.restore_orig();
info->proxy.push_to_store();
OPENVPN_LOG("MacProxy: set_proxy " << info->to_string());
}
};
}
@@ -0,0 +1,76 @@
// OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012-2017 OpenVPN Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License Version 3
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
// Tun interface utilities for Mac OS X.
#ifndef OPENVPN_TUN_MAC_TUNUTIL_H
#define OPENVPN_TUN_MAC_TUNUTIL_H
#include <fcntl.h>
#include <errno.h>
#include <string>
#include <openvpn/common/size.hpp>
#include <openvpn/common/exception.hpp>
#include <openvpn/asio/asioerr.hpp>
#include <openvpn/common/to_string.hpp>
#include <openvpn/common/scoped_fd.hpp>
#include <openvpn/tun/layer.hpp>
namespace openvpn {
namespace TunMac {
namespace Util {
OPENVPN_EXCEPTION(tun_mac_util);
inline int tuntap_open(const Layer& layer, std::string& name)
{
for (int i = 0; i < 256; ++i)
{
const char *tuntap;
if (layer() == Layer::OSI_LAYER_3)
tuntap = "tun";
else if (layer() == Layer::OSI_LAYER_2)
tuntap = "tap";
else
throw tun_mac_util("unknown OSI layer");
const std::string node_str = tuntap + to_string(i);
const std::string node_fn = "/dev/" + node_str;
ScopedFD fd(open(node_fn.c_str(), O_RDWR));
if (fd.defined())
{
// got it
if (fcntl(fd(), F_SETFL, O_NONBLOCK) < 0)
throw tun_mac_util("fcntl error on " + node_fn + " : " + errinfo(errno));
name = node_str;
return fd.release();
}
}
throw tun_mac_util(std::string("error opening Mac ") + layer.dev_type() + " device");
}
}
}
}
#endif
+114
View File
@@ -0,0 +1,114 @@
// OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012-2017 OpenVPN Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License Version 3
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
//
// Thanks to Jonathan Levin for proof-of-concept utun code for Mac OS X.
// http://newosxbook.com/src.jl?tree=listings&file=17-15-utun.c
// Open a utun device on Mac OS X.
#ifndef OPENVPN_TUN_MAC_UTUN_H
#define OPENVPN_TUN_MAC_UTUN_H
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/sys_domain.h>
#include <sys/kern_control.h>
#include <net/if_utun.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>
#include <stdlib.h>
#include <string>
#include <openvpn/common/size.hpp>
#include <openvpn/common/exception.hpp>
#include <openvpn/common/to_string.hpp>
#include <openvpn/common/scoped_fd.hpp>
namespace openvpn {
namespace TunMac {
namespace UTun {
OPENVPN_EXCEPTION(utun_error);
// Open specific utun device unit and return fd.
// If the unit number is already in use, return -1.
// Throw exceptions for all other errors.
// Return the iface name in name.
inline int utun_open(std::string& name, const int unit)
{
struct sockaddr_ctl sc;
struct ctl_info ctlInfo;
memset(&ctlInfo, 0, sizeof(ctlInfo));
if (strlcpy(ctlInfo.ctl_name, UTUN_CONTROL_NAME, sizeof(ctlInfo.ctl_name))
>= sizeof(ctlInfo.ctl_name))
throw utun_error("UTUN_CONTROL_NAME too long");
ScopedFD fd(socket(PF_SYSTEM, SOCK_DGRAM, SYSPROTO_CONTROL));
if (!fd.defined())
throw utun_error("socket(SYSPROTO_CONTROL)");
if (ioctl(fd(), CTLIOCGINFO, &ctlInfo) == -1)
throw utun_error("ioctl(CTLIOCGINFO)");
sc.sc_id = ctlInfo.ctl_id;
sc.sc_len = sizeof(sc);
sc.sc_family = AF_SYSTEM;
sc.ss_sysaddr = AF_SYS_CONTROL;
sc.sc_unit = unit + 1;
// If the connect is successful, a utunX device will be created, where X
// is our unit number - 1.
if (connect(fd(), (struct sockaddr *)&sc, sizeof(sc)) == -1)
return -1;
// Get iface name of newly created utun dev.
char utunname[20];
socklen_t utunname_len = sizeof(utunname);
if (getsockopt(fd(), SYSPROTO_CONTROL, UTUN_OPT_IFNAME, utunname, &utunname_len))
throw utun_error("getsockopt(SYSPROTO_CONTROL)");
name = utunname;
return fd.release();
}
// Try to open an available utun device unit.
// Return the iface name in name.
inline int utun_open(std::string& name)
{
for (int unit = 0; unit < 256; ++unit)
{
const int fd = utun_open(name, unit);
if (fd >= 0)
return fd;
}
throw utun_error("cannot open available utun device");
}
}
}
}
#endif