mirror of
https://github.com/deneraraujo/OpenVPNAdapter.git
synced 2026-04-24 00:00:05 +08:00
Merge commit '86cc97e55fe346502462284d2e636a2b3708163e' as 'Sources/OpenVPN3'
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
// 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-2019 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_CLIENT_ASYNC_RESOLVE_H
|
||||
#define OPENVPN_CLIENT_ASYNC_RESOLVE_H
|
||||
|
||||
#ifdef USE_ASIO
|
||||
#include <openvpn/client/async_resolve/asio.hpp>
|
||||
#else
|
||||
#include <openvpn/client/async_resolve/generic.hpp>
|
||||
#endif
|
||||
|
||||
// create shortcuts for common templated classes
|
||||
namespace openvpn {
|
||||
typedef AsyncResolvable<openvpn_io::ip::udp::resolver> AsyncResolvableUDP;
|
||||
typedef AsyncResolvable<openvpn_io::ip::tcp::resolver> AsyncResolvableTCP;
|
||||
}
|
||||
|
||||
#endif /* OPENVPN_CLIENT_ASYNC_RESOLVE_H */
|
||||
@@ -0,0 +1,163 @@
|
||||
// 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-2019 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_CLIENT_ASYNC_RESOLVE_ASIO_H
|
||||
#define OPENVPN_CLIENT_ASYNC_RESOLVE_ASIO_H
|
||||
|
||||
#include <openvpn/io/io.hpp>
|
||||
#include <openvpn/asio/asiowork.hpp>
|
||||
|
||||
#include <openvpn/common/bigmutex.hpp>
|
||||
#include <openvpn/common/rc.hpp>
|
||||
#include <openvpn/common/hostport.hpp>
|
||||
|
||||
|
||||
namespace openvpn {
|
||||
template<typename RESOLVER_TYPE>
|
||||
class AsyncResolvable
|
||||
{
|
||||
private:
|
||||
typedef RCPtr<AsyncResolvable> Ptr;
|
||||
|
||||
class ResolveThread : public RC<thread_safe_refcount>
|
||||
{
|
||||
friend class AsyncResolvable<RESOLVER_TYPE>;
|
||||
|
||||
private:
|
||||
typedef RCPtr<ResolveThread> Ptr;
|
||||
|
||||
openvpn_io::io_context& io_context;
|
||||
AsyncResolvable<RESOLVER_TYPE> *parent;
|
||||
std::atomic<bool> detached{false};
|
||||
|
||||
ResolveThread(openvpn_io::io_context &io_context_arg,
|
||||
AsyncResolvable<RESOLVER_TYPE> *parent_arg,
|
||||
const std::string& host, const std::string& port)
|
||||
: io_context(io_context_arg),
|
||||
parent(parent_arg)
|
||||
{
|
||||
std::thread t([self=Ptr(this), host, port]()
|
||||
{
|
||||
openvpn_io::io_context io_context(1);
|
||||
openvpn_io::error_code error;
|
||||
RESOLVER_TYPE resolver(io_context);
|
||||
typename RESOLVER_TYPE::results_type results;
|
||||
|
||||
results = resolver.resolve(host, port, error);
|
||||
if (!self->is_detached())
|
||||
{
|
||||
self->post_callback(results, error);
|
||||
}
|
||||
});
|
||||
// detach the thread so that the client won't need to wait for
|
||||
// it to join.
|
||||
t.detach();
|
||||
}
|
||||
|
||||
void detach()
|
||||
{
|
||||
detached.store(true, std::memory_order_relaxed);
|
||||
parent = nullptr;
|
||||
}
|
||||
|
||||
bool is_detached() const
|
||||
{
|
||||
return detached.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
void post_callback(typename RESOLVER_TYPE::results_type results,
|
||||
openvpn_io::error_code error)
|
||||
{
|
||||
openvpn_io::post(io_context, [self=Ptr(this), results, error]()
|
||||
{
|
||||
auto parent = self->parent;
|
||||
if (!self->is_detached() && parent)
|
||||
{
|
||||
self->detach();
|
||||
OPENVPN_ASYNC_HANDLER;
|
||||
parent->resolve_callback(error, results);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
openvpn_io::io_context& io_context;
|
||||
std::unique_ptr<AsioWork> asio_work;
|
||||
typename ResolveThread::Ptr resolve_thread;
|
||||
|
||||
public:
|
||||
AsyncResolvable(openvpn_io::io_context& io_context_arg)
|
||||
: io_context(io_context_arg)
|
||||
{
|
||||
}
|
||||
|
||||
virtual ~AsyncResolvable()
|
||||
{
|
||||
async_resolve_cancel();
|
||||
}
|
||||
|
||||
virtual void resolve_callback(const openvpn_io::error_code& error,
|
||||
typename RESOLVER_TYPE::results_type results) = 0;
|
||||
|
||||
// mimic the asynchronous DNS resolution by performing a
|
||||
// synchronous one in a detached thread.
|
||||
//
|
||||
// This strategy has the advantage of allowing the core to
|
||||
// stop/exit without waiting for the getaddrinfo() (used
|
||||
// internally) to terminate.
|
||||
// Note: getaddrinfo() is non-interruptible by design.
|
||||
//
|
||||
// In other words, we are re-creating exactly what ASIO would
|
||||
// normally do in case of async_resolve(), with the difference
|
||||
// that here we have control over the resolving thread and we
|
||||
// can easily detach it. Deatching the internal thread created
|
||||
// by ASIO would not be feasible as it is not exposed.
|
||||
void async_resolve_name(const std::string& host, const std::string& port)
|
||||
{
|
||||
resolve_thread.reset(new ResolveThread(io_context, this, host, port));
|
||||
}
|
||||
|
||||
// there might be nothing else in the main io_context queue
|
||||
// right now, therefore we use AsioWork to prevent the loop
|
||||
// from exiting while we perform the DNS resolution in the
|
||||
// detached thread.
|
||||
void async_resolve_lock()
|
||||
{
|
||||
asio_work.reset(new AsioWork(io_context));
|
||||
}
|
||||
|
||||
// to be called by the child class when the core wants to stop
|
||||
// and we don't need to wait for the detached thread any longer.
|
||||
// It simulates a resolve abort
|
||||
void async_resolve_cancel()
|
||||
{
|
||||
if (resolve_thread)
|
||||
{
|
||||
resolve_thread->detach();
|
||||
resolve_thread.reset();
|
||||
}
|
||||
|
||||
asio_work.reset();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#endif /* OPENVPN_CLIENT_ASYNC_RESOLVE_ASIO_H */
|
||||
@@ -0,0 +1,79 @@
|
||||
// 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-2019 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_CLIENT_ASYNC_RESOLVE_GENERIC_H
|
||||
#define OPENVPN_CLIENT_ASYNC_RESOLVE_GENERIC_H
|
||||
|
||||
#include <openvpn/common/bigmutex.hpp>
|
||||
#include <openvpn/common/rc.hpp>
|
||||
#include <openvpn/common/hostport.hpp>
|
||||
|
||||
|
||||
namespace openvpn {
|
||||
template<typename RESOLVER_TYPE>
|
||||
class AsyncResolvable: public virtual RC<thread_unsafe_refcount>
|
||||
{
|
||||
private:
|
||||
typedef RCPtr<AsyncResolvable> Ptr;
|
||||
|
||||
openvpn_io::io_context& io_context;
|
||||
RESOLVER_TYPE resolver;
|
||||
|
||||
public:
|
||||
AsyncResolvable(openvpn_io::io_context& io_context_arg)
|
||||
: io_context(io_context_arg),
|
||||
resolver(io_context_arg)
|
||||
{
|
||||
}
|
||||
|
||||
virtual void resolve_callback(const openvpn_io::error_code& error,
|
||||
typename RESOLVER_TYPE::results_type results) = 0;
|
||||
|
||||
// This implementation assumes that the i/o reactor provides an asynchronous
|
||||
// DNS resolution routine using its own primitives and that doesn't require
|
||||
// us to take care of any non-interruptible opration (i.e. getaddrinfo() in
|
||||
// case of ASIO).
|
||||
//
|
||||
// For example, iOS implements aync_resolve using GCD and CFHost. This
|
||||
// implementation satisfies the constraints mentioned above
|
||||
void async_resolve_name(const std::string& host, const std::string& port)
|
||||
{
|
||||
resolver.async_resolve(host, port, [self=Ptr(this)](const openvpn_io::error_code& error,
|
||||
typename RESOLVER_TYPE::results_type results)
|
||||
{
|
||||
OPENVPN_ASYNC_HANDLER;
|
||||
self->resolve_callback(error, results);
|
||||
});
|
||||
}
|
||||
|
||||
// no-op: needed to provide the same class signature of the ASIO version
|
||||
void async_resolve_lock()
|
||||
{
|
||||
}
|
||||
|
||||
void async_resolve_cancel()
|
||||
{
|
||||
resolver.cancel();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#endif /* OPENVPN_CLIENT_ASYNC_RESOLVE_GENERIC_H */
|
||||
@@ -0,0 +1,684 @@
|
||||
// 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/>.
|
||||
|
||||
// This file implements the top-level connection logic for an OpenVPN client
|
||||
// connection. It is concerned with starting, stopping, pausing, and resuming
|
||||
// OpenVPN client connections. It deals with retrying a connection and handles
|
||||
// the connection timeout. It also deals with connection exceptions and understands
|
||||
// the difference between an exception that should halt any further reconnection
|
||||
// attempts (such as AUTH_FAILED), and other exceptions such as network errors
|
||||
// that would justify a retry.
|
||||
//
|
||||
// Some of the methods in the class (such as stop, pause, and reconnect) are often
|
||||
// called by another thread that is controlling the connection, therefore
|
||||
// thread-safe methods are provided where the thread-safe function posts a message
|
||||
// to the actual connection thread.
|
||||
//
|
||||
// In an OpenVPN client connection, the following object stack would be used:
|
||||
//
|
||||
// 1. class ClientConnect --
|
||||
// The top level object in an OpenVPN client connection.
|
||||
// 2. class ClientProto::Session --
|
||||
// The OpenVPN client protocol object.
|
||||
// 3. class ProtoContext --
|
||||
// The core OpenVPN protocol implementation that is common to both
|
||||
// client and server.
|
||||
// 4. ProtoStackBase<Packet> --
|
||||
// The lowest-level class that implements the basic functionality of
|
||||
// tunneling a protocol over a reliable or unreliable transport
|
||||
// layer, but isn't specific to OpenVPN per-se.
|
||||
|
||||
#ifndef OPENVPN_CLIENT_CLICONNECT_H
|
||||
#define OPENVPN_CLIENT_CLICONNECT_H
|
||||
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
#include <openvpn/common/bigmutex.hpp>
|
||||
#include <openvpn/common/rc.hpp>
|
||||
#include <openvpn/asio/asiowork.hpp>
|
||||
#include <openvpn/error/excode.hpp>
|
||||
#include <openvpn/time/asiotimer.hpp>
|
||||
#include <openvpn/client/cliopt.hpp>
|
||||
#include <openvpn/client/remotelist.hpp>
|
||||
#include <openvpn/client/clilife.hpp>
|
||||
|
||||
namespace openvpn {
|
||||
|
||||
// ClientConnect implements an "always-try-to-reconnect" approach, with remote
|
||||
// list rotation. Only gives up on auth failure or other fatal errors that
|
||||
// cannot be remedied by retrying.
|
||||
class ClientConnect : ClientProto::NotifyCallback,
|
||||
RemoteList::PreResolve::NotifyCallback,
|
||||
ClientLifeCycle::NotifyCallback,
|
||||
public RC<thread_unsafe_refcount>
|
||||
{
|
||||
public:
|
||||
typedef RCPtr<ClientConnect> Ptr;
|
||||
typedef ClientOptions::Client Client;
|
||||
|
||||
OPENVPN_SIMPLE_EXCEPTION(client_connect_unhandled_exception);
|
||||
|
||||
ClientConnect(openvpn_io::io_context& io_context_arg,
|
||||
const ClientOptions::Ptr& client_options_arg)
|
||||
: generation(0),
|
||||
halt(false),
|
||||
paused(false),
|
||||
client_finalized(false),
|
||||
dont_restart_(false),
|
||||
lifecycle_started(false),
|
||||
conn_timeout(client_options_arg->conn_timeout()),
|
||||
io_context(io_context_arg),
|
||||
client_options(client_options_arg),
|
||||
server_poll_timer(io_context_arg),
|
||||
restart_wait_timer(io_context_arg),
|
||||
conn_timer(io_context_arg),
|
||||
conn_timer_pending(false)
|
||||
{
|
||||
}
|
||||
|
||||
void start()
|
||||
{
|
||||
if (!client && !halt)
|
||||
{
|
||||
if (!test_network())
|
||||
throw ErrorCode(Error::NETWORK_UNAVAILABLE, true, "Network Unavailable");
|
||||
|
||||
RemoteList::Ptr remote_list = client_options->remote_list_precache();
|
||||
RemoteList::PreResolve::Ptr preres(new RemoteList::PreResolve(io_context,
|
||||
remote_list,
|
||||
client_options->stats_ptr()));
|
||||
if (preres->work_available())
|
||||
{
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::Resolve();
|
||||
client_options->events().add_event(std::move(ev));
|
||||
pre_resolve = preres;
|
||||
pre_resolve->start(this); // asynchronous -- will call back to pre_resolve_done
|
||||
}
|
||||
else
|
||||
new_client();
|
||||
}
|
||||
}
|
||||
|
||||
void send_explicit_exit_notify()
|
||||
{
|
||||
if (!halt && client)
|
||||
client->send_explicit_exit_notify();
|
||||
}
|
||||
|
||||
void graceful_stop()
|
||||
{
|
||||
send_explicit_exit_notify();
|
||||
//sleep(5); // simulate slow stop (comment out for production)
|
||||
stop();
|
||||
}
|
||||
|
||||
void stop()
|
||||
{
|
||||
if (!halt)
|
||||
{
|
||||
halt = true;
|
||||
if (pre_resolve)
|
||||
pre_resolve->cancel();
|
||||
if (client)
|
||||
{
|
||||
client->tun_set_disconnect();
|
||||
client->stop(false);
|
||||
}
|
||||
cancel_timers();
|
||||
asio_work.reset();
|
||||
|
||||
client_options->finalize(true);
|
||||
|
||||
if (lifecycle_started)
|
||||
{
|
||||
ClientLifeCycle* lc = client_options->lifecycle();
|
||||
if (lc)
|
||||
lc->stop();
|
||||
}
|
||||
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::Disconnected();
|
||||
client_options->events().add_event(std::move(ev));
|
||||
#ifdef OPENVPN_IO_REQUIRES_STOP
|
||||
io_context.stop();
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
void stop_on_signal(const openvpn_io::error_code& error, int signal_number)
|
||||
{
|
||||
stop();
|
||||
}
|
||||
|
||||
// like stop() but may be safely called by another thread
|
||||
void thread_safe_stop()
|
||||
{
|
||||
if (!halt)
|
||||
openvpn_io::post(io_context, [self=Ptr(this)]()
|
||||
{
|
||||
OPENVPN_ASYNC_HANDLER;
|
||||
self->graceful_stop();
|
||||
});
|
||||
}
|
||||
|
||||
void pause(const std::string& reason)
|
||||
{
|
||||
if (!halt && !paused)
|
||||
{
|
||||
paused = true;
|
||||
if (client)
|
||||
{
|
||||
client->send_explicit_exit_notify();
|
||||
client->stop(false);
|
||||
interim_finalize();
|
||||
}
|
||||
cancel_timers();
|
||||
asio_work.reset(new AsioWork(io_context));
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::Pause(reason);
|
||||
client_options->events().add_event(std::move(ev));
|
||||
client_options->stats().error(Error::N_PAUSE);
|
||||
}
|
||||
}
|
||||
|
||||
void resume()
|
||||
{
|
||||
if (!halt && paused)
|
||||
{
|
||||
paused = false;
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::Resume();
|
||||
client_options->events().add_event(std::move(ev));
|
||||
client_options->remote_reset_cache_item();
|
||||
new_client();
|
||||
}
|
||||
}
|
||||
|
||||
void reconnect(int seconds)
|
||||
{
|
||||
if (!halt)
|
||||
{
|
||||
if (seconds < 0)
|
||||
seconds = 0;
|
||||
OPENVPN_LOG("Client terminated, reconnecting in " << seconds << "...");
|
||||
server_poll_timer.cancel();
|
||||
client_options->remote_reset_cache_item();
|
||||
restart_wait_timer.expires_after(Time::Duration::seconds(seconds));
|
||||
restart_wait_timer.async_wait([self=Ptr(this), gen=generation](const openvpn_io::error_code& error)
|
||||
{
|
||||
OPENVPN_ASYNC_HANDLER;
|
||||
self->restart_wait_callback(gen, error);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void thread_safe_pause(const std::string& reason)
|
||||
{
|
||||
if (!halt)
|
||||
openvpn_io::post(io_context, [self=Ptr(this), reason]()
|
||||
{
|
||||
OPENVPN_ASYNC_HANDLER;
|
||||
self->pause(reason);
|
||||
});
|
||||
}
|
||||
|
||||
void thread_safe_resume()
|
||||
{
|
||||
if (!halt)
|
||||
openvpn_io::post(io_context, [self=Ptr(this)]()
|
||||
{
|
||||
OPENVPN_ASYNC_HANDLER;
|
||||
self->resume();
|
||||
});
|
||||
}
|
||||
|
||||
void thread_safe_reconnect(int seconds)
|
||||
{
|
||||
if (!halt)
|
||||
openvpn_io::post(io_context, [self=Ptr(this), seconds]()
|
||||
{
|
||||
OPENVPN_ASYNC_HANDLER;
|
||||
self->reconnect(seconds);
|
||||
});
|
||||
}
|
||||
|
||||
void dont_restart()
|
||||
{
|
||||
dont_restart_ = true;
|
||||
}
|
||||
|
||||
void post_cc_msg(const std::string& msg)
|
||||
{
|
||||
if (!halt && client)
|
||||
client->post_cc_msg(msg);
|
||||
}
|
||||
|
||||
void thread_safe_post_cc_msg(std::string msg)
|
||||
{
|
||||
if (!halt)
|
||||
openvpn_io::post(io_context, [self=Ptr(this), msg=std::move(msg)]()
|
||||
{
|
||||
OPENVPN_ASYNC_HANDLER;
|
||||
self->post_cc_msg(msg);
|
||||
});
|
||||
}
|
||||
|
||||
~ClientConnect()
|
||||
{
|
||||
stop();
|
||||
}
|
||||
|
||||
private:
|
||||
void interim_finalize()
|
||||
{
|
||||
if (!client_finalized)
|
||||
{
|
||||
client_options->finalize(false);
|
||||
client_finalized = true;
|
||||
}
|
||||
}
|
||||
|
||||
virtual void pre_resolve_done()
|
||||
{
|
||||
if (!halt)
|
||||
new_client();
|
||||
}
|
||||
|
||||
void cancel_timers()
|
||||
{
|
||||
restart_wait_timer.cancel();
|
||||
server_poll_timer.cancel();
|
||||
conn_timer.cancel();
|
||||
conn_timer_pending = false;
|
||||
}
|
||||
|
||||
void restart_wait_callback(unsigned int gen, const openvpn_io::error_code& e)
|
||||
{
|
||||
if (!e && gen == generation && !halt)
|
||||
{
|
||||
if (paused)
|
||||
resume();
|
||||
else
|
||||
{
|
||||
if (client)
|
||||
client->send_explicit_exit_notify();
|
||||
new_client();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void server_poll_callback(unsigned int gen, const openvpn_io::error_code& e)
|
||||
{
|
||||
if (!e && gen == generation && !halt && !client->first_packet_received())
|
||||
{
|
||||
OPENVPN_LOG("Server poll timeout, trying next remote entry...");
|
||||
new_client();
|
||||
}
|
||||
}
|
||||
|
||||
void conn_timer_callback(unsigned int gen, const openvpn_io::error_code& e)
|
||||
{
|
||||
if (!e && !halt)
|
||||
{
|
||||
client_options->stats().error(Error::CONNECTION_TIMEOUT);
|
||||
if (!paused && client_options->pause_on_connection_timeout())
|
||||
{
|
||||
// go into pause state instead of disconnect
|
||||
pause("");
|
||||
}
|
||||
else
|
||||
{
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::ConnectionTimeout();
|
||||
client_options->events().add_event(std::move(ev));
|
||||
stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void conn_timer_start()
|
||||
{
|
||||
if (!conn_timer_pending && conn_timeout > 0)
|
||||
{
|
||||
conn_timer.expires_after(Time::Duration::seconds(conn_timeout));
|
||||
conn_timer.async_wait([self=Ptr(this), gen=generation](const openvpn_io::error_code& error)
|
||||
{
|
||||
OPENVPN_ASYNC_HANDLER;
|
||||
self->conn_timer_callback(gen, error);
|
||||
});
|
||||
conn_timer_pending = true;
|
||||
}
|
||||
}
|
||||
|
||||
bool test_network() const
|
||||
{
|
||||
ClientLifeCycle* lc = client_options->lifecycle();
|
||||
if (lc)
|
||||
{
|
||||
if (!lc->network_available())
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
virtual void client_proto_connected()
|
||||
{
|
||||
conn_timer.cancel();
|
||||
conn_timer_pending = false;
|
||||
|
||||
// Monitor connection lifecycle notifications, such as sleep,
|
||||
// wakeup, network-unavailable, and network-available.
|
||||
// Not all platforms define a lifecycle object. Some platforms
|
||||
// such as Android and iOS manage lifecycle notifications
|
||||
// in the UI, and they call pause(), resume(), reconnect(), etc.
|
||||
// as needed using the main ovpncli API.
|
||||
if (!lifecycle_started)
|
||||
{
|
||||
ClientLifeCycle* lc = client_options->lifecycle(); // lifecycle is defined by platform, and may be NULL
|
||||
if (lc)
|
||||
{
|
||||
lc->start(this);
|
||||
lifecycle_started = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void queue_restart(const unsigned int delay_ms = 2000)
|
||||
{
|
||||
OPENVPN_LOG("Client terminated, restarting in " << delay_ms << " ms...");
|
||||
server_poll_timer.cancel();
|
||||
interim_finalize();
|
||||
client_options->remote_reset_cache_item();
|
||||
restart_wait_timer.expires_after(Time::Duration::milliseconds(delay_ms));
|
||||
restart_wait_timer.async_wait([self=Ptr(this), gen=generation](const openvpn_io::error_code& error)
|
||||
{
|
||||
OPENVPN_ASYNC_HANDLER;
|
||||
self->restart_wait_callback(gen, error);
|
||||
});
|
||||
}
|
||||
|
||||
virtual void client_proto_terminate()
|
||||
{
|
||||
if (!halt)
|
||||
{
|
||||
if (dont_restart_)
|
||||
{
|
||||
stop();
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (client->fatal())
|
||||
{
|
||||
case Error::UNDEF: // means that there wasn't a fatal error
|
||||
queue_restart();
|
||||
break;
|
||||
|
||||
// Errors below will cause the client to NOT retry the connection,
|
||||
// or otherwise give the error special handling.
|
||||
|
||||
case Error::AUTH_FAILED:
|
||||
{
|
||||
const std::string& reason = client->fatal_reason();
|
||||
if (ChallengeResponse::is_dynamic(reason)) // dynamic challenge/response?
|
||||
{
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::DynamicChallenge(reason);
|
||||
client_options->events().add_event(std::move(ev));
|
||||
stop();
|
||||
}
|
||||
else
|
||||
{
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::AuthFailed(reason);
|
||||
client_options->events().add_event(std::move(ev));
|
||||
client_options->stats().error(Error::AUTH_FAILED);
|
||||
if (client_options->retry_on_auth_failed())
|
||||
queue_restart(5000);
|
||||
else
|
||||
stop();
|
||||
}
|
||||
}
|
||||
break;
|
||||
case Error::TUN_SETUP_FAILED:
|
||||
{
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::TunSetupFailed(client->fatal_reason());
|
||||
client_options->events().add_event(std::move(ev));
|
||||
client_options->stats().error(Error::TUN_SETUP_FAILED);
|
||||
stop();
|
||||
}
|
||||
break;
|
||||
case Error::TUN_REGISTER_RINGS_ERROR:
|
||||
{
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::TunSetupFailed(client->fatal_reason());
|
||||
client_options->events().add_event(std::move(ev));
|
||||
client_options->stats().error(Error::TUN_REGISTER_RINGS_ERROR);
|
||||
stop();
|
||||
}
|
||||
break;
|
||||
case Error::TUN_IFACE_CREATE:
|
||||
{
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::TunIfaceCreate(client->fatal_reason());
|
||||
client_options->events().add_event(std::move(ev));
|
||||
client_options->stats().error(Error::TUN_IFACE_CREATE);
|
||||
stop();
|
||||
}
|
||||
break;
|
||||
case Error::TUN_IFACE_DISABLED:
|
||||
{
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::TunIfaceDisabled(client->fatal_reason());
|
||||
client_options->events().add_event(std::move(ev));
|
||||
client_options->stats().error(Error::TUN_IFACE_DISABLED);
|
||||
queue_restart(5000);
|
||||
}
|
||||
break;
|
||||
case Error::PROXY_ERROR:
|
||||
{
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::ProxyError(client->fatal_reason());
|
||||
client_options->events().add_event(std::move(ev));
|
||||
client_options->stats().error(Error::PROXY_ERROR);
|
||||
stop();
|
||||
}
|
||||
break;
|
||||
case Error::PROXY_NEED_CREDS:
|
||||
{
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::ProxyNeedCreds(client->fatal_reason());
|
||||
client_options->events().add_event(std::move(ev));
|
||||
client_options->stats().error(Error::PROXY_NEED_CREDS);
|
||||
stop();
|
||||
}
|
||||
break;
|
||||
case Error::CERT_VERIFY_FAIL:
|
||||
{
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::CertVerifyFail(client->fatal_reason());
|
||||
client_options->events().add_event(std::move(ev));
|
||||
client_options->stats().error(Error::CERT_VERIFY_FAIL);
|
||||
stop();
|
||||
}
|
||||
break;
|
||||
case Error::TLS_VERSION_MIN:
|
||||
{
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::TLSVersionMinFail();
|
||||
client_options->events().add_event(std::move(ev));
|
||||
client_options->stats().error(Error::TLS_VERSION_MIN);
|
||||
stop();
|
||||
}
|
||||
break;
|
||||
case Error::CLIENT_HALT:
|
||||
{
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::ClientHalt(client->fatal_reason());
|
||||
client_options->events().add_event(std::move(ev));
|
||||
client_options->stats().error(Error::CLIENT_HALT);
|
||||
stop();
|
||||
}
|
||||
break;
|
||||
case Error::CLIENT_RESTART:
|
||||
{
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::ClientRestart(client->fatal_reason());
|
||||
client_options->events().add_event(std::move(ev));
|
||||
client_options->stats().error(Error::CLIENT_RESTART);
|
||||
queue_restart();
|
||||
}
|
||||
break;
|
||||
case Error::INACTIVE_TIMEOUT:
|
||||
{
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::InactiveTimeout();
|
||||
client_options->events().add_event(std::move(ev));
|
||||
client_options->stats().error(Error::INACTIVE_TIMEOUT);
|
||||
|
||||
// explicit exit notify is sent earlier by
|
||||
// ClientProto::Session::inactive_callback()
|
||||
stop();
|
||||
}
|
||||
break;
|
||||
case Error::TRANSPORT_ERROR:
|
||||
{
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::TransportError(client->fatal_reason());
|
||||
client_options->events().add_event(std::move(ev));
|
||||
client_options->stats().error(Error::TRANSPORT_ERROR);
|
||||
queue_restart(5000); // use a larger timeout to allow preemption from higher levels
|
||||
}
|
||||
break;
|
||||
case Error::TUN_ERROR:
|
||||
{
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::TunError(client->fatal_reason());
|
||||
client_options->events().add_event(std::move(ev));
|
||||
client_options->stats().error(Error::TUN_ERROR);
|
||||
queue_restart(5000);
|
||||
}
|
||||
break;
|
||||
case Error::TUN_HALT:
|
||||
{
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::TunHalt(client->fatal_reason());
|
||||
client_options->events().add_event(std::move(ev));
|
||||
client_options->stats().error(Error::TUN_HALT);
|
||||
stop();
|
||||
}
|
||||
break;
|
||||
case Error::RELAY:
|
||||
{
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::Relay();
|
||||
client_options->events().add_event(std::move(ev));
|
||||
client_options->stats().error(Error::RELAY);
|
||||
transport_factory_relay = client->transport_factory_relay();
|
||||
queue_restart(0);
|
||||
}
|
||||
break;
|
||||
case Error::RELAY_ERROR:
|
||||
{
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::RelayError(client->fatal_reason());
|
||||
client_options->events().add_event(std::move(ev));
|
||||
client_options->stats().error(Error::RELAY_ERROR);
|
||||
stop();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
throw client_connect_unhandled_exception();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void new_client()
|
||||
{
|
||||
++generation;
|
||||
if (client_options->asio_work_always_on())
|
||||
asio_work.reset(new AsioWork(io_context));
|
||||
else
|
||||
asio_work.reset();
|
||||
if (client)
|
||||
{
|
||||
client->stop(false);
|
||||
interim_finalize();
|
||||
}
|
||||
if (generation > 1 && !transport_factory_relay)
|
||||
{
|
||||
ClientEvent::Base::Ptr ev = new ClientEvent::Reconnecting();
|
||||
client_options->events().add_event(std::move(ev));
|
||||
client_options->stats().error(Error::N_RECONNECT);
|
||||
if (!(client && client->reached_connected_state()))
|
||||
client_options->next();
|
||||
}
|
||||
|
||||
// client_config in cliopt.hpp
|
||||
Client::Config::Ptr cli_config = client_options->client_config(!transport_factory_relay);
|
||||
client.reset(new Client(io_context, *cli_config, this)); // build ClientProto::Session from cliproto.hpp
|
||||
client_finalized = false;
|
||||
|
||||
// relay?
|
||||
if (transport_factory_relay)
|
||||
{
|
||||
client->transport_factory_override(std::move(transport_factory_relay));
|
||||
transport_factory_relay.reset();
|
||||
}
|
||||
|
||||
restart_wait_timer.cancel();
|
||||
if (client_options->server_poll_timeout_enabled())
|
||||
{
|
||||
server_poll_timer.expires_after(client_options->server_poll_timeout());
|
||||
server_poll_timer.async_wait([self=Ptr(this), gen=generation](const openvpn_io::error_code& error)
|
||||
{
|
||||
OPENVPN_ASYNC_HANDLER;
|
||||
self->server_poll_callback(gen, error);
|
||||
});
|
||||
}
|
||||
conn_timer_start();
|
||||
client->start();
|
||||
}
|
||||
|
||||
// ClientLifeCycle::NotifyCallback callbacks
|
||||
|
||||
virtual void cln_stop()
|
||||
{
|
||||
thread_safe_stop();
|
||||
}
|
||||
|
||||
virtual void cln_pause(const std::string& reason)
|
||||
{
|
||||
thread_safe_pause(reason);
|
||||
}
|
||||
|
||||
virtual void cln_resume()
|
||||
{
|
||||
thread_safe_resume();
|
||||
}
|
||||
|
||||
virtual void cln_reconnect(int seconds)
|
||||
{
|
||||
thread_safe_reconnect(seconds);
|
||||
}
|
||||
|
||||
unsigned int generation;
|
||||
bool halt;
|
||||
bool paused;
|
||||
bool client_finalized;
|
||||
bool dont_restart_;
|
||||
bool lifecycle_started;
|
||||
int conn_timeout;
|
||||
openvpn_io::io_context& io_context;
|
||||
ClientOptions::Ptr client_options;
|
||||
Client::Ptr client;
|
||||
TransportClientFactory::Ptr transport_factory_relay;
|
||||
AsioTimer server_poll_timer;
|
||||
AsioTimer restart_wait_timer;
|
||||
AsioTimer conn_timer;
|
||||
bool conn_timer_pending;
|
||||
std::unique_ptr<AsioWork> asio_work;
|
||||
RemoteList::PreResolve::Ptr pre_resolve;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,41 @@
|
||||
// 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_CLIENT_CLICONSTANTS_H
|
||||
#define OPENVPN_CLIENT_CLICONSTANTS_H
|
||||
|
||||
// Various sanity checks for different limits on OpenVPN clients
|
||||
|
||||
namespace openvpn {
|
||||
namespace ProfileParseLimits {
|
||||
enum {
|
||||
MAX_PROFILE_SIZE=262144, // maximum size of an OpenVPN configuration file
|
||||
MAX_PUSH_SIZE=262144, // maximum size of aggregate data that can be pushed to a client
|
||||
MAX_LINE_SIZE=512, // maximum size of an OpenVPN configuration file line
|
||||
MAX_DIRECTIVE_SIZE=64, // maximum number of chars in an OpenVPN directive
|
||||
OPT_OVERHEAD=64, // bytes overhead of one option/directive, for accounting purposes
|
||||
TERM_OVERHEAD=16, // bytes overhead of one argument in an option, for accounting purposes
|
||||
MAX_SERVER_LIST_SIZE=4096, // maximum server list size, i.e. "setenv SERVER ..."
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,227 @@
|
||||
// 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/>.
|
||||
|
||||
// This class encapsulates the state of authentication credentials
|
||||
// maintained by an OpenVPN client. It understands dynamic
|
||||
// challenge/response cookies, and Session Token IDs (where the
|
||||
// password in the object is wiped and replaced by a token used
|
||||
// for further authentications).
|
||||
|
||||
#ifndef OPENVPN_CLIENT_CLICREDS_H
|
||||
#define OPENVPN_CLIENT_CLICREDS_H
|
||||
|
||||
#include <string>
|
||||
|
||||
#include <openvpn/common/exception.hpp>
|
||||
#include <openvpn/common/rc.hpp>
|
||||
#include <openvpn/transport/protocol.hpp>
|
||||
#include <openvpn/auth/cr.hpp>
|
||||
|
||||
namespace openvpn {
|
||||
|
||||
class ClientCreds : public RC<thread_unsafe_refcount> {
|
||||
public:
|
||||
typedef RCPtr<ClientCreds> Ptr;
|
||||
|
||||
ClientCreds() : allow_cache_password(false),
|
||||
password_save_defined(false),
|
||||
replace_password_with_session_id(false),
|
||||
did_replace_password_with_session_id(false) {}
|
||||
|
||||
void set_username(const std::string& username_arg)
|
||||
{
|
||||
username = username_arg;
|
||||
}
|
||||
|
||||
void set_password(const std::string& password_arg)
|
||||
{
|
||||
password = password_arg;
|
||||
did_replace_password_with_session_id = false;
|
||||
}
|
||||
|
||||
void set_response(const std::string& response_arg)
|
||||
{
|
||||
response = response_arg;
|
||||
}
|
||||
|
||||
void set_dynamic_challenge_cookie(const std::string& cookie, const std::string& username)
|
||||
{
|
||||
if (!cookie.empty())
|
||||
dynamic_challenge.reset(new ChallengeResponse(cookie, username));
|
||||
}
|
||||
|
||||
void set_replace_password_with_session_id(const bool value)
|
||||
{
|
||||
replace_password_with_session_id = value;
|
||||
}
|
||||
|
||||
void enable_password_cache(const bool value)
|
||||
{
|
||||
allow_cache_password = value;
|
||||
}
|
||||
|
||||
bool get_replace_password_with_session_id() const
|
||||
{
|
||||
return replace_password_with_session_id;
|
||||
}
|
||||
|
||||
void set_session_id(const std::string& user, const std::string& sess_id)
|
||||
{
|
||||
// force Session ID use if dynamic challenge is enabled
|
||||
if (dynamic_challenge && !replace_password_with_session_id)
|
||||
replace_password_with_session_id = true;
|
||||
|
||||
if (replace_password_with_session_id)
|
||||
{
|
||||
if (allow_cache_password && !password_save_defined)
|
||||
{
|
||||
password_save = password;
|
||||
password_save_defined = true;
|
||||
}
|
||||
password = sess_id;
|
||||
response = "";
|
||||
if (dynamic_challenge)
|
||||
{
|
||||
username = dynamic_challenge->get_username();
|
||||
dynamic_challenge.reset();
|
||||
}
|
||||
else if (!user.empty())
|
||||
username = user;
|
||||
did_replace_password_with_session_id = true;
|
||||
}
|
||||
}
|
||||
|
||||
std::string get_username() const
|
||||
{
|
||||
if (dynamic_challenge)
|
||||
return dynamic_challenge->get_username();
|
||||
else
|
||||
return username;
|
||||
}
|
||||
|
||||
std::string get_password() const
|
||||
{
|
||||
if (dynamic_challenge)
|
||||
return dynamic_challenge->construct_dynamic_password(response);
|
||||
else if (response.empty())
|
||||
return password;
|
||||
else
|
||||
return ChallengeResponse::construct_static_password(password, response);
|
||||
}
|
||||
|
||||
bool username_defined() const
|
||||
{
|
||||
return !username.empty();
|
||||
}
|
||||
|
||||
bool password_defined() const
|
||||
{
|
||||
return !password.empty();
|
||||
}
|
||||
|
||||
bool session_id_defined() const
|
||||
{
|
||||
return did_replace_password_with_session_id;
|
||||
}
|
||||
|
||||
// If we have a saved password that is not a session ID,
|
||||
// restore it and wipe any existing session ID.
|
||||
bool can_retry_auth_with_cached_password()
|
||||
{
|
||||
if (password_save_defined)
|
||||
{
|
||||
password = password_save;
|
||||
password_save.clear();
|
||||
password_save_defined = false;
|
||||
did_replace_password_with_session_id = false;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
void purge_session_id()
|
||||
{
|
||||
if (!can_retry_auth_with_cached_password())
|
||||
{
|
||||
password.clear();
|
||||
did_replace_password_with_session_id = false;
|
||||
}
|
||||
}
|
||||
|
||||
std::string auth_info() const
|
||||
{
|
||||
std::string ret;
|
||||
if (dynamic_challenge)
|
||||
{
|
||||
ret = "DynamicChallenge";
|
||||
}
|
||||
else if (response.empty())
|
||||
{
|
||||
if (!username.empty())
|
||||
ret += "Username";
|
||||
else
|
||||
ret += "UsernameEmpty";
|
||||
ret += '/';
|
||||
if (!password.empty())
|
||||
{
|
||||
if (did_replace_password_with_session_id)
|
||||
ret += "SessionID";
|
||||
else
|
||||
ret += "Password";
|
||||
}
|
||||
else
|
||||
ret += "PasswordEmpty";
|
||||
}
|
||||
else
|
||||
{
|
||||
ret = "StaticChallenge";
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
private:
|
||||
// Standard credentials
|
||||
std::string username;
|
||||
std::string password;
|
||||
|
||||
// Password caching
|
||||
bool allow_cache_password;
|
||||
bool password_save_defined;
|
||||
std::string password_save;
|
||||
|
||||
// Response to challenge
|
||||
std::string response;
|
||||
|
||||
// Info describing a dynamic challenge
|
||||
ChallengeResponse::Ptr dynamic_challenge;
|
||||
|
||||
// If true, on successful connect, we will replace the password
|
||||
// with the session ID we receive from the server.
|
||||
bool replace_password_with_session_id;
|
||||
|
||||
// true if password has been replaced with Session ID
|
||||
bool did_replace_password_with_session_id;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,177 @@
|
||||
// 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/>.
|
||||
|
||||
// Emulate Excluded Routes implementation (needed by Android)
|
||||
|
||||
#ifndef OPENVPN_CLIENT_CLIEMUEXR_H
|
||||
#define OPENVPN_CLIENT_CLIEMUEXR_H
|
||||
|
||||
#include <openvpn/common/exception.hpp>
|
||||
#include <openvpn/tun/client/emuexr.hpp>
|
||||
#include <openvpn/addr/addrspacesplit.hpp>
|
||||
|
||||
namespace openvpn {
|
||||
class EmulateExcludeRouteImpl : public EmulateExcludeRoute
|
||||
{
|
||||
public:
|
||||
OPENVPN_EXCEPTION(emulate_exclude_route_error);
|
||||
|
||||
typedef RCPtr<EmulateExcludeRouteImpl> Ptr;
|
||||
|
||||
explicit EmulateExcludeRouteImpl(const bool exclude_server_address)
|
||||
: exclude_server_address_(exclude_server_address)
|
||||
{
|
||||
}
|
||||
|
||||
private:
|
||||
void add_route(const bool add, const IP::Addr& addr, const int prefix_len) override
|
||||
{
|
||||
(add ? include : exclude).emplace_back(addr, prefix_len);
|
||||
}
|
||||
|
||||
void add_default_routes(bool ipv4, bool ipv6) override
|
||||
{
|
||||
if (ipv4)
|
||||
add_route(true, IP::Addr::from_zero(IP::Addr::V4), 0);
|
||||
if (ipv6)
|
||||
add_route(true, IP::Addr::from_zero(IP::Addr::V6), 0);
|
||||
}
|
||||
|
||||
bool enabled(const IPVerFlags& ipv) const override
|
||||
{
|
||||
return exclude.size() && (ipv.rgv4() || ipv.rgv6());
|
||||
}
|
||||
|
||||
void emulate(TunBuilderBase* tb, IPVerFlags& ipv, const IP::Addr& server_addr) const override
|
||||
{
|
||||
const unsigned int ip_ver_flags = ipv.ip_ver_flags();
|
||||
IP::RouteList rl, tempExcludeList;
|
||||
rl.reserve(include.size() + exclude.size());
|
||||
rl.insert(rl.end(), include.begin(), include.end());
|
||||
rl.insert(rl.end(), exclude.begin(), exclude.end());
|
||||
|
||||
// Check if we have to exclude the server, if yes we temporarily add it to the list
|
||||
// of excluded networks as small individual /32 or /128 network
|
||||
const IP::RouteList* excludedRoutes = &exclude;
|
||||
|
||||
if (exclude_server_address_ && (server_addr.version_mask() & ip_ver_flags) &&
|
||||
!exclude.contains(IP::Route(server_addr, server_addr.size())))
|
||||
{
|
||||
rl.emplace_back(server_addr, server_addr.size());
|
||||
// Create a temporary list that includes all the routes + the server
|
||||
tempExcludeList = exclude;
|
||||
tempExcludeList.emplace_back(server_addr, server_addr.size());
|
||||
excludedRoutes = &tempExcludeList;
|
||||
}
|
||||
|
||||
|
||||
if (excludedRoutes->empty())
|
||||
{
|
||||
// Samsung's Android VPN API does different things if you have
|
||||
// 0.0.0.0/0 in the list of installed routes
|
||||
// (even if 0.0.0.0/1 and 128.0.0.0/1 and are present it behaves different)
|
||||
|
||||
// We normally always split the address space, breaking a 0.0.0.0/0 into
|
||||
// smaller routes. If no routes are excluded, we install the original
|
||||
// routes without modifying them
|
||||
|
||||
for (const auto& rt: include)
|
||||
{
|
||||
if (rt.version() & ip_ver_flags)
|
||||
{
|
||||
if (!tb->tun_builder_add_route(rt.addr.to_string(), rt.prefix_len, -1, rt.addr.version() == IP::Addr::V6))
|
||||
throw emulate_exclude_route_error("tun_builder_add_route failed");
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Complete address space (0.0.0.0/0 or ::/0) split into smaller networks
|
||||
// Figure out which parts of this non overlapping address we want to install
|
||||
for (const auto& r: IP::AddressSpaceSplitter(rl, ip_ver_flags))
|
||||
{
|
||||
if (check_route_should_be_installed(r, *excludedRoutes))
|
||||
if (!tb->tun_builder_add_route(r.addr.to_string(), r.prefix_len, -1, r.addr.version() == IP::Addr::V6))
|
||||
throw emulate_exclude_route_error("tun_builder_add_route failed");
|
||||
}
|
||||
|
||||
ipv.set_emulate_exclude_routes();
|
||||
}
|
||||
|
||||
bool check_route_should_be_installed(const IP::Route& r, const IP::RouteList & excludedRoutes) const
|
||||
{
|
||||
// The whole address space was partioned into NON-overlapping routes that
|
||||
// we get one by one with the parameter r.
|
||||
// Therefore we already know that the whole route r either is included or
|
||||
// excluded IPs.
|
||||
// Figure out if this particular route should be installed or not
|
||||
|
||||
IP::Route const* bestroute = nullptr;
|
||||
// Get the best (longest-prefix/smallest) route from included routes that completely
|
||||
// matches this route
|
||||
for (const auto& incRoute: include)
|
||||
{
|
||||
if (incRoute.contains(r))
|
||||
{
|
||||
if (!bestroute || bestroute->prefix_len < incRoute.prefix_len)
|
||||
bestroute = &incRoute;
|
||||
}
|
||||
}
|
||||
|
||||
// No positive route matches the route at all, do not install it
|
||||
if (!bestroute)
|
||||
return false;
|
||||
|
||||
// Check if there is a more specific exclude route
|
||||
for (const auto& exclRoute: excludedRoutes)
|
||||
{
|
||||
if (exclRoute.contains(r) && exclRoute.prefix_len > bestroute->prefix_len)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
const bool exclude_server_address_;
|
||||
IP::RouteList include;
|
||||
IP::RouteList exclude;
|
||||
};
|
||||
|
||||
class EmulateExcludeRouteFactoryImpl : public EmulateExcludeRouteFactory
|
||||
{
|
||||
public:
|
||||
typedef RCPtr<EmulateExcludeRouteFactoryImpl> Ptr;
|
||||
|
||||
EmulateExcludeRouteFactoryImpl(const bool exclude_server_address)
|
||||
: exclude_server_address_(exclude_server_address)
|
||||
{
|
||||
}
|
||||
|
||||
private:
|
||||
virtual EmulateExcludeRoute::Ptr new_obj() const
|
||||
{
|
||||
return EmulateExcludeRoute::Ptr(new EmulateExcludeRouteImpl(exclude_server_address_));
|
||||
}
|
||||
|
||||
const bool exclude_server_address_;
|
||||
};
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,486 @@
|
||||
// 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/>.
|
||||
|
||||
// This file describes the basic set of OpenVPN client events, including the
|
||||
// normal events leading up to a connection as well as error events.
|
||||
|
||||
#ifndef OPENVPN_CLIENT_CLIEVENT_H
|
||||
#define OPENVPN_CLIENT_CLIEVENT_H
|
||||
|
||||
#include <sstream>
|
||||
#include <deque>
|
||||
#include <utility>
|
||||
|
||||
#include <openvpn/common/size.hpp>
|
||||
#include <openvpn/common/exception.hpp>
|
||||
#include <openvpn/common/rc.hpp>
|
||||
#include <openvpn/transport/protocol.hpp>
|
||||
|
||||
namespace openvpn {
|
||||
namespace ClientEvent {
|
||||
enum Type {
|
||||
// normal events including disconnected, connected, and other transitional events
|
||||
DISCONNECTED=0,
|
||||
CONNECTED,
|
||||
RECONNECTING,
|
||||
AUTH_PENDING,
|
||||
RESOLVE,
|
||||
WAIT,
|
||||
WAIT_PROXY,
|
||||
CONNECTING,
|
||||
GET_CONFIG,
|
||||
ASSIGN_IP,
|
||||
ADD_ROUTES,
|
||||
ECHO_OPT,
|
||||
INFO,
|
||||
WARN,
|
||||
PAUSE,
|
||||
RESUME,
|
||||
RELAY,
|
||||
COMPRESSION_ENABLED,
|
||||
UNSUPPORTED_FEATURE,
|
||||
|
||||
// start of nonfatal errors, must be marked by NONFATAL_ERROR_START below
|
||||
TRANSPORT_ERROR,
|
||||
TUN_ERROR,
|
||||
CLIENT_RESTART,
|
||||
|
||||
// start of errors, must be marked by FATAL_ERROR_START below
|
||||
AUTH_FAILED,
|
||||
CERT_VERIFY_FAIL,
|
||||
TLS_VERSION_MIN,
|
||||
CLIENT_HALT,
|
||||
CLIENT_SETUP,
|
||||
TUN_HALT,
|
||||
CONNECTION_TIMEOUT,
|
||||
INACTIVE_TIMEOUT,
|
||||
DYNAMIC_CHALLENGE,
|
||||
PROXY_NEED_CREDS,
|
||||
PROXY_ERROR,
|
||||
TUN_SETUP_FAILED,
|
||||
TUN_IFACE_CREATE,
|
||||
TUN_IFACE_DISABLED,
|
||||
EPKI_ERROR, // EPKI refers to External PKI errors, i.e. errors in accessing external
|
||||
EPKI_INVALID_ALIAS, // certificates or keys.
|
||||
RELAY_ERROR,
|
||||
|
||||
N_TYPES
|
||||
};
|
||||
|
||||
enum {
|
||||
NONFATAL_ERROR_START = TRANSPORT_ERROR, // start of nonfatal errors that automatically reconnect
|
||||
FATAL_ERROR_START = AUTH_FAILED, // start of fatal errors
|
||||
};
|
||||
|
||||
inline const char *event_name(const Type type)
|
||||
{
|
||||
static const char *names[] = {
|
||||
"DISCONNECTED",
|
||||
"CONNECTED",
|
||||
"RECONNECTING",
|
||||
"AUTH_PENDING",
|
||||
"RESOLVE",
|
||||
"WAIT",
|
||||
"WAIT_PROXY",
|
||||
"CONNECTING",
|
||||
"GET_CONFIG",
|
||||
"ASSIGN_IP",
|
||||
"ADD_ROUTES",
|
||||
"ECHO",
|
||||
"INFO",
|
||||
"WARN",
|
||||
"PAUSE",
|
||||
"RESUME",
|
||||
"RELAY",
|
||||
"COMPRESSION_ENABLED",
|
||||
"UNSUPPORTED_FEATURE",
|
||||
|
||||
// nonfatal errors
|
||||
"TRANSPORT_ERROR",
|
||||
"TUN_ERROR",
|
||||
"CLIENT_RESTART",
|
||||
|
||||
// fatal errors
|
||||
"AUTH_FAILED",
|
||||
"CERT_VERIFY_FAIL",
|
||||
"TLS_VERSION_MIN",
|
||||
"CLIENT_HALT",
|
||||
"CLIENT_SETUP",
|
||||
"TUN_HALT",
|
||||
"CONNECTION_TIMEOUT",
|
||||
"INACTIVE_TIMEOUT",
|
||||
"DYNAMIC_CHALLENGE",
|
||||
"PROXY_NEED_CREDS",
|
||||
"PROXY_ERROR",
|
||||
"TUN_SETUP_FAILED",
|
||||
"TUN_IFACE_CREATE",
|
||||
"TUN_IFACE_DISABLED",
|
||||
"EPKI_ERROR",
|
||||
"EPKI_INVALID_ALIAS",
|
||||
"RELAY_ERROR",
|
||||
};
|
||||
|
||||
static_assert(N_TYPES == array_size(names), "event names array inconsistency");
|
||||
if (type < N_TYPES)
|
||||
return names[type];
|
||||
else
|
||||
return "UNKNOWN_EVENT_TYPE";
|
||||
}
|
||||
|
||||
struct Connected;
|
||||
|
||||
// The base class for all events.
|
||||
class Base : public RC<thread_safe_refcount>
|
||||
{
|
||||
public:
|
||||
typedef RCPtr<Base> Ptr;
|
||||
Base(Type id) : id_(id) {}
|
||||
|
||||
Type id() const { return id_; }
|
||||
|
||||
const char *name() const
|
||||
{
|
||||
return event_name(id_);
|
||||
}
|
||||
|
||||
bool is_error() const
|
||||
{
|
||||
return int(id_) >= NONFATAL_ERROR_START;
|
||||
}
|
||||
|
||||
bool is_fatal() const
|
||||
{
|
||||
return int(id_) >= FATAL_ERROR_START;
|
||||
}
|
||||
|
||||
virtual std::string render() const
|
||||
{
|
||||
return "";
|
||||
}
|
||||
|
||||
const Connected* connected_cast() const
|
||||
{
|
||||
if (id_ == CONNECTED)
|
||||
return (const Connected*)this;
|
||||
else
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
Type id_;
|
||||
};
|
||||
|
||||
// Specific client events. Some events have no additional data attached to them,
|
||||
// while other events (such as Connected) have many additional data fields.
|
||||
|
||||
struct Resolve : public Base
|
||||
{
|
||||
Resolve() : Base(RESOLVE) {}
|
||||
};
|
||||
|
||||
struct Wait : public Base
|
||||
{
|
||||
Wait() : Base(WAIT) {}
|
||||
};
|
||||
|
||||
struct WaitProxy : public Base
|
||||
{
|
||||
WaitProxy() : Base(WAIT_PROXY) {}
|
||||
};
|
||||
|
||||
struct Connecting : public Base
|
||||
{
|
||||
Connecting() : Base(CONNECTING) {}
|
||||
};
|
||||
|
||||
struct Reconnecting : public Base
|
||||
{
|
||||
Reconnecting() : Base(RECONNECTING) {}
|
||||
};
|
||||
|
||||
struct AuthPending : public Base
|
||||
{
|
||||
AuthPending() : Base(AUTH_PENDING) {}
|
||||
};
|
||||
|
||||
struct GetConfig : public Base
|
||||
{
|
||||
GetConfig() : Base(GET_CONFIG) {}
|
||||
};
|
||||
|
||||
struct AssignIP : public Base
|
||||
{
|
||||
AssignIP() : Base(ASSIGN_IP) {}
|
||||
};
|
||||
|
||||
struct AddRoutes : public Base
|
||||
{
|
||||
AddRoutes() : Base(ADD_ROUTES) {}
|
||||
};
|
||||
|
||||
struct Resume : public Base
|
||||
{
|
||||
Resume() : Base(RESUME) {}
|
||||
};
|
||||
|
||||
struct Relay : public Base
|
||||
{
|
||||
Relay() : Base(RELAY) {}
|
||||
};
|
||||
|
||||
struct Disconnected : public Base
|
||||
{
|
||||
Disconnected() : Base(DISCONNECTED) {}
|
||||
};
|
||||
|
||||
struct ConnectionTimeout : public Base
|
||||
{
|
||||
ConnectionTimeout() : Base(CONNECTION_TIMEOUT) {}
|
||||
};
|
||||
|
||||
struct InactiveTimeout : public Base
|
||||
{
|
||||
InactiveTimeout() : Base(INACTIVE_TIMEOUT) {}
|
||||
};
|
||||
|
||||
struct TLSVersionMinFail : public Base
|
||||
{
|
||||
TLSVersionMinFail() : Base(TLS_VERSION_MIN) {}
|
||||
};
|
||||
|
||||
struct UnsupportedFeature : public Base
|
||||
{
|
||||
typedef RCPtr<UnsupportedFeature> Ptr;
|
||||
|
||||
UnsupportedFeature(const std::string& name_arg, const std::string& reason_arg, bool critical_arg)
|
||||
: Base(UNSUPPORTED_FEATURE),
|
||||
name(name_arg),
|
||||
reason(reason_arg),
|
||||
critical(critical_arg) {}
|
||||
|
||||
std::string name;
|
||||
std::string reason;
|
||||
bool critical;
|
||||
|
||||
virtual std::string render() const
|
||||
{
|
||||
std::ostringstream out;
|
||||
out << "name: " << name << ", reason: " << reason << ", critical: " << critical;
|
||||
return out.str();
|
||||
}
|
||||
};
|
||||
|
||||
struct Connected : public Base
|
||||
{
|
||||
typedef RCPtr<Connected> Ptr;
|
||||
|
||||
Connected() : Base(CONNECTED) {}
|
||||
|
||||
std::string user;
|
||||
std::string server_host;
|
||||
std::string server_port;
|
||||
std::string server_proto;
|
||||
std::string server_ip;
|
||||
std::string vpn_ip4;
|
||||
std::string vpn_ip6;
|
||||
std::string vpn_gw4;
|
||||
std::string vpn_gw6;
|
||||
std::string client_ip;
|
||||
std::string tun_name;
|
||||
|
||||
virtual std::string render() const
|
||||
{
|
||||
std::ostringstream out;
|
||||
// eg. "godot@foo.bar.gov:443 (1.2.3.4) via TCPv4 on tun0/5.5.1.1"
|
||||
if (!user.empty())
|
||||
out << user << '@';
|
||||
if (server_host.find_first_of(':') == std::string::npos)
|
||||
out << server_host;
|
||||
else
|
||||
out << '[' << server_host << ']';
|
||||
out << ':' << server_port
|
||||
<< " (" << server_ip << ") via " << client_ip << '/' << server_proto
|
||||
<< " on " << tun_name << '/' << vpn_ip4 << '/' << vpn_ip6
|
||||
<< " gw=[" << vpn_gw4 << '/' << vpn_gw6 << ']';
|
||||
return out.str();
|
||||
}
|
||||
};
|
||||
|
||||
struct ReasonBase : public Base {
|
||||
ReasonBase(const Type id, const std::string& reason_arg)
|
||||
: Base(id),
|
||||
reason(reason_arg)
|
||||
{
|
||||
}
|
||||
|
||||
ReasonBase(const Type id, std::string&& reason_arg)
|
||||
: Base(id),
|
||||
reason(std::move(reason_arg))
|
||||
{
|
||||
}
|
||||
|
||||
virtual std::string render() const
|
||||
{
|
||||
return reason;
|
||||
}
|
||||
|
||||
std::string reason;
|
||||
};
|
||||
|
||||
struct AuthFailed : public ReasonBase
|
||||
{
|
||||
AuthFailed(std::string reason) : ReasonBase(AUTH_FAILED, std::move(reason)) {}
|
||||
};
|
||||
|
||||
struct CertVerifyFail : public ReasonBase
|
||||
{
|
||||
CertVerifyFail(std::string reason) : ReasonBase(CERT_VERIFY_FAIL, std::move(reason)) {}
|
||||
};
|
||||
|
||||
struct ClientHalt : public ReasonBase
|
||||
{
|
||||
ClientHalt(std::string reason) : ReasonBase(CLIENT_HALT, std::move(reason)) {}
|
||||
};
|
||||
|
||||
struct ClientRestart : public ReasonBase
|
||||
{
|
||||
ClientRestart(std::string reason) : ReasonBase(CLIENT_RESTART, std::move(reason)) {}
|
||||
};
|
||||
|
||||
struct TunHalt : public ReasonBase
|
||||
{
|
||||
TunHalt(std::string reason) : ReasonBase(TUN_HALT, std::move(reason)) {}
|
||||
};
|
||||
|
||||
struct RelayError : public ReasonBase
|
||||
{
|
||||
RelayError(std::string reason) : ReasonBase(RELAY_ERROR, std::move(reason)) {}
|
||||
};
|
||||
|
||||
struct DynamicChallenge : public ReasonBase
|
||||
{
|
||||
DynamicChallenge(std::string reason) : ReasonBase(DYNAMIC_CHALLENGE, std::move(reason)) {}
|
||||
};
|
||||
|
||||
struct Pause : public ReasonBase
|
||||
{
|
||||
Pause(std::string reason) : ReasonBase(PAUSE, std::move(reason)) {}
|
||||
};
|
||||
|
||||
struct ProxyError : public ReasonBase
|
||||
{
|
||||
ProxyError(std::string reason) : ReasonBase(PROXY_ERROR, std::move(reason)) {}
|
||||
};
|
||||
|
||||
struct ProxyNeedCreds : public ReasonBase
|
||||
{
|
||||
ProxyNeedCreds(std::string reason) : ReasonBase(PROXY_NEED_CREDS, std::move(reason)) {}
|
||||
};
|
||||
|
||||
struct TransportError : public ReasonBase
|
||||
{
|
||||
TransportError(std::string reason) : ReasonBase(TRANSPORT_ERROR, std::move(reason)) {}
|
||||
};
|
||||
|
||||
struct TunSetupFailed : public ReasonBase
|
||||
{
|
||||
TunSetupFailed(std::string reason) : ReasonBase(TUN_SETUP_FAILED, std::move(reason)) {}
|
||||
};
|
||||
|
||||
struct TunIfaceCreate : public ReasonBase
|
||||
{
|
||||
TunIfaceCreate(std::string reason) : ReasonBase(TUN_IFACE_CREATE, std::move(reason)) {}
|
||||
};
|
||||
|
||||
struct TunIfaceDisabled : public ReasonBase
|
||||
{
|
||||
TunIfaceDisabled(std::string reason) : ReasonBase(TUN_IFACE_DISABLED, std::move(reason)) {}
|
||||
};
|
||||
|
||||
struct TunError : public ReasonBase
|
||||
{
|
||||
TunError(std::string reason) : ReasonBase(TUN_ERROR, std::move(reason)) {}
|
||||
};
|
||||
|
||||
struct EpkiError : public ReasonBase
|
||||
{
|
||||
EpkiError(std::string reason) : ReasonBase(EPKI_ERROR, std::move(reason)) {}
|
||||
};
|
||||
|
||||
struct EpkiInvalidAlias : public ReasonBase
|
||||
{
|
||||
EpkiInvalidAlias(std::string reason) : ReasonBase(EPKI_INVALID_ALIAS, std::move(reason)) {}
|
||||
};
|
||||
|
||||
struct Echo : public ReasonBase
|
||||
{
|
||||
Echo(std::string value) : ReasonBase(ECHO_OPT, std::move(value)) {}
|
||||
};
|
||||
|
||||
struct Info : public ReasonBase
|
||||
{
|
||||
Info(std::string value) : ReasonBase(INFO, std::move(value)) {}
|
||||
};
|
||||
|
||||
struct Warn : public ReasonBase
|
||||
{
|
||||
Warn(std::string value) : ReasonBase(WARN, std::move(value)) {}
|
||||
};
|
||||
|
||||
class ClientSetup : public ReasonBase
|
||||
{
|
||||
public:
|
||||
ClientSetup(const std::string& status, const std::string& message)
|
||||
: ReasonBase(CLIENT_SETUP, make(status, message))
|
||||
{
|
||||
}
|
||||
|
||||
private:
|
||||
static std::string make(const std::string& status, const std::string& message)
|
||||
{
|
||||
std::string ret;
|
||||
ret += status;
|
||||
if (!status.empty() && !message.empty())
|
||||
ret += ": ";
|
||||
ret += message;
|
||||
return ret;
|
||||
}
|
||||
};
|
||||
|
||||
struct CompressionEnabled : public ReasonBase
|
||||
{
|
||||
CompressionEnabled(std::string msg)
|
||||
: ReasonBase(COMPRESSION_ENABLED, std::move(msg))
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
class Queue : public RC<thread_unsafe_refcount>
|
||||
{
|
||||
public:
|
||||
typedef RCPtr<Queue> Ptr;
|
||||
|
||||
virtual void add_event(Base::Ptr event) = 0;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#endif // OPENVPN_CLIENT_CLIEVENT_H
|
||||
@@ -0,0 +1,119 @@
|
||||
// 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_CLIENT_CLIHALT_H
|
||||
#define OPENVPN_CLIENT_CLIHALT_H
|
||||
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
#include <openvpn/common/exception.hpp>
|
||||
#include <openvpn/common/split.hpp>
|
||||
#include <openvpn/common/unicode.hpp>
|
||||
#include <openvpn/common/string.hpp>
|
||||
|
||||
// Process halt/restart messages from server:
|
||||
// HALT,<client_reason> -> disconnect
|
||||
// RESTART,<client_reason> -> restart with reason, don't preserve session ID
|
||||
// RESTART,[P]:<client_reason> -> restart with reason, do preserve session ID
|
||||
|
||||
namespace openvpn {
|
||||
class ClientHalt
|
||||
{
|
||||
typedef std::vector<std::string> StringList;
|
||||
|
||||
public:
|
||||
OPENVPN_SIMPLE_EXCEPTION(client_halt_error);
|
||||
|
||||
ClientHalt(const std::string& msg, const bool unicode_filter)
|
||||
{
|
||||
// get operator (halt or restart)
|
||||
StringList sl;
|
||||
parse_msg(sl, msg);
|
||||
if (is_halt(sl))
|
||||
;
|
||||
else if (is_restart(sl))
|
||||
restart_ = true;
|
||||
else
|
||||
throw client_halt_error();
|
||||
|
||||
// get flags and reason
|
||||
if (sl.size() >= 2)
|
||||
{
|
||||
size_t reason_pos = 0;
|
||||
if (restart_ && string::starts_with(sl[1], "[P]:"))
|
||||
{
|
||||
psid_ = true;
|
||||
reason_pos = 4;
|
||||
}
|
||||
reason_ = sl[1].substr(reason_pos);
|
||||
if (unicode_filter)
|
||||
reason_ = Unicode::utf8_printable(reason_, 256);
|
||||
}
|
||||
}
|
||||
|
||||
static bool match(const std::string& msg)
|
||||
{
|
||||
StringList sl;
|
||||
parse_msg(sl, msg);
|
||||
return is_halt(sl) || is_restart(sl);
|
||||
}
|
||||
|
||||
// returns true for restart, false for halt
|
||||
bool restart() const { return restart_; }
|
||||
|
||||
// returns true if session ID should be preserved
|
||||
bool psid() const { return psid_; }
|
||||
|
||||
// returns user-visible reason string
|
||||
const std::string& reason() const { return reason_; }
|
||||
|
||||
std::string render() const {
|
||||
std::ostringstream os;
|
||||
os << (restart_ ? "RESTART" : "HALT") << " psid=" << psid_ << " reason='" << reason_ << '\'';
|
||||
return os.str();
|
||||
}
|
||||
|
||||
private:
|
||||
static void parse_msg(StringList& sl, const std::string& msg)
|
||||
{
|
||||
sl.reserve(2);
|
||||
Split::by_char_void<StringList, NullLex, Split::NullLimit>(sl, msg, ',', 0, 1);
|
||||
}
|
||||
|
||||
static bool is_halt(const StringList& sl)
|
||||
{
|
||||
return sl.size() >= 1 && sl[0] == "HALT";
|
||||
}
|
||||
|
||||
static bool is_restart(const StringList& sl)
|
||||
{
|
||||
return sl.size() >= 1 && sl[0] == "RESTART";
|
||||
}
|
||||
|
||||
bool restart_ = false;
|
||||
bool psid_ = false;
|
||||
std::string reason_;
|
||||
};
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,50 @@
|
||||
// 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_CLIENT_CLILIFE_H
|
||||
#define OPENVPN_CLIENT_CLILIFE_H
|
||||
|
||||
#include <string>
|
||||
|
||||
#include <openvpn/common/rc.hpp>
|
||||
|
||||
namespace openvpn {
|
||||
// Base class for managing connection lifecycle notifications,
|
||||
// such as sleep, wakeup, network-unavailable, network-available.
|
||||
class ClientLifeCycle : public RC<thread_unsafe_refcount> {
|
||||
public:
|
||||
struct NotifyCallback {
|
||||
virtual void cln_stop() = 0;
|
||||
virtual void cln_pause(const std::string& reason) = 0;
|
||||
virtual void cln_resume() = 0;
|
||||
virtual void cln_reconnect(int seconds) = 0;
|
||||
};
|
||||
|
||||
typedef RCPtr<ClientLifeCycle> Ptr;
|
||||
|
||||
virtual bool network_available() = 0;
|
||||
|
||||
virtual void start(NotifyCallback*) = 0;
|
||||
virtual void stop() = 0;
|
||||
};
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,918 @@
|
||||
// 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/>.
|
||||
|
||||
// These classes encapsulate the basic setup of the various objects needed to
|
||||
// create an OpenVPN client session. The basic idea here is to look at both
|
||||
// compile time settings (i.e. crypto/SSL/random libraries), and run-time
|
||||
// (such as transport layer using UDP, TCP, or HTTP-proxy), and
|
||||
// build the actual objects that will be used to construct a client session.
|
||||
|
||||
#ifndef OPENVPN_CLIENT_CLIOPT_H
|
||||
#define OPENVPN_CLIENT_CLIOPT_H
|
||||
|
||||
#include <string>
|
||||
|
||||
#include <openvpn/error/excode.hpp>
|
||||
|
||||
#include <openvpn/common/size.hpp>
|
||||
#include <openvpn/common/platform.hpp>
|
||||
#include <openvpn/common/options.hpp>
|
||||
#include <openvpn/common/stop.hpp>
|
||||
#include <openvpn/frame/frame_init.hpp>
|
||||
#include <openvpn/pki/epkibase.hpp>
|
||||
#include <openvpn/crypto/cryptodcsel.hpp>
|
||||
#include <openvpn/ssl/mssparms.hpp>
|
||||
#include <openvpn/tun/tunmtu.hpp>
|
||||
#include <openvpn/tun/ipv6_setting.hpp>
|
||||
#include <openvpn/netconf/hwaddr.hpp>
|
||||
|
||||
#include <openvpn/transport/socket_protect.hpp>
|
||||
#include <openvpn/transport/reconnect_notify.hpp>
|
||||
#include <openvpn/transport/client/udpcli.hpp>
|
||||
#include <openvpn/transport/client/tcpcli.hpp>
|
||||
#include <openvpn/transport/client/httpcli.hpp>
|
||||
#include <openvpn/transport/altproxy.hpp>
|
||||
#include <openvpn/transport/dco.hpp>
|
||||
#include <openvpn/client/cliproto.hpp>
|
||||
#include <openvpn/client/cliopthelper.hpp>
|
||||
#include <openvpn/client/optfilt.hpp>
|
||||
#include <openvpn/client/clilife.hpp>
|
||||
|
||||
#include <openvpn/ssl/sslchoose.hpp>
|
||||
|
||||
#ifdef OPENVPN_GREMLIN
|
||||
#include <openvpn/transport/gremlin.hpp>
|
||||
#endif
|
||||
|
||||
#if defined(OPENVPN_PLATFORM_ANDROID)
|
||||
#include <openvpn/client/cliemuexr.hpp>
|
||||
#endif
|
||||
|
||||
#if defined(OPENVPN_EXTERNAL_TRANSPORT_FACTORY)
|
||||
#include <openvpn/transport/client/extern/config.hpp>
|
||||
#include <openvpn/transport/client/extern/fw.hpp>
|
||||
#endif
|
||||
|
||||
#if defined(OPENVPN_EXTERNAL_TUN_FACTORY)
|
||||
// requires that client implements ExternalTun::Factory::new_tun_factory
|
||||
#include <openvpn/tun/extern/config.hpp>
|
||||
#elif defined(USE_TUN_BUILDER)
|
||||
#include <openvpn/tun/builder/client.hpp>
|
||||
#elif defined(OPENVPN_PLATFORM_LINUX) && !defined(OPENVPN_FORCE_TUN_NULL)
|
||||
#include <openvpn/tun/linux/client/tuncli.hpp>
|
||||
#ifdef OPENVPN_COMMAND_AGENT
|
||||
#include <openvpn/client/unix/cmdagent.hpp>
|
||||
#endif
|
||||
#elif defined(OPENVPN_PLATFORM_MAC) && !defined(OPENVPN_FORCE_TUN_NULL)
|
||||
#include <openvpn/tun/mac/client/tuncli.hpp>
|
||||
#include <openvpn/apple/maclife.hpp>
|
||||
#ifdef OPENVPN_COMMAND_AGENT
|
||||
#include <openvpn/client/unix/cmdagent.hpp>
|
||||
#endif
|
||||
#elif defined(OPENVPN_PLATFORM_WIN) && !defined(OPENVPN_FORCE_TUN_NULL)
|
||||
#include <openvpn/tun/win/client/tuncli.hpp>
|
||||
#ifdef OPENVPN_COMMAND_AGENT
|
||||
#include <openvpn/client/win/cmdagent.hpp>
|
||||
#endif
|
||||
#else
|
||||
#include <openvpn/tun/client/tunnull.hpp>
|
||||
#endif
|
||||
|
||||
#ifdef PRIVATE_TUNNEL_PROXY
|
||||
#include <openvpn/pt/ptproxy.hpp>
|
||||
#endif
|
||||
|
||||
#if defined(ENABLE_DCO)
|
||||
#include <openvpn/dco/dcocli.hpp>
|
||||
#endif
|
||||
|
||||
#ifndef OPENVPN_UNUSED_OPTIONS
|
||||
#define OPENVPN_UNUSED_OPTIONS "UNUSED OPTIONS"
|
||||
#endif
|
||||
|
||||
namespace openvpn {
|
||||
|
||||
class ClientOptions : public RC<thread_unsafe_refcount>
|
||||
{
|
||||
public:
|
||||
typedef RCPtr<ClientOptions> Ptr;
|
||||
|
||||
typedef ClientProto::Session Client;
|
||||
|
||||
struct Config
|
||||
{
|
||||
std::string gui_version;
|
||||
std::string sso_methods;
|
||||
std::string server_override;
|
||||
std::string port_override;
|
||||
std::string hw_addr_override;
|
||||
std::string platform_version;
|
||||
Protocol proto_override;
|
||||
IPv6Setting ipv6;
|
||||
int conn_timeout = 0;
|
||||
SessionStats::Ptr cli_stats;
|
||||
ClientEvent::Queue::Ptr cli_events;
|
||||
ProtoContextOptions::Ptr proto_context_options;
|
||||
HTTPProxyTransport::Options::Ptr http_proxy_options;
|
||||
bool alt_proxy = false;
|
||||
bool dco = false;
|
||||
bool echo = false;
|
||||
bool info = false;
|
||||
bool tun_persist = false;
|
||||
bool wintun = false;
|
||||
bool google_dns_fallback = false;
|
||||
bool synchronous_dns_lookup = false;
|
||||
std::string private_key_password;
|
||||
bool disable_client_cert = false;
|
||||
int ssl_debug_level = 0;
|
||||
int default_key_direction = -1;
|
||||
bool force_aes_cbc_ciphersuites = false;
|
||||
bool autologin_sessions = false;
|
||||
bool retry_on_auth_failed = false;
|
||||
bool allow_local_lan_access = false;
|
||||
std::string tls_version_min_override;
|
||||
std::string tls_cert_profile_override;
|
||||
PeerInfo::Set::Ptr extra_peer_info;
|
||||
#ifdef OPENVPN_GREMLIN
|
||||
Gremlin::Config::Ptr gremlin_config;
|
||||
#endif
|
||||
Stop* stop = nullptr;
|
||||
|
||||
// callbacks -- must remain in scope for lifetime of ClientOptions object
|
||||
ExternalPKIBase* external_pki = nullptr;
|
||||
SocketProtect* socket_protect = nullptr;
|
||||
ReconnectNotify* reconnect_notify = nullptr;
|
||||
RemoteList::RemoteOverride* remote_override = nullptr;
|
||||
|
||||
#if defined(USE_TUN_BUILDER)
|
||||
TunBuilderBase* builder = nullptr;
|
||||
#endif
|
||||
|
||||
#if defined(OPENVPN_EXTERNAL_TUN_FACTORY)
|
||||
ExternalTun::Factory* extern_tun_factory = nullptr;
|
||||
#endif
|
||||
|
||||
#if defined(OPENVPN_EXTERNAL_TRANSPORT_FACTORY)
|
||||
ExternalTransport::Factory* extern_transport_factory = nullptr;
|
||||
#endif
|
||||
};
|
||||
|
||||
ClientOptions(const OptionList& opt, // only needs to remain in scope for duration of constructor call
|
||||
const Config& config)
|
||||
: server_addr_float(false),
|
||||
socket_protect(config.socket_protect),
|
||||
reconnect_notify(config.reconnect_notify),
|
||||
cli_stats(config.cli_stats),
|
||||
cli_events(config.cli_events),
|
||||
server_poll_timeout_(10),
|
||||
server_override(config.server_override),
|
||||
port_override(config.port_override),
|
||||
proto_override(config.proto_override),
|
||||
conn_timeout_(config.conn_timeout),
|
||||
tcp_queue_limit(64),
|
||||
proto_context_options(config.proto_context_options),
|
||||
http_proxy_options(config.http_proxy_options),
|
||||
#ifdef OPENVPN_GREMLIN
|
||||
gremlin_config(config.gremlin_config),
|
||||
#endif
|
||||
echo(config.echo),
|
||||
info(config.info),
|
||||
autologin(false),
|
||||
autologin_sessions(false),
|
||||
creds_locked(false),
|
||||
asio_work_always_on_(false),
|
||||
synchronous_dns_lookup(false),
|
||||
retry_on_auth_failed_(config.retry_on_auth_failed)
|
||||
#ifdef OPENVPN_EXTERNAL_TRANSPORT_FACTORY
|
||||
,extern_transport_factory(config.extern_transport_factory)
|
||||
#endif
|
||||
{
|
||||
// parse general client options
|
||||
const ParseClientConfig pcc(opt);
|
||||
|
||||
// creds
|
||||
userlocked_username = pcc.userlockedUsername();
|
||||
autologin = pcc.autologin();
|
||||
autologin_sessions = (autologin && config.autologin_sessions);
|
||||
|
||||
// digest factory
|
||||
DigestFactory::Ptr digest_factory(new CryptoDigestFactory<SSLLib::CryptoAPI>());
|
||||
|
||||
// initialize RNG/PRNG
|
||||
rng.reset(new SSLLib::RandomAPI(false));
|
||||
prng.reset(new SSLLib::RandomAPI(true));
|
||||
|
||||
#if defined(ENABLE_DCO) && !defined(OPENVPN_FORCE_TUN_NULL) && !defined(OPENVPN_EXTERNAL_TUN_FACTORY)
|
||||
if (config.dco)
|
||||
dco = DCOTransport::new_controller();
|
||||
#else
|
||||
if (config.dco)
|
||||
throw option_error("DCO not enabled in this build");
|
||||
#endif
|
||||
|
||||
// frame
|
||||
const unsigned int tun_mtu = parse_tun_mtu(opt, 0); // get tun-mtu parameter from config
|
||||
const MSSCtrlParms mc(opt);
|
||||
frame = frame_init(true, tun_mtu, mc.mssfix_ctrl, true);
|
||||
|
||||
// TCP queue limit
|
||||
tcp_queue_limit = opt.get_num<decltype(tcp_queue_limit)>("tcp-queue-limit", 1, tcp_queue_limit, 1, 65536);
|
||||
|
||||
// route-nopull
|
||||
pushed_options_filter.reset(new PushedOptionsFilter(opt.exists("route-nopull")));
|
||||
|
||||
// OpenVPN Protocol context (including SSL)
|
||||
cp_main = proto_config(opt, config, pcc, false);
|
||||
cp_relay = proto_config(opt, config, pcc, true); // may be null
|
||||
layer = cp_main->layer;
|
||||
|
||||
#ifdef PRIVATE_TUNNEL_PROXY
|
||||
if (config.alt_proxy && !dco)
|
||||
alt_proxy = PTProxy::new_proxy(opt, rng);
|
||||
#endif
|
||||
|
||||
// If HTTP proxy parameters are not supplied by API, try to get them from config
|
||||
if (!http_proxy_options)
|
||||
http_proxy_options = HTTPProxyTransport::Options::parse(opt);
|
||||
|
||||
// load remote list
|
||||
if (config.remote_override)
|
||||
remote_list.reset(new RemoteList(config.remote_override));
|
||||
else
|
||||
remote_list.reset(new RemoteList(opt, "", RemoteList::WARN_UNSUPPORTED, nullptr));
|
||||
if (!remote_list->defined())
|
||||
throw option_error("no remote option specified");
|
||||
|
||||
// Set remote list prng
|
||||
remote_list->set_random(prng);
|
||||
|
||||
// If running in tun_persist mode, we need to do basic DNS caching so that
|
||||
// we can avoid emitting DNS requests while the tunnel is blocked during
|
||||
// reconnections.
|
||||
remote_list->set_enable_cache(config.tun_persist);
|
||||
|
||||
// process server/port overrides
|
||||
remote_list->set_server_override(config.server_override);
|
||||
remote_list->set_port_override(config.port_override);
|
||||
|
||||
// process protocol override, should be called after set_enable_cache
|
||||
remote_list->handle_proto_override(config.proto_override,
|
||||
http_proxy_options || (alt_proxy && alt_proxy->requires_tcp()));
|
||||
|
||||
// process remote-random
|
||||
if (opt.exists("remote-random"))
|
||||
remote_list->randomize();
|
||||
|
||||
// get "float" option
|
||||
server_addr_float = opt.exists("float");
|
||||
|
||||
// special remote cache handling for proxies
|
||||
if (alt_proxy)
|
||||
{
|
||||
remote_list->set_enable_cache(false); // remote server addresses will be resolved by proxy
|
||||
alt_proxy->set_enable_cache(config.tun_persist);
|
||||
}
|
||||
else if (http_proxy_options)
|
||||
{
|
||||
remote_list->set_enable_cache(false); // remote server addresses will be resolved by proxy
|
||||
http_proxy_options->proxy_server_set_enable_cache(config.tun_persist);
|
||||
}
|
||||
|
||||
// secret option not supported
|
||||
if (opt.exists("secret"))
|
||||
throw option_error("sorry, static key encryption mode (non-SSL/TLS) is not supported");
|
||||
|
||||
// fragment option not supported
|
||||
if (opt.exists("fragment"))
|
||||
throw option_error("sorry, 'fragment' directive is not supported, nor is connecting to a server that uses 'fragment' directive");
|
||||
|
||||
#ifdef OPENVPN_PLATFORM_UWP
|
||||
// workaround for OVPN3-62 Busy loop in win_event.hpp
|
||||
asio_work_always_on_ = true;
|
||||
#endif
|
||||
|
||||
synchronous_dns_lookup = config.synchronous_dns_lookup;
|
||||
|
||||
#ifdef OPENVPN_TLS_LINK
|
||||
if (opt.exists("tls-ca"))
|
||||
{
|
||||
tls_ca = opt.cat("tls-ca");
|
||||
}
|
||||
#endif
|
||||
|
||||
// init transport config
|
||||
const std::string session_name = load_transport_config();
|
||||
|
||||
// initialize tun/tap
|
||||
if (dco)
|
||||
{
|
||||
DCO::TunConfig tunconf;
|
||||
tunconf.tun_prop.layer = layer;
|
||||
tunconf.tun_prop.session_name = session_name;
|
||||
if (tun_mtu)
|
||||
tunconf.tun_prop.mtu = tun_mtu;
|
||||
tunconf.tun_prop.google_dns_fallback = config.google_dns_fallback;
|
||||
tunconf.tun_prop.remote_list = remote_list;
|
||||
tunconf.stop = config.stop;
|
||||
tun_factory = dco->new_tun_factory(tunconf, opt);
|
||||
}
|
||||
else
|
||||
{
|
||||
#if defined(OPENVPN_EXTERNAL_TUN_FACTORY)
|
||||
{
|
||||
ExternalTun::Config tunconf;
|
||||
tunconf.tun_prop.layer = layer;
|
||||
tunconf.tun_prop.session_name = session_name;
|
||||
tunconf.tun_prop.google_dns_fallback = config.google_dns_fallback;
|
||||
if (tun_mtu)
|
||||
tunconf.tun_prop.mtu = tun_mtu;
|
||||
tunconf.frame = frame;
|
||||
tunconf.stats = cli_stats;
|
||||
tunconf.tun_prop.remote_list = remote_list;
|
||||
tunconf.tun_persist = config.tun_persist;
|
||||
tunconf.stop = config.stop;
|
||||
tun_factory.reset(config.extern_tun_factory->new_tun_factory(tunconf, opt));
|
||||
if (!tun_factory)
|
||||
throw option_error("OPENVPN_EXTERNAL_TUN_FACTORY: no tun factory");
|
||||
}
|
||||
#elif defined(USE_TUN_BUILDER)
|
||||
{
|
||||
TunBuilderClient::ClientConfig::Ptr tunconf = TunBuilderClient::ClientConfig::new_obj();
|
||||
tunconf->builder = config.builder;
|
||||
tunconf->tun_prop.session_name = session_name;
|
||||
tunconf->tun_prop.google_dns_fallback = config.google_dns_fallback;
|
||||
tunconf->tun_prop.allow_local_lan_access = config.allow_local_lan_access;
|
||||
if (tun_mtu)
|
||||
tunconf->tun_prop.mtu = tun_mtu;
|
||||
tunconf->frame = frame;
|
||||
tunconf->stats = cli_stats;
|
||||
tunconf->tun_prop.remote_list = remote_list;
|
||||
tun_factory = tunconf;
|
||||
#if defined(OPENVPN_PLATFORM_IPHONE)
|
||||
tunconf->retain_sd = true;
|
||||
tunconf->tun_prefix = true;
|
||||
if (config.tun_persist)
|
||||
tunconf->tun_prop.remote_bypass = true;
|
||||
#endif
|
||||
#if defined(OPENVPN_PLATFORM_ANDROID)
|
||||
// Android VPN API doesn't support excluded routes, so we must emulate them
|
||||
tunconf->eer_factory.reset(new EmulateExcludeRouteFactoryImpl(false));
|
||||
#endif
|
||||
#if defined(OPENVPN_PLATFORM_MAC)
|
||||
tunconf->tun_prefix = true;
|
||||
#endif
|
||||
if (config.tun_persist)
|
||||
tunconf->tun_persist.reset(new TunBuilderClient::TunPersist(true, tunconf->retain_sd, config.builder));
|
||||
tun_factory = tunconf;
|
||||
}
|
||||
#elif defined(OPENVPN_PLATFORM_LINUX) && !defined(OPENVPN_FORCE_TUN_NULL)
|
||||
{
|
||||
TunLinux::ClientConfig::Ptr tunconf = TunLinux::ClientConfig::new_obj();
|
||||
tunconf->tun_prop.layer = layer;
|
||||
tunconf->tun_prop.session_name = session_name;
|
||||
if (tun_mtu)
|
||||
tunconf->tun_prop.mtu = tun_mtu;
|
||||
tunconf->tun_prop.google_dns_fallback = config.google_dns_fallback;
|
||||
tunconf->tun_prop.remote_list = remote_list;
|
||||
tunconf->frame = frame;
|
||||
tunconf->stats = cli_stats;
|
||||
if (config.tun_persist)
|
||||
tunconf->tun_persist.reset(new TunLinux::TunPersist(true, false, nullptr));
|
||||
tunconf->load(opt);
|
||||
tun_factory = tunconf;
|
||||
}
|
||||
#elif defined(OPENVPN_PLATFORM_MAC) && !defined(OPENVPN_FORCE_TUN_NULL)
|
||||
{
|
||||
TunMac::ClientConfig::Ptr tunconf = TunMac::ClientConfig::new_obj();
|
||||
tunconf->tun_prop.layer = layer;
|
||||
tunconf->tun_prop.session_name = session_name;
|
||||
tunconf->tun_prop.google_dns_fallback = config.google_dns_fallback;
|
||||
if (tun_mtu)
|
||||
tunconf->tun_prop.mtu = tun_mtu;
|
||||
tunconf->frame = frame;
|
||||
tunconf->stats = cli_stats;
|
||||
tunconf->stop = config.stop;
|
||||
if (config.tun_persist)
|
||||
{
|
||||
tunconf->tun_persist.reset(new TunMac::TunPersist(true, false, nullptr));
|
||||
#ifndef OPENVPN_COMMAND_AGENT
|
||||
/* remote_list is required by remote_bypass to work */
|
||||
tunconf->tun_prop.remote_bypass = true;
|
||||
tunconf->tun_prop.remote_list = remote_list;
|
||||
#endif
|
||||
}
|
||||
client_lifecycle.reset(new MacLifeCycle);
|
||||
#ifdef OPENVPN_COMMAND_AGENT
|
||||
tunconf->tun_setup_factory = UnixCommandAgent::new_agent(opt);
|
||||
#endif
|
||||
tun_factory = tunconf;
|
||||
}
|
||||
#elif defined(OPENVPN_PLATFORM_WIN) && !defined(OPENVPN_FORCE_TUN_NULL)
|
||||
{
|
||||
TunWin::ClientConfig::Ptr tunconf = TunWin::ClientConfig::new_obj();
|
||||
tunconf->tun_prop.layer = layer;
|
||||
tunconf->tun_prop.session_name = session_name;
|
||||
tunconf->tun_prop.google_dns_fallback = config.google_dns_fallback;
|
||||
if (tun_mtu)
|
||||
tunconf->tun_prop.mtu = tun_mtu;
|
||||
tunconf->frame = frame;
|
||||
tunconf->stats = cli_stats;
|
||||
tunconf->stop = config.stop;
|
||||
tunconf->wintun = config.wintun;
|
||||
if (config.tun_persist)
|
||||
{
|
||||
tunconf->tun_persist.reset(new TunWin::TunPersist(true, false, nullptr));
|
||||
#ifndef OPENVPN_COMMAND_AGENT
|
||||
/* remote_list is required by remote_bypass to work */
|
||||
tunconf->tun_prop.remote_bypass = true;
|
||||
tunconf->tun_prop.remote_list = remote_list;
|
||||
#endif
|
||||
}
|
||||
#ifdef OPENVPN_COMMAND_AGENT
|
||||
tunconf->tun_setup_factory = WinCommandAgent::new_agent(opt);
|
||||
#endif
|
||||
tun_factory = tunconf;
|
||||
}
|
||||
#else
|
||||
{
|
||||
TunNull::ClientConfig::Ptr tunconf = TunNull::ClientConfig::new_obj();
|
||||
tunconf->frame = frame;
|
||||
tunconf->stats = cli_stats;
|
||||
tun_factory = tunconf;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// The Core Library itself does not handle TAP/OSI_LAYER_2 currently,
|
||||
// so we bail out early whenever someone tries to use TAP configurations
|
||||
if (layer == Layer(Layer::OSI_LAYER_2))
|
||||
throw ErrorCode(Error::TAP_NOT_SUPPORTED, true, "OSI layer 2 tunnels are not currently supported");
|
||||
|
||||
// server-poll-timeout
|
||||
{
|
||||
const Option *o = opt.get_ptr("server-poll-timeout");
|
||||
if (o)
|
||||
server_poll_timeout_ = parse_number_throw<unsigned int>(o->get(1, 16), "server-poll-timeout");
|
||||
}
|
||||
|
||||
// create default creds object in case submit_creds is not called,
|
||||
// and populate it with embedded creds, if available
|
||||
{
|
||||
ClientCreds::Ptr cc = new ClientCreds();
|
||||
if (pcc.hasEmbeddedPassword())
|
||||
{
|
||||
cc->set_username(userlocked_username);
|
||||
cc->set_password(pcc.embeddedPassword());
|
||||
cc->enable_password_cache(true);
|
||||
cc->set_replace_password_with_session_id(true);
|
||||
submit_creds(cc);
|
||||
creds_locked = true;
|
||||
}
|
||||
else if (autologin_sessions)
|
||||
{
|
||||
// autologin sessions require replace_password_with_session_id
|
||||
cc->set_replace_password_with_session_id(true);
|
||||
submit_creds(cc);
|
||||
creds_locked = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
submit_creds(cc);
|
||||
}
|
||||
}
|
||||
|
||||
// configure push_base, a set of base options that will be combined with
|
||||
// options pushed by server.
|
||||
{
|
||||
push_base.reset(new PushOptionsBase());
|
||||
|
||||
// base options where multiple options of the same type can aggregate
|
||||
push_base->multi.extend(opt, "route");
|
||||
push_base->multi.extend(opt, "route-ipv6");
|
||||
push_base->multi.extend(opt, "redirect-gateway");
|
||||
push_base->multi.extend(opt, "redirect-private");
|
||||
push_base->multi.extend(opt, "dhcp-option");
|
||||
|
||||
// base options where only a single instance of each option makes sense
|
||||
push_base->singleton.extend(opt, "redirect-dns");
|
||||
push_base->singleton.extend(opt, "inactive");
|
||||
push_base->singleton.extend(opt, "route-metric");
|
||||
|
||||
// IPv6
|
||||
{
|
||||
const unsigned int n = push_base->singleton.extend(opt, "block-ipv6");
|
||||
if (!n && config.ipv6() == IPv6Setting::No)
|
||||
push_base->singleton.emplace_back("block-ipv6");
|
||||
}
|
||||
}
|
||||
|
||||
// show unused options
|
||||
opt.show_unused_options(OPENVPN_UNUSED_OPTIONS);
|
||||
}
|
||||
|
||||
static PeerInfo::Set::Ptr build_peer_info(const Config& config, const ParseClientConfig& pcc, const bool autologin_sessions)
|
||||
{
|
||||
PeerInfo::Set::Ptr pi(new PeerInfo::Set);
|
||||
|
||||
// IPv6
|
||||
if (config.ipv6() == IPv6Setting::No)
|
||||
pi->emplace_back("IV_IPv6", "0");
|
||||
else if (config.ipv6() == IPv6Setting::Yes)
|
||||
pi->emplace_back("IV_IPv6", "1");
|
||||
|
||||
// autologin sessions
|
||||
if (autologin_sessions)
|
||||
pi->emplace_back("IV_AUTO_SESS", "1");
|
||||
|
||||
// Config::peerInfo
|
||||
pi->append_foreign_set_ptr(config.extra_peer_info.get());
|
||||
|
||||
// setenv UV_ options
|
||||
pi->append_foreign_set_ptr(pcc.peerInfoUV());
|
||||
|
||||
// UI version
|
||||
if (!config.gui_version.empty())
|
||||
pi->emplace_back("IV_GUI_VER", config.gui_version);
|
||||
|
||||
// Supported SSO methods
|
||||
if (!config.sso_methods.empty())
|
||||
pi->emplace_back("IV_SSO", config.sso_methods);
|
||||
|
||||
// MAC address
|
||||
if (pcc.pushPeerInfo())
|
||||
{
|
||||
std::string hwaddr = get_hwaddr();
|
||||
if (!config.hw_addr_override.empty())
|
||||
pi->emplace_back("IV_HWADDR", config.hw_addr_override);
|
||||
else if (!hwaddr.empty())
|
||||
pi->emplace_back("IV_HWADDR", hwaddr);
|
||||
pi->emplace_back ("IV_SSL", get_ssl_library_version());
|
||||
|
||||
if (!config.platform_version.empty())
|
||||
pi->emplace_back("IV_PLAT_VER", config.platform_version);
|
||||
}
|
||||
return pi;
|
||||
}
|
||||
|
||||
void next()
|
||||
{
|
||||
bool omit_next = false;
|
||||
|
||||
if (alt_proxy)
|
||||
omit_next = alt_proxy->next();
|
||||
if (!omit_next)
|
||||
remote_list->next();
|
||||
load_transport_config();
|
||||
}
|
||||
|
||||
void remote_reset_cache_item()
|
||||
{
|
||||
remote_list->reset_cache_item();
|
||||
}
|
||||
|
||||
bool pause_on_connection_timeout()
|
||||
{
|
||||
if (reconnect_notify)
|
||||
return reconnect_notify->pause_on_connection_timeout();
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
bool retry_on_auth_failed() const
|
||||
{
|
||||
return retry_on_auth_failed_;
|
||||
}
|
||||
|
||||
Client::Config::Ptr client_config(const bool relay_mode)
|
||||
{
|
||||
Client::Config::Ptr cli_config = new Client::Config;
|
||||
|
||||
// Copy ProtoConfig so that modifications due to server push will
|
||||
// not persist across client instantiations.
|
||||
cli_config->proto_context_config.reset(new Client::ProtoConfig(proto_config_cached(relay_mode)));
|
||||
|
||||
cli_config->proto_context_options = proto_context_options;
|
||||
cli_config->push_base = push_base;
|
||||
cli_config->transport_factory = transport_factory;
|
||||
cli_config->tun_factory = tun_factory;
|
||||
cli_config->cli_stats = cli_stats;
|
||||
cli_config->cli_events = cli_events;
|
||||
cli_config->creds = creds;
|
||||
cli_config->pushed_options_filter = pushed_options_filter;
|
||||
cli_config->tcp_queue_limit = tcp_queue_limit;
|
||||
cli_config->echo = echo;
|
||||
cli_config->info = info;
|
||||
cli_config->autologin_sessions = autologin_sessions;
|
||||
return cli_config;
|
||||
}
|
||||
|
||||
bool need_creds() const
|
||||
{
|
||||
return !autologin;
|
||||
}
|
||||
|
||||
void submit_creds(const ClientCreds::Ptr& creds_arg)
|
||||
{
|
||||
if (creds_arg && !creds_locked)
|
||||
{
|
||||
// if no username is defined in creds and userlocked_username is defined
|
||||
// in profile, set the creds username to be the userlocked_username
|
||||
if (!creds_arg->username_defined() && !userlocked_username.empty())
|
||||
creds_arg->set_username(userlocked_username);
|
||||
creds = creds_arg;
|
||||
}
|
||||
}
|
||||
|
||||
bool server_poll_timeout_enabled() const
|
||||
{
|
||||
return !http_proxy_options;
|
||||
}
|
||||
|
||||
Time::Duration server_poll_timeout() const
|
||||
{
|
||||
return Time::Duration::seconds(server_poll_timeout_);
|
||||
}
|
||||
|
||||
SessionStats& stats() { return *cli_stats; }
|
||||
const SessionStats::Ptr& stats_ptr() const { return cli_stats; }
|
||||
ClientEvent::Queue& events() { return *cli_events; }
|
||||
ClientLifeCycle* lifecycle() { return client_lifecycle.get(); }
|
||||
|
||||
int conn_timeout() const { return conn_timeout_; }
|
||||
|
||||
bool asio_work_always_on() const { return asio_work_always_on_; }
|
||||
|
||||
RemoteList::Ptr remote_list_precache() const
|
||||
{
|
||||
RemoteList::Ptr r;
|
||||
if (alt_proxy)
|
||||
{
|
||||
alt_proxy->precache(r);
|
||||
if (r)
|
||||
return r;
|
||||
}
|
||||
if (http_proxy_options)
|
||||
{
|
||||
http_proxy_options->proxy_server_precache(r);
|
||||
if (r)
|
||||
return r;
|
||||
}
|
||||
return remote_list;
|
||||
}
|
||||
|
||||
void update_now()
|
||||
{
|
||||
now_.update();
|
||||
}
|
||||
|
||||
void finalize(const bool disconnected)
|
||||
{
|
||||
if (tun_factory)
|
||||
tun_factory->finalize(disconnected);
|
||||
}
|
||||
|
||||
private:
|
||||
Client::ProtoConfig& proto_config_cached(const bool relay_mode)
|
||||
{
|
||||
if (relay_mode && cp_relay)
|
||||
return *cp_relay;
|
||||
else
|
||||
return *cp_main;
|
||||
}
|
||||
|
||||
Client::ProtoConfig::Ptr proto_config(const OptionList& opt,
|
||||
const Config& config,
|
||||
const ParseClientConfig& pcc,
|
||||
const bool relay_mode)
|
||||
{
|
||||
// relay mode is null unless one of the below directives is defined
|
||||
if (relay_mode && !opt.exists("relay-mode"))
|
||||
return Client::ProtoConfig::Ptr();
|
||||
|
||||
// load flags
|
||||
unsigned int lflags = SSLConfigAPI::LF_PARSE_MODE;
|
||||
if (relay_mode)
|
||||
lflags |= SSLConfigAPI::LF_RELAY_MODE;
|
||||
|
||||
if (opt.exists("allow-name-constraints"))
|
||||
lflags |= SSLConfigAPI::LF_ALLOW_NAME_CONSTRAINTS;
|
||||
|
||||
// client SSL config
|
||||
SSLLib::SSLAPI::Config::Ptr cc(new SSLLib::SSLAPI::Config());
|
||||
cc->set_external_pki_callback(config.external_pki);
|
||||
cc->set_frame(frame);
|
||||
cc->set_flags(SSLConst::LOG_VERIFY_STATUS);
|
||||
cc->set_debug_level(config.ssl_debug_level);
|
||||
cc->set_rng(rng);
|
||||
cc->set_local_cert_enabled(pcc.clientCertEnabled() && !config.disable_client_cert);
|
||||
cc->set_private_key_password(config.private_key_password);
|
||||
cc->set_force_aes_cbc_ciphersuites(config.force_aes_cbc_ciphersuites);
|
||||
cc->load(opt, lflags);
|
||||
cc->set_tls_version_min_override(config.tls_version_min_override);
|
||||
cc->set_tls_cert_profile_override(config.tls_cert_profile_override);
|
||||
if (!cc->get_mode().is_client())
|
||||
throw option_error("only client configuration supported");
|
||||
|
||||
// client ProtoContext config
|
||||
Client::ProtoConfig::Ptr cp(new Client::ProtoConfig());
|
||||
cp->relay_mode = relay_mode;
|
||||
cp->dc.set_factory(new CryptoDCSelect<SSLLib::CryptoAPI>(frame, cli_stats, prng));
|
||||
cp->dc_deferred = true; // defer data channel setup until after options pull
|
||||
cp->tls_auth_factory.reset(new CryptoOvpnHMACFactory<SSLLib::CryptoAPI>());
|
||||
cp->tls_crypt_factory.reset(new CryptoTLSCryptFactory<SSLLib::CryptoAPI>());
|
||||
cp->tls_crypt_metadata_factory.reset(new CryptoTLSCryptMetadataFactory());
|
||||
cp->tlsprf_factory.reset(new CryptoTLSPRFFactory<SSLLib::CryptoAPI>());
|
||||
cp->ssl_factory = cc->new_factory();
|
||||
cp->load(opt, *proto_context_options, config.default_key_direction, false);
|
||||
cp->set_xmit_creds(!autologin || pcc.hasEmbeddedPassword() || autologin_sessions);
|
||||
cp->force_aes_cbc_ciphersuites = config.force_aes_cbc_ciphersuites; // also used to disable proto V2
|
||||
cp->extra_peer_info = build_peer_info(config, pcc, autologin_sessions);
|
||||
cp->frame = frame;
|
||||
cp->now = &now_;
|
||||
cp->rng = rng;
|
||||
cp->prng = prng;
|
||||
|
||||
return cp;
|
||||
}
|
||||
|
||||
std::string load_transport_config()
|
||||
{
|
||||
// get current transport protocol
|
||||
const Protocol& transport_protocol = remote_list->current_transport_protocol();
|
||||
|
||||
// If we are connecting over a proxy, and TCP protocol is required, but current
|
||||
// transport protocol is NOT TCP, we will throw an internal error because this
|
||||
// should have been caught earlier in RemoteList::handle_proto_override.
|
||||
|
||||
// construct transport object
|
||||
#ifdef OPENVPN_EXTERNAL_TRANSPORT_FACTORY
|
||||
ExternalTransport::Config transconf;
|
||||
transconf.remote_list = remote_list;
|
||||
transconf.frame = frame;
|
||||
transconf.stats = cli_stats;
|
||||
transconf.socket_protect = socket_protect;
|
||||
transconf.server_addr_float = server_addr_float;
|
||||
transconf.synchronous_dns_lookup = synchronous_dns_lookup;
|
||||
transconf.protocol = transport_protocol;
|
||||
transport_factory = extern_transport_factory->new_transport_factory(transconf);
|
||||
#ifdef OPENVPN_GREMLIN
|
||||
udpconf->gremlin_config = gremlin_config;
|
||||
#endif
|
||||
|
||||
#else
|
||||
if (dco)
|
||||
{
|
||||
DCO::TransportConfig transconf;
|
||||
transconf.protocol = transport_protocol;
|
||||
transconf.remote_list = remote_list;
|
||||
transconf.frame = frame;
|
||||
transconf.stats = cli_stats;
|
||||
transconf.server_addr_float = server_addr_float;
|
||||
transport_factory = dco->new_transport_factory(transconf);
|
||||
}
|
||||
else if (alt_proxy)
|
||||
{
|
||||
if (alt_proxy->requires_tcp() && !transport_protocol.is_tcp())
|
||||
throw option_error("internal error: no TCP server entries for " + alt_proxy->name() + " transport");
|
||||
AltProxy::Config conf;
|
||||
conf.remote_list = remote_list;
|
||||
conf.frame = frame;
|
||||
conf.stats = cli_stats;
|
||||
conf.digest_factory.reset(new CryptoDigestFactory<SSLLib::CryptoAPI>());
|
||||
conf.socket_protect = socket_protect;
|
||||
conf.rng = rng;
|
||||
transport_factory = alt_proxy->new_transport_client_factory(conf);
|
||||
}
|
||||
else if (http_proxy_options)
|
||||
{
|
||||
if (!transport_protocol.is_tcp())
|
||||
throw option_error("internal error: no TCP server entries for HTTP proxy transport");
|
||||
|
||||
// HTTP Proxy transport
|
||||
HTTPProxyTransport::ClientConfig::Ptr httpconf = HTTPProxyTransport::ClientConfig::new_obj();
|
||||
httpconf->remote_list = remote_list;
|
||||
httpconf->frame = frame;
|
||||
httpconf->stats = cli_stats;
|
||||
httpconf->digest_factory.reset(new CryptoDigestFactory<SSLLib::CryptoAPI>());
|
||||
httpconf->socket_protect = socket_protect;
|
||||
httpconf->http_proxy_options = http_proxy_options;
|
||||
httpconf->rng = rng;
|
||||
#ifdef PRIVATE_TUNNEL_PROXY
|
||||
httpconf->skip_html = true;
|
||||
#endif
|
||||
transport_factory = httpconf;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (transport_protocol.is_udp())
|
||||
{
|
||||
// UDP transport
|
||||
UDPTransport::ClientConfig::Ptr udpconf = UDPTransport::ClientConfig::new_obj();
|
||||
udpconf->remote_list = remote_list;
|
||||
udpconf->frame = frame;
|
||||
udpconf->stats = cli_stats;
|
||||
udpconf->socket_protect = socket_protect;
|
||||
udpconf->server_addr_float = server_addr_float;
|
||||
#ifdef OPENVPN_GREMLIN
|
||||
udpconf->gremlin_config = gremlin_config;
|
||||
#endif
|
||||
transport_factory = udpconf;
|
||||
}
|
||||
else if (transport_protocol.is_tcp()
|
||||
#ifdef OPENVPN_TLS_LINK
|
||||
|| transport_protocol.is_tls()
|
||||
#endif
|
||||
)
|
||||
{
|
||||
// TCP transport
|
||||
TCPTransport::ClientConfig::Ptr tcpconf = TCPTransport::ClientConfig::new_obj();
|
||||
tcpconf->remote_list = remote_list;
|
||||
tcpconf->frame = frame;
|
||||
tcpconf->stats = cli_stats;
|
||||
tcpconf->socket_protect = socket_protect;
|
||||
#ifdef OPENVPN_TLS_LINK
|
||||
if (transport_protocol.is_tls())
|
||||
tcpconf->use_tls = true;
|
||||
tcpconf->tls_ca = tls_ca;
|
||||
#endif
|
||||
#ifdef OPENVPN_GREMLIN
|
||||
tcpconf->gremlin_config = gremlin_config;
|
||||
#endif
|
||||
transport_factory = tcpconf;
|
||||
}
|
||||
else
|
||||
throw option_error("internal error: unknown transport protocol");
|
||||
}
|
||||
#endif // OPENVPN_EXTERNAL_TRANSPORT_FACTORY
|
||||
return remote_list->current_server_host();
|
||||
}
|
||||
|
||||
Time now_; // current time
|
||||
RandomAPI::Ptr rng;
|
||||
RandomAPI::Ptr prng;
|
||||
Frame::Ptr frame;
|
||||
Layer layer;
|
||||
Client::ProtoConfig::Ptr cp_main;
|
||||
Client::ProtoConfig::Ptr cp_relay;
|
||||
RemoteList::Ptr remote_list;
|
||||
bool server_addr_float;
|
||||
TransportClientFactory::Ptr transport_factory;
|
||||
TunClientFactory::Ptr tun_factory;
|
||||
SocketProtect* socket_protect;
|
||||
ReconnectNotify* reconnect_notify;
|
||||
SessionStats::Ptr cli_stats;
|
||||
ClientEvent::Queue::Ptr cli_events;
|
||||
ClientCreds::Ptr creds;
|
||||
unsigned int server_poll_timeout_;
|
||||
std::string server_override;
|
||||
std::string port_override;
|
||||
Protocol proto_override;
|
||||
int conn_timeout_;
|
||||
unsigned int tcp_queue_limit;
|
||||
ProtoContextOptions::Ptr proto_context_options;
|
||||
HTTPProxyTransport::Options::Ptr http_proxy_options;
|
||||
#ifdef OPENVPN_GREMLIN
|
||||
Gremlin::Config::Ptr gremlin_config;
|
||||
#endif
|
||||
std::string userlocked_username;
|
||||
bool echo;
|
||||
bool info;
|
||||
bool autologin;
|
||||
bool autologin_sessions;
|
||||
bool creds_locked;
|
||||
bool asio_work_always_on_;
|
||||
bool synchronous_dns_lookup;
|
||||
bool retry_on_auth_failed_;
|
||||
PushOptionsBase::Ptr push_base;
|
||||
OptionList::FilterBase::Ptr pushed_options_filter;
|
||||
ClientLifeCycle::Ptr client_lifecycle;
|
||||
AltProxy::Ptr alt_proxy;
|
||||
DCO::Ptr dco;
|
||||
#ifdef OPENVPN_EXTERNAL_TRANSPORT_FACTORY
|
||||
ExternalTransport::Factory* extern_transport_factory;
|
||||
#endif
|
||||
#ifdef OPENVPN_TLS_LINK
|
||||
std::string tls_ca;
|
||||
#endif
|
||||
};
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,722 @@
|
||||
// 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/>.
|
||||
|
||||
// A preliminary parser for OpenVPN client configuration files.
|
||||
|
||||
#ifndef OPENVPN_CLIENT_CLIOPTHELPER_H
|
||||
#define OPENVPN_CLIENT_CLIOPTHELPER_H
|
||||
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
#include <utility>
|
||||
|
||||
#ifdef HAVE_CONFIG_JSONCPP
|
||||
#include "json/json.h"
|
||||
#endif /* HAVE_CONFIG_JSONCPP */
|
||||
|
||||
#include <openvpn/common/size.hpp>
|
||||
#include <openvpn/common/exception.hpp>
|
||||
#include <openvpn/common/options.hpp>
|
||||
#include <openvpn/common/string.hpp>
|
||||
#include <openvpn/common/split.hpp>
|
||||
#include <openvpn/common/splitlines.hpp>
|
||||
#include <openvpn/common/userpass.hpp>
|
||||
#include <openvpn/client/remotelist.hpp>
|
||||
#include <openvpn/client/cliconstants.hpp>
|
||||
#include <openvpn/ssl/peerinfo.hpp>
|
||||
#include <openvpn/ssl/proto.hpp>
|
||||
#include <openvpn/ssl/proto_context_options.hpp>
|
||||
#include <openvpn/ssl/sslchoose.hpp>
|
||||
|
||||
namespace openvpn {
|
||||
class ParseClientConfig {
|
||||
public:
|
||||
struct ServerEntry {
|
||||
std::string server;
|
||||
std::string friendlyName;
|
||||
};
|
||||
|
||||
struct ServerList : public std::vector<ServerEntry>
|
||||
{
|
||||
};
|
||||
|
||||
struct RemoteItem {
|
||||
std::string host;
|
||||
std::string port;
|
||||
std::string proto;
|
||||
};
|
||||
|
||||
ParseClientConfig()
|
||||
{
|
||||
reset_pod();
|
||||
}
|
||||
|
||||
ParseClientConfig(const OptionList& options)
|
||||
{
|
||||
try {
|
||||
// reset POD types
|
||||
reset_pod();
|
||||
|
||||
// limits
|
||||
const size_t max_server_list_size = ProfileParseLimits::MAX_SERVER_LIST_SIZE;
|
||||
|
||||
// setenv UV_x
|
||||
PeerInfo::Set::Ptr peer_info_uv(new PeerInfo::Set);
|
||||
|
||||
// process setenv directives
|
||||
{
|
||||
const OptionList::IndexList* se = options.get_index_ptr("setenv");
|
||||
if (se)
|
||||
{
|
||||
for (OptionList::IndexList::const_iterator i = se->begin(); i != se->end(); ++i)
|
||||
{
|
||||
const Option& o = options[*i];
|
||||
o.touch();
|
||||
const std::string arg1 = o.get_optional(1, 256);
|
||||
|
||||
// server-locked profiles not supported
|
||||
if (arg1 == "GENERIC_CONFIG")
|
||||
{
|
||||
error_ = true;
|
||||
message_ = "ERR_PROFILE_SERVER_LOCKED_UNSUPPORTED: server locked profiles are currently unsupported";
|
||||
return;
|
||||
}
|
||||
else if (arg1 == "ALLOW_PASSWORD_SAVE")
|
||||
allowPasswordSave_ = parse_bool(o, "setenv ALLOW_PASSWORD_SAVE", 2);
|
||||
else if (arg1 == "CLIENT_CERT")
|
||||
clientCertEnabled_ = parse_bool(o, "setenv CLIENT_CERT", 2);
|
||||
else if (arg1 == "USERNAME")
|
||||
userlockedUsername_ = o.get(2, 256);
|
||||
else if (arg1 == "FRIENDLY_NAME")
|
||||
friendlyName_ = o.get(2, 256);
|
||||
else if (arg1 == "SERVER")
|
||||
{
|
||||
const std::string& serv = o.get(2, 256);
|
||||
std::vector<std::string> slist = Split::by_char<std::vector<std::string>, NullLex, Split::NullLimit>(serv, '/', 0, 1);
|
||||
ServerEntry se;
|
||||
if (slist.size() == 1)
|
||||
{
|
||||
se.server = slist[0];
|
||||
se.friendlyName = slist[0];
|
||||
}
|
||||
else if (slist.size() == 2)
|
||||
{
|
||||
se.server = slist[0];
|
||||
se.friendlyName = slist[1];
|
||||
}
|
||||
if (!se.server.empty() && !se.friendlyName.empty() && serverList_.size() < max_server_list_size)
|
||||
serverList_.push_back(std::move(se));
|
||||
}
|
||||
else if (arg1 == "PUSH_PEER_INFO")
|
||||
pushPeerInfo_ = true;
|
||||
else if (string::starts_with(arg1, "UV_") && arg1.length() >= 4 && string::is_word(arg1))
|
||||
{
|
||||
const std::string value = o.get_optional(2, 256);
|
||||
if (string::is_printable(value))
|
||||
peer_info_uv->emplace_back(arg1, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Alternative to "setenv CLIENT_CERT 0". Note that as of OpenVPN 2.3, this option
|
||||
// is only supported server-side, so this extends its meaning into the client realm.
|
||||
if (options.exists("client-cert-not-required"))
|
||||
clientCertEnabled_ = false;
|
||||
|
||||
// userlocked username
|
||||
{
|
||||
const Option* o = options.get_ptr("USERNAME");
|
||||
if (o)
|
||||
userlockedUsername_ = o->get(1, 256);
|
||||
}
|
||||
|
||||
// userlocked username/password via <auth-user-pass>
|
||||
std::vector<std::string> user_pass;
|
||||
const bool auth_user_pass = parse_auth_user_pass(options, &user_pass);
|
||||
if (auth_user_pass && user_pass.size() >= 1)
|
||||
{
|
||||
userlockedUsername_ = user_pass[0];
|
||||
if (user_pass.size() >= 2)
|
||||
{
|
||||
hasEmbeddedPassword_ = true;
|
||||
embeddedPassword_ = user_pass[1];
|
||||
}
|
||||
}
|
||||
|
||||
// External PKI
|
||||
externalPki_ = (clientCertEnabled_ && is_external_pki(options));
|
||||
|
||||
// allow password save
|
||||
{
|
||||
const Option* o = options.get_ptr("allow-password-save");
|
||||
if (o)
|
||||
allowPasswordSave_ = parse_bool(*o, "allow-password-save", 1);
|
||||
}
|
||||
|
||||
// autologin
|
||||
{
|
||||
autologin_ = is_autologin(options, auth_user_pass, user_pass);
|
||||
if (autologin_)
|
||||
allowPasswordSave_ = false; // saving passwords is incompatible with autologin
|
||||
}
|
||||
|
||||
// static challenge
|
||||
{
|
||||
const Option* o = options.get_ptr("static-challenge");
|
||||
if (o)
|
||||
{
|
||||
staticChallenge_ = o->get(1, 256);
|
||||
if (o->get_optional(2, 16) == "1")
|
||||
staticChallengeEcho_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
// validate remote list
|
||||
remoteList.reset(new RemoteList(options, "", 0, nullptr));
|
||||
{
|
||||
const RemoteList::Item* ri = remoteList->first_item();
|
||||
if (ri)
|
||||
{
|
||||
firstRemoteListItem_.host = ri->server_host;
|
||||
firstRemoteListItem_.port = ri->server_port;
|
||||
if (ri->transport_protocol.is_udp())
|
||||
firstRemoteListItem_.proto = "udp";
|
||||
else if (ri->transport_protocol.is_tcp())
|
||||
firstRemoteListItem_.proto = "tcp-client";
|
||||
}
|
||||
}
|
||||
|
||||
// determine if private key is encrypted
|
||||
if (!externalPki_)
|
||||
{
|
||||
const Option* o = options.get_ptr("key");
|
||||
if (o)
|
||||
{
|
||||
const std::string& key_txt = o->get(1, Option::MULTILINE);
|
||||
privateKeyPasswordRequired_ = (
|
||||
key_txt.find("-----BEGIN RSA PRIVATE KEY-----\nProc-Type: 4,ENCRYPTED\n") != std::string::npos
|
||||
|| key_txt.find("-----BEGIN ENCRYPTED PRIVATE KEY-----") != std::string::npos
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// profile name
|
||||
{
|
||||
const Option* o = options.get_ptr("PROFILE");
|
||||
if (o)
|
||||
{
|
||||
// take PROFILE substring up to '/'
|
||||
const std::string& pn = o->get(1, 256);
|
||||
const size_t slashpos = pn.find('/');
|
||||
if (slashpos != std::string::npos)
|
||||
profileName_ = pn.substr(0, slashpos);
|
||||
else
|
||||
profileName_ = pn;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (remoteList)
|
||||
profileName_ = remoteList->first_server_host();
|
||||
}
|
||||
}
|
||||
|
||||
// friendly name
|
||||
{
|
||||
const Option* o = options.get_ptr("FRIENDLY_NAME");
|
||||
if (o)
|
||||
friendlyName_ = o->get(1, 256);
|
||||
}
|
||||
|
||||
// server list
|
||||
{
|
||||
const Option* o = options.get_ptr("HOST_LIST");
|
||||
if (o)
|
||||
{
|
||||
SplitLines in(o->get(1, 4096 | Option::MULTILINE), 0);
|
||||
while (in(true))
|
||||
{
|
||||
ServerEntry se;
|
||||
se.server = in.line_ref();
|
||||
se.friendlyName = se.server;
|
||||
Option::validate_string("HOST_LIST server", se.server, 256);
|
||||
Option::validate_string("HOST_LIST friendly name", se.friendlyName, 256);
|
||||
if (!se.server.empty() && !se.friendlyName.empty() && serverList_.size() < max_server_list_size)
|
||||
serverList_.push_back(std::move(se));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// push-peer-info
|
||||
{
|
||||
if (options.exists("push-peer-info"))
|
||||
pushPeerInfo_ = true;
|
||||
if (pushPeerInfo_)
|
||||
peerInfoUV_ = peer_info_uv;
|
||||
}
|
||||
|
||||
// dev name
|
||||
{
|
||||
const Option *o = options.get_ptr("dev");
|
||||
if (o)
|
||||
{
|
||||
dev = o->get(1, 256);
|
||||
}
|
||||
}
|
||||
|
||||
// protocol configuration
|
||||
{
|
||||
protoConfig.reset(new ProtoContext::Config());
|
||||
protoConfig->tls_auth_factory.reset(new CryptoOvpnHMACFactory<SSLLib::CryptoAPI>());
|
||||
protoConfig->tls_crypt_factory.reset(new CryptoTLSCryptFactory<SSLLib::CryptoAPI>());
|
||||
protoConfig->load(options, ProtoContextOptions(), -1, false);
|
||||
}
|
||||
|
||||
unsigned int lflags = SSLConfigAPI::LF_PARSE_MODE;
|
||||
|
||||
if (options.exists("allow-name-constraints"))
|
||||
lflags |= SSLConfigAPI::LF_ALLOW_NAME_CONSTRAINTS;
|
||||
|
||||
// ssl lib configuration
|
||||
try {
|
||||
sslConfig.reset(new SSLLib::SSLAPI::Config());
|
||||
sslConfig->load(options, lflags);
|
||||
} catch (...) {
|
||||
sslConfig.reset();
|
||||
}
|
||||
}
|
||||
catch (const option_error& e)
|
||||
{
|
||||
error_ = true;
|
||||
message_ = Unicode::utf8_printable<std::string>(std::string("ERR_PROFILE_OPTION: ") + e.what(), 256);
|
||||
}
|
||||
catch (const std::exception& e)
|
||||
{
|
||||
error_ = true;
|
||||
message_ = Unicode::utf8_printable<std::string>(std::string("ERR_PROFILE_GENERIC: ") + e.what(), 256);
|
||||
}
|
||||
}
|
||||
|
||||
static ParseClientConfig parse(const std::string& content)
|
||||
{
|
||||
return parse(content, nullptr);
|
||||
}
|
||||
|
||||
static ParseClientConfig parse(const std::string& content, OptionList::KeyValueList* content_list)
|
||||
{
|
||||
OptionList options;
|
||||
return parse(content, content_list, options);
|
||||
}
|
||||
|
||||
static ParseClientConfig parse(const std::string& content,
|
||||
OptionList::KeyValueList* content_list,
|
||||
OptionList& options)
|
||||
{
|
||||
try {
|
||||
OptionList::Limits limits("profile is too large",
|
||||
ProfileParseLimits::MAX_PROFILE_SIZE,
|
||||
ProfileParseLimits::OPT_OVERHEAD,
|
||||
ProfileParseLimits::TERM_OVERHEAD,
|
||||
ProfileParseLimits::MAX_LINE_SIZE,
|
||||
ProfileParseLimits::MAX_DIRECTIVE_SIZE);
|
||||
options.clear();
|
||||
options.parse_from_config(content, &limits);
|
||||
options.parse_meta_from_config(content, "OVPN_ACCESS_SERVER", &limits);
|
||||
if (content_list)
|
||||
{
|
||||
content_list->preprocess();
|
||||
options.parse_from_key_value_list(*content_list, &limits);
|
||||
}
|
||||
process_setenv_opt(options);
|
||||
options.update_map();
|
||||
|
||||
// add in missing options
|
||||
bool added = false;
|
||||
|
||||
// client
|
||||
if (!options.exists("client"))
|
||||
{
|
||||
Option opt;
|
||||
opt.push_back("client");
|
||||
options.push_back(std::move(opt));
|
||||
added = true;
|
||||
}
|
||||
|
||||
// dev
|
||||
if (!options.exists("dev"))
|
||||
{
|
||||
Option opt;
|
||||
opt.push_back("dev");
|
||||
opt.push_back("tun");
|
||||
options.push_back(std::move(opt));
|
||||
added = true;
|
||||
}
|
||||
if (added)
|
||||
options.update_map();
|
||||
|
||||
return ParseClientConfig(options);
|
||||
}
|
||||
catch (const std::exception& e)
|
||||
{
|
||||
ParseClientConfig ret;
|
||||
ret.error_ = true;
|
||||
ret.message_ = Unicode::utf8_printable<std::string>(std::string("ERR_PROFILE_GENERIC: ") + e.what(), 256);
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
|
||||
// true if error
|
||||
bool error() const { return error_; }
|
||||
|
||||
// if error, message given here
|
||||
const std::string& message() const { return message_; }
|
||||
|
||||
// this username must be used with profile
|
||||
const std::string& userlockedUsername() const { return userlockedUsername_; }
|
||||
|
||||
// profile name of config
|
||||
const std::string& profileName() const { return profileName_; }
|
||||
|
||||
// "friendly" name of config
|
||||
const std::string& friendlyName() const { return friendlyName_; }
|
||||
|
||||
// true: no creds required, false: username/password required
|
||||
bool autologin() const { return autologin_; }
|
||||
|
||||
// profile embedded password via <auth-user-pass>
|
||||
bool hasEmbeddedPassword() const { return hasEmbeddedPassword_; }
|
||||
const std::string& embeddedPassword() const { return embeddedPassword_; }
|
||||
|
||||
// true: no client cert/key required, false: client cert/key required
|
||||
bool clientCertEnabled() const { return clientCertEnabled_; }
|
||||
|
||||
// if true, this is an External PKI profile (no cert or key directives)
|
||||
bool externalPki() const { return externalPki_; }
|
||||
|
||||
// static challenge, may be empty, ignored if autologin
|
||||
const std::string& staticChallenge() const { return staticChallenge_; }
|
||||
|
||||
// true if static challenge response should be echoed to UI, ignored if autologin
|
||||
bool staticChallengeEcho() const { return staticChallengeEcho_; }
|
||||
|
||||
// true if this profile requires a private key password
|
||||
bool privateKeyPasswordRequired() const { return privateKeyPasswordRequired_; }
|
||||
|
||||
// true if user is allowed to save authentication password in UI
|
||||
bool allowPasswordSave() const { return allowPasswordSave_; }
|
||||
|
||||
// true if "setenv PUSH_PEER_INFO" or "push-peer-info" are defined
|
||||
bool pushPeerInfo() const { return pushPeerInfo_; }
|
||||
|
||||
// "setenv UV_x" directives if pushPeerInfo() is true
|
||||
const PeerInfo::Set* peerInfoUV() const { return peerInfoUV_.get(); }
|
||||
|
||||
// optional list of user-selectable VPN servers
|
||||
const ServerList& serverList() const { return serverList_; }
|
||||
|
||||
// return first remote directive in config
|
||||
const RemoteItem& firstRemoteListItem() const { return firstRemoteListItem_; }
|
||||
|
||||
std::string to_string() const
|
||||
{
|
||||
std::ostringstream os;
|
||||
os << "user=" << userlockedUsername_
|
||||
<< " pn=" << profileName_
|
||||
<< " fn=" << friendlyName_
|
||||
<< " auto=" << autologin_
|
||||
<< " embed_pw=" << hasEmbeddedPassword_
|
||||
<< " epki=" << externalPki_
|
||||
<< " schal=" << staticChallenge_
|
||||
<< " scecho=" << staticChallengeEcho_;
|
||||
return os.str();
|
||||
}
|
||||
|
||||
std::string to_string_config() const
|
||||
{
|
||||
std::ostringstream os;
|
||||
|
||||
os << "client" << std::endl;
|
||||
os << "dev " << dev << std::endl;
|
||||
os << "dev-type " << protoConfig->layer.dev_type() << std::endl;
|
||||
for (size_t i = 0; i < remoteList->size(); i++)
|
||||
{
|
||||
const RemoteList::Item& item = remoteList->get_item(i);
|
||||
|
||||
os << "remote " << item.server_host << " " << item.server_port;
|
||||
const char *proto = item.transport_protocol.protocol_to_string();
|
||||
if (proto)
|
||||
os << " " << proto;
|
||||
os << std::endl;
|
||||
}
|
||||
if (protoConfig->tls_crypt_context)
|
||||
{
|
||||
os << "<tls-crypt>" << std::endl << protoConfig->tls_key.render() << "</tls-crypt>"
|
||||
<< std::endl;
|
||||
}
|
||||
else if (protoConfig->tls_auth_context)
|
||||
{
|
||||
os << "<tls-auth>" << std::endl << protoConfig->tls_key.render() << "</tls-auth>"
|
||||
<< std::endl;
|
||||
os << "key_direction " << protoConfig->key_direction << std::endl;
|
||||
}
|
||||
|
||||
// SSL parameters
|
||||
if (sslConfig)
|
||||
{
|
||||
print_pem(os, "ca", sslConfig->extract_ca());
|
||||
print_pem(os, "crl", sslConfig->extract_crl());
|
||||
print_pem(os, "key", sslConfig->extract_private_key());
|
||||
print_pem(os, "cert", sslConfig->extract_cert());
|
||||
|
||||
std::vector<std::string> extra_certs = sslConfig->extract_extra_certs();
|
||||
if (extra_certs.size() > 0)
|
||||
{
|
||||
os << "<extra-certs>" << std::endl;
|
||||
for (auto& cert : extra_certs)
|
||||
{
|
||||
os << cert;
|
||||
}
|
||||
os << "</extra-certs>" << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
os << "cipher " << CryptoAlgs::name(protoConfig->dc.cipher(), "none")
|
||||
<< std::endl;
|
||||
os << "auth " << CryptoAlgs::name(protoConfig->dc.digest(), "none")
|
||||
<< std::endl;
|
||||
const char *comp = protoConfig->comp_ctx.method_to_string();
|
||||
if (comp)
|
||||
os << "compress " << comp << std::endl;
|
||||
os << "keepalive " << protoConfig->keepalive_ping.to_seconds() << " "
|
||||
<< protoConfig->keepalive_timeout.to_seconds() << std::endl;
|
||||
os << "tun-mtu " << protoConfig->tun_mtu << std::endl;
|
||||
os << "reneg-sec " << protoConfig->renegotiate.to_seconds() << std::endl;
|
||||
|
||||
return os.str();
|
||||
}
|
||||
|
||||
#ifdef HAVE_CONFIG_JSONCPP
|
||||
|
||||
std::string to_json_config() const
|
||||
{
|
||||
std::ostringstream os;
|
||||
|
||||
Json::Value root(Json::objectValue);
|
||||
|
||||
root["mode"] = Json::Value("client");
|
||||
root["dev"] = Json::Value(dev);
|
||||
root["dev-type"] = Json::Value(protoConfig->layer.dev_type());
|
||||
root["remotes"] = Json::Value(Json::arrayValue);
|
||||
for (size_t i = 0; i < remoteList->size(); i++)
|
||||
{
|
||||
const RemoteList::Item& item = remoteList->get_item(i);
|
||||
|
||||
Json::Value el = Json::Value(Json::objectValue);
|
||||
el["address"] = Json::Value(item.server_host);
|
||||
el["port"] = Json::Value((Json::UInt)std::stoi(item.server_port));
|
||||
if (item.transport_protocol() == Protocol::NONE)
|
||||
el["proto"] = Json::Value("adaptive");
|
||||
else
|
||||
el["proto"] = Json::Value(item.transport_protocol.str());
|
||||
|
||||
root["remotes"].append(el);
|
||||
}
|
||||
if (protoConfig->tls_crypt_context)
|
||||
{
|
||||
root["tls_wrap"] = Json::Value(Json::objectValue);
|
||||
root["tls_wrap"]["mode"] = Json::Value("tls_crypt");
|
||||
root["tls_wrap"]["key"] = Json::Value(protoConfig->tls_key.render());
|
||||
}
|
||||
else if (protoConfig->tls_auth_context)
|
||||
{
|
||||
root["tls_wrap"] = Json::Value(Json::objectValue);
|
||||
root["tls_wrap"]["mode"] = Json::Value("tls_auth");
|
||||
root["tls_wrap"]["key_direction"] = Json::Value((Json::UInt)protoConfig->key_direction);
|
||||
root["tls_wrap"]["key"] = Json::Value(protoConfig->tls_key.render());
|
||||
}
|
||||
|
||||
// SSL parameters
|
||||
if (sslConfig)
|
||||
{
|
||||
json_pem(root, "ca", sslConfig->extract_ca());
|
||||
json_pem(root, "crl", sslConfig->extract_crl());
|
||||
json_pem(root, "cert", sslConfig->extract_cert());
|
||||
|
||||
// JSON config is aimed to users, therefore we do not export the raw private
|
||||
// key, but only some basic info
|
||||
PKType::Type priv_key_type = sslConfig->private_key_type();
|
||||
if (priv_key_type != PKType::PK_NONE)
|
||||
{
|
||||
root["key"] = Json::Value(Json::objectValue);
|
||||
root["key"]["type"] = Json::Value(sslConfig->private_key_type_string());
|
||||
root["key"]["length"] = Json::Value((Json::UInt)sslConfig->private_key_length());
|
||||
}
|
||||
|
||||
std::vector<std::string> extra_certs = sslConfig->extract_extra_certs();
|
||||
if (extra_certs.size() > 0)
|
||||
{
|
||||
root["extra_certs"] = Json::Value(Json::arrayValue);
|
||||
for (auto cert = extra_certs.begin(); cert != extra_certs.end(); cert++)
|
||||
{
|
||||
if (!cert->empty())
|
||||
root["extra_certs"].append(Json::Value(*cert));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
root["cipher"] = Json::Value(CryptoAlgs::name(protoConfig->dc.cipher(), "none"));
|
||||
root["auth"] = Json::Value(CryptoAlgs::name(protoConfig->dc.digest(), "none"));
|
||||
if (protoConfig->comp_ctx.type() != CompressContext::NONE)
|
||||
root["compression"] = Json::Value(protoConfig->comp_ctx.str());
|
||||
root["keepalive"] = Json::Value(Json::objectValue);
|
||||
root["keepalive"]["ping"] = Json::Value((Json::UInt)protoConfig->keepalive_ping.to_seconds());
|
||||
root["keepalive"]["timeout"] = Json::Value((Json::UInt)protoConfig->keepalive_timeout.to_seconds());
|
||||
root["tun_mtu"] = Json::Value((Json::UInt)protoConfig->tun_mtu);
|
||||
root["reneg_sec"] = Json::Value((Json::UInt)protoConfig->renegotiate.to_seconds());
|
||||
|
||||
return root.toStyledString();
|
||||
}
|
||||
|
||||
#endif /* HAVE_CONFIG_JSONCPP */
|
||||
|
||||
private:
|
||||
static void print_pem(std::ostream& os, std::string label, std::string pem)
|
||||
{
|
||||
if (pem.empty())
|
||||
return;
|
||||
os << "<" << label << ">" << std::endl << pem << "</" << label << ">" << std::endl;
|
||||
}
|
||||
|
||||
#ifdef HAVE_CONFIG_JSONCPP
|
||||
|
||||
static void json_pem(Json::Value& obj, std::string key, std::string pem)
|
||||
{
|
||||
if (pem.empty())
|
||||
return;
|
||||
obj[key] = Json::Value(pem);
|
||||
}
|
||||
|
||||
#endif /* HAVE_CONFIG_JSONCPP */
|
||||
|
||||
static bool parse_auth_user_pass(const OptionList& options, std::vector<std::string>* user_pass)
|
||||
{
|
||||
return UserPass::parse(options, "auth-user-pass", 0, user_pass);
|
||||
}
|
||||
|
||||
static void process_setenv_opt(OptionList& options)
|
||||
{
|
||||
for (OptionList::iterator i = options.begin(); i != options.end(); ++i)
|
||||
{
|
||||
Option& o = *i;
|
||||
if (o.size() >= 3 && o.ref(0) == "setenv" && o.ref(1) == "opt")
|
||||
o.remove_first(2);
|
||||
}
|
||||
}
|
||||
|
||||
static bool is_autologin(const OptionList& options,
|
||||
const bool auth_user_pass,
|
||||
const std::vector<std::string>& user_pass)
|
||||
{
|
||||
if (auth_user_pass && user_pass.size() >= 2) // embedded password?
|
||||
return true;
|
||||
else
|
||||
{
|
||||
const Option* autologin = options.get_ptr("AUTOLOGIN");
|
||||
if (autologin)
|
||||
return string::is_true(autologin->get_optional(1, 16));
|
||||
else
|
||||
{
|
||||
bool ret = !auth_user_pass;
|
||||
if (ret)
|
||||
{
|
||||
// External PKI profiles from AS don't declare auth-user-pass,
|
||||
// and we have no way of knowing if they are autologin unless
|
||||
// we examine their cert, which requires accessing the system-level
|
||||
// cert store on the client. For now, we are going to assume
|
||||
// that External PKI profiles from the AS are always userlogin,
|
||||
// unless explicitly overriden by AUTOLOGIN above.
|
||||
if (options.exists("EXTERNAL_PKI"))
|
||||
return false;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static bool is_external_pki(const OptionList& options)
|
||||
{
|
||||
const Option* epki = options.get_ptr("EXTERNAL_PKI");
|
||||
if (epki)
|
||||
return string::is_true(epki->get_optional(1, 16));
|
||||
else
|
||||
{
|
||||
const Option* cert = options.get_ptr("cert");
|
||||
const Option* key = options.get_ptr("key");
|
||||
return !cert || !key;
|
||||
}
|
||||
}
|
||||
|
||||
void reset_pod()
|
||||
{
|
||||
error_ = autologin_ = externalPki_ = staticChallengeEcho_ = false;
|
||||
privateKeyPasswordRequired_ = hasEmbeddedPassword_ = false;
|
||||
pushPeerInfo_ = false;
|
||||
allowPasswordSave_ = clientCertEnabled_ = true;
|
||||
}
|
||||
|
||||
bool parse_bool(const Option& o, const std::string& title, const size_t index)
|
||||
{
|
||||
const std::string parm = o.get(index, 16);
|
||||
if (parm == "0")
|
||||
return false;
|
||||
else if (parm == "1")
|
||||
return true;
|
||||
else
|
||||
throw option_error(title + ": parameter must be 0 or 1");
|
||||
}
|
||||
|
||||
bool error_;
|
||||
std::string message_;
|
||||
std::string userlockedUsername_;
|
||||
std::string profileName_;
|
||||
std::string friendlyName_;
|
||||
bool autologin_;
|
||||
bool clientCertEnabled_;
|
||||
bool externalPki_;
|
||||
bool pushPeerInfo_;
|
||||
std::string staticChallenge_;
|
||||
bool staticChallengeEcho_;
|
||||
bool privateKeyPasswordRequired_;
|
||||
bool allowPasswordSave_;
|
||||
ServerList serverList_;
|
||||
bool hasEmbeddedPassword_;
|
||||
std::string embeddedPassword_;
|
||||
RemoteList::Ptr remoteList;
|
||||
RemoteItem firstRemoteListItem_;
|
||||
PeerInfo::Set::Ptr peerInfoUV_;
|
||||
ProtoContext::Config::Ptr protoConfig;
|
||||
SSLLib::SSLAPI::Config::Ptr sslConfig;
|
||||
std::string dev;
|
||||
};
|
||||
}
|
||||
|
||||
#endif
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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-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_CLIENT_IPVERFLAGS_H
|
||||
#define OPENVPN_CLIENT_IPVERFLAGS_H
|
||||
|
||||
#include <openvpn/addr/ip.hpp>
|
||||
#include <openvpn/client/rgopt.hpp>
|
||||
#include <openvpn/tun/builder/rgwflags.hpp>
|
||||
|
||||
namespace openvpn {
|
||||
class IPVerFlags
|
||||
{
|
||||
public:
|
||||
IPVerFlags(const OptionList& opt,
|
||||
const IP::Addr::VersionMask ip_ver_flags)
|
||||
: ip_ver_flags_(ip_ver_flags),
|
||||
rg_flags_(opt),
|
||||
api_flags_(0)
|
||||
{
|
||||
}
|
||||
|
||||
bool rgv4() const
|
||||
{
|
||||
return v4() && rg_flags_.redirect_gateway_ipv4_enabled();
|
||||
}
|
||||
|
||||
bool rgv6() const
|
||||
{
|
||||
return v6() && rg_flags_.redirect_gateway_ipv6_enabled();
|
||||
}
|
||||
|
||||
bool v4() const
|
||||
{
|
||||
return (ip_ver_flags_ & IP::Addr::V4_MASK) ? true : false;
|
||||
}
|
||||
|
||||
bool v6() const
|
||||
{
|
||||
return (ip_ver_flags_ & IP::Addr::V6_MASK) ? true : false;
|
||||
}
|
||||
|
||||
IP::Addr::VersionMask rg_ver_flags() const
|
||||
{
|
||||
IP::Addr::VersionMask flags = 0;
|
||||
if (rgv4())
|
||||
flags |= IP::Addr::V4_MASK;
|
||||
if (rgv6())
|
||||
flags |= IP::Addr::V6_MASK;
|
||||
return flags;
|
||||
}
|
||||
|
||||
IP::Addr::VersionMask ip_ver_flags() const
|
||||
{
|
||||
IP::Addr::VersionMask flags = 0;
|
||||
if (v4())
|
||||
flags |= IP::Addr::V4_MASK;
|
||||
if (v6())
|
||||
flags |= IP::Addr::V6_MASK;
|
||||
return flags;
|
||||
}
|
||||
|
||||
// these flags are passed to tun_builder_reroute_gw method
|
||||
unsigned int api_flags() const
|
||||
{
|
||||
return api_flags_ | rg_flags_();
|
||||
}
|
||||
|
||||
void set_emulate_exclude_routes()
|
||||
{
|
||||
api_flags_ |= RGWFlags::EmulateExcludeRoutes;
|
||||
}
|
||||
|
||||
private:
|
||||
const IP::Addr::VersionMask ip_ver_flags_;
|
||||
const RedirectGatewayFlags rg_flags_;
|
||||
unsigned int api_flags_;
|
||||
};
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,104 @@
|
||||
// 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_CLIENT_OPTFILT_H
|
||||
#define OPENVPN_CLIENT_OPTFILT_H
|
||||
|
||||
#include <openvpn/common/options.hpp>
|
||||
|
||||
// Options filters
|
||||
|
||||
namespace openvpn {
|
||||
|
||||
class PushedOptionsFilter : public OptionList::FilterBase
|
||||
{
|
||||
public:
|
||||
PushedOptionsFilter(const bool route_nopull)
|
||||
: route_nopull_(route_nopull) {}
|
||||
|
||||
virtual bool filter(const Option& opt)
|
||||
{
|
||||
const bool ret = filt(opt);
|
||||
if (!ret)
|
||||
OPENVPN_LOG("Ignored due to route-nopull: " << opt.render(Option::RENDER_TRUNC_64|Option::RENDER_BRACKET));
|
||||
return ret;
|
||||
}
|
||||
|
||||
private:
|
||||
// return false if pushed option should be ignored due to route-nopull directive.
|
||||
bool filt(const Option& opt)
|
||||
{
|
||||
if (route_nopull_)
|
||||
{
|
||||
if (opt.size() >= 1)
|
||||
{
|
||||
const std::string& directive = opt.ref(0);
|
||||
if (directive.length() >= 1)
|
||||
{
|
||||
switch (directive[0])
|
||||
{
|
||||
case 'b':
|
||||
if (directive == "block-ipv6")
|
||||
return false;
|
||||
break;
|
||||
case 'c':
|
||||
if (directive == "client-nat")
|
||||
return false;
|
||||
break;
|
||||
case 'd':
|
||||
if (directive == "dhcp-option" ||
|
||||
directive == "dhcp-renew" ||
|
||||
directive == "dhcp-pre-release" ||
|
||||
directive == "dhcp-release")
|
||||
return false;
|
||||
break;
|
||||
case 'i':
|
||||
if (directive == "ip-win32")
|
||||
return false;
|
||||
break;
|
||||
case 'r':
|
||||
if (directive == "route" ||
|
||||
directive == "route-ipv6" ||
|
||||
directive == "route-metric" ||
|
||||
directive == "redirect-gateway" ||
|
||||
directive == "redirect-private" ||
|
||||
directive == "register-dns" ||
|
||||
directive == "route-delay" ||
|
||||
directive == "route-method")
|
||||
return false;
|
||||
break;
|
||||
case 't':
|
||||
if (directive == "tap-sleep")
|
||||
return false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool route_nopull_;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,926 @@
|
||||
// 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/>.
|
||||
|
||||
// These classes handle parsing and representation of OpenVPN "remote" directives,
|
||||
// and the list of IP addresses that they resolve to.
|
||||
// <connection> blocks are supported.
|
||||
|
||||
#ifndef OPENVPN_CLIENT_REMOTELIST_H
|
||||
#define OPENVPN_CLIENT_REMOTELIST_H
|
||||
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
#include <utility>
|
||||
#include <thread>
|
||||
|
||||
#include <openvpn/io/io.hpp>
|
||||
#include <openvpn/asio/asiowork.hpp>
|
||||
|
||||
#include <openvpn/common/bigmutex.hpp>
|
||||
#include <openvpn/common/exception.hpp>
|
||||
#include <openvpn/common/rc.hpp>
|
||||
#include <openvpn/common/options.hpp>
|
||||
#include <openvpn/common/number.hpp>
|
||||
#include <openvpn/common/hostport.hpp>
|
||||
#include <openvpn/random/randapi.hpp>
|
||||
#include <openvpn/addr/ip.hpp>
|
||||
#include <openvpn/addr/addrlist.hpp>
|
||||
#include <openvpn/transport/protocol.hpp>
|
||||
#include <openvpn/client/cliconstants.hpp>
|
||||
#include <openvpn/log/sessionstats.hpp>
|
||||
#include <openvpn/client/async_resolve.hpp>
|
||||
|
||||
#if OPENVPN_DEBUG_REMOTELIST >= 1
|
||||
#define OPENVPN_LOG_REMOTELIST(x) OPENVPN_LOG(x)
|
||||
#else
|
||||
#define OPENVPN_LOG_REMOTELIST(x)
|
||||
#endif
|
||||
|
||||
namespace openvpn {
|
||||
class RemoteList : public RC<thread_unsafe_refcount>
|
||||
{
|
||||
// A single IP address that is part of a list of IP addresses
|
||||
// associated with a "remote" item.
|
||||
struct ResolvedAddr : public RC<thread_unsafe_refcount>
|
||||
{
|
||||
typedef RCPtr<ResolvedAddr> Ptr;
|
||||
IP::Addr addr;
|
||||
|
||||
std::string to_string() const
|
||||
{
|
||||
return addr.to_string();
|
||||
}
|
||||
};
|
||||
|
||||
// The IP address list associated with a single "remote" item.
|
||||
struct ResolvedAddrList : public std::vector<ResolvedAddr::Ptr>, public RC<thread_unsafe_refcount>
|
||||
{
|
||||
typedef RCPtr<ResolvedAddrList> Ptr;
|
||||
|
||||
std::string to_string() const
|
||||
{
|
||||
std::string ret;
|
||||
for (std::vector<ResolvedAddr::Ptr>::const_iterator i = begin(); i != end(); ++i)
|
||||
{
|
||||
if (!ret.empty())
|
||||
ret += ' ';
|
||||
ret += (*i)->to_string();
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
};
|
||||
|
||||
public:
|
||||
struct Item;
|
||||
|
||||
struct ConnBlock : public RC<thread_unsafe_refcount>
|
||||
{
|
||||
typedef RCPtr<ConnBlock> Ptr;
|
||||
|
||||
virtual void new_item(const Item& item) = 0;
|
||||
};
|
||||
|
||||
struct ConnBlockFactory
|
||||
{
|
||||
typedef RCPtr<ConnBlockFactory> Ptr;
|
||||
|
||||
virtual ConnBlock::Ptr new_conn_block(const OptionList::Ptr& opt) = 0;
|
||||
};
|
||||
|
||||
// A single "remote" item
|
||||
struct Item : public RC<thread_unsafe_refcount>
|
||||
{
|
||||
typedef RCPtr<Item> Ptr;
|
||||
|
||||
// "remote" item parameters from config file
|
||||
std::string server_host;
|
||||
std::string server_port;
|
||||
Protocol transport_protocol;
|
||||
|
||||
// IP address list defined after server_host is resolved
|
||||
ResolvedAddrList::Ptr res_addr_list;
|
||||
|
||||
// Other options if this is a <connection> block
|
||||
ConnBlock::Ptr conn_block;
|
||||
|
||||
bool res_addr_list_defined() const
|
||||
{
|
||||
return res_addr_list && res_addr_list->size() > 0;
|
||||
}
|
||||
|
||||
// cache a single IP address
|
||||
void set_ip_addr(const IP::Addr& addr)
|
||||
{
|
||||
res_addr_list.reset(new ResolvedAddrList());
|
||||
ResolvedAddr::Ptr ra(new ResolvedAddr());
|
||||
ra->addr = addr;
|
||||
res_addr_list->push_back(std::move(ra));
|
||||
OPENVPN_LOG_REMOTELIST("*** RemoteList::Item endpoint SET " << to_string());
|
||||
}
|
||||
|
||||
// cache a list of DNS-resolved IP addresses
|
||||
template <class EPRANGE>
|
||||
void set_endpoint_range(const EPRANGE& endpoint_range, RandomAPI* rng)
|
||||
{
|
||||
res_addr_list.reset(new ResolvedAddrList());
|
||||
for (const auto &i : endpoint_range)
|
||||
{
|
||||
ResolvedAddr::Ptr addr(new ResolvedAddr());
|
||||
addr->addr = IP::Addr::from_asio(i.endpoint().address());
|
||||
res_addr_list->push_back(addr);
|
||||
}
|
||||
if (rng && res_addr_list->size() >= 2)
|
||||
std::shuffle(res_addr_list->begin(), res_addr_list->end(), *rng);
|
||||
OPENVPN_LOG_REMOTELIST("*** RemoteList::Item endpoint SET " << to_string());
|
||||
}
|
||||
|
||||
// get an endpoint for contacting server
|
||||
template <class EP>
|
||||
bool get_endpoint(EP& endpoint, const size_t index) const
|
||||
{
|
||||
if (res_addr_list && index < res_addr_list->size())
|
||||
{
|
||||
endpoint.address((*res_addr_list)[index]->addr.to_asio());
|
||||
endpoint.port(parse_number_throw<unsigned int>(server_port, "remote_port"));
|
||||
OPENVPN_LOG_REMOTELIST("*** RemoteList::Item endpoint GET[" << index << "] " << endpoint << ' ' << to_string());
|
||||
return true;
|
||||
}
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string to_string() const
|
||||
{
|
||||
std::ostringstream out;
|
||||
out << "host=" << server_host;
|
||||
if (res_addr_list)
|
||||
out << '[' << res_addr_list->to_string() << ']';
|
||||
out << " port=" << server_port
|
||||
<< " proto=" << transport_protocol.str();
|
||||
return out.str();
|
||||
}
|
||||
};
|
||||
|
||||
struct RemoteOverride
|
||||
{
|
||||
virtual Item::Ptr get() = 0;
|
||||
};
|
||||
|
||||
private:
|
||||
// Directive names that we search for in options
|
||||
struct Directives
|
||||
{
|
||||
void init(const std::string& connection_tag)
|
||||
{
|
||||
connection = connection_tag.length() ? connection_tag : "connection";
|
||||
remote = "remote";
|
||||
proto = "proto";
|
||||
port = "port";
|
||||
}
|
||||
|
||||
std::string connection;
|
||||
std::string remote;
|
||||
std::string proto;
|
||||
std::string port;
|
||||
};
|
||||
|
||||
// Used to index into remote list.
|
||||
// The primary index is the remote list index.
|
||||
// The secondary index is the index into the
|
||||
// Item's IP address list (res_addr_list).
|
||||
class Index
|
||||
{
|
||||
public:
|
||||
Index()
|
||||
{
|
||||
reset();
|
||||
}
|
||||
|
||||
void reset()
|
||||
{
|
||||
primary_ = secondary_ = 0;
|
||||
}
|
||||
|
||||
void reset_secondary()
|
||||
{
|
||||
secondary_ = 0;
|
||||
}
|
||||
|
||||
// return true if primary index was incremented
|
||||
bool increment(const size_t pri_len, const size_t sec_len)
|
||||
{
|
||||
if (++secondary_ >= sec_len)
|
||||
{
|
||||
secondary_ = 0;
|
||||
if (++primary_ >= pri_len)
|
||||
primary_ = 0;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
bool equals(const Index& other) const
|
||||
{
|
||||
return primary_ == other.primary_ && secondary_ == other.secondary_;
|
||||
}
|
||||
|
||||
size_t primary() const { return primary_; }
|
||||
size_t secondary() const { return secondary_; }
|
||||
|
||||
private:
|
||||
size_t primary_;
|
||||
size_t secondary_;
|
||||
};
|
||||
|
||||
public:
|
||||
// Used for errors occurring after initial options processing,
|
||||
// and generally indicate logic errors
|
||||
// (option_error used during initial options processing).
|
||||
OPENVPN_EXCEPTION(remote_list_error);
|
||||
|
||||
typedef RCPtr<RemoteList> Ptr;
|
||||
|
||||
// Helper class used to pre-resolve all items in remote list.
|
||||
// This is useful in tun_persist mode, where it may be necessary
|
||||
// to pre-resolve all potential remote server items prior
|
||||
// to initial tunnel establishment.
|
||||
class PreResolve : public virtual RC<thread_unsafe_refcount>, AsyncResolvableTCP
|
||||
{
|
||||
public:
|
||||
typedef RCPtr<PreResolve> Ptr;
|
||||
|
||||
struct NotifyCallback
|
||||
{
|
||||
// client callback when resolve operation is complete
|
||||
virtual void pre_resolve_done() = 0;
|
||||
};
|
||||
|
||||
PreResolve(openvpn_io::io_context& io_context_arg,
|
||||
const RemoteList::Ptr& remote_list_arg,
|
||||
const SessionStats::Ptr& stats_arg)
|
||||
: AsyncResolvableTCP(io_context_arg),
|
||||
notify_callback(nullptr),
|
||||
remote_list(remote_list_arg),
|
||||
stats(stats_arg),
|
||||
index(0)
|
||||
{
|
||||
}
|
||||
|
||||
bool work_available() const
|
||||
{
|
||||
return remote_list->defined() && remote_list->enable_cache;
|
||||
}
|
||||
|
||||
void start(NotifyCallback* notify_callback_arg)
|
||||
{
|
||||
if (notify_callback_arg)
|
||||
{
|
||||
// This method is a no-op (i.e. pre_resolve_done is called immediately)
|
||||
// if caching not enabled in underlying remote_list or if start() was
|
||||
// previously called and is still in progress.
|
||||
if (!notify_callback && work_available())
|
||||
{
|
||||
notify_callback = notify_callback_arg;
|
||||
remote_list->index.reset();
|
||||
index = 0;
|
||||
async_resolve_lock();
|
||||
next();
|
||||
}
|
||||
else
|
||||
notify_callback_arg->pre_resolve_done();
|
||||
}
|
||||
}
|
||||
|
||||
void cancel()
|
||||
{
|
||||
notify_callback = nullptr;
|
||||
index = 0;
|
||||
async_resolve_cancel();
|
||||
}
|
||||
|
||||
private:
|
||||
void next()
|
||||
{
|
||||
while (index < remote_list->list.size())
|
||||
{
|
||||
Item& item = *remote_list->list[index];
|
||||
|
||||
// try to resolve item if no cached data present
|
||||
if (!item.res_addr_list_defined())
|
||||
{
|
||||
// next item to resolve
|
||||
const Item* sitem = remote_list->search_server_host(item.server_host);
|
||||
if (sitem)
|
||||
{
|
||||
// item's server_host matches one previously resolved -- use it
|
||||
OPENVPN_LOG_REMOTELIST("*** PreResolve USED CACHE for " << item.server_host);
|
||||
item.res_addr_list = sitem->res_addr_list;
|
||||
}
|
||||
else
|
||||
{
|
||||
OPENVPN_LOG_REMOTELIST("*** PreResolve RESOLVE on " << item.server_host << " : " << item.server_port);
|
||||
async_resolve_name(item.server_host, item.server_port);
|
||||
return;
|
||||
}
|
||||
}
|
||||
++index;
|
||||
}
|
||||
|
||||
// Done resolving list. Prune out all entries we were unable to
|
||||
// resolve unless doing so would result in an empty list.
|
||||
// Then call client's callback method.
|
||||
{
|
||||
async_resolve_cancel();
|
||||
NotifyCallback* ncb = notify_callback;
|
||||
if (remote_list->cached_item_exists())
|
||||
remote_list->prune_uncached();
|
||||
cancel();
|
||||
ncb->pre_resolve_done();
|
||||
}
|
||||
}
|
||||
|
||||
// callback on resolve completion
|
||||
void resolve_callback(const openvpn_io::error_code& error,
|
||||
openvpn_io::ip::tcp::resolver::results_type results) override
|
||||
{
|
||||
if (notify_callback && index < remote_list->list.size())
|
||||
{
|
||||
Item& item = *remote_list->list[index++];
|
||||
if (!error)
|
||||
{
|
||||
// resolve succeeded
|
||||
item.set_endpoint_range(results, remote_list->rng.get());
|
||||
}
|
||||
else
|
||||
{
|
||||
// resolve failed
|
||||
OPENVPN_LOG("DNS pre-resolve error on " << item.server_host << ": " << error.message());
|
||||
if (stats)
|
||||
stats->error(Error::RESOLVE_ERROR);
|
||||
}
|
||||
next();
|
||||
}
|
||||
}
|
||||
|
||||
NotifyCallback* notify_callback;
|
||||
RemoteList::Ptr remote_list;
|
||||
SessionStats::Ptr stats;
|
||||
size_t index;
|
||||
};
|
||||
|
||||
// create an empty remote list
|
||||
RemoteList()
|
||||
{
|
||||
init("");
|
||||
}
|
||||
|
||||
// create a remote list with a RemoteOverride callback
|
||||
RemoteList(RemoteOverride* remote_override_arg)
|
||||
: remote_override(remote_override_arg)
|
||||
{
|
||||
init("");
|
||||
next();
|
||||
}
|
||||
|
||||
// create a remote list with exactly one item
|
||||
RemoteList(const std::string& server_host,
|
||||
const std::string& server_port,
|
||||
const Protocol& transport_protocol,
|
||||
const std::string& title)
|
||||
{
|
||||
init("");
|
||||
|
||||
HostPort::validate_port(server_port, title);
|
||||
|
||||
Item::Ptr item(new Item());
|
||||
item->server_host = server_host;
|
||||
item->server_port = server_port;
|
||||
item->transport_protocol = transport_protocol;
|
||||
list.push_back(item);
|
||||
}
|
||||
|
||||
// RemoteList flags
|
||||
enum {
|
||||
WARN_UNSUPPORTED=1<<0,
|
||||
CONN_BLOCK_ONLY=1<<1,
|
||||
CONN_BLOCK_OMIT_UNDEF=1<<2,
|
||||
ALLOW_EMPTY=1<<3,
|
||||
};
|
||||
|
||||
// create a remote list from config file option list
|
||||
RemoteList(const OptionList& opt,
|
||||
const std::string& connection_tag,
|
||||
const unsigned int flags,
|
||||
ConnBlockFactory* conn_block_factory)
|
||||
{
|
||||
init(connection_tag);
|
||||
|
||||
// defaults
|
||||
Protocol default_proto(Protocol::UDPv4);
|
||||
std::string default_port = "1194";
|
||||
|
||||
// handle remote, port, and proto at the top-level
|
||||
if (!(flags & CONN_BLOCK_ONLY))
|
||||
add(opt, default_proto, default_port, ConnBlock::Ptr());
|
||||
|
||||
// cycle through <connection> blocks
|
||||
{
|
||||
const size_t max_conn_block_size = 4096;
|
||||
const OptionList::IndexList* conn = opt.get_index_ptr(directives.connection);
|
||||
if (conn)
|
||||
{
|
||||
for (OptionList::IndexList::const_iterator i = conn->begin(); i != conn->end(); ++i)
|
||||
{
|
||||
try {
|
||||
const Option& o = opt[*i];
|
||||
o.touch();
|
||||
const std::string& conn_block_text = o.get(1, Option::MULTILINE);
|
||||
OptionList::Limits limits("<connection> block is too large",
|
||||
max_conn_block_size,
|
||||
ProfileParseLimits::OPT_OVERHEAD,
|
||||
ProfileParseLimits::TERM_OVERHEAD,
|
||||
ProfileParseLimits::MAX_LINE_SIZE,
|
||||
ProfileParseLimits::MAX_DIRECTIVE_SIZE);
|
||||
OptionList::Ptr conn_block = OptionList::parse_from_config_static_ptr(conn_block_text, &limits);
|
||||
Protocol proto(default_proto);
|
||||
std::string port(default_port);
|
||||
|
||||
// unsupported options
|
||||
if (flags & WARN_UNSUPPORTED)
|
||||
{
|
||||
unsupported_in_connection_block(*conn_block, "http-proxy");
|
||||
unsupported_in_connection_block(*conn_block, "http-proxy-option");
|
||||
unsupported_in_connection_block(*conn_block, "http-proxy-user-pass");
|
||||
}
|
||||
|
||||
// connection block options encapsulation via user-defined factory
|
||||
{
|
||||
ConnBlock::Ptr cb;
|
||||
if (conn_block_factory)
|
||||
cb = conn_block_factory->new_conn_block(conn_block);
|
||||
if (!(flags & CONN_BLOCK_OMIT_UNDEF) || cb)
|
||||
add(*conn_block, proto, port, cb);
|
||||
}
|
||||
}
|
||||
catch (Exception& e)
|
||||
{
|
||||
e.remove_label("option_error");
|
||||
e.add_label("connection_block");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!(flags & ALLOW_EMPTY) && list.empty())
|
||||
throw option_error("remote option not specified");
|
||||
|
||||
//OPENVPN_LOG(to_string());
|
||||
}
|
||||
|
||||
// if cache is enabled, all DNS names will be preemptively queried
|
||||
void set_enable_cache(const bool enable_cache_arg)
|
||||
{
|
||||
enable_cache = enable_cache_arg;
|
||||
}
|
||||
|
||||
bool get_enable_cache() const
|
||||
{
|
||||
return enable_cache;
|
||||
}
|
||||
|
||||
// override all server hosts to server_override
|
||||
void set_server_override(const std::string& server_override)
|
||||
{
|
||||
if (server_override.empty())
|
||||
return;
|
||||
for (auto &item : list)
|
||||
{
|
||||
item->server_host = server_override;
|
||||
item->res_addr_list.reset();
|
||||
}
|
||||
reset_cache();
|
||||
}
|
||||
|
||||
// override all server ports to port_override
|
||||
void set_port_override(const std::string& port_override)
|
||||
{
|
||||
if (port_override.empty())
|
||||
return;
|
||||
for (auto &item : list)
|
||||
{
|
||||
item->server_port = port_override;
|
||||
item->res_addr_list.reset();
|
||||
}
|
||||
reset_cache();
|
||||
}
|
||||
|
||||
void set_random(const RandomAPI::Ptr& rng_arg)
|
||||
{
|
||||
rng = rng_arg;
|
||||
}
|
||||
|
||||
// randomize item list, used to implement remote-random directive
|
||||
void randomize()
|
||||
{
|
||||
if (rng)
|
||||
{
|
||||
std::shuffle(list.begin(), list.end(), *rng);
|
||||
index.reset();
|
||||
}
|
||||
}
|
||||
|
||||
// return true if at least one remote entry is of type proto
|
||||
bool contains_protocol(const Protocol& proto)
|
||||
{
|
||||
for (std::vector<Item::Ptr>::const_iterator i = list.begin(); i != list.end(); ++i)
|
||||
{
|
||||
if (proto.transport_match((*i)->transport_protocol))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Higher-level version of set_proto_override that also supports indication
|
||||
// on whether or not TCP-based proxies are enabled. Should be called after set_enable_cache
|
||||
// because it may modify enable_cache flag.
|
||||
void handle_proto_override(const Protocol& proto_override, const bool tcp_proxy_enabled)
|
||||
{
|
||||
if (tcp_proxy_enabled)
|
||||
{
|
||||
const Protocol tcp(Protocol::TCP);
|
||||
if (contains_protocol(tcp))
|
||||
set_proto_override(tcp);
|
||||
else
|
||||
throw option_error("cannot connect via TCP-based proxy because no TCP server entries exist in profile");
|
||||
}
|
||||
else if (proto_override.defined() && contains_protocol(proto_override))
|
||||
set_proto_override(proto_override);
|
||||
}
|
||||
|
||||
// increment to next IP address
|
||||
void next()
|
||||
{
|
||||
if (remote_override)
|
||||
{
|
||||
Item::Ptr item = remote_override->get();
|
||||
if (item)
|
||||
{
|
||||
list.clear();
|
||||
index.reset();
|
||||
list.push_back(std::move(item));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
index.increment(list.size(), secondary_length(index.primary()));
|
||||
if (!enable_cache)
|
||||
reset_item(index.primary());
|
||||
}
|
||||
|
||||
// Return details about current connection entry.
|
||||
// Return value is true if get_endpoint may be called
|
||||
// without raising an exception.
|
||||
bool endpoint_available(std::string* server_host, std::string* server_port, Protocol* transport_protocol) const
|
||||
{
|
||||
const Item& item = *list[primary_index()];
|
||||
if (server_host)
|
||||
*server_host = item.server_host;
|
||||
if (server_port)
|
||||
*server_port = item.server_port;
|
||||
const bool cached = (item.res_addr_list && index.secondary() < item.res_addr_list->size());
|
||||
if (transport_protocol)
|
||||
{
|
||||
if (cached)
|
||||
{
|
||||
// Since we know whether resolved address is IPv4 or IPv6, add
|
||||
// that info to the returned Protocol object.
|
||||
Protocol proto(item.transport_protocol);
|
||||
proto.mod_addr_version((*item.res_addr_list)[index.secondary()]->addr);
|
||||
*transport_protocol = proto;
|
||||
}
|
||||
else
|
||||
*transport_protocol = item.transport_protocol;
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
|
||||
// cache a list of DNS-resolved IP addresses
|
||||
template <class EPRANGE>
|
||||
void set_endpoint_range(EPRANGE& endpoint_range)
|
||||
{
|
||||
Item& item = *list[primary_index()];
|
||||
item.set_endpoint_range(endpoint_range, rng.get());
|
||||
index.reset_secondary();
|
||||
}
|
||||
|
||||
// get an endpoint for contacting server
|
||||
template <class EP>
|
||||
void get_endpoint(EP& endpoint) const
|
||||
{
|
||||
const Item& item = *list[primary_index()];
|
||||
if (!item.get_endpoint(endpoint, index.secondary()))
|
||||
throw remote_list_error("current remote server endpoint is undefined");
|
||||
}
|
||||
|
||||
// return true if object has at least one connection entry
|
||||
bool defined() const { return list.size() > 0; }
|
||||
|
||||
// return remote list size
|
||||
size_t size() const { return list.size(); }
|
||||
|
||||
const Item& get_item(const size_t index) const
|
||||
{
|
||||
return *list.at(index);
|
||||
}
|
||||
|
||||
// return hostname (or IP address) of current connection entry
|
||||
const std::string& current_server_host() const
|
||||
{
|
||||
const Item& item = *list[primary_index()];
|
||||
return item.server_host;
|
||||
}
|
||||
|
||||
// return transport protocol of current connection entry
|
||||
const Protocol& current_transport_protocol() const
|
||||
{
|
||||
const Item& item = *list[primary_index()];
|
||||
return item.transport_protocol;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
typename T::Ptr current_conn_block() const
|
||||
{
|
||||
const Item& item = *list[primary_index()];
|
||||
return item.conn_block.template dynamic_pointer_cast<T>();
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
T* current_conn_block_rawptr() const
|
||||
{
|
||||
const Item& item = *list[primary_index()];
|
||||
return dynamic_cast<T*>(item.conn_block.get());
|
||||
}
|
||||
|
||||
// return hostname (or IP address) of first connection entry
|
||||
std::string first_server_host() const
|
||||
{
|
||||
const Item& item = *list.at(0);
|
||||
return item.server_host;
|
||||
}
|
||||
|
||||
const Item* first_item() const
|
||||
{
|
||||
if (defined())
|
||||
return list[0].get();
|
||||
else
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::string to_string() const
|
||||
{
|
||||
std::ostringstream out;
|
||||
for (size_t i = 0; i < list.size(); ++i)
|
||||
{
|
||||
const Item& e = *list[i];
|
||||
out << '[' << i << "] " << e.to_string() << std::endl;
|
||||
}
|
||||
return out.str();
|
||||
}
|
||||
|
||||
// return a list of unique, cached IP addresses
|
||||
void cached_ip_address_list(IP::AddrList& addrlist) const
|
||||
{
|
||||
for (std::vector<Item::Ptr>::const_iterator i = list.begin(); i != list.end(); ++i)
|
||||
{
|
||||
const Item& item = **i;
|
||||
if (item.res_addr_list_defined())
|
||||
{
|
||||
const ResolvedAddrList& ral = *item.res_addr_list;
|
||||
for (ResolvedAddrList::const_iterator j = ral.begin(); j != ral.end(); ++j)
|
||||
{
|
||||
const ResolvedAddr& addr = **j;
|
||||
addrlist.add(addr.addr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// reset the cache associated with all items
|
||||
void reset_cache()
|
||||
{
|
||||
for (auto &e : list)
|
||||
e->res_addr_list.reset(nullptr);
|
||||
index.reset();
|
||||
}
|
||||
|
||||
// if caching is disabled, reset the cache for current item
|
||||
void reset_cache_item()
|
||||
{
|
||||
if (!enable_cache)
|
||||
reset_item(index.primary());
|
||||
}
|
||||
|
||||
private:
|
||||
// initialization, called by constructors
|
||||
void init(const std::string& connection_tag)
|
||||
{
|
||||
enable_cache = false;
|
||||
directives.init(connection_tag);
|
||||
}
|
||||
|
||||
// reset the cache associated with a given item
|
||||
void reset_item(const size_t i)
|
||||
{
|
||||
if (i <= list.size())
|
||||
list[i]->res_addr_list.reset(nullptr);
|
||||
}
|
||||
|
||||
// return the current primary index (into list) and raise an exception
|
||||
// if it is undefined
|
||||
size_t primary_index() const
|
||||
{
|
||||
const size_t pri = index.primary();
|
||||
if (pri < list.size())
|
||||
return pri;
|
||||
else
|
||||
throw remote_list_error("current remote server item is undefined");
|
||||
}
|
||||
|
||||
// return the number of cached IP addresses associated with a given item
|
||||
size_t secondary_length(const size_t i) const
|
||||
{
|
||||
if (i < list.size())
|
||||
{
|
||||
const Item& item = *list[i];
|
||||
if (item.res_addr_list)
|
||||
return item.res_addr_list->size();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Search for cached Item by server_host
|
||||
Item* search_server_host(const std::string& server_host)
|
||||
{
|
||||
for (std::vector<Item::Ptr>::iterator i = list.begin(); i != list.end(); ++i)
|
||||
{
|
||||
Item* item = i->get();
|
||||
if (server_host == item->server_host && item->res_addr_list_defined())
|
||||
return item;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// prune remote entries so that only those of Protocol proto_override remain
|
||||
void set_proto_override(const Protocol& proto_override)
|
||||
{
|
||||
if (proto_override.defined())
|
||||
{
|
||||
size_t di = 0;
|
||||
for (size_t si = 0; si < list.size(); ++si)
|
||||
{
|
||||
const Item& item = *list[si];
|
||||
if (proto_override.transport_match(item.transport_protocol))
|
||||
{
|
||||
if (si != di)
|
||||
list[di] = list[si];
|
||||
++di;
|
||||
}
|
||||
}
|
||||
if (di != list.size())
|
||||
list.resize(di);
|
||||
reset_cache();
|
||||
}
|
||||
}
|
||||
|
||||
// Return true if at least one cached Item exists
|
||||
bool cached_item_exists() const
|
||||
{
|
||||
for (std::vector<Item::Ptr>::const_iterator i = list.begin(); i != list.end(); ++i)
|
||||
{
|
||||
const Item& item = **i;
|
||||
if (item.res_addr_list_defined())
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Prune uncached Items so that only Items containing a res_addr_list with
|
||||
// size > 0 remain.
|
||||
void prune_uncached()
|
||||
{
|
||||
size_t di = 0;
|
||||
for (size_t si = 0; si < list.size(); ++si)
|
||||
{
|
||||
const Item& item = *list[si];
|
||||
if (item.res_addr_list_defined())
|
||||
{
|
||||
if (si != di)
|
||||
list[di] = list[si];
|
||||
++di;
|
||||
}
|
||||
}
|
||||
if (di != list.size())
|
||||
list.resize(di);
|
||||
index.reset();
|
||||
}
|
||||
|
||||
void add(const OptionList& opt, Protocol& default_proto, std::string& default_port, ConnBlock::Ptr conn_block)
|
||||
{
|
||||
// parse "proto" option if present
|
||||
{
|
||||
const Option* o = opt.get_ptr(directives.proto);
|
||||
if (o)
|
||||
default_proto = Protocol::parse(o->get(1, 16), Protocol::CLIENT_SUFFIX);
|
||||
}
|
||||
|
||||
// parse "port" option if present
|
||||
{
|
||||
const Option* o = opt.get_ptr(directives.port);
|
||||
if (o)
|
||||
{
|
||||
default_port = o->get(1, 16);
|
||||
HostPort::validate_port(default_port, directives.port);
|
||||
}
|
||||
}
|
||||
|
||||
// cycle through remote entries
|
||||
{
|
||||
const OptionList::IndexList* rem = opt.get_index_ptr(directives.remote);
|
||||
if (rem)
|
||||
{
|
||||
for (OptionList::IndexList::const_iterator i = rem->begin(); i != rem->end(); ++i)
|
||||
{
|
||||
Item::Ptr e(new Item());
|
||||
const Option& o = opt[*i];
|
||||
o.touch();
|
||||
e->server_host = o.get(1, 256);
|
||||
int adj = 0;
|
||||
if (o.size() >= 3)
|
||||
{
|
||||
e->server_port = o.get(2, 16);
|
||||
if (Protocol::is_local_type(e->server_port))
|
||||
{
|
||||
adj = -1;
|
||||
e->server_port = "";
|
||||
}
|
||||
else
|
||||
HostPort::validate_port(e->server_port, directives.port);
|
||||
}
|
||||
else
|
||||
e->server_port = default_port;
|
||||
if (o.size() >= (size_t)(4+adj))
|
||||
e->transport_protocol = Protocol::parse(o.get(3+adj, 16), Protocol::CLIENT_SUFFIX);
|
||||
else
|
||||
e->transport_protocol = default_proto;
|
||||
e->conn_block = conn_block;
|
||||
if (conn_block)
|
||||
conn_block->new_item(*e);
|
||||
list.push_back(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void unsupported_in_connection_block(const OptionList& options, const std::string& option)
|
||||
{
|
||||
if (options.exists(option))
|
||||
OPENVPN_LOG("NOTE: " << option << " directive is not currently supported in <connection> blocks");
|
||||
}
|
||||
|
||||
bool enable_cache;
|
||||
Index index;
|
||||
|
||||
std::vector<Item::Ptr> list;
|
||||
|
||||
Directives directives;
|
||||
|
||||
RemoteOverride* remote_override = nullptr;
|
||||
|
||||
RandomAPI::Ptr rng;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,158 @@
|
||||
// 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/>.
|
||||
|
||||
// This class handles parsing and representation of redirect-gateway
|
||||
// and redirect-private directives.
|
||||
|
||||
#ifndef OPENVPN_CLIENT_RGOPT_H
|
||||
#define OPENVPN_CLIENT_RGOPT_H
|
||||
|
||||
#include <openvpn/common/options.hpp>
|
||||
|
||||
namespace openvpn {
|
||||
class RedirectGatewayFlags {
|
||||
public:
|
||||
enum Flags {
|
||||
RG_ENABLE = (1<<0),
|
||||
RG_REROUTE_GW = (1<<1),
|
||||
RG_LOCAL = (1<<2),
|
||||
RG_AUTO_LOCAL = (1<<3),
|
||||
RG_DEF1 = (1<<4),
|
||||
RG_BYPASS_DHCP = (1<<5),
|
||||
RG_BYPASS_DNS = (1<<6),
|
||||
RG_BLOCK_LOCAL = (1<<7),
|
||||
RG_IPv4 = (1<<8),
|
||||
RG_IPv6 = (1<<9),
|
||||
|
||||
RG_DEFAULT = (RG_IPv4),
|
||||
};
|
||||
|
||||
RedirectGatewayFlags() : flags_(RG_DEFAULT) {}
|
||||
|
||||
RedirectGatewayFlags(unsigned int flags) : flags_(flags) {}
|
||||
|
||||
explicit RedirectGatewayFlags(const OptionList& opt)
|
||||
{
|
||||
init(opt);
|
||||
}
|
||||
|
||||
void init(const OptionList& opt)
|
||||
{
|
||||
flags_ = RG_DEFAULT;
|
||||
doinit(opt, "redirect-gateway", true); // DIRECTIVE
|
||||
doinit(opt, "redirect-private", false); // DIRECTIVE
|
||||
}
|
||||
|
||||
unsigned int operator()() const { return flags_; }
|
||||
|
||||
bool redirect_gateway_ipv4_enabled() const
|
||||
{
|
||||
return rg_enabled() && (flags_ & RG_IPv4);
|
||||
}
|
||||
|
||||
bool redirect_gateway_ipv6_enabled() const
|
||||
{
|
||||
return rg_enabled() && (flags_ & RG_IPv6);
|
||||
}
|
||||
|
||||
std::string to_string() const
|
||||
{
|
||||
std::string ret;
|
||||
ret += "[ ";
|
||||
if (flags_ & RG_ENABLE)
|
||||
ret += "ENABLE ";
|
||||
if (flags_ & RG_REROUTE_GW)
|
||||
ret += "REROUTE_GW ";
|
||||
if (flags_ & RG_LOCAL)
|
||||
ret += "LOCAL ";
|
||||
if (flags_ & RG_AUTO_LOCAL)
|
||||
ret += "AUTO_LOCAL ";
|
||||
if (flags_ & RG_DEF1)
|
||||
ret += "DEF1 ";
|
||||
if (flags_ & RG_BYPASS_DHCP)
|
||||
ret += "BYPASS_DHCP ";
|
||||
if (flags_ & RG_BYPASS_DNS)
|
||||
ret += "BYPASS_DNS ";
|
||||
if (flags_ & RG_BLOCK_LOCAL)
|
||||
ret += "BLOCK_LOCAL ";
|
||||
if (flags_ & RG_IPv4)
|
||||
ret += "IPv4 ";
|
||||
if (flags_ & RG_IPv6)
|
||||
ret += "IPv6 ";
|
||||
ret += "]";
|
||||
return ret;
|
||||
}
|
||||
|
||||
private:
|
||||
bool rg_enabled() const
|
||||
{
|
||||
return (flags_ & (RG_ENABLE|RG_REROUTE_GW)) == (RG_ENABLE|RG_REROUTE_GW);
|
||||
}
|
||||
|
||||
void doinit(const OptionList& opt, const std::string& directive, const bool redirect_gateway)
|
||||
{
|
||||
OptionList::IndexMap::const_iterator rg = opt.map().find(directive);
|
||||
if (rg != opt.map().end())
|
||||
add_flags(opt, rg->second, redirect_gateway);
|
||||
}
|
||||
|
||||
void add_flags(const OptionList& opt, const OptionList::IndexList& idx, const bool redirect_gateway)
|
||||
{
|
||||
flags_ |= RG_ENABLE;
|
||||
if (redirect_gateway)
|
||||
flags_ |= RG_REROUTE_GW;
|
||||
else
|
||||
flags_ &= ~RG_REROUTE_GW;
|
||||
for (OptionList::IndexList::const_iterator i = idx.begin(); i != idx.end(); ++i)
|
||||
{
|
||||
const Option& o = opt[*i];
|
||||
for (size_t j = 1; j < o.size(); ++j)
|
||||
{
|
||||
const std::string& f = o.get(j, 64);
|
||||
if (f == "local")
|
||||
flags_ |= RG_LOCAL;
|
||||
else if (f == "autolocal")
|
||||
flags_ |= RG_AUTO_LOCAL;
|
||||
else if (f == "def1")
|
||||
flags_ |= RG_DEF1;
|
||||
else if (f == "bypass-dhcp")
|
||||
flags_ |= RG_BYPASS_DHCP;
|
||||
else if (f == "bypass-dns")
|
||||
flags_ |= RG_BYPASS_DNS;
|
||||
else if (f == "block-local")
|
||||
flags_ |= RG_BLOCK_LOCAL;
|
||||
else if (f == "ipv4")
|
||||
flags_ |= RG_IPv4;
|
||||
else if (f == "!ipv4")
|
||||
flags_ &= ~RG_IPv4;
|
||||
else if (f == "ipv6")
|
||||
flags_ |= RG_IPv6;
|
||||
else if (f == "!ipv6")
|
||||
flags_ &= ~RG_IPv6;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsigned int flags_;
|
||||
};
|
||||
}
|
||||
|
||||
#endif
|
||||
Reference in New Issue
Block a user