blob: ea93796e610d115daf5263c31d5329b4fa7fbe70 [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
45// Returns the URL encoded value of |text|. It also verifies if the string was
46// already encoded and, if true it returns it unmodified.
47std::string UrlEncode(const std::string& text) {
48 if (text == brillo::data_encoding::UrlDecode(text.c_str()))
49 return brillo::data_encoding::UrlEncode(text.c_str(), false);
50 return text;
51}
52
Andreea Costinas44cefa22020-03-09 09:07:39 +010053} // namespace
54
Andreea Costinas41e06442020-03-09 09:41:51 +010055ServerProxy::ServerProxy(base::OnceClosure quit_closure)
Andreea Costinasbb2aa022020-06-13 00:03:23 +020056 : system_credentials_(kCredentialsColonSeparator),
57 quit_closure_(std::move(quit_closure)),
58 weak_ptr_factory_(this) {}
Andreea Costinase45d54b2020-03-10 09:21:14 +010059ServerProxy::~ServerProxy() = default;
Andreea Costinas41e06442020-03-09 09:41:51 +010060
61void ServerProxy::Init() {
62 // Start listening for input.
63 stdin_watcher_ = base::FileDescriptorWatcher::WatchReadable(
Andreea Costinase45d54b2020-03-10 09:21:14 +010064 GetStdinPipe(), base::Bind(&ServerProxy::HandleStdinReadable,
65 weak_ptr_factory_.GetWeakPtr()));
Andreea Costinas41e06442020-03-09 09:41:51 +010066
67 // Handle termination signals.
68 signal_handler_.Init();
69 for (int signal : {SIGINT, SIGTERM, SIGHUP, SIGQUIT}) {
70 signal_handler_.RegisterHandler(
71 signal, base::BindRepeating(&ServerProxy::HandleSignal,
72 base::Unretained(this)));
73 }
74}
75
Andreea Costinase45d54b2020-03-10 09:21:14 +010076void ServerProxy::ResolveProxy(const std::string& target_url,
77 OnProxyResolvedCallback callback) {
Andreea Costinas5862b102020-03-19 14:45:36 +010078 auto it = pending_proxy_resolution_requests_.find(target_url);
79 if (it != pending_proxy_resolution_requests_.end()) {
80 it->second.push_back(std::move(callback));
81 return;
82 }
Andreea Costinasaae97382020-05-05 13:31:58 +020083 worker::ProxyResolutionRequest proxy_request;
Andreea Costinas5862b102020-03-19 14:45:36 +010084 proxy_request.set_target_url(target_url);
Andreea Costinasaae97382020-05-05 13:31:58 +020085 worker::WorkerRequest request;
Andreea Costinas5862b102020-03-19 14:45:36 +010086 *request.mutable_proxy_resolution_request() = proxy_request;
87 if (!WriteProtobuf(GetStdoutPipe(), request)) {
88 LOG(ERROR) << "Failed to send proxy resolution request for url: "
89 << target_url;
90 std::move(callback).Run({brillo::http::kDirectProxy});
91 return;
92 }
93 pending_proxy_resolution_requests_[target_url].push_back(std::move(callback));
Andreea Costinase45d54b2020-03-10 09:21:14 +010094}
Andreea Costinas41e06442020-03-09 09:41:51 +010095
Andreea Costinasbb2aa022020-06-13 00:03:23 +020096void ServerProxy::AuthenticationRequired(const std::string& proxy_url,
97 const std::string& scheme,
98 const std::string& realm,
99 OnAuthAcquiredCallback callback) {
100 // TODO(acostinas): Request the credentials from the main process.
101 std::move(callback).Run(std::string());
102}
103
Andreea Costinas41e06442020-03-09 09:41:51 +0100104void ServerProxy::HandleStdinReadable() {
Andreea Costinasaae97382020-05-05 13:31:58 +0200105 worker::WorkerConfigs config;
Andreea Costinas44cefa22020-03-09 09:07:39 +0100106 if (!ReadProtobuf(GetStdinPipe(), &config)) {
107 LOG(ERROR) << "Error decoding protobuf configurations." << std::endl;
Andreea Costinas41e06442020-03-09 09:41:51 +0100108 return;
109 }
Andreea Costinas44cefa22020-03-09 09:07:39 +0100110
111 if (config.has_credentials()) {
Andreea Costinase45d54b2020-03-10 09:21:14 +0100112 const std::string username = UrlEncode(config.credentials().username());
113 const std::string password = UrlEncode(config.credentials().password());
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200114 system_credentials_ = base::JoinString({username.c_str(), password.c_str()},
115 kCredentialsColonSeparator);
Andreea Costinas44cefa22020-03-09 09:07:39 +0100116 }
117
118 if (config.has_listening_address()) {
119 if (listening_addr_ != 0) {
120 LOG(ERROR)
121 << "Failure to set configurations: listening port was already set."
122 << std::endl;
123 return;
124 }
125 listening_addr_ = config.listening_address().addr();
126 listening_port_ = config.listening_address().port();
127 CreateListeningSocket();
128 }
Andreea Costinas5862b102020-03-19 14:45:36 +0100129
130 if (config.has_proxy_resolution_reply()) {
131 std::list<std::string> proxies;
Andreea Costinasaae97382020-05-05 13:31:58 +0200132 const worker::ProxyResolutionReply& reply = config.proxy_resolution_reply();
Andreea Costinas5862b102020-03-19 14:45:36 +0100133 for (auto const& proxy : reply.proxy_servers())
134 proxies.push_back(proxy);
135
136 OnProxyResolved(reply.target_url(), proxies);
137 }
Andreea Costinas922fbaf2020-05-28 11:55:22 +0200138
139 if (config.has_kerberos_config()) {
140 if (config.kerberos_config().enabled()) {
141 // Set the environment variables that allow libcurl to use the existing
142 // kerberos ticket for proxy authentication. The files to which the env
143 // variables point to are maintained by the parent process.
144 setenv(kKrb5ConfEnvKey, config.kerberos_config().krb5conf_path().c_str(),
145 /* overwrite = */ 1);
146 setenv(kKrb5CCEnvKey, config.kerberos_config().krb5cc_path().c_str(),
147 /* overwrite = */ 1);
148 } else {
149 unsetenv(kKrb5ConfEnvKey);
150 unsetenv(kKrb5CCEnvKey);
151 }
152 }
Andreea Costinas41e06442020-03-09 09:41:51 +0100153}
154
155bool ServerProxy::HandleSignal(const struct signalfd_siginfo& siginfo) {
156 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
157 std::move(quit_closure_));
158 return true;
159}
160
Andreea Costinas44cefa22020-03-09 09:07:39 +0100161int ServerProxy::GetStdinPipe() {
162 return STDIN_FILENO;
163}
164
Andreea Costinas5862b102020-03-19 14:45:36 +0100165int ServerProxy::GetStdoutPipe() {
166 return STDOUT_FILENO;
167}
168
Andreea Costinas44cefa22020-03-09 09:07:39 +0100169void ServerProxy::CreateListeningSocket() {
Garrick Evans3388a032020-03-24 11:25:55 +0900170 listening_fd_ = std::make_unique<patchpanel::Socket>(
Andreea Costinas44cefa22020-03-09 09:07:39 +0100171 AF_INET, SOCK_STREAM | SOCK_NONBLOCK);
172
173 struct sockaddr_in addr = {0};
174 addr.sin_family = AF_INET;
175 addr.sin_port = htons(listening_port_);
176 addr.sin_addr.s_addr = listening_addr_;
177 if (!listening_fd_->Bind((const struct sockaddr*)&addr, sizeof(addr))) {
178 LOG(ERROR) << "Cannot bind source socket" << std::endl;
179 return;
180 }
181
182 if (!listening_fd_->Listen(kMaxConn)) {
183 LOG(ERROR) << "Cannot listen on source socket." << std::endl;
184 return;
185 }
186
187 fd_watcher_ = base::FileDescriptorWatcher::WatchReadable(
Andreea Costinase45d54b2020-03-10 09:21:14 +0100188 listening_fd_->fd(), base::BindRepeating(&ServerProxy::OnConnectionAccept,
189 weak_ptr_factory_.GetWeakPtr()));
Andreea Costinas44cefa22020-03-09 09:07:39 +0100190}
191
Andreea Costinase45d54b2020-03-10 09:21:14 +0100192void ServerProxy::OnConnectionAccept() {
Andreea Costinas44cefa22020-03-09 09:07:39 +0100193 struct sockaddr_storage client_src = {};
194 socklen_t sockaddr_len = sizeof(client_src);
195 if (auto client_conn =
196 listening_fd_->Accept((struct sockaddr*)&client_src, &sockaddr_len)) {
Andreea Costinase45d54b2020-03-10 09:21:14 +0100197 auto connect_job = std::make_unique<ProxyConnectJob>(
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200198 std::move(client_conn), system_credentials_,
Andreea Costinase45d54b2020-03-10 09:21:14 +0100199 base::BindOnce(&ServerProxy::ResolveProxy, base::Unretained(this)),
Andreea Costinasbb2aa022020-06-13 00:03:23 +0200200 base::BindOnce(&ServerProxy::AuthenticationRequired,
201 base::Unretained(this)),
Andreea Costinase45d54b2020-03-10 09:21:14 +0100202 base::BindOnce(&ServerProxy::OnConnectionSetupFinished,
203 base::Unretained(this)));
204 if (connect_job->Start())
205 pending_connect_jobs_[connect_job.get()] = std::move(connect_job);
Andreea Costinas44cefa22020-03-09 09:07:39 +0100206 }
Andreea Costinase45d54b2020-03-10 09:21:14 +0100207 // Cleanup any defunct forwarders.
208 // TODO(acostinas, chromium:1064536) Monitor the client and server sockets
209 // and remove the corresponding SocketForwarder when a socket closes.
210 for (auto it = forwarders_.begin(); it != forwarders_.end(); ++it) {
211 if (!(*it)->IsRunning() && (*it)->HasBeenStarted())
212 it = forwarders_.erase(it);
213 }
214}
215
Andreea Costinas5862b102020-03-19 14:45:36 +0100216void ServerProxy::OnProxyResolved(const std::string& target_url,
217 const std::list<std::string>& proxy_servers) {
218 auto callbacks = std::move(pending_proxy_resolution_requests_[target_url]);
219 pending_proxy_resolution_requests_.erase(target_url);
220
221 for (auto& callback : callbacks)
222 std::move(callback).Run(proxy_servers);
223}
224
Andreea Costinase45d54b2020-03-10 09:21:14 +0100225void ServerProxy::OnConnectionSetupFinished(
Garrick Evans3388a032020-03-24 11:25:55 +0900226 std::unique_ptr<patchpanel::SocketForwarder> fwd,
Andreea Costinase45d54b2020-03-10 09:21:14 +0100227 ProxyConnectJob* connect_job) {
228 if (fwd) {
229 // The connection was set up successfully.
230 forwarders_.emplace_back(std::move(fwd));
231 }
232 pending_connect_jobs_.erase(connect_job);
Andreea Costinas44cefa22020-03-09 09:07:39 +0100233}
234
Andreea Costinas41e06442020-03-09 09:41:51 +0100235} // namespace system_proxy