blob: 4c9e3426b455344ac365e55a47185e10f1f17333 [file] [log] [blame]
Andreea Costinase45d54b2020-03-10 09:21:14 +01001// Copyright 2020 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "system-proxy/proxy_connect_job.h"
6
7#include <algorithm>
8#include <utility>
9#include <vector>
10
11#include <curl/curl.h>
12#include <curl/easy.h>
13
Andreea Costinase45d54b2020-03-10 09:21:14 +010014#include <base/base64.h>
15#include <base/bind.h>
16#include <base/bind_helpers.h>
17#include <base/callback_helpers.h>
18#include <base/files/file_util.h>
19#include <base/strings/stringprintf.h>
20#include <base/strings/string_split.h>
21#include <base/strings/string_util.h>
22#include <base/time/time.h>
Andreea Costinas08a5d182020-04-29 22:12:47 +020023#include <base/threading/thread.h>
24#include <base/threading/thread_task_runner_handle.h>
Andreea Costinase45d54b2020-03-10 09:21:14 +010025#include <brillo/http/http_transport.h>
Garrick Evanscd8c2972020-04-14 14:35:52 +090026#include <chromeos/patchpanel/net_util.h>
27#include <chromeos/patchpanel/socket.h>
28#include <chromeos/patchpanel/socket_forwarder.h>
Andreea Costinase45d54b2020-03-10 09:21:14 +010029
30#include "system-proxy/curl_socket.h"
31
32// The libarcnetwork-util library overloads << for socket data structures.
33// By C++'s argument-dependent lookup rules, operators defined in a
34// different namespace are not visible. We need the using directive to make
35// the overload available this namespace.
Garrick Evans3388a032020-03-24 11:25:55 +090036using patchpanel::operator<<;
Andreea Costinase45d54b2020-03-10 09:21:14 +010037
38namespace {
39// There's no RFC recomandation for the max size of http request headers but
40// popular http server implementations (Apache, IIS, Tomcat) set the lower limit
41// to 8000.
42constexpr int kMaxHttpRequestHeadersSize = 8000;
43constexpr char kConnectMethod[] = "CONNECT";
Andreea Costinase45d54b2020-03-10 09:21:14 +010044constexpr base::TimeDelta kCurlConnectTimeout = base::TimeDelta::FromMinutes(2);
Andreea Costinas08a5d182020-04-29 22:12:47 +020045constexpr base::TimeDelta kWaitClientConnectTimeout =
46 base::TimeDelta::FromMinutes(2);
Andreea Costinase45d54b2020-03-10 09:21:14 +010047constexpr size_t kMaxBadRequestPrintSize = 120;
Andreea Costinasa2246592020-04-12 23:24:01 +020048// This sequence is used to identify the end of a HTTP header which should be an
49// empty line. Note: all HTTP header lines end with CRLF. HTTP connect requests
50// don't have a body so end of header is end of request.
51const std::string_view kCrlfCrlf = "\r\n\r\n";
Andreea Costinase45d54b2020-03-10 09:21:14 +010052
53// HTTP error codes and messages with origin information for debugging (RFC723,
54// section 6.1).
55const std::string_view kHttpBadRequest =
56 "HTTP/1.1 400 Bad Request - Origin: local proxy\r\n\r\n";
Andreea Costinas08a5d182020-04-29 22:12:47 +020057const std::string_view kHttpConnectionTimeout =
58 "HTTP/1.1 408 Request Timeout - Origin: local proxy\r\n\r\n";
Andreea Costinase45d54b2020-03-10 09:21:14 +010059const std::string_view kHttpInternalServerError =
60 "HTTP/1.1 500 Internal Server Error - Origin: local proxy\r\n\r\n";
61const std::string_view kHttpBadGateway =
62 "HTTP/1.1 502 Bad Gateway - Origin: local proxy\r\n\r\n";
63
Andreea Costinasa2246592020-04-12 23:24:01 +020064// Verifies if the http headers are ending with an http empty line, meaning a
65// line that contains only CR LF preceded by a line ending with CRLF.
66bool IsEndingWithHttpEmptyLine(const char* headers, int headers_size) {
67 return headers_size > kCrlfCrlf.size() &&
68 std::memcmp(kCrlfCrlf.data(),
69 headers + headers_size - kCrlfCrlf.size(),
70 kCrlfCrlf.size()) == 0;
71}
72
73// CURLOPT_HEADERFUNCTION callback implementation that only returns the headers
74// from the last response sent by the sever. This is to make sure that we
75// send back valid HTTP replies and auhentication data from the HTTP messages is
76// not being leaked to the client. |userdata| is set on the libcurl CURL handle
77// used to configure the request, using the the CURLOPT_HEADERDATA option. Note,
78// from the libcurl documentation: This callback is being called for all the
79// responses received from the proxy server after intiating the connection
80// request. Multiple responses can be received in an authentication sequence.
81// Only the last response's headers should be forwarded to the System-proxy
82// client. The header callback will be called once for each header and only
83// complete header lines are passed on to the callback.
84static size_t WriteHeadersCallback(char* contents,
85 size_t size,
86 size_t nmemb,
87 void* userdata) {
88 std::vector<char>* vec = (std::vector<char>*)userdata;
89
90 // Check if we are receiving a new HTTP message (after the last one was
91 // terminated with an empty line).
92 if (IsEndingWithHttpEmptyLine(vec->data(), vec->size())) {
93 VLOG(1) << "Removing the http reply headers from the server "
94 << base::StringPiece(vec->data(), vec->size());
95 vec->clear();
Andreea Costinase45d54b2020-03-10 09:21:14 +010096 }
Andreea Costinasa2246592020-04-12 23:24:01 +020097 vec->insert(vec->end(), contents, contents + (nmemb * size));
Andreea Costinase45d54b2020-03-10 09:21:14 +010098 return size * nmemb;
99}
100
Andreea Costinasa2246592020-04-12 23:24:01 +0200101// CONNECT requests may have a reply body. This method will capture the reply
102// and save it in |userdata|. |userdata| is set on the libcurl CURL handle
103// used to configure the request, using the the CURLOPT_WRITEDATA option.
104static size_t WriteCallback(char* contents,
105 size_t size,
106 size_t nmemb,
107 void* userdata) {
108 std::vector<char>* vec = (std::vector<char>*)userdata;
109 vec->insert(vec->end(), contents, contents + (nmemb * size));
110 return size * nmemb;
111}
112
113// Parses the first line of the http CONNECT request and extracts the URI
114// authority, defined in RFC3986, section 3.2, as the host name and port number
115// separated by a colon. The destination URI is specified in the request line
116// (RFC2817, section 5.2):
Andreea Costinase45d54b2020-03-10 09:21:14 +0100117// CONNECT server.example.com:80 HTTP/1.1
118// If the first line in |raw_request| (the Request-Line) is a correctly formed
Andreea Costinasa2246592020-04-12 23:24:01 +0200119// CONNECT request, it will return the destination URI as host:port, otherwise
120// it will return an empty string.
121std::string GetUriAuthorityFromHttpHeader(
122 const std::vector<char>& raw_request) {
Andreea Costinase45d54b2020-03-10 09:21:14 +0100123 base::StringPiece request(raw_request.data(), raw_request.size());
124 // Request-Line ends with CRLF (RFC2616, section 5.1).
125 size_t i = request.find_first_of("\r\n");
126 if (i == base::StringPiece::npos)
127 return std::string();
128 // Elements are delimited by non-breaking space (SP).
129 auto pieces =
130 base::SplitString(request.substr(0, i), " ", base::TRIM_WHITESPACE,
131 base::SPLIT_WANT_NONEMPTY);
132 // Request-Line has the format: Method SP Request-URI SP HTTP-Version CRLF.
133 if (pieces.size() < 3)
134 return std::string();
135 if (pieces[0] != kConnectMethod)
136 return std::string();
137
Andreea Costinasa2246592020-04-12 23:24:01 +0200138 return pieces[1];
Andreea Costinase45d54b2020-03-10 09:21:14 +0100139}
140} // namespace
141
142namespace system_proxy {
143
144ProxyConnectJob::ProxyConnectJob(
Garrick Evans3388a032020-03-24 11:25:55 +0900145 std::unique_ptr<patchpanel::Socket> socket,
Andreea Costinase45d54b2020-03-10 09:21:14 +0100146 const std::string& credentials,
147 ResolveProxyCallback resolve_proxy_callback,
148 OnConnectionSetupFinishedCallback setup_finished_callback)
149 : credentials_(credentials),
150 resolve_proxy_callback_(std::move(resolve_proxy_callback)),
Andreea Costinas08a5d182020-04-29 22:12:47 +0200151 setup_finished_callback_(std::move(setup_finished_callback)),
152 // Safe to use |base::Unretained| because the callback will be canceled
153 // when it goes out of scope.
154 client_connect_timeout_callback_(base::Bind(
155 &ProxyConnectJob::OnClientConnectTimeout, base::Unretained(this))) {
Andreea Costinase45d54b2020-03-10 09:21:14 +0100156 client_socket_ = std::move(socket);
157}
158
159ProxyConnectJob::~ProxyConnectJob() = default;
160
161bool ProxyConnectJob::Start() {
162 // Make the socket non-blocking.
163 if (!base::SetNonBlocking(client_socket_->fd())) {
164 PLOG(ERROR) << *this << " Failed to mark the socket as non-blocking.";
165 client_socket_->SendTo(kHttpInternalServerError.data(),
166 kHttpInternalServerError.size());
167 return false;
168 }
Andreea Costinas08a5d182020-04-29 22:12:47 +0200169 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
170 FROM_HERE, client_connect_timeout_callback_.callback(),
171 kWaitClientConnectTimeout);
Andreea Costinase45d54b2020-03-10 09:21:14 +0100172 read_watcher_ = base::FileDescriptorWatcher::WatchReadable(
173 client_socket_->fd(),
174 base::Bind(&ProxyConnectJob::OnClientReadReady, base::Unretained(this)));
175 return true;
176}
177
178void ProxyConnectJob::OnClientReadReady() {
Andreea Costinas08a5d182020-04-29 22:12:47 +0200179 if (!read_watcher_) {
180 // The connection has timed out while waiting for the client's HTTP CONNECT
181 // request. See |OnClientConnectTimeout|.
182 return;
183 }
184 client_connect_timeout_callback_.Cancel();
Andreea Costinase45d54b2020-03-10 09:21:14 +0100185 // Stop watching.
186 read_watcher_.reset();
187 // The first message should be a HTTP CONNECT request.
188 std::vector<char> connect_request;
189 if (!TryReadHttpHeader(&connect_request)) {
190 std::string encoded;
191 base::Base64Encode(
192 base::StringPiece(connect_request.data(), connect_request.size()),
193 &encoded);
194 LOG(ERROR) << *this
195 << " Failure to read proxy CONNECT request. Base 64 encoded "
196 "request message from client: "
197 << encoded;
198 OnError(kHttpBadRequest);
199 return;
200 }
201
Andreea Costinasa2246592020-04-12 23:24:01 +0200202 target_url_ = GetUriAuthorityFromHttpHeader(connect_request);
Andreea Costinase45d54b2020-03-10 09:21:14 +0100203 if (target_url_.empty()) {
204 LOG(ERROR)
205 << *this
206 << " Failed to extract target url from the HTTP CONNECT request.";
207 OnError(kHttpBadRequest);
208 return;
209 }
210
Andreea Costinasa89309d2020-05-08 15:51:12 +0200211 // The proxy resolution service in Chrome expects a proper URL, formatted as
212 // scheme://host:port. It's safe to assume only https will be used for the
213 // target url.
Andreea Costinase45d54b2020-03-10 09:21:14 +0100214 std::move(resolve_proxy_callback_)
Andreea Costinasa89309d2020-05-08 15:51:12 +0200215 .Run(base::StringPrintf("https://%s", target_url_.c_str()),
216 base::Bind(&ProxyConnectJob::OnProxyResolution,
217 base::Unretained(this)));
Andreea Costinase45d54b2020-03-10 09:21:14 +0100218}
219
220bool ProxyConnectJob::TryReadHttpHeader(std::vector<char>* raw_request) {
Andreea Costinase45d54b2020-03-10 09:21:14 +0100221 size_t read_byte_count = 0;
222 raw_request->resize(kMaxHttpRequestHeadersSize);
223
224 // Read byte-by-byte and stop when reading an empty line (only CRLF) or when
225 // exceeding the max buffer size.
226 // TODO(acostinas, chromium:1064536) This may have some measurable performance
227 // impact. We should read larger blocks of data, consume the HTTP headers,
228 // cache the tunneled payload that may have already been included (e.g. TLS
229 // ClientHello) and send it to server after the connection is established.
230 while (read_byte_count < kMaxHttpRequestHeadersSize) {
231 if (client_socket_->RecvFrom(raw_request->data() + read_byte_count, 1) <=
232 0) {
233 raw_request->resize(std::min(read_byte_count, kMaxBadRequestPrintSize));
234 return false;
235 }
236 ++read_byte_count;
237
Andreea Costinasa2246592020-04-12 23:24:01 +0200238 if (IsEndingWithHttpEmptyLine(raw_request->data(), read_byte_count)) {
Andreea Costinase45d54b2020-03-10 09:21:14 +0100239 raw_request->resize(read_byte_count);
240 return true;
241 }
242 }
243 return false;
244}
245
246void ProxyConnectJob::OnProxyResolution(
247 const std::list<std::string>& proxy_servers) {
248 proxy_servers_ = proxy_servers;
249 DoCurlServerConnection(proxy_servers.front());
250}
251
252void ProxyConnectJob::DoCurlServerConnection(const std::string& proxy_url) {
253 CURL* easyhandle = curl_easy_init();
254 CURLcode res;
Andreea Costinasa2246592020-04-12 23:24:01 +0200255 curl_socket_t newSocket = -1;
256 std::vector<char> server_header_reply, server_body_reply;
Andreea Costinase45d54b2020-03-10 09:21:14 +0100257
258 if (!easyhandle) {
259 // Unfortunately it's not possible to get the failure reason.
260 LOG(ERROR) << *this << " Failure to create curl handle.";
261 curl_easy_cleanup(easyhandle);
262 OnError(kHttpInternalServerError);
263 return;
264 }
265 curl_easy_setopt(easyhandle, CURLOPT_URL, target_url_.c_str());
266
267 if (proxy_url != brillo::http::kDirectProxy) {
268 curl_easy_setopt(easyhandle, CURLOPT_PROXY, proxy_url.c_str());
269 curl_easy_setopt(easyhandle, CURLOPT_HTTPPROXYTUNNEL, 1L);
270 curl_easy_setopt(easyhandle, CURLOPT_CONNECT_ONLY, 1);
271 // Allow libcurl to pick authentication method. Curl will use the most
272 // secure one the remote site claims to support.
273 curl_easy_setopt(easyhandle, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
274 curl_easy_setopt(easyhandle, CURLOPT_PROXYUSERPWD, credentials_.c_str());
275 }
276 curl_easy_setopt(easyhandle, CURLOPT_CONNECTTIMEOUT_MS,
277 kCurlConnectTimeout.InMilliseconds());
Andreea Costinasa2246592020-04-12 23:24:01 +0200278 curl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, WriteHeadersCallback);
279 curl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &server_header_reply);
280 curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, WriteCallback);
281 curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &server_body_reply);
Andreea Costinase45d54b2020-03-10 09:21:14 +0100282
283 res = curl_easy_perform(easyhandle);
284
285 if (res != CURLE_OK) {
286 LOG(ERROR) << *this << " curl_easy_perform() failed with error: ",
287 curl_easy_strerror(res);
288 curl_easy_cleanup(easyhandle);
Andreea Costinasa2246592020-04-12 23:24:01 +0200289
290 if (server_header_reply.size() > 0) {
291 // Send the error message from the remote server back to the client.
292 OnError(std::string_view(server_header_reply.data(),
293 server_header_reply.size()));
294 } else {
295 OnError(kHttpInternalServerError);
296 }
Andreea Costinase45d54b2020-03-10 09:21:14 +0100297 return;
298 }
299 // Extract the socket from the curl handle.
300 res = curl_easy_getinfo(easyhandle, CURLINFO_ACTIVESOCKET, &newSocket);
301 if (res != CURLE_OK) {
302 LOG(ERROR) << *this << " Failed to get socket from curl with error: "
303 << curl_easy_strerror(res);
304 curl_easy_cleanup(easyhandle);
305 OnError(kHttpBadGateway);
306 return;
307 }
308
309 ScopedCurlEasyhandle scoped_handle(easyhandle, FreeCurlEasyhandle());
310 auto server_conn = std::make_unique<CurlSocket>(base::ScopedFD(newSocket),
311 std::move(scoped_handle));
312
313 // Send the server reply to the client. If the connection is successful, the
Andreea Costinasa2246592020-04-12 23:24:01 +0200314 // reply headers should be "HTTP/1.1 200 Connection Established".
315 if (client_socket_->SendTo(server_header_reply.data(),
316 server_header_reply.size()) !=
317 server_header_reply.size()) {
318 PLOG(ERROR) << *this << " Failed to send HTTP reply headers to client: "
319 << base::StringPiece(server_header_reply.data(),
320 server_header_reply.size());
321 OnError(kHttpInternalServerError);
322 return;
323 }
324 // HTTP CONNECT responses can have a payload body which should be forwarded to
325 // the client.
326 if (server_body_reply.size() > 0) {
327 // TODO(acostinas, chromium:1064536) Resend the reply body in case of EAGAIN
328 // or EWOULDBLOCK errors.
329 if (client_socket_->SendTo(server_body_reply.data(),
330 server_body_reply.size()) !=
331 server_body_reply.size()) {
332 PLOG(ERROR) << *this
Andreea Costinas08a5d182020-04-29 22:12:47 +0200333 << " Failed to send HTTP CONNECT reply body to client: "
Andreea Costinasa2246592020-04-12 23:24:01 +0200334 << base::StringPiece(server_body_reply.data(),
335 server_body_reply.size());
336 }
337 }
Andreea Costinase45d54b2020-03-10 09:21:14 +0100338
Garrick Evans3388a032020-03-24 11:25:55 +0900339 auto fwd = std::make_unique<patchpanel::SocketForwarder>(
Andreea Costinase45d54b2020-03-10 09:21:14 +0100340 base::StringPrintf("%d-%d", client_socket_->fd(), server_conn->fd()),
341 std::move(client_socket_), std::move(server_conn));
342 // Start forwarding data between sockets.
343 fwd->Start();
344 std::move(setup_finished_callback_).Run(std::move(fwd), this);
345}
346
347void ProxyConnectJob::OnError(const std::string_view& http_error_message) {
348 client_socket_->SendTo(http_error_message.data(), http_error_message.size());
349 std::move(setup_finished_callback_).Run(nullptr, this);
350}
351
Andreea Costinas08a5d182020-04-29 22:12:47 +0200352void ProxyConnectJob::OnClientConnectTimeout() {
353 // Stop listening for client connect requests.
354 read_watcher_.reset();
355 LOG(ERROR) << *this
356 << " Connection timed out while waiting for the client to send a "
357 "connect request.";
358 OnError(kHttpConnectionTimeout);
359}
360
Andreea Costinase45d54b2020-03-10 09:21:14 +0100361std::ostream& operator<<(std::ostream& stream, const ProxyConnectJob& job) {
362 stream << "{fd: " << job.client_socket_->fd();
363 if (!job.target_url_.empty()) {
364 stream << ", url: " << job.target_url_;
365 }
366 stream << "}";
367 return stream;
368}
369
370} // namespace system_proxy