1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
|
// 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- OpenVPN Inc.
//
// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
//
// OpenVPN agent for Mac
// #define OPENVPN_EXIT_IN 30
// #define OPENVPN_SSL_DEBUG 9 // MbedTLS debugging max level
#include <iostream>
#include <string>
#include <utility>
#include <unistd.h>
// VERSION version can be passed on build command line
#include <openvpn/common/stringize.hpp>
#ifdef VERSION
#define HTTP_SERVER_VERSION OPENVPN_STRINGIZE(VERSION)
#else
#define HTTP_SERVER_VERSION "0.1.1"
#endif
#ifdef OVPNAGENT_NAME
#define OVPNAGENT_NAME_STRING OPENVPN_STRINGIZE(OVPNAGENT_NAME)
#else
#define OVPNAGENT_NAME_STRING "ovpnagent"
#endif
#include <openvpn/log/logbase.hpp>
#include <openvpn/common/platform.hpp>
#include <openvpn/common/size.hpp>
#include <openvpn/common/exception.hpp>
#include <openvpn/common/rc.hpp>
#include <openvpn/common/runcontext.hpp>
#include <openvpn/common/file.hpp>
#include <openvpn/common/getopt.hpp>
#include <openvpn/common/scoped_fd.hpp>
#include <openvpn/common/daemon.hpp>
#include <openvpn/common/waitbarrier.hpp>
#include <openvpn/common/usergroup.hpp>
#include <openvpn/common/xmitfd.hpp>
#include <openvpn/buffer/bufstr.hpp>
#include <openvpn/buffer/buflist.hpp>
#include <openvpn/init/initprocess.hpp>
#include <openvpn/ssl/sslchoose.hpp>
#include <openvpn/ws/httpserv.hpp>
#include <openvpn/tun/mac/client/tunsetup.hpp>
void log_version()
{
std::cout << "OpenVPN Agent (Mac) " HTTP_SERVER_VERSION " [" SSL_LIB_NAME "]"
#ifdef OPENVPN_DEBUG
<< " built on " __DATE__ " " __TIME__
#endif
<< std::endl;
}
using namespace openvpn;
class MySessionStats : public SessionStats
{
public:
typedef RCPtr<MySessionStats> Ptr;
void error(const size_t err_type, const std::string *text = nullptr) override
{
OPENVPN_LOG(Error::name(err_type));
}
std::string dump() const
{
std::ostringstream os;
os << "OpenVPN Agent Stats" << std::endl;
return os.str();
}
};
struct ThreadCommon
{
ThreadCommon(const char *unix_sock, const char *user, const char *group)
: listen_list(build_listen_list(unix_sock)),
user_group(user, group, true),
stats(new MySessionStats),
event_loop_bar(1)
{
}
static Listen::List build_listen_list(const char *unix_sock)
{
Listen::List ll;
if (unix_sock)
{
Listen::Item li;
li.directive = "http-listen";
li.addr = unix_sock;
li.proto = Protocol(Protocol::UnixStream);
li.n_threads = 1;
ll.push_back(std::move(li));
}
return ll;
}
void show_unused_options() const
{
}
const Listen::List listen_list;
const SetUserGroup user_group;
MySessionStats::Ptr stats;
PThreadBarrier event_loop_bar;
};
class MyListener : public WS::Server::Listener
{
// handles ungraceful exit of client and closes tun
class WatchdogThread : public RC<thread_safe_refcount>
{
private:
typedef RCPtr<WatchdogThread> Ptr;
friend class MyListener;
MyListener *parent;
public:
WatchdogThread(MyListener *parent_arg, openvpn_io::io_context &io_context_arg)
: parent(parent_arg), io_context(io_context_arg)
{
}
~WatchdogThread()
{
if (th.joinable())
{
OPENVPN_LOG("Reaping watchdog thread");
th.join();
}
}
// starts a thread which blocks until:
// - process with given pid exits
// - there is a data in pipe
void watch(pid_t pid)
{
if (client_pid != -1)
{
OPENVPN_LOG("Watchdog already set for pid " << client_pid << ", won't set for pid " << pid);
return;
}
OPENVPN_LOG("Setting up watchdog for pid " << pid << " exit notification");
// self-pipe trick to be able to interrupt wait when agent exits
if (pipe(fds) == -1)
{
OPENVPN_LOG("pipe() failed: " << strerror(errno));
return;
}
// make write nonblocking
fcntl(fds[1], F_SETFL, O_NONBLOCK);
kq = kqueue();
if (kq == -1)
{
OPENVPN_LOG("kqueue() failed: " << strerror(errno));
close_pipe_fds();
return;
}
// add pid exit and self-pipe read_fd to kevent changelist
struct kevent chlist[2];
EV_SET(&chlist[0], pid, EVFILT_PROC, EV_ADD | EV_RECEIPT, NOTE_EXIT, 0, NULL);
EV_SET(&chlist[1], fds[0], EVFILT_READ, EV_ADD, 0, 0, NULL);
if (kevent(kq, chlist, 2, NULL, 0, NULL) == -1)
{
OPENVPN_LOG("kevent() failed: " << strerror(errno));
close_pipe_fds();
return;
}
// reap thread if previous client didn't exit gracefullt
if (th.joinable())
{
OPENVPN_LOG("Reaping watchdog thread");
th.join();
}
client_pid = pid;
th = std::thread([self = Ptr(this), pid]()
{
struct kevent evlist[2];
int nev = kevent(self->kq, 0, 0, evlist, 2, NULL);
if (nev == -1)
{
OPENVPN_LOG("kevent() failed: " << strerror(errno));
self->close_pipe_fds();
return;
}
for (int i = 0; i < nev; ++ i)
{
if (evlist[i].filter == EVFILT_PROC)
{
openvpn_io::post(self->io_context, [self, pid]() {
OPENVPN_LOG("Process " << pid << " has exited, destroy tun");
std::ostringstream os;
self->parent->destroy_tun(os);
});
}
}
self->client_pid = -1;
self->close_pipe_fds(); });
}
void unwatch()
{
OPENVPN_LOG("Stopping watchdog thread");
write(fds[1], "x", 1);
if (th.joinable())
{
OPENVPN_LOG("Reaping watchdog thread");
th.join();
}
}
private:
void close_pipe_fds()
{
close(fds[0]);
close(fds[1]);
}
pid_t client_pid = -1;
openvpn_io::io_context &io_context;
int kq; // kqueue
int fds[2]; // file descriptors for self-pipe trick
std::thread th;
};
public:
typedef RCPtr<MyListener> Ptr;
MyListener(openvpn_io::io_context &io_context,
const WS::Server::Config::Ptr &config,
const Listen::List &listen_list,
const WS::Server::Listener::Client::Factory::Ptr &client_factory)
: WS::Server::Listener(io_context, config, listen_list, client_factory)
{
watchdog.reset(new WatchdogThread(this, io_context));
}
ScopedFD establish_tun(const TunBuilderCapture &tbc,
TunBuilderSetup::Config *config,
Stop *stop,
std::ostream &os)
{
if (!tun)
tun.reset(new TunMac::Setup);
return ScopedFD(tun->establish(tbc, config, stop, os));
}
void destroy_tun(std::ostream &os)
{
if (tun)
{
tun->destroy(os);
tun.reset();
}
remove_cmds_bypass_hosts.execute(os);
remove_cmds_bypass_hosts.clear();
bypass_host.clear();
}
void set_watchdog(pid_t pid)
{
watchdog->watch(pid);
}
void unset_watchdog()
{
watchdog->unwatch();
}
void add_bypass_route(const std::string &host, bool ipv6)
{
if (host != bypass_host)
{
bypass_host = host;
std::ostringstream os;
remove_cmds_bypass_hosts.execute(os);
remove_cmds_bypass_hosts.clear();
ActionList add_cmds;
TunMac::Setup::add_bypass_route(host, ipv6, add_cmds, remove_cmds_bypass_hosts);
add_cmds.execute(os);
OPENVPN_LOG(os.str());
}
}
private:
bool allow_client(AsioPolySock::Base &sock) override
{
return true;
}
std::string bypass_host;
ActionList remove_cmds_bypass_hosts;
TunMac::Setup::Ptr tun;
WatchdogThread::Ptr watchdog;
};
class MyClientInstance : public WS::Server::Listener::Client
{
public:
typedef RCPtr<MyClientInstance> Ptr;
MyClientInstance(WS::Server::Listener::Client::Initializer &ci)
: WS::Server::Listener::Client(ci)
{
}
virtual ~MyClientInstance() = default;
private:
void generate_reply(const Json::Value &jout)
{
out = buf_from_string(jout.toStyledString());
WS::Server::ContentInfo ci;
ci.http_status = HTTP::Status::OK;
ci.type = "application/json";
ci.length = out->size();
ci.keepalive = keepalive_request();
generate_reply_headers(ci);
}
void http_request_received() override
{
// alloc output buffer
std::ostringstream os;
try
{
const HTTP::Request &req = request();
OPENVPN_LOG("HTTP request received from " << sock->remote_endpoint_str() << '\n'
<< req.to_string());
// get content-type
const std::string content_type = req.headers.get_value_trim("content-type");
if (req.method == "POST")
{
// verify correct content-type
if (string::strcasecmp(content_type, "application/json"))
throw Exception("bad content-type");
// parse the json dict
const Json::Value root = json::parse(in.to_string(), "JSON request");
if (!root.isObject())
throw Exception("json parse error: top level json object is not a dictionary");
if (req.uri == "/tun-setup")
{
send_fd.reset();
// get PID
pid_t pid = json::get_int_optional(root, "pid", -1);
if (pid != -1)
parent()->set_watchdog(pid);
// parse JSON data into a TunBuilderCapture object
TunBuilderCapture::Ptr tbc = TunBuilderCapture::from_json(json::get_dict(root, "tun", false));
tbc->validate();
// get config
TunMac::Setup::Config config;
config.from_json(json::get_dict(root, "config", false), "config");
// establish the tun setup object
send_fd = parent()->establish_tun(*tbc, &config, nullptr, os);
// build JSON return dictionary
Json::Value jout(Json::objectValue);
jout["log_txt"] = Json::Value(string::remove_blanks(os.str()));
jout["config"] = config.to_json();
generate_reply(jout);
}
else if (req.uri == "/add-bypass-route")
{
pid_t pid = json::get_int_optional(root, "pid", -1);
if (pid != -1)
parent()->set_watchdog(pid);
bool ipv6 = json::get_bool(root, "ipv6");
std::string host = json::get_string(root, "host");
parent()->add_bypass_route(host, ipv6);
Json::Value jout(Json::objectValue);
generate_reply(jout);
}
}
else if (req.method == "GET" && req.uri == "/tun-destroy")
{
// destroy tun object
parent()->destroy_tun(os);
// build JSON return dictionary
Json::Value jout(Json::objectValue);
jout["log_txt"] = Json::Value(string::remove_blanks(os.str()));
generate_reply(jout);
}
else
{
out = buf_from_string("page not found\n");
WS::Server::ContentInfo ci;
ci.http_status = HTTP::Status::NotFound;
ci.type = "text/plain";
ci.length = out->size();
generate_reply_headers(ci);
}
}
catch (const std::exception &e)
{
out = buf_from_string(string::remove_blanks(os.str() + e.what() + '\n'));
WS::Server::ContentInfo ci;
ci.http_status = HTTP::Status::BadRequest;
ci.type = "text/plain";
ci.length = out->size();
generate_reply_headers(ci);
}
}
void http_content_in(BufferAllocated &buf) override
{
if (buf.defined())
in.emplace_back(BufferAllocatedRc::Create(std::move(buf)));
}
BufferPtr http_content_out() override
{
BufferPtr ret;
ret.swap(out);
return ret;
}
// Normally true is returned, however return false if we
// are planning to send the tun file descriptor to the client.
bool http_out_eof() override
{
// OPENVPN_LOG("HTTP output EOF send_fd=" << send_fd());
return !send_fd.defined();
}
// After HTTP reply has been transmitted, wait for client to
// send a 't' message. On receipt, reply with a 'T' message
// that bundles the tun file descriptor.
void http_pipeline_peek(BufferAllocated &buf) override
{
// OPENVPN_LOG("HTTP PIPELINE PEEK send_fd=" << send_fd() << " CONTENT=" << buf_to_string(buf));
if (send_fd.defined())
{
if (buf.size() == 1 && buf.front() == 't')
{
const int fd = unix_fd();
if (fd < 0)
OPENVPN_THROW_EXCEPTION("http_pipeline_peek: not a unix socket");
XmitFD::xmit_fd(fd, send_fd(), "T", 5000);
external_stop("FD transmitted");
}
else
OPENVPN_THROW_EXCEPTION("bad FD request message");
}
}
bool http_stop(const int status, const std::string &description) override
{
OPENVPN_LOG("INSTANCE STOP : " << WS::Server::Status::error_str(status) << " : " << description);
// if the shutdown happened due to an unexpected error, the TUN status has
// to be cleaned up to avoid configuration inconsistency.
//
// A problem we have witnessed was that the DNS settings were not being
// reverted when the HTTP connection with the core was interrupted in the
// middle of the establish() call.
if (status != WS::Server::Status::E_SUCCESS
&& status != WS::Server::Status::E_EXTERNAL_STOP)
{
std::ostringstream os;
parent()->destroy_tun(os);
}
// returning true here triggers socket shutdown, which triggers "Socket is not connected" error
return false;
}
MyListener *parent()
{
return static_cast<MyListener *>(get_parent());
}
ScopedFD send_fd;
BufferList in;
BufferPtr out;
};
class MyClientFactory : public WS::Server::Listener::Client::Factory
{
public:
typedef RCPtr<MyClientFactory> Ptr;
WS::Server::Listener::Client::Ptr new_client(WS::Server::Listener::Client::Initializer &ci) override
{
return new MyClientInstance(ci);
}
};
class ServerThread : public ServerThreadBase
{
public:
typedef RCPtr<ServerThread> Ptr;
ServerThread(openvpn_io::io_context &io_context_arg,
ThreadCommon &tc)
: io_context(io_context_arg),
halt(false)
{
Frame::Ptr frame = frame_init_simple(2048);
WS::Server::Config::Ptr config = new WS::Server::Config();
config->http_server_id = OVPNAGENT_NAME_STRING "/" HTTP_SERVER_VERSION;
config->frame = frame;
config->stats = tc.stats;
config->unix_mode = 0777;
MyClientFactory::Ptr factory = new MyClientFactory();
listener.reset(new MyListener(io_context_arg, config, tc.listen_list, factory));
}
void start()
{
if (!halt)
{
listener->start();
}
}
void stop()
{
if (!halt)
{
halt = true;
listener->stop();
listener->unset_watchdog();
}
}
void thread_safe_stop() override
{
if (!halt)
{
openvpn_io::post(io_context, [self = Ptr(this)]()
{ self->stop(); });
}
}
private:
openvpn_io::io_context &io_context;
MyListener::Ptr listener;
bool halt;
};
typedef RunContext<ServerThreadBase, MySessionStats> MyRunContext;
void work(openvpn_io::io_context &io_context,
ThreadCommon &tc,
MyRunContext &runctx,
const unsigned int unit)
{
ServerThread::Ptr serv;
try
{
serv.reset(new ServerThread(io_context, tc));
runctx.set_server(unit, serv.get());
serv->start();
// barrier prior to event-loop entry
event_loop_wait_barrier(tc);
// privilege has now been downgraded
// run i/o reactor
io_context.run();
runctx.clear_server(unit);
serv->stop();
}
catch (...)
{
tc.event_loop_bar.error();
if (serv)
{
runctx.clear_server(unit);
serv->stop(); // on exception, stop server
}
io_context.poll(); // execute completion handlers
throw;
}
}
void worker_thread(ThreadCommon &tc,
MyRunContext &runctx,
const unsigned int unit)
{
SignalBlockerDefault signal_blocker;
openvpn_io::io_context io_context(1); // concurrency hint=1
Log::Context log_context(runctx.log_wrapper());
MyRunContext::ThreadContext thread_ctx(runctx);
try
{
work(io_context, tc, runctx, unit);
}
catch (const std::exception &e)
{
OPENVPN_LOG("Worker thread exception: " << e.what());
}
}
int ovpnagent(const char *sock_fn,
const char *log_fn,
const bool log_append,
const char *pid_fn,
const char *user,
const char *group)
{
if (log_fn)
daemonize(log_fn, nullptr, log_append, 0);
if (pid_fn)
write_pid(pid_fn);
log_version();
MyRunContext::Ptr runctx(new MyRunContext());
ThreadCommon tc(sock_fn, user, group);
// Give runctx visibility into global stats
// for SIGUSR2 dump.
runctx->set_stats_obj(tc.stats);
// Main worker thread
{
const unsigned int thread_num = 0;
std::thread *thread = new std::thread([&tc, &runctx]()
{ worker_thread(tc, *runctx, thread_num); });
runctx->set_thread(thread_num, thread);
}
// wait for worker to exit
runctx->run();
runctx->join();
// dump final stats
OPENVPN_LOG_NTNL(tc.stats->dump());
// remove pidfile
if (pid_fn)
::unlink(pid_fn);
return 0;
}
OPENVPN_SIMPLE_EXCEPTION(usage);
int main(int argc, char *argv[])
{
static const struct option longopts[] = {
{"help", no_argument, nullptr, 'h'},
{"append", no_argument, nullptr, 'a'},
{"daemon", required_argument, nullptr, 'd'},
{"pidfile", required_argument, nullptr, 'p'},
{"user", required_argument, nullptr, 'u'},
{"group", required_argument, nullptr, 'g'},
{nullptr, 0, nullptr, 0}};
int ret = 0;
bool append = false;
const char *logfile = nullptr;
const char *pidfile = nullptr;
const char *user = nullptr;
const char *group = nullptr;
// process-wide initialization
InitProcess::Init init;
// set global MbedTLS debug level
#if defined(USE_MBEDTLS) && defined(OPENVPN_SSL_DEBUG)
debug_set_threshold(OPENVPN_SSL_DEBUG);
#endif
try
{
if (argc < 1)
throw usage();
int ch;
while ((ch = getopt_long(argc, argv, "had:p:u:g:", longopts, nullptr)) != -1)
{
switch (ch)
{
case 'a':
append = true;
break;
case 'd':
logfile = optarg;
break;
case 'p':
pidfile = optarg;
break;
case 'u':
user = optarg;
break;
case 'g':
group = optarg;
break;
default:
throw usage();
}
}
argc -= optind;
argv += optind;
ret = ovpnagent("/var/run/" OVPNAGENT_NAME_STRING ".sock", logfile, append, pidfile, user, group);
}
catch (const usage &)
{
log_version();
std::cout << "usage: ovpnagent [options]" << std::endl;
std::cout << " --daemon <file>, -d : daemonize, log to file" << std::endl;
std::cout << " --append, -a : append to log file" << std::endl;
std::cout << " --pidfile <file>, -p : write pid to file" << std::endl;
std::cout << " --user <user>, -u : set UID to user" << std::endl;
std::cout << " --group <group>, -g : set group" << std::endl;
ret = 2;
}
catch (const std::exception &e)
{
std::cout << "Main thread exception: " << e.what() << std::endl;
ret = 1;
}
return ret;
}
|