blob: 13ea7cb1fb9f3f361afae9542e2c76f94df1f818 [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
12#include <base/bind.h>
13#include <base/bind_helpers.h>
14#include <base/callback_helpers.h>
15#include <base/posix/eintr_wrapper.h>
16#include <base/files/file_util.h>
Andreea Costinase45d54b2020-03-10 09:21:14 +010017#include <base/strings/string_util.h>
Andreea Costinas41e06442020-03-09 09:41:51 +010018#include <base/threading/thread.h>
Andreea Costinas41e06442020-03-09 09:41:51 +010019#include <base/threading/thread_task_runner_handle.h>
Andreea Costinase45d54b2020-03-10 09:21:14 +010020#include <brillo/data_encoding.h>
21#include <brillo/http/http_transport.h>
Garrick Evanscd8c2972020-04-14 14:35:52 +090022#include <chromeos/patchpanel/socket.h>
23#include <chromeos/patchpanel/socket_forwarder.h>
Andreea Costinas41e06442020-03-09 09:41:51 +010024
25#include "bindings/worker_common.pb.h"
26#include "system-proxy/protobuf_util.h"
Andreea Costinase45d54b2020-03-10 09:21:14 +010027#include "system-proxy/proxy_connect_job.h"
Andreea Costinas41e06442020-03-09 09:41:51 +010028
29namespace system_proxy {
30
Andreea Costinas44cefa22020-03-09 09:07:39 +010031namespace {
Andreea Costinase45d54b2020-03-10 09:21:14 +010032
33constexpr int kMaxConn = 100;
Andreea Costinas922fbaf2020-05-28 11:55:22 +020034// Name of the environment variable that points to the location of the kerberos
35// credentials (ticket) cache.
36constexpr char kKrb5CCEnvKey[] = "KRB5CCNAME";
37// Name of the environment variable that points to the kerberos configuration
38// file which contains information regarding the locations of KDCs and admin
39// servers for the Kerberos realms of interest, defaults for the current realm
40// and for Kerberos applications, and mappings of hostnames onto Kerberos
41// realms.
42constexpr char kKrb5ConfEnvKey[] = "KRB5_CONFIG";
Andreea Costinasbb2aa022020-06-13 00:03:23 +020043constexpr char kCredentialsColonSeparator[] = ":";
Andreea Costinase45d54b2020-03-10 09:21:14 +010044
Andreea Costinas20660a12020-07-07 09:32:42 +020045// Returns the URL encoded value of |text|.
Andreea Costinase45d54b2020-03-10 09:21:14 +010046std::string UrlEncode(const std::string& text) {
Andreea Costinas20660a12020-07-07 09:32:42 +020047 return brillo::data_encoding::UrlEncode(text.c_str(),
48 /* encodeSpaceAsPlus= */ false);
Andreea Costinase45d54b2020-03-10 09:21:14 +010049}
50
Andreea Costinas44cefa22020-03-09 09:07:39 +010051} // namespace
52
Andreea Costinas41e06442020-03-09 09:41:51 +010053ServerProxy::ServerProxy(base::OnceClosure quit_closure)
Andreea Costinasbb2aa022020-06-13 00:03:23 +020054 : system_credentials_(kCredentialsColonSeparator),
55 quit_closure_(std::move(quit_closure)),
56 weak_ptr_factory_(this) {}
Andreea Costinase45d54b2020-03-10 09:21:14 +010057ServerProxy::~ServerProxy() = default;
Andreea Costinas41e06442020-03-09 09:41:51 +010058
59void ServerProxy::Init() {
60 // Start listening for input.
61 stdin_watcher_ = base::FileDescriptorWatcher::WatchReadable(
Andreea Costinase45d54b2020-03-10 09:21:14 +010062 GetStdinPipe(), base::Bind(&ServerProxy::HandleStdinReadable,
63 weak_ptr_factory_.GetWeakPtr()));
Andreea Costinas41e06442020-03-09 09:41:51 +010064
65 // Handle termination signals.
66 signal_handler_.Init();
67 for (int signal : {SIGINT, SIGTERM, SIGHUP, SIGQUIT}) {
68 signal_handler_.RegisterHandler(
69 signal, base::BindRepeating(&ServerProxy::HandleSignal,
70 base::Unretained(this)));
71 }
72}
73
Andreea Costinase45d54b2020-03-10 09:21:14 +010074void ServerProxy::ResolveProxy(const std::string& target_url,
75 OnProxyResolvedCallback callback) {
Andreea Costinas5862b102020-03-19 14:45:36 +010076 auto it = pending_proxy_resolution_requests_.find(target_url);
77 if (it != pending_proxy_resolution_requests_.end()) {
78 it->second.push_back(std::move(callback));
79 return;
80 }
Andreea Costinasaae97382020-05-05 13:31:58 +020081 worker::ProxyResolutionRequest proxy_request;
Andreea Costinas5862b102020-03-19 14:45:36 +010082 proxy_request.set_target_url(target_url);
Andreea Costinasaae97382020-05-05 13:31:58 +020083 worker::WorkerRequest request;
Andreea Costinas5862b102020-03-19 14:45:36 +010084 *request.mutable_proxy_resolution_request() = proxy_request;
85 if (!WriteProtobuf(GetStdoutPipe(), request)) {
86 LOG(ERROR) << "Failed to send proxy resolution request for url: "
87 << target_url;
88 std::move(callback).Run({brillo::http::kDirectProxy});
89 return;
90 }
91 pending_proxy_resolution_requests_[target_url].push_back(std::move(callback));
Andreea Costinase45d54b2020-03-10 09:21:14 +010092}
Andreea Costinas41e06442020-03-09 09:41:51 +010093
Andreea Costinased9e6122020-08-12 12:06:19 +020094void ServerProxy::AuthenticationRequired(
95 const std::string& proxy_url,
96 const std::string& scheme,
97 const std::string& realm,
98 const std::string& bad_cached_credentials,
99 OnAuthAcquiredCallback callback) {
Andreea Costinasdb2cbee2020-06-15 11:43:44 +0200100 worker::ProtectionSpace protection_space;
101 protection_space.set_origin(proxy_url);
102 protection_space.set_realm(realm);
103 protection_space.set_scheme(scheme);
104
105 std::string auth_key = protection_space.SerializeAsString();
106 // Check the local cache.
107 auto it = auth_cache_.find(auth_key);
108 if (it != auth_cache_.end()) {
Andreea Costinased9e6122020-08-12 12:06:19 +0200109 // Don't use the cached credentials if they are flagged by the connection as
110 // "bad".
111 if (it->second != bad_cached_credentials) {
112 std::move(callback).Run(it->second);
113 return;
114 }
Andreea Costinasdb2cbee2020-06-15 11:43:44 +0200115 }
116
117 // Request the credentials from the main process.
118 worker::AuthRequiredRequest auth_request;
119 *auth_request.mutable_protection_space() = protection_space;
Andreea Costinased9e6122020-08-12 12:06:19 +0200120 auth_request.set_bad_cached_credentials(bad_cached_credentials !=
121 kCredentialsColonSeparator);
Andreea Costinasdb2cbee2020-06-15 11:43:44 +0200122
123 worker::WorkerRequest request;
124 *request.mutable_auth_required_request() = auth_request;
125
126 if (!WriteProtobuf(GetStdoutPipe(), request)) {
127 LOG(ERROR) << "Failed to send authentication required request";
128 std::move(callback).Run(/* credentials= */ std::string());
129 return;
130 }
131 pending_auth_required_requests_[auth_key].push_back(std::move(callback));
132}
133
134void ServerProxy::AuthCredentialsProvided(
135 const std::string& auth_credentials_key, const std::string& credentials) {
136 auto it = pending_auth_required_requests_.find(auth_credentials_key);
137 if (it == pending_auth_required_requests_.end()) {
138 LOG(WARNING) << "No pending requests found for credentials";
139 return;
140 }
141 for (auto& auth_acquired_callback : it->second) {
142 std::move(auth_acquired_callback).Run(credentials);
143 }
144 pending_auth_required_requests_.erase(auth_credentials_key);
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200145}
146
Andreea Costinas41e06442020-03-09 09:41:51 +0100147void ServerProxy::HandleStdinReadable() {
Andreea Costinasaae97382020-05-05 13:31:58 +0200148 worker::WorkerConfigs config;
Andreea Costinas44cefa22020-03-09 09:07:39 +0100149 if (!ReadProtobuf(GetStdinPipe(), &config)) {
150 LOG(ERROR) << "Error decoding protobuf configurations." << std::endl;
Andreea Costinas41e06442020-03-09 09:41:51 +0100151 return;
152 }
Andreea Costinas44cefa22020-03-09 09:07:39 +0100153
154 if (config.has_credentials()) {
Andreea Costinasdb2cbee2020-06-15 11:43:44 +0200155 std::string credentials;
Andreea Costinase45d54b2020-03-10 09:21:14 +0100156 const std::string username = UrlEncode(config.credentials().username());
157 const std::string password = UrlEncode(config.credentials().password());
Andreea Costinasdb2cbee2020-06-15 11:43:44 +0200158 credentials = base::JoinString({username.c_str(), password.c_str()},
159 kCredentialsColonSeparator);
160 if (config.credentials().has_protection_space()) {
161 std::string auth_key =
162 config.credentials().protection_space().SerializeAsString();
163 if (!username.empty() && !password.empty()) {
164 auth_cache_[auth_key] = credentials;
165 AuthCredentialsProvided(auth_key, credentials);
166 } else {
167 AuthCredentialsProvided(auth_key, std::string());
168 }
169 } else {
170 system_credentials_ = credentials;
171 }
Andreea Costinas44cefa22020-03-09 09:07:39 +0100172 }
173
174 if (config.has_listening_address()) {
175 if (listening_addr_ != 0) {
176 LOG(ERROR)
177 << "Failure to set configurations: listening port was already set."
178 << std::endl;
179 return;
180 }
181 listening_addr_ = config.listening_address().addr();
182 listening_port_ = config.listening_address().port();
183 CreateListeningSocket();
184 }
Andreea Costinas5862b102020-03-19 14:45:36 +0100185
186 if (config.has_proxy_resolution_reply()) {
187 std::list<std::string> proxies;
Andreea Costinasaae97382020-05-05 13:31:58 +0200188 const worker::ProxyResolutionReply& reply = config.proxy_resolution_reply();
Andreea Costinas5862b102020-03-19 14:45:36 +0100189 for (auto const& proxy : reply.proxy_servers())
190 proxies.push_back(proxy);
191
192 OnProxyResolved(reply.target_url(), proxies);
193 }
Andreea Costinas922fbaf2020-05-28 11:55:22 +0200194
195 if (config.has_kerberos_config()) {
196 if (config.kerberos_config().enabled()) {
197 // Set the environment variables that allow libcurl to use the existing
198 // kerberos ticket for proxy authentication. The files to which the env
199 // variables point to are maintained by the parent process.
200 setenv(kKrb5ConfEnvKey, config.kerberos_config().krb5conf_path().c_str(),
201 /* overwrite = */ 1);
202 setenv(kKrb5CCEnvKey, config.kerberos_config().krb5cc_path().c_str(),
203 /* overwrite = */ 1);
204 } else {
205 unsetenv(kKrb5ConfEnvKey);
206 unsetenv(kKrb5CCEnvKey);
207 }
208 }
Andreea Costinase9c73592020-07-17 15:27:54 +0200209
210 if (config.has_clear_user_credentials()) {
211 auth_cache_.clear();
212 }
Andreea Costinas41e06442020-03-09 09:41:51 +0100213}
214
215bool ServerProxy::HandleSignal(const struct signalfd_siginfo& siginfo) {
216 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
217 std::move(quit_closure_));
218 return true;
219}
220
Andreea Costinas44cefa22020-03-09 09:07:39 +0100221int ServerProxy::GetStdinPipe() {
222 return STDIN_FILENO;
223}
224
Andreea Costinas5862b102020-03-19 14:45:36 +0100225int ServerProxy::GetStdoutPipe() {
226 return STDOUT_FILENO;
227}
228
Andreea Costinas44cefa22020-03-09 09:07:39 +0100229void ServerProxy::CreateListeningSocket() {
Garrick Evans3388a032020-03-24 11:25:55 +0900230 listening_fd_ = std::make_unique<patchpanel::Socket>(
Andreea Costinas44cefa22020-03-09 09:07:39 +0100231 AF_INET, SOCK_STREAM | SOCK_NONBLOCK);
232
233 struct sockaddr_in addr = {0};
234 addr.sin_family = AF_INET;
235 addr.sin_port = htons(listening_port_);
236 addr.sin_addr.s_addr = listening_addr_;
237 if (!listening_fd_->Bind((const struct sockaddr*)&addr, sizeof(addr))) {
238 LOG(ERROR) << "Cannot bind source socket" << std::endl;
239 return;
240 }
241
242 if (!listening_fd_->Listen(kMaxConn)) {
243 LOG(ERROR) << "Cannot listen on source socket." << std::endl;
244 return;
245 }
246
247 fd_watcher_ = base::FileDescriptorWatcher::WatchReadable(
Andreea Costinase45d54b2020-03-10 09:21:14 +0100248 listening_fd_->fd(), base::BindRepeating(&ServerProxy::OnConnectionAccept,
249 weak_ptr_factory_.GetWeakPtr()));
Andreea Costinas44cefa22020-03-09 09:07:39 +0100250}
251
Andreea Costinase45d54b2020-03-10 09:21:14 +0100252void ServerProxy::OnConnectionAccept() {
Andreea Costinas44cefa22020-03-09 09:07:39 +0100253 struct sockaddr_storage client_src = {};
254 socklen_t sockaddr_len = sizeof(client_src);
255 if (auto client_conn =
256 listening_fd_->Accept((struct sockaddr*)&client_src, &sockaddr_len)) {
Andreea Costinase45d54b2020-03-10 09:21:14 +0100257 auto connect_job = std::make_unique<ProxyConnectJob>(
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200258 std::move(client_conn), system_credentials_,
Andreea Costinase45d54b2020-03-10 09:21:14 +0100259 base::BindOnce(&ServerProxy::ResolveProxy, base::Unretained(this)),
Andreea Costinased9e6122020-08-12 12:06:19 +0200260 base::BindRepeating(&ServerProxy::AuthenticationRequired,
261 base::Unretained(this)),
Andreea Costinase45d54b2020-03-10 09:21:14 +0100262 base::BindOnce(&ServerProxy::OnConnectionSetupFinished,
263 base::Unretained(this)));
264 if (connect_job->Start())
265 pending_connect_jobs_[connect_job.get()] = std::move(connect_job);
Andreea Costinas44cefa22020-03-09 09:07:39 +0100266 }
Andreea Costinase45d54b2020-03-10 09:21:14 +0100267 // Cleanup any defunct forwarders.
268 // TODO(acostinas, chromium:1064536) Monitor the client and server sockets
269 // and remove the corresponding SocketForwarder when a socket closes.
270 for (auto it = forwarders_.begin(); it != forwarders_.end(); ++it) {
271 if (!(*it)->IsRunning() && (*it)->HasBeenStarted())
272 it = forwarders_.erase(it);
273 }
274}
275
Andreea Costinas5862b102020-03-19 14:45:36 +0100276void ServerProxy::OnProxyResolved(const std::string& target_url,
277 const std::list<std::string>& proxy_servers) {
278 auto callbacks = std::move(pending_proxy_resolution_requests_[target_url]);
279 pending_proxy_resolution_requests_.erase(target_url);
280
281 for (auto& callback : callbacks)
282 std::move(callback).Run(proxy_servers);
283}
284
Andreea Costinase45d54b2020-03-10 09:21:14 +0100285void ServerProxy::OnConnectionSetupFinished(
Garrick Evans3388a032020-03-24 11:25:55 +0900286 std::unique_ptr<patchpanel::SocketForwarder> fwd,
Andreea Costinase45d54b2020-03-10 09:21:14 +0100287 ProxyConnectJob* connect_job) {
288 if (fwd) {
289 // The connection was set up successfully.
290 forwarders_.emplace_back(std::move(fwd));
291 }
292 pending_connect_jobs_.erase(connect_job);
Andreea Costinas44cefa22020-03-09 09:07:39 +0100293}
294
Andreea Costinas41e06442020-03-09 09:41:51 +0100295} // namespace system_proxy