blob: a63f343c74ecbe17fdbc124ab36625a85701c62b [file] [log] [blame]
Andreea Costinas41e06442020-03-09 09:41:51 +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/server_proxy.h"
6
7#include <iostream>
8#include <string>
9#include <utility>
10#include <vector>
11
Andreea Costinascc4d54e2020-10-19 15:46:25 +020012#include <curl/curl.h>
13
Andreea Costinas41e06442020-03-09 09:41:51 +010014#include <base/bind.h>
Andreea Costinas41e06442020-03-09 09:41:51 +010015#include <base/callback_helpers.h>
16#include <base/posix/eintr_wrapper.h>
17#include <base/files/file_util.h>
Andreea Costinascc4d54e2020-10-19 15:46:25 +020018#include <base/strings/string_split.h>
Andreea Costinase45d54b2020-03-10 09:21:14 +010019#include <base/strings/string_util.h>
Andreea Costinas41e06442020-03-09 09:41:51 +010020#include <base/threading/thread.h>
Andreea Costinas41e06442020-03-09 09:41:51 +010021#include <base/threading/thread_task_runner_handle.h>
Andreea Costinase45d54b2020-03-10 09:21:14 +010022#include <brillo/data_encoding.h>
23#include <brillo/http/http_transport.h>
Garrick Evanscd8c2972020-04-14 14:35:52 +090024#include <chromeos/patchpanel/socket.h>
25#include <chromeos/patchpanel/socket_forwarder.h>
Andreea Costinas41e06442020-03-09 09:41:51 +010026
27#include "bindings/worker_common.pb.h"
Andreea Costinascc4d54e2020-10-19 15:46:25 +020028#include "system-proxy/http_util.h"
Andreea Costinas41e06442020-03-09 09:41:51 +010029#include "system-proxy/protobuf_util.h"
Andreea Costinase45d54b2020-03-10 09:21:14 +010030#include "system-proxy/proxy_connect_job.h"
Andreea Costinas41e06442020-03-09 09:41:51 +010031
32namespace system_proxy {
33
Andreea Costinas44cefa22020-03-09 09:07:39 +010034namespace {
Andreea Costinase45d54b2020-03-10 09:21:14 +010035
36constexpr int kMaxConn = 100;
Andreea Costinas922fbaf2020-05-28 11:55:22 +020037// Name of the environment variable that points to the location of the kerberos
38// credentials (ticket) cache.
39constexpr char kKrb5CCEnvKey[] = "KRB5CCNAME";
40// Name of the environment variable that points to the kerberos configuration
41// file which contains information regarding the locations of KDCs and admin
42// servers for the Kerberos realms of interest, defaults for the current realm
43// and for Kerberos applications, and mappings of hostnames onto Kerberos
44// realms.
45constexpr char kKrb5ConfEnvKey[] = "KRB5_CONFIG";
Andreea Costinasbb2aa022020-06-13 00:03:23 +020046constexpr char kCredentialsColonSeparator[] = ":";
Andreea Costinase45d54b2020-03-10 09:21:14 +010047
Andreea Costinas20660a12020-07-07 09:32:42 +020048// Returns the URL encoded value of |text|.
Andreea Costinase45d54b2020-03-10 09:21:14 +010049std::string UrlEncode(const std::string& text) {
Andreea Costinas20660a12020-07-07 09:32:42 +020050 return brillo::data_encoding::UrlEncode(text.c_str(),
51 /* encodeSpaceAsPlus= */ false);
Andreea Costinase45d54b2020-03-10 09:21:14 +010052}
53
Andreea Costinascc4d54e2020-10-19 15:46:25 +020054// Converts the list of proxy authentication schemes in string format to the
55// curl bit-mask format.
56int64_t GetAuthSchemes(
57 const google::protobuf::RepeatedPtrField<std::string>& auth_schemes) {
58 if (auth_schemes.empty())
59 return CURLAUTH_ANY;
60 // Convert auth schemes to curl format.
61 int64_t curl_scheme = CURLAUTH_NEGOTIATE;
62 // Auth scheme is case insensitive, see
63 // https://tools.ietf.org/html/rfc7235#section-2.1
64 for (auto const& scheme : auth_schemes) {
65 const std::string lower_scheme = base::ToLowerASCII(scheme);
66 if (lower_scheme == "basic")
67 curl_scheme |= CURLAUTH_BASIC;
68 if (lower_scheme == "digest")
69 curl_scheme |= CURLAUTH_DIGEST;
70 if (lower_scheme == "ntlm")
71 curl_scheme |= CURLAUTH_NTLM;
72 }
73 return curl_scheme;
74}
Andreea Costinas44cefa22020-03-09 09:07:39 +010075} // namespace
76
Andreea Costinas41e06442020-03-09 09:41:51 +010077ServerProxy::ServerProxy(base::OnceClosure quit_closure)
Andreea Costinasbb2aa022020-06-13 00:03:23 +020078 : system_credentials_(kCredentialsColonSeparator),
79 quit_closure_(std::move(quit_closure)),
80 weak_ptr_factory_(this) {}
Andreea Costinase45d54b2020-03-10 09:21:14 +010081ServerProxy::~ServerProxy() = default;
Andreea Costinas41e06442020-03-09 09:41:51 +010082
83void ServerProxy::Init() {
84 // Start listening for input.
85 stdin_watcher_ = base::FileDescriptorWatcher::WatchReadable(
Andreea Costinase45d54b2020-03-10 09:21:14 +010086 GetStdinPipe(), base::Bind(&ServerProxy::HandleStdinReadable,
87 weak_ptr_factory_.GetWeakPtr()));
Andreea Costinas41e06442020-03-09 09:41:51 +010088
89 // Handle termination signals.
90 signal_handler_.Init();
91 for (int signal : {SIGINT, SIGTERM, SIGHUP, SIGQUIT}) {
92 signal_handler_.RegisterHandler(
93 signal, base::BindRepeating(&ServerProxy::HandleSignal,
94 base::Unretained(this)));
95 }
96}
97
Andreea Costinase45d54b2020-03-10 09:21:14 +010098void ServerProxy::ResolveProxy(const std::string& target_url,
99 OnProxyResolvedCallback callback) {
Andreea Costinas5862b102020-03-19 14:45:36 +0100100 auto it = pending_proxy_resolution_requests_.find(target_url);
101 if (it != pending_proxy_resolution_requests_.end()) {
102 it->second.push_back(std::move(callback));
103 return;
104 }
Andreea Costinasaae97382020-05-05 13:31:58 +0200105 worker::ProxyResolutionRequest proxy_request;
Andreea Costinas5862b102020-03-19 14:45:36 +0100106 proxy_request.set_target_url(target_url);
Andreea Costinasaae97382020-05-05 13:31:58 +0200107 worker::WorkerRequest request;
Andreea Costinas5862b102020-03-19 14:45:36 +0100108 *request.mutable_proxy_resolution_request() = proxy_request;
109 if (!WriteProtobuf(GetStdoutPipe(), request)) {
110 LOG(ERROR) << "Failed to send proxy resolution request for url: "
111 << target_url;
112 std::move(callback).Run({brillo::http::kDirectProxy});
113 return;
114 }
115 pending_proxy_resolution_requests_[target_url].push_back(std::move(callback));
Andreea Costinase45d54b2020-03-10 09:21:14 +0100116}
Andreea Costinas41e06442020-03-09 09:41:51 +0100117
Andreea Costinased9e6122020-08-12 12:06:19 +0200118void ServerProxy::AuthenticationRequired(
119 const std::string& proxy_url,
120 const std::string& scheme,
121 const std::string& realm,
122 const std::string& bad_cached_credentials,
123 OnAuthAcquiredCallback callback) {
Andreea Costinasdb2cbee2020-06-15 11:43:44 +0200124 worker::ProtectionSpace protection_space;
125 protection_space.set_origin(proxy_url);
126 protection_space.set_realm(realm);
127 protection_space.set_scheme(scheme);
128
129 std::string auth_key = protection_space.SerializeAsString();
130 // Check the local cache.
131 auto it = auth_cache_.find(auth_key);
132 if (it != auth_cache_.end()) {
Andreea Costinased9e6122020-08-12 12:06:19 +0200133 // Don't use the cached credentials if they are flagged by the connection as
134 // "bad".
135 if (it->second != bad_cached_credentials) {
136 std::move(callback).Run(it->second);
137 return;
138 }
Andreea Costinasdb2cbee2020-06-15 11:43:44 +0200139 }
140
141 // Request the credentials from the main process.
142 worker::AuthRequiredRequest auth_request;
143 *auth_request.mutable_protection_space() = protection_space;
Andreea Costinased9e6122020-08-12 12:06:19 +0200144 auth_request.set_bad_cached_credentials(bad_cached_credentials !=
145 kCredentialsColonSeparator);
Andreea Costinasdb2cbee2020-06-15 11:43:44 +0200146
147 worker::WorkerRequest request;
148 *request.mutable_auth_required_request() = auth_request;
149
150 if (!WriteProtobuf(GetStdoutPipe(), request)) {
151 LOG(ERROR) << "Failed to send authentication required request";
152 std::move(callback).Run(/* credentials= */ std::string());
153 return;
154 }
155 pending_auth_required_requests_[auth_key].push_back(std::move(callback));
156}
157
158void ServerProxy::AuthCredentialsProvided(
159 const std::string& auth_credentials_key, const std::string& credentials) {
160 auto it = pending_auth_required_requests_.find(auth_credentials_key);
161 if (it == pending_auth_required_requests_.end()) {
162 LOG(WARNING) << "No pending requests found for credentials";
163 return;
164 }
165 for (auto& auth_acquired_callback : it->second) {
166 std::move(auth_acquired_callback).Run(credentials);
167 }
168 pending_auth_required_requests_.erase(auth_credentials_key);
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200169}
170
Andreea Costinas41e06442020-03-09 09:41:51 +0100171void ServerProxy::HandleStdinReadable() {
Andreea Costinasaae97382020-05-05 13:31:58 +0200172 worker::WorkerConfigs config;
Andreea Costinas44cefa22020-03-09 09:07:39 +0100173 if (!ReadProtobuf(GetStdinPipe(), &config)) {
174 LOG(ERROR) << "Error decoding protobuf configurations." << std::endl;
Andreea Costinas41e06442020-03-09 09:41:51 +0100175 return;
176 }
Andreea Costinas44cefa22020-03-09 09:07:39 +0100177
178 if (config.has_credentials()) {
Andreea Costinasdb2cbee2020-06-15 11:43:44 +0200179 std::string credentials;
Andreea Costinase45d54b2020-03-10 09:21:14 +0100180 const std::string username = UrlEncode(config.credentials().username());
181 const std::string password = UrlEncode(config.credentials().password());
Andreea Costinasdb2cbee2020-06-15 11:43:44 +0200182 credentials = base::JoinString({username.c_str(), password.c_str()},
183 kCredentialsColonSeparator);
184 if (config.credentials().has_protection_space()) {
185 std::string auth_key =
186 config.credentials().protection_space().SerializeAsString();
187 if (!username.empty() && !password.empty()) {
188 auth_cache_[auth_key] = credentials;
189 AuthCredentialsProvided(auth_key, credentials);
190 } else {
191 AuthCredentialsProvided(auth_key, std::string());
192 }
193 } else {
Andreea Costinascc4d54e2020-10-19 15:46:25 +0200194 system_credentials_auth_schemes_ = GetAuthSchemes(
195 config.credentials().policy_credentials_auth_schemes());
Andreea Costinasdb2cbee2020-06-15 11:43:44 +0200196 system_credentials_ = credentials;
197 }
Andreea Costinas44cefa22020-03-09 09:07:39 +0100198 }
199
200 if (config.has_listening_address()) {
201 if (listening_addr_ != 0) {
202 LOG(ERROR)
203 << "Failure to set configurations: listening port was already set."
204 << std::endl;
205 return;
206 }
207 listening_addr_ = config.listening_address().addr();
208 listening_port_ = config.listening_address().port();
209 CreateListeningSocket();
210 }
Andreea Costinas5862b102020-03-19 14:45:36 +0100211
212 if (config.has_proxy_resolution_reply()) {
213 std::list<std::string> proxies;
Andreea Costinasaae97382020-05-05 13:31:58 +0200214 const worker::ProxyResolutionReply& reply = config.proxy_resolution_reply();
Andreea Costinas5862b102020-03-19 14:45:36 +0100215 for (auto const& proxy : reply.proxy_servers())
216 proxies.push_back(proxy);
217
218 OnProxyResolved(reply.target_url(), proxies);
219 }
Andreea Costinas922fbaf2020-05-28 11:55:22 +0200220
221 if (config.has_kerberos_config()) {
222 if (config.kerberos_config().enabled()) {
223 // Set the environment variables that allow libcurl to use the existing
224 // kerberos ticket for proxy authentication. The files to which the env
225 // variables point to are maintained by the parent process.
226 setenv(kKrb5ConfEnvKey, config.kerberos_config().krb5conf_path().c_str(),
227 /* overwrite = */ 1);
228 setenv(kKrb5CCEnvKey, config.kerberos_config().krb5cc_path().c_str(),
229 /* overwrite = */ 1);
230 } else {
231 unsetenv(kKrb5ConfEnvKey);
232 unsetenv(kKrb5CCEnvKey);
233 }
234 }
Andreea Costinase9c73592020-07-17 15:27:54 +0200235
236 if (config.has_clear_user_credentials()) {
237 auth_cache_.clear();
238 }
Andreea Costinas41e06442020-03-09 09:41:51 +0100239}
240
241bool ServerProxy::HandleSignal(const struct signalfd_siginfo& siginfo) {
242 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
243 std::move(quit_closure_));
244 return true;
245}
246
Andreea Costinas44cefa22020-03-09 09:07:39 +0100247int ServerProxy::GetStdinPipe() {
248 return STDIN_FILENO;
249}
250
Andreea Costinas5862b102020-03-19 14:45:36 +0100251int ServerProxy::GetStdoutPipe() {
252 return STDOUT_FILENO;
253}
254
Andreea Costinas44cefa22020-03-09 09:07:39 +0100255void ServerProxy::CreateListeningSocket() {
Garrick Evans3388a032020-03-24 11:25:55 +0900256 listening_fd_ = std::make_unique<patchpanel::Socket>(
Andreea Costinas44cefa22020-03-09 09:07:39 +0100257 AF_INET, SOCK_STREAM | SOCK_NONBLOCK);
258
259 struct sockaddr_in addr = {0};
260 addr.sin_family = AF_INET;
261 addr.sin_port = htons(listening_port_);
262 addr.sin_addr.s_addr = listening_addr_;
263 if (!listening_fd_->Bind((const struct sockaddr*)&addr, sizeof(addr))) {
264 LOG(ERROR) << "Cannot bind source socket" << std::endl;
265 return;
266 }
267
268 if (!listening_fd_->Listen(kMaxConn)) {
269 LOG(ERROR) << "Cannot listen on source socket." << std::endl;
270 return;
271 }
272
273 fd_watcher_ = base::FileDescriptorWatcher::WatchReadable(
Andreea Costinase45d54b2020-03-10 09:21:14 +0100274 listening_fd_->fd(), base::BindRepeating(&ServerProxy::OnConnectionAccept,
275 weak_ptr_factory_.GetWeakPtr()));
Andreea Costinas44cefa22020-03-09 09:07:39 +0100276}
277
Andreea Costinase45d54b2020-03-10 09:21:14 +0100278void ServerProxy::OnConnectionAccept() {
Andreea Costinas44cefa22020-03-09 09:07:39 +0100279 struct sockaddr_storage client_src = {};
280 socklen_t sockaddr_len = sizeof(client_src);
281 if (auto client_conn =
282 listening_fd_->Accept((struct sockaddr*)&client_src, &sockaddr_len)) {
Andreea Costinase45d54b2020-03-10 09:21:14 +0100283 auto connect_job = std::make_unique<ProxyConnectJob>(
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200284 std::move(client_conn), system_credentials_,
Andreea Costinascc4d54e2020-10-19 15:46:25 +0200285 system_credentials_auth_schemes_,
Andreea Costinase45d54b2020-03-10 09:21:14 +0100286 base::BindOnce(&ServerProxy::ResolveProxy, base::Unretained(this)),
Andreea Costinased9e6122020-08-12 12:06:19 +0200287 base::BindRepeating(&ServerProxy::AuthenticationRequired,
288 base::Unretained(this)),
Andreea Costinase45d54b2020-03-10 09:21:14 +0100289 base::BindOnce(&ServerProxy::OnConnectionSetupFinished,
290 base::Unretained(this)));
291 if (connect_job->Start())
292 pending_connect_jobs_[connect_job.get()] = std::move(connect_job);
Andreea Costinas44cefa22020-03-09 09:07:39 +0100293 }
Andreea Costinase45d54b2020-03-10 09:21:14 +0100294 // Cleanup any defunct forwarders.
295 // TODO(acostinas, chromium:1064536) Monitor the client and server sockets
296 // and remove the corresponding SocketForwarder when a socket closes.
297 for (auto it = forwarders_.begin(); it != forwarders_.end(); ++it) {
298 if (!(*it)->IsRunning() && (*it)->HasBeenStarted())
299 it = forwarders_.erase(it);
300 }
301}
302
Andreea Costinas5862b102020-03-19 14:45:36 +0100303void ServerProxy::OnProxyResolved(const std::string& target_url,
304 const std::list<std::string>& proxy_servers) {
305 auto callbacks = std::move(pending_proxy_resolution_requests_[target_url]);
306 pending_proxy_resolution_requests_.erase(target_url);
307
308 for (auto& callback : callbacks)
309 std::move(callback).Run(proxy_servers);
310}
311
Andreea Costinase45d54b2020-03-10 09:21:14 +0100312void ServerProxy::OnConnectionSetupFinished(
Garrick Evans3388a032020-03-24 11:25:55 +0900313 std::unique_ptr<patchpanel::SocketForwarder> fwd,
Andreea Costinase45d54b2020-03-10 09:21:14 +0100314 ProxyConnectJob* connect_job) {
315 if (fwd) {
316 // The connection was set up successfully.
317 forwarders_.emplace_back(std::move(fwd));
318 }
319 pending_connect_jobs_.erase(connect_job);
Andreea Costinas44cefa22020-03-09 09:07:39 +0100320}
321
Andreea Costinas41e06442020-03-09 09:41:51 +0100322} // namespace system_proxy