blob: 96da8c1193e95f3b3813108d7dce6dddd245e7f6 [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
211 std::move(resolve_proxy_callback_)
212 .Run(target_url_, base::Bind(&ProxyConnectJob::OnProxyResolution,
213 base::Unretained(this)));
214}
215
216bool ProxyConnectJob::TryReadHttpHeader(std::vector<char>* raw_request) {
Andreea Costinase45d54b2020-03-10 09:21:14 +0100217 size_t read_byte_count = 0;
218 raw_request->resize(kMaxHttpRequestHeadersSize);
219
220 // Read byte-by-byte and stop when reading an empty line (only CRLF) or when
221 // exceeding the max buffer size.
222 // TODO(acostinas, chromium:1064536) This may have some measurable performance
223 // impact. We should read larger blocks of data, consume the HTTP headers,
224 // cache the tunneled payload that may have already been included (e.g. TLS
225 // ClientHello) and send it to server after the connection is established.
226 while (read_byte_count < kMaxHttpRequestHeadersSize) {
227 if (client_socket_->RecvFrom(raw_request->data() + read_byte_count, 1) <=
228 0) {
229 raw_request->resize(std::min(read_byte_count, kMaxBadRequestPrintSize));
230 return false;
231 }
232 ++read_byte_count;
233
Andreea Costinasa2246592020-04-12 23:24:01 +0200234 if (IsEndingWithHttpEmptyLine(raw_request->data(), read_byte_count)) {
Andreea Costinase45d54b2020-03-10 09:21:14 +0100235 raw_request->resize(read_byte_count);
236 return true;
237 }
238 }
239 return false;
240}
241
242void ProxyConnectJob::OnProxyResolution(
243 const std::list<std::string>& proxy_servers) {
244 proxy_servers_ = proxy_servers;
245 DoCurlServerConnection(proxy_servers.front());
246}
247
248void ProxyConnectJob::DoCurlServerConnection(const std::string& proxy_url) {
249 CURL* easyhandle = curl_easy_init();
250 CURLcode res;
Andreea Costinasa2246592020-04-12 23:24:01 +0200251 curl_socket_t newSocket = -1;
252 std::vector<char> server_header_reply, server_body_reply;
Andreea Costinase45d54b2020-03-10 09:21:14 +0100253
254 if (!easyhandle) {
255 // Unfortunately it's not possible to get the failure reason.
256 LOG(ERROR) << *this << " Failure to create curl handle.";
257 curl_easy_cleanup(easyhandle);
258 OnError(kHttpInternalServerError);
259 return;
260 }
261 curl_easy_setopt(easyhandle, CURLOPT_URL, target_url_.c_str());
262
263 if (proxy_url != brillo::http::kDirectProxy) {
264 curl_easy_setopt(easyhandle, CURLOPT_PROXY, proxy_url.c_str());
265 curl_easy_setopt(easyhandle, CURLOPT_HTTPPROXYTUNNEL, 1L);
266 curl_easy_setopt(easyhandle, CURLOPT_CONNECT_ONLY, 1);
267 // Allow libcurl to pick authentication method. Curl will use the most
268 // secure one the remote site claims to support.
269 curl_easy_setopt(easyhandle, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
270 curl_easy_setopt(easyhandle, CURLOPT_PROXYUSERPWD, credentials_.c_str());
271 }
272 curl_easy_setopt(easyhandle, CURLOPT_CONNECTTIMEOUT_MS,
273 kCurlConnectTimeout.InMilliseconds());
Andreea Costinasa2246592020-04-12 23:24:01 +0200274 curl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, WriteHeadersCallback);
275 curl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &server_header_reply);
276 curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, WriteCallback);
277 curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &server_body_reply);
Andreea Costinase45d54b2020-03-10 09:21:14 +0100278
279 res = curl_easy_perform(easyhandle);
280
281 if (res != CURLE_OK) {
282 LOG(ERROR) << *this << " curl_easy_perform() failed with error: ",
283 curl_easy_strerror(res);
284 curl_easy_cleanup(easyhandle);
Andreea Costinasa2246592020-04-12 23:24:01 +0200285
286 if (server_header_reply.size() > 0) {
287 // Send the error message from the remote server back to the client.
288 OnError(std::string_view(server_header_reply.data(),
289 server_header_reply.size()));
290 } else {
291 OnError(kHttpInternalServerError);
292 }
Andreea Costinase45d54b2020-03-10 09:21:14 +0100293 return;
294 }
295 // Extract the socket from the curl handle.
296 res = curl_easy_getinfo(easyhandle, CURLINFO_ACTIVESOCKET, &newSocket);
297 if (res != CURLE_OK) {
298 LOG(ERROR) << *this << " Failed to get socket from curl with error: "
299 << curl_easy_strerror(res);
300 curl_easy_cleanup(easyhandle);
301 OnError(kHttpBadGateway);
302 return;
303 }
304
305 ScopedCurlEasyhandle scoped_handle(easyhandle, FreeCurlEasyhandle());
306 auto server_conn = std::make_unique<CurlSocket>(base::ScopedFD(newSocket),
307 std::move(scoped_handle));
308
309 // Send the server reply to the client. If the connection is successful, the
Andreea Costinasa2246592020-04-12 23:24:01 +0200310 // reply headers should be "HTTP/1.1 200 Connection Established".
311 if (client_socket_->SendTo(server_header_reply.data(),
312 server_header_reply.size()) !=
313 server_header_reply.size()) {
314 PLOG(ERROR) << *this << " Failed to send HTTP reply headers to client: "
315 << base::StringPiece(server_header_reply.data(),
316 server_header_reply.size());
317 OnError(kHttpInternalServerError);
318 return;
319 }
320 // HTTP CONNECT responses can have a payload body which should be forwarded to
321 // the client.
322 if (server_body_reply.size() > 0) {
323 // TODO(acostinas, chromium:1064536) Resend the reply body in case of EAGAIN
324 // or EWOULDBLOCK errors.
325 if (client_socket_->SendTo(server_body_reply.data(),
326 server_body_reply.size()) !=
327 server_body_reply.size()) {
328 PLOG(ERROR) << *this
Andreea Costinas08a5d182020-04-29 22:12:47 +0200329 << " Failed to send HTTP CONNECT reply body to client: "
Andreea Costinasa2246592020-04-12 23:24:01 +0200330 << base::StringPiece(server_body_reply.data(),
331 server_body_reply.size());
332 }
333 }
Andreea Costinase45d54b2020-03-10 09:21:14 +0100334
Garrick Evans3388a032020-03-24 11:25:55 +0900335 auto fwd = std::make_unique<patchpanel::SocketForwarder>(
Andreea Costinase45d54b2020-03-10 09:21:14 +0100336 base::StringPrintf("%d-%d", client_socket_->fd(), server_conn->fd()),
337 std::move(client_socket_), std::move(server_conn));
338 // Start forwarding data between sockets.
339 fwd->Start();
340 std::move(setup_finished_callback_).Run(std::move(fwd), this);
341}
342
343void ProxyConnectJob::OnError(const std::string_view& http_error_message) {
344 client_socket_->SendTo(http_error_message.data(), http_error_message.size());
345 std::move(setup_finished_callback_).Run(nullptr, this);
346}
347
Andreea Costinas08a5d182020-04-29 22:12:47 +0200348void ProxyConnectJob::OnClientConnectTimeout() {
349 // Stop listening for client connect requests.
350 read_watcher_.reset();
351 LOG(ERROR) << *this
352 << " Connection timed out while waiting for the client to send a "
353 "connect request.";
354 OnError(kHttpConnectionTimeout);
355}
356
Andreea Costinase45d54b2020-03-10 09:21:14 +0100357std::ostream& operator<<(std::ostream& stream, const ProxyConnectJob& job) {
358 stream << "{fd: " << job.client_socket_->fd();
359 if (!job.target_url_.empty()) {
360 stream << ", url: " << job.target_url_;
361 }
362 stream << "}";
363 return stream;
364}
365
366} // namespace system_proxy