blob: c9108098f87add601f07ca872c8d7ae64b48cea7 [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
Andreea Costinase45d54b2020-03-10 09:21:14 +010011#include <curl/easy.h>
12
Andreea Costinase45d54b2020-03-10 09:21:14 +010013#include <base/base64.h>
14#include <base/bind.h>
15#include <base/bind_helpers.h>
16#include <base/callback_helpers.h>
17#include <base/files/file_util.h>
18#include <base/strings/stringprintf.h>
Andreea Costinase45d54b2020-03-10 09:21:14 +010019#include <base/strings/string_util.h>
20#include <base/time/time.h>
Andreea Costinas08a5d182020-04-29 22:12:47 +020021#include <base/threading/thread.h>
22#include <base/threading/thread_task_runner_handle.h>
Andreea Costinase45d54b2020-03-10 09:21:14 +010023#include <brillo/http/http_transport.h>
Garrick Evanscd8c2972020-04-14 14:35:52 +090024#include <chromeos/patchpanel/net_util.h>
25#include <chromeos/patchpanel/socket.h>
26#include <chromeos/patchpanel/socket_forwarder.h>
Andreea Costinase45d54b2020-03-10 09:21:14 +010027
28#include "system-proxy/curl_socket.h"
Andreea Costinas90b71642020-06-12 10:18:25 +020029#include "system-proxy/http_util.h"
Andreea Costinase45d54b2020-03-10 09:21:14 +010030
Garrick Evans2d5e7c92020-06-08 14:14:28 +090031// The libpatchpanel-util library overloads << for socket data structures.
Andreea Costinase45d54b2020-03-10 09:21:14 +010032// By C++'s argument-dependent lookup rules, operators defined in a
33// different namespace are not visible. We need the using directive to make
34// the overload available this namespace.
Garrick Evans3388a032020-03-24 11:25:55 +090035using patchpanel::operator<<;
Andreea Costinase45d54b2020-03-10 09:21:14 +010036
37namespace {
38// There's no RFC recomandation for the max size of http request headers but
39// popular http server implementations (Apache, IIS, Tomcat) set the lower limit
40// to 8000.
41constexpr int kMaxHttpRequestHeadersSize = 8000;
Andreea Costinase45d54b2020-03-10 09:21:14 +010042constexpr base::TimeDelta kCurlConnectTimeout = base::TimeDelta::FromMinutes(2);
Andreea Costinas08a5d182020-04-29 22:12:47 +020043constexpr base::TimeDelta kWaitClientConnectTimeout =
44 base::TimeDelta::FromMinutes(2);
Andreea Costinase45d54b2020-03-10 09:21:14 +010045constexpr size_t kMaxBadRequestPrintSize = 120;
46
Andreea Costinasf90a4c02020-06-12 22:30:51 +020047constexpr int64_t kHttpCodeProxyAuthRequired = 407;
48
Andreea Costinase45d54b2020-03-10 09:21:14 +010049// HTTP error codes and messages with origin information for debugging (RFC723,
50// section 6.1).
51const std::string_view kHttpBadRequest =
52 "HTTP/1.1 400 Bad Request - Origin: local proxy\r\n\r\n";
Andreea Costinas08a5d182020-04-29 22:12:47 +020053const std::string_view kHttpConnectionTimeout =
54 "HTTP/1.1 408 Request Timeout - Origin: local proxy\r\n\r\n";
Andreea Costinase45d54b2020-03-10 09:21:14 +010055const std::string_view kHttpInternalServerError =
56 "HTTP/1.1 500 Internal Server Error - Origin: local proxy\r\n\r\n";
57const std::string_view kHttpBadGateway =
58 "HTTP/1.1 502 Bad Gateway - Origin: local proxy\r\n\r\n";
Andreea Costinasf90a4c02020-06-12 22:30:51 +020059const std::string_view kHttpProxyAuthRequired =
60 "HTTP/1.1 407 Credentials required - Origin: local proxy\r\n\r\n";
61constexpr char kHttpErrorTunnelFailed[] =
62 "HTTP/1.1 %s Error creating tunnel - Origin: local proxy\r\n\r\n";
Andreea Costinas90b71642020-06-12 10:18:25 +020063} // namespace
Andreea Costinasa2246592020-04-12 23:24:01 +020064
Andreea Costinas90b71642020-06-12 10:18:25 +020065namespace system_proxy {
Andreea Costinasa2246592020-04-12 23:24:01 +020066// CURLOPT_HEADERFUNCTION callback implementation that only returns the headers
67// from the last response sent by the sever. This is to make sure that we
68// send back valid HTTP replies and auhentication data from the HTTP messages is
69// not being leaked to the client. |userdata| is set on the libcurl CURL handle
70// used to configure the request, using the the CURLOPT_HEADERDATA option. Note,
71// from the libcurl documentation: This callback is being called for all the
72// responses received from the proxy server after intiating the connection
73// request. Multiple responses can be received in an authentication sequence.
74// Only the last response's headers should be forwarded to the System-proxy
75// client. The header callback will be called once for each header and only
76// complete header lines are passed on to the callback.
77static size_t WriteHeadersCallback(char* contents,
78 size_t size,
79 size_t nmemb,
80 void* userdata) {
81 std::vector<char>* vec = (std::vector<char>*)userdata;
82
83 // Check if we are receiving a new HTTP message (after the last one was
84 // terminated with an empty line).
Andreea Costinas90b71642020-06-12 10:18:25 +020085 if (IsEndingWithHttpEmptyLine(base::StringPiece(vec->data(), vec->size()))) {
Andreea Costinasa2246592020-04-12 23:24:01 +020086 VLOG(1) << "Removing the http reply headers from the server "
87 << base::StringPiece(vec->data(), vec->size());
88 vec->clear();
Andreea Costinase45d54b2020-03-10 09:21:14 +010089 }
Andreea Costinasa2246592020-04-12 23:24:01 +020090 vec->insert(vec->end(), contents, contents + (nmemb * size));
Andreea Costinase45d54b2020-03-10 09:21:14 +010091 return size * nmemb;
92}
93
Andreea Costinasa2246592020-04-12 23:24:01 +020094// CONNECT requests may have a reply body. This method will capture the reply
95// and save it in |userdata|. |userdata| is set on the libcurl CURL handle
96// used to configure the request, using the the CURLOPT_WRITEDATA option.
97static size_t WriteCallback(char* contents,
98 size_t size,
99 size_t nmemb,
100 void* userdata) {
101 std::vector<char>* vec = (std::vector<char>*)userdata;
102 vec->insert(vec->end(), contents, contents + (nmemb * size));
103 return size * nmemb;
104}
105
Andreea Costinase45d54b2020-03-10 09:21:14 +0100106ProxyConnectJob::ProxyConnectJob(
Garrick Evans3388a032020-03-24 11:25:55 +0900107 std::unique_ptr<patchpanel::Socket> socket,
Andreea Costinase45d54b2020-03-10 09:21:14 +0100108 const std::string& credentials,
109 ResolveProxyCallback resolve_proxy_callback,
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200110 AuthenticationRequiredCallback auth_required_callback,
Andreea Costinase45d54b2020-03-10 09:21:14 +0100111 OnConnectionSetupFinishedCallback setup_finished_callback)
112 : credentials_(credentials),
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200113 first_http_connect_attempt_(true),
Andreea Costinase45d54b2020-03-10 09:21:14 +0100114 resolve_proxy_callback_(std::move(resolve_proxy_callback)),
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200115 auth_required_callback_(std::move(auth_required_callback)),
Andreea Costinas08a5d182020-04-29 22:12:47 +0200116 setup_finished_callback_(std::move(setup_finished_callback)),
117 // Safe to use |base::Unretained| because the callback will be canceled
118 // when it goes out of scope.
119 client_connect_timeout_callback_(base::Bind(
120 &ProxyConnectJob::OnClientConnectTimeout, base::Unretained(this))) {
Andreea Costinase45d54b2020-03-10 09:21:14 +0100121 client_socket_ = std::move(socket);
122}
123
124ProxyConnectJob::~ProxyConnectJob() = default;
125
126bool ProxyConnectJob::Start() {
127 // Make the socket non-blocking.
128 if (!base::SetNonBlocking(client_socket_->fd())) {
129 PLOG(ERROR) << *this << " Failed to mark the socket as non-blocking.";
130 client_socket_->SendTo(kHttpInternalServerError.data(),
131 kHttpInternalServerError.size());
132 return false;
133 }
Andreea Costinas08a5d182020-04-29 22:12:47 +0200134 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
135 FROM_HERE, client_connect_timeout_callback_.callback(),
136 kWaitClientConnectTimeout);
Andreea Costinase45d54b2020-03-10 09:21:14 +0100137 read_watcher_ = base::FileDescriptorWatcher::WatchReadable(
Andreea Costinas833eb7c2020-06-12 11:09:15 +0200138 client_socket_->fd(), base::Bind(&ProxyConnectJob::OnClientReadReady,
139 weak_ptr_factory_.GetWeakPtr()));
Andreea Costinase45d54b2020-03-10 09:21:14 +0100140 return true;
141}
142
143void ProxyConnectJob::OnClientReadReady() {
Andreea Costinas08a5d182020-04-29 22:12:47 +0200144 if (!read_watcher_) {
145 // The connection has timed out while waiting for the client's HTTP CONNECT
146 // request. See |OnClientConnectTimeout|.
147 return;
148 }
149 client_connect_timeout_callback_.Cancel();
Andreea Costinase45d54b2020-03-10 09:21:14 +0100150 // Stop watching.
151 read_watcher_.reset();
152 // The first message should be a HTTP CONNECT request.
153 std::vector<char> connect_request;
154 if (!TryReadHttpHeader(&connect_request)) {
155 std::string encoded;
156 base::Base64Encode(
157 base::StringPiece(connect_request.data(), connect_request.size()),
158 &encoded);
159 LOG(ERROR) << *this
160 << " Failure to read proxy CONNECT request. Base 64 encoded "
161 "request message from client: "
162 << encoded;
163 OnError(kHttpBadRequest);
164 return;
165 }
Andreea Costinas90b71642020-06-12 10:18:25 +0200166 base::StringPiece request(connect_request.data(), connect_request.size());
167 target_url_ = GetUriAuthorityFromHttpHeader(request);
Andreea Costinase45d54b2020-03-10 09:21:14 +0100168 if (target_url_.empty()) {
169 LOG(ERROR)
170 << *this
171 << " Failed to extract target url from the HTTP CONNECT request.";
172 OnError(kHttpBadRequest);
173 return;
174 }
175
Andreea Costinasa89309d2020-05-08 15:51:12 +0200176 // The proxy resolution service in Chrome expects a proper URL, formatted as
177 // scheme://host:port. It's safe to assume only https will be used for the
178 // target url.
Andreea Costinase45d54b2020-03-10 09:21:14 +0100179 std::move(resolve_proxy_callback_)
Andreea Costinasa89309d2020-05-08 15:51:12 +0200180 .Run(base::StringPrintf("https://%s", target_url_.c_str()),
181 base::Bind(&ProxyConnectJob::OnProxyResolution,
Andreea Costinas833eb7c2020-06-12 11:09:15 +0200182 weak_ptr_factory_.GetWeakPtr()));
Andreea Costinase45d54b2020-03-10 09:21:14 +0100183}
184
185bool ProxyConnectJob::TryReadHttpHeader(std::vector<char>* raw_request) {
Andreea Costinase45d54b2020-03-10 09:21:14 +0100186 size_t read_byte_count = 0;
187 raw_request->resize(kMaxHttpRequestHeadersSize);
188
189 // Read byte-by-byte and stop when reading an empty line (only CRLF) or when
190 // exceeding the max buffer size.
191 // TODO(acostinas, chromium:1064536) This may have some measurable performance
192 // impact. We should read larger blocks of data, consume the HTTP headers,
193 // cache the tunneled payload that may have already been included (e.g. TLS
194 // ClientHello) and send it to server after the connection is established.
195 while (read_byte_count < kMaxHttpRequestHeadersSize) {
196 if (client_socket_->RecvFrom(raw_request->data() + read_byte_count, 1) <=
197 0) {
198 raw_request->resize(std::min(read_byte_count, kMaxBadRequestPrintSize));
199 return false;
200 }
201 ++read_byte_count;
202
Andreea Costinas90b71642020-06-12 10:18:25 +0200203 if (IsEndingWithHttpEmptyLine(
204 base::StringPiece(raw_request->data(), read_byte_count))) {
Andreea Costinase45d54b2020-03-10 09:21:14 +0100205 raw_request->resize(read_byte_count);
206 return true;
207 }
208 }
209 return false;
210}
211
212void ProxyConnectJob::OnProxyResolution(
213 const std::list<std::string>& proxy_servers) {
214 proxy_servers_ = proxy_servers;
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200215 DoCurlServerConnection();
Andreea Costinase45d54b2020-03-10 09:21:14 +0100216}
217
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200218void ProxyConnectJob::AuthenticationRequired(
219 const std::vector<char>& http_response_headers) {
220 DCHECK(!proxy_servers_.empty());
221 SchemeRealmPairList scheme_realm_pairs = ParseAuthChallenge(base::StringPiece(
222 http_response_headers.data(), http_response_headers.size()));
223 if (scheme_realm_pairs.empty()) {
224 LOG(ERROR) << "Failed to parse authentication challenge";
225 OnError(kHttpBadGateway);
226 return;
227 }
228
229 std::move(auth_required_callback_)
230 .Run(proxy_servers_.front(), scheme_realm_pairs.front().first,
231 scheme_realm_pairs.front().second,
232 base::Bind(&ProxyConnectJob::OnAuthCredentialsProvided,
233 base::Unretained(this)));
234}
235
236void ProxyConnectJob::OnAuthCredentialsProvided(
237 const std::string& credentials) {
238 if (credentials.empty()) {
239 SendHttpResponseToClient(/* http_response_headers= */ {},
240 /* http_response_body= */ {});
241 std::move(setup_finished_callback_).Run(nullptr, this);
242 return;
243 }
244 credentials_ = credentials;
245 VLOG(1) << "Connecting to the remote server with provided credentials";
246 DoCurlServerConnection();
247}
248
249bool ProxyConnectJob::AreAuthCredentialsRequired(CURL* easyhandle) {
250 if (http_response_code_ != kHttpCodeProxyAuthRequired) {
251 return false;
252 }
253
254 CURLcode res;
255 int64_t server_proxy_auth_scheme = 0;
256 res = curl_easy_getinfo(easyhandle, CURLINFO_PROXYAUTH_AVAIL,
257 &server_proxy_auth_scheme);
258 if (res != CURLE_OK || !server_proxy_auth_scheme) {
259 return false;
260 }
261
262 // If kerberos is enabled, then we need to wait for the user to request a
263 // kerberos ticket from Chrome.
264 return !(server_proxy_auth_scheme & CURLAUTH_NEGOTIATE);
265}
266
267void ProxyConnectJob::DoCurlServerConnection() {
268 DCHECK(!proxy_servers_.empty());
Andreea Costinase45d54b2020-03-10 09:21:14 +0100269 CURL* easyhandle = curl_easy_init();
270 CURLcode res;
Andreea Costinasa2246592020-04-12 23:24:01 +0200271 curl_socket_t newSocket = -1;
Andreea Costinase45d54b2020-03-10 09:21:14 +0100272
273 if (!easyhandle) {
274 // Unfortunately it's not possible to get the failure reason.
275 LOG(ERROR) << *this << " Failure to create curl handle.";
276 curl_easy_cleanup(easyhandle);
277 OnError(kHttpInternalServerError);
278 return;
279 }
280 curl_easy_setopt(easyhandle, CURLOPT_URL, target_url_.c_str());
Andreea Costinasf90a4c02020-06-12 22:30:51 +0200281 std::vector<char> http_response_headers;
282 std::vector<char> http_response_body;
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200283
284 if (proxy_servers_.front().c_str() != brillo::http::kDirectProxy) {
285 curl_easy_setopt(easyhandle, CURLOPT_PROXY, proxy_servers_.front().c_str());
Andreea Costinase45d54b2020-03-10 09:21:14 +0100286 curl_easy_setopt(easyhandle, CURLOPT_HTTPPROXYTUNNEL, 1L);
287 curl_easy_setopt(easyhandle, CURLOPT_CONNECT_ONLY, 1);
288 // Allow libcurl to pick authentication method. Curl will use the most
289 // secure one the remote site claims to support.
290 curl_easy_setopt(easyhandle, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
291 curl_easy_setopt(easyhandle, CURLOPT_PROXYUSERPWD, credentials_.c_str());
292 }
293 curl_easy_setopt(easyhandle, CURLOPT_CONNECTTIMEOUT_MS,
294 kCurlConnectTimeout.InMilliseconds());
Andreea Costinasa2246592020-04-12 23:24:01 +0200295 curl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, WriteHeadersCallback);
Andreea Costinasf90a4c02020-06-12 22:30:51 +0200296 curl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &http_response_headers);
Andreea Costinasa2246592020-04-12 23:24:01 +0200297 curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, WriteCallback);
Andreea Costinasf90a4c02020-06-12 22:30:51 +0200298 curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &http_response_body);
Andreea Costinase45d54b2020-03-10 09:21:14 +0100299
300 res = curl_easy_perform(easyhandle);
Andreea Costinasf90a4c02020-06-12 22:30:51 +0200301 curl_easy_getinfo(easyhandle, CURLINFO_HTTP_CONNECTCODE,
302 &http_response_code_);
Andreea Costinase45d54b2020-03-10 09:21:14 +0100303
304 if (res != CURLE_OK) {
Andreea Costinas90b71642020-06-12 10:18:25 +0200305 LOG(ERROR) << *this << " curl_easy_perform() failed with error: "
306 << curl_easy_strerror(res);
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200307 if (first_http_connect_attempt_ && AreAuthCredentialsRequired(easyhandle)) {
308 first_http_connect_attempt_ = false;
309 AuthenticationRequired(http_response_headers);
310 curl_easy_cleanup(easyhandle);
311 return;
312 }
Andreea Costinase45d54b2020-03-10 09:21:14 +0100313 curl_easy_cleanup(easyhandle);
Andreea Costinasa2246592020-04-12 23:24:01 +0200314
Andreea Costinasf90a4c02020-06-12 22:30:51 +0200315 SendHttpResponseToClient(/* http_response_headers= */ {},
316 /* http_response_body= */ {});
317 std::move(setup_finished_callback_).Run(nullptr, this);
Andreea Costinase45d54b2020-03-10 09:21:14 +0100318 return;
319 }
320 // Extract the socket from the curl handle.
321 res = curl_easy_getinfo(easyhandle, CURLINFO_ACTIVESOCKET, &newSocket);
322 if (res != CURLE_OK) {
323 LOG(ERROR) << *this << " Failed to get socket from curl with error: "
324 << curl_easy_strerror(res);
325 curl_easy_cleanup(easyhandle);
326 OnError(kHttpBadGateway);
327 return;
328 }
329
330 ScopedCurlEasyhandle scoped_handle(easyhandle, FreeCurlEasyhandle());
331 auto server_conn = std::make_unique<CurlSocket>(base::ScopedFD(newSocket),
332 std::move(scoped_handle));
333
334 // Send the server reply to the client. If the connection is successful, the
Andreea Costinasa2246592020-04-12 23:24:01 +0200335 // reply headers should be "HTTP/1.1 200 Connection Established".
Andreea Costinasf90a4c02020-06-12 22:30:51 +0200336 if (!SendHttpResponseToClient(http_response_headers, http_response_body)) {
337 std::move(setup_finished_callback_).Run(nullptr, this);
Andreea Costinasa2246592020-04-12 23:24:01 +0200338 return;
339 }
Andreea Costinase45d54b2020-03-10 09:21:14 +0100340
Garrick Evans3388a032020-03-24 11:25:55 +0900341 auto fwd = std::make_unique<patchpanel::SocketForwarder>(
Andreea Costinase45d54b2020-03-10 09:21:14 +0100342 base::StringPrintf("%d-%d", client_socket_->fd(), server_conn->fd()),
343 std::move(client_socket_), std::move(server_conn));
344 // Start forwarding data between sockets.
345 fwd->Start();
346 std::move(setup_finished_callback_).Run(std::move(fwd), this);
347}
348
Andreea Costinasf90a4c02020-06-12 22:30:51 +0200349bool ProxyConnectJob::SendHttpResponseToClient(
350 const std::vector<char>& http_response_headers,
351 const std::vector<char>& http_response_body) {
352 if (http_response_code_ == 0) {
353 // No HTTP CONNECT response code is available.
354 return client_socket_->SendTo(kHttpInternalServerError.data(),
355 kHttpInternalServerError.size());
356 }
357
358 if (http_response_code_ == kHttpCodeProxyAuthRequired) {
359 // This will be a hint for the user to authenticate via the Browser or
360 // acquire a Kerberos ticket.
361 return client_socket_->SendTo(kHttpProxyAuthRequired.data(),
362 kHttpProxyAuthRequired.size());
363 }
364
365 if (http_response_code_ >= 400) {
366 VLOG(1) << "Failed to set up HTTP tunnel with code " << http_response_code_;
367 std::string http_error = base::StringPrintf(
368 kHttpErrorTunnelFailed, std::to_string(http_response_code_).c_str());
369 return client_socket_->SendTo(http_error.c_str(), http_error.size());
370 }
371
372 if (http_response_headers.empty()) {
373 return client_socket_->SendTo(kHttpInternalServerError.data(),
374 kHttpInternalServerError.size());
375 }
376
377 VLOG(1) << "Sending server reply to client";
378 if (!client_socket_->SendTo(http_response_headers.data(),
379 http_response_headers.size())) {
380 PLOG(ERROR) << "Failed to send HTTP server response headers to client";
381 return false;
382 }
383 if (!http_response_body.empty()) {
384 if (!client_socket_->SendTo(http_response_body.data(),
385 http_response_body.size())) {
386 PLOG(ERROR) << "Failed to send HTTP server response payload to client";
387 return false;
388 }
389 }
390 return true;
391}
392
Andreea Costinase45d54b2020-03-10 09:21:14 +0100393void ProxyConnectJob::OnError(const std::string_view& http_error_message) {
394 client_socket_->SendTo(http_error_message.data(), http_error_message.size());
395 std::move(setup_finished_callback_).Run(nullptr, this);
396}
397
Andreea Costinas08a5d182020-04-29 22:12:47 +0200398void ProxyConnectJob::OnClientConnectTimeout() {
399 // Stop listening for client connect requests.
400 read_watcher_.reset();
401 LOG(ERROR) << *this
402 << " Connection timed out while waiting for the client to send a "
403 "connect request.";
404 OnError(kHttpConnectionTimeout);
405}
406
Andreea Costinase45d54b2020-03-10 09:21:14 +0100407std::ostream& operator<<(std::ostream& stream, const ProxyConnectJob& job) {
408 stream << "{fd: " << job.client_socket_->fd();
409 if (!job.target_url_.empty()) {
410 stream << ", url: " << job.target_url_;
411 }
412 stream << "}";
413 return stream;
414}
415
416} // namespace system_proxy