Commit bbc22192 authored by Ivan Vilata-i-Balaguer's avatar Ivan Vilata-i-Balaguer
Browse files

Merge branch 'doh-client'.

This adds experimental support for resolving names using DNS over HTTPS (DoH)
for the Origin request mechanism.  To enable it, you must provide the client
with an `--origin-doh-base` option and give it a DoH base URL argument (like
`https://mozilla.cloudflare-dns.com/dns-query` as used by Mozilla, more
options [here](https://github.com/curl/curl/wiki/DNS-over-HTTPS)).

DoH requests are handled internally by the client and follow the usual request
routes, so they heed public/private browsing differences and enabled/disabled
request mechanisms.  This means that requests sent in private browsing mode
can use the Origin and Proxy mechanisms (thus staying private), and requests
sent in public mode can use Origin, Injector or Cache (and thus get retrieved
from others or cached and shared).

Separate DoH requests for both IPv4 and IPv6 addresses are always performed.
Entries cached by other clients can be fetched as long as they use the same
DoH base URL, IP version and stick to the minimal DNS query message (so that
they `GET` URLs match).

**Important note:** Results are not yet privately cached (beyond the
distributed cache), which means that each requested URL triggers a full DoH
request, which makes browsing quite slow.
parents 7bd4d4b4 6b954814
......@@ -121,6 +121,7 @@ file(GLOB client_sources
"./src/util/reachability.cpp"
"./src/util.cpp"
"./src/util/handler_tracker.cpp"
"./src/doh.cpp"
"./src/http_util.cpp"
${VERSION_CPP}
)
......@@ -140,6 +141,7 @@ target_link_libraries(client
Boost::iostreams
lib::asio_utp
cpp_upnp
lib::zdnsparser
lib::gcrypt
lib::json
lib::uri
......
......@@ -2,6 +2,7 @@
include(${CMAKE_CURRENT_LIST_DIR}/dependencies/openssl.cmake)
include(${CMAKE_CURRENT_LIST_DIR}/dependencies/boost.cmake)
include(${CMAKE_CURRENT_LIST_DIR}/dependencies/zdnsparser.cmake)
include(${CMAKE_CURRENT_LIST_DIR}/dependencies/gcrypt.cmake)
include(${CMAKE_CURRENT_LIST_DIR}/dependencies/golang.cmake)
include(${CMAKE_CURRENT_LIST_DIR}/dependencies/json.cmake)
......
include(ExternalProject)
set(ZDNSPARSER_FILENAME
"${CMAKE_CURRENT_BINARY_DIR}/zdnsparser/src/zdnsparser-build/lib/${CMAKE_STATIC_LIBRARY_PREFIX}zdnsparser${CMAKE_STATIC_LIBRARY_SUFFIX}"
)
set(PATCHES
${CMAKE_CURRENT_LIST_DIR}/zdnsparser/disable-tests.patch
${CMAKE_CURRENT_LIST_DIR}/zdnsparser/virtual-destructors.patch
)
set(PATCH_COMMAND
cd ${CMAKE_CURRENT_BINARY_DIR}/zdnsparser/src/zdnsparser
)
foreach (patch ${PATCHES})
set(PATCH_COMMAND ${PATCH_COMMAND} && patch -p1 -i ${patch})
endforeach()
externalproject_add(zdnsparser
# The specified commit supports answers with QNAME format,
# as indicated in <https://github.com/packetzero/dnsparser/pull/3>.
# Some DoH servers use the mentioned answer format.
GIT_REPOSITORY https://github.com/packetzero/dnsparser
GIT_TAG ad79c9b681f6afede9e9af8837159e1b2fbdb836
PATCH_COMMAND "${PATCH_COMMAND}"
UPDATE_COMMAND ""
INSTALL_COMMAND ""
CMAKE_ARGS
-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE}
-DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS}
-DCMAKE_MAKE_PROGRAM=${CMAKE_MAKE_PROGRAM}
-DANDROID_ABI=${ANDROID_ABI}
-DANDROID_PLATFORM=${ANDROID_PLATFORM}
BUILD_BYPRODUCTS ${ZDNSPARSER_FILENAME}
PREFIX "zdnsparser"
)
add_library(lib_zdnsparser INTERFACE)
add_dependencies(lib_zdnsparser zdnsparser)
add_library(lib::zdnsparser ALIAS lib_zdnsparser)
target_include_directories(lib_zdnsparser
INTERFACE
"${CMAKE_CURRENT_BINARY_DIR}/zdnsparser/src/zdnsparser/include"
)
target_link_libraries(lib_zdnsparser
INTERFACE ${ZDNSPARSER_FILENAME}
)
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 1fa1462..6e9e8d8 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -24,5 +24,4 @@ include(cmake/cxx_flag_overrides.cmake)
# subdirs
add_subdirectory(src)
-add_subdirectory(test)
diff --git a/include/dnsparser.h b/include/dnsparser.h
index 4d81ea3..5dfaa6c 100644
--- a/include/dnsparser.h
+++ b/include/dnsparser.h
@@ -18,6 +18,8 @@
class DnsParserListener
{
public:
+ virtual ~DnsParserListener() = default;
+
/**
* @param addr Binary IPV4 or IPV6 address in network order.
* @param name Domain name requested.
@@ -30,6 +32,8 @@ public:
class DnsParser
{
public:
+ virtual ~DnsParser() = default;
+
/**
* parse
* When response records are discovered, DnsParserListener.onDnsRec()
......@@ -26,6 +26,7 @@ json;Niels Lohmann;${BUILD}/json/src/json/LICENSE.MIT
uri;Glyn Matthews;${BUILD}/uri/src/uri/LICENSE_1_0.txt
asio-utp;Peter Jankuliak;${SRC}/modules/asio-utp/LICENSE.txt
lampshade;various;${BUILD}/src/ouiservice/lampshade/lampshade-prefix/src/lampshade/LICENSE
zdnsparser;various;${SRC}/scripts/licenses/Apache-2.0
"
echo "$LICENSE_DATA" | (
......
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
......@@ -15,6 +15,7 @@
#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/adaptor/indexed.hpp>
#include <boost/regex.hpp>
#include <iterator>
#include <iostream>
#include <cstdlib> // for atexit()
......@@ -22,6 +23,7 @@
#include "namespaces.h"
#include "origin_pools.h"
#include "doh.h"
#include "http_util.h"
#include "fetch_http_page.h"
#include "client_front_end.h"
......@@ -85,6 +87,7 @@ namespace bt = ouinet::bittorrent;
using tcp = asio::ip::tcp;
using Request = http::request<http::string_body>;
using Response = http::response<http::dynamic_body>;
using TcpLookup = tcp::resolver::results_type;
static const fs::path OUINET_CA_CERT_FILE = "ssl-ca-cert.pem";
static const fs::path OUINET_CA_KEY_FILE = "ssl-ca-key.pem";
......@@ -123,6 +126,15 @@ struct UserAgentMetaData {
return ret;
}
// Apply the metadata to the given request.
template<class Req>
void apply_to(Req& rq) const {
if (is_private && *is_private)
rq.set(http_::request_private_hdr, http_::request_private_true);
if (dht_group)
rq.set(http_::request_group_hdr, *dht_group);
}
};
//------------------------------------------------------------------------------
......@@ -232,8 +244,14 @@ private:
, Cancel& cancel
, Yield yield);
template<class Rq>
Session fetch_via_self( Rq, const UserAgentMetaData&
, Cancel&, Yield);
Response fetch_fresh_from_front_end(const Request&, Yield);
Session fetch_fresh_from_origin(const Request&, Cancel, Yield);
Session fetch_fresh_from_origin( const Request&
, const UserAgentMetaData&
, Cancel, Yield);
Session fetch_fresh_through_connect_proxy(const Request&, Cancel&, Yield);
......@@ -282,7 +300,17 @@ private:
, Request&
, Yield);
GenericStream connect_to_origin(const Request&, Cancel&, Yield);
// Resolve host and port strings.
TcpLookup resolve_tcp_dns( const std::string&, const std::string&
, Cancel&, Yield);
TcpLookup resolve_tcp_doh( const std::string&, const std::string&
, const UserAgentMetaData&
, const doh::Endpoint&
, Cancel&, Yield);
GenericStream connect_to_origin( const Request&
, const UserAgentMetaData&
, Cancel&, Yield);
unique_ptr<OuiServiceImplementationClient>
maybe_wrap_tls(unique_ptr<OuiServiceImplementationClient>);
......@@ -373,6 +401,7 @@ private:
// For debugging
uint64_t _next_connection_id = 0;
ConnectionPool<Endpoint> _injector_connections;
ConnectionPool<bool> _self_connections; // stored value is unused
OriginPools _origin_pools;
asio::ssl::context ssl_ctx;
......@@ -538,8 +567,195 @@ Client::State::fetch_stored_in_dcache( const Request& request
}
//------------------------------------------------------------------------------
template<class Rq>
Session
Client::State::fetch_via_self( Rq request, const UserAgentMetaData& meta
, Cancel& cancel, Yield yield)
{
sys::error_code ec;
// Connect to the client proxy port.
// TODO: Maybe refactor with `fetch_fresh_through_simple_proxy`.
ConnectionPool<bool>::Connection con;
if (_self_connections.empty()) {
if (log_transactions()) {
yield.log("Connecting to self");
}
// TODO: Keep lookup object or allow connecting to endpoint.
auto epl = TcpLookup::create(_config.local_endpoint(), "dummy", "dummy");
auto c = connect_to_host(epl, _ctx.get_executor(), cancel, yield[ec]);
assert(!cancel || ec == asio::error::operation_aborted);
if (ec) {
if (log_transactions()) {
yield.log("Failed to connect to self ec:", ec.message());
}
return or_throw<Session>(yield, ec);
}
con = _self_connections.wrap(std::move(c));
} else {
if (log_transactions()) {
yield.log("Reusing existing self connection");
}
con = _self_connections.pop_front();
}
auto cancel_slot = cancel.connect([&] {
con.close();
});
// Build the actual request to send to self.
if (!_config.client_credentials().empty())
request = authorize(request, _config.client_credentials());
request.keep_alive(true);
meta.apply_to(request);
if (log_transactions()) {
yield.log("Sending a request to self");
}
// Send request
http::async_write(con, request, yield[ec].tag("self-request"));
if (cancel_slot) {
ec = asio::error::operation_aborted;
}
if (ec && log_transactions()) {
yield.log("Failed to send request to self");
}
if (ec) return or_throw<Session>(yield, ec);
return Session::create(move(con), cancel, yield);
}
// Transforms addresses to endpoints with the given port.
template<class Addrs, class Endpoint>
class AddrsAsEndpoints {
public:
using value_type = Endpoint;
using addrs_iterator = typename Addrs::const_iterator;
AddrsAsEndpoints(const Addrs& addrs, unsigned short port)
: _addrs(addrs), _port(port)
{}
class const_iterator : public std::iterator<std::input_iterator_tag, value_type> {
public:
const_iterator(const addrs_iterator& it, unsigned short port)
: _it(it), _port(port)
{}
value_type operator*() const { return {*_it, _port}; }
const_iterator& operator++() { ++_it; return *this; }
bool operator==(const const_iterator& other) const { return _it == other._it; }
bool operator!=(const const_iterator& other) const { return _it != other._it; }
private:
addrs_iterator _it;
unsigned short _port;
};
const_iterator begin() const { return {_addrs.begin(), _port}; };
const_iterator end() const { return {_addrs.end(), _port}; };
private:
const Addrs& _addrs;
unsigned short _port;
};
TcpLookup
Client::State::resolve_tcp_doh( const std::string& host
, const std::string& port
, const UserAgentMetaData& meta
, const doh::Endpoint& ep
, Cancel& cancel
, Yield yield)
{
using TcpEndpoint = typename TcpLookup::endpoint_type;
boost::string_view portsv(port);
auto portn_o = parse::number<unsigned short>(portsv);
if (!portn_o) return or_throw<TcpLookup>(yield, asio::error::invalid_argument);
// Build and return lookup if `host` is already a network address.
{
sys::error_code e;
auto addr = asio::ip::make_address(host, e);
if (!e) return TcpLookup::create(TcpEndpoint{move(addr), *portn_o}, host, port);
}
// TODO: When to disable queries for IPv4 or IPv6 addresses?
auto rq4_o = doh::build_request_ipv4(host, ep);
auto rq6_o = doh::build_request_ipv6(host, ep);
if (!rq4_o || !rq6_o) return or_throw<TcpLookup>(yield, asio::error::invalid_argument);
sys::error_code ec4, ec6;
doh::Response rs4, rs6;
WaitCondition wc(_ctx);
// By passing user agent metadata as is,
// we ensure that the DoH request is done with the same browsing mode
// as the content request that triggered it,
// and is announced under the same group.
// TODO: Handle redirects.
#define SPAWN_QUERY(VER) \
TRACK_SPAWN(_ctx, ([ \
this, \
rq = move(*rq##VER##_o), &meta, &ec##VER, &rs##VER, \
&cancel, &yield, lock = wc.lock() \
] (asio::yield_context y_) { \
sys::error_code ec; \
auto y = yield.detach(y_); \
auto s = fetch_via_self(move(rq), meta, cancel, y[ec].tag("fetch##VER")); \
if (ec) { ec##VER = ec; return; } \
rs##VER = http_response::slurp_response<doh::Response::body_type> \
(s, doh::payload_size, cancel, y[ec].tag("slurp##VER")); \
if (ec) { ec##VER = ec; return; } \
}));
SPAWN_QUERY(4);
SPAWN_QUERY(6);
wc.wait(yield.tag("wait"));
if (log_transactions())
yield.log("DoH query ip4_ec:", ec4.message(), " ip6_ec:", ec6.message());
if (ec4 && ec6) return or_throw<TcpLookup>(yield, ec4 /* arbitrary */);
doh::Answers answers4, answers6;
if (!ec4) answers4 = doh::parse_response(rs4, host, ec4);
if (!ec6) answers6 = doh::parse_response(rs6, host, ec6);
if (log_transactions())
yield.log("DoH parse ip4_ec:", ec4.message(), " ip6_ec:", ec6.message());
if (ec4 && ec6) return or_throw<TcpLookup>(yield, ec4 /* arbitrary */);
answers4.insert( answers4.end()
, std::make_move_iterator(answers6.begin())
, std::make_move_iterator(answers6.end()));
AddrsAsEndpoints<doh::Answers, TcpEndpoint> eps{answers4, *portn_o};
return TcpLookup::create(eps.begin(), eps.end(), host, port);
}
TcpLookup
Client::State::resolve_tcp_dns( const std::string& host
, const std::string& port
, Cancel& cancel
, Yield yield)
{
return util::tcp_async_resolve( host, port
, _ctx.get_executor()
, cancel
, yield);
}
GenericStream
Client::State::connect_to_origin( const Request& rq
, const UserAgentMetaData& meta
, Cancel& cancel
, Yield yield)
{
......@@ -548,11 +764,15 @@ Client::State::connect_to_origin( const Request& rq
sys::error_code ec;
auto lookup = util::tcp_async_resolve( host, port
, _ctx.get_executor()
, cancel
, yield[ec]);
// Resolve using DoH if configured and not resolving the resolver's address itself.
auto doh_ep_o = _config.origin_doh_endpoint();
bool do_doh = doh_ep_o && !rq.target().starts_with(*doh_ep_o);
auto lookup = do_doh
? resolve_tcp_doh(host, port, meta, *doh_ep_o, cancel, yield[ec].tag("resolve_doh"))
: resolve_tcp_dns(host, port, cancel, yield[ec].tag("resolve_dns"));
if (log_transactions())
yield.log( do_doh ? "DoH name resolution: " : "DNS name resolution: "
, host, " naddrs=", lookup.size(), " ec:", ec.message());
return_or_throw_on_error(yield, cancel, ec, GenericStream());
auto sock = connect_to_host(lookup, _ctx.get_executor(), cancel, yield[ec]);
......@@ -603,7 +823,9 @@ Response Client::State::fetch_fresh_from_front_end(const Request& rq, Yield yiel
}
//------------------------------------------------------------------------------
Session Client::State::fetch_fresh_from_origin(const Request& rq, Cancel cancel, Yield yield)
Session Client::State::fetch_fresh_from_origin( const Request& rq
, const UserAgentMetaData& meta
, Cancel cancel, Yield yield)