Line data Source code
1 : //! A stand-alone program that routes connections, e.g. from
2 : //! `aaa--bbb--1234.external.domain` to `aaa.bbb.internal.domain:1234`.
3 : //!
4 : //! This allows connecting to pods/services running in the same Kubernetes cluster from
5 : //! the outside. Similar to an ingress controller for HTTPS.
6 :
7 : use std::net::SocketAddr;
8 : use std::path::Path;
9 : use std::sync::Arc;
10 :
11 : use anyhow::{Context, anyhow, bail, ensure};
12 : use clap::Arg;
13 : use futures::future::Either;
14 : use futures::{FutureExt, TryFutureExt};
15 : use itertools::Itertools;
16 : use rustls::crypto::ring;
17 : use rustls::pki_types::{DnsName, PrivateKeyDer};
18 : use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
19 : use tokio::net::TcpListener;
20 : use tokio_rustls::TlsConnector;
21 : use tokio_rustls::server::TlsStream;
22 : use tokio_util::sync::CancellationToken;
23 : use tracing::{Instrument, error, info};
24 : use utils::project_git_version;
25 : use utils::sentry_init::init_sentry;
26 :
27 : use crate::context::RequestContext;
28 : use crate::metrics::{Metrics, ThreadPoolMetrics};
29 : use crate::pqproto::FeStartupPacket;
30 : use crate::protocol2::ConnectionInfo;
31 : use crate::proxy::{ErrorSource, TlsRequired, copy_bidirectional_client_compute};
32 : use crate::stream::{PqStream, Stream};
33 : use crate::util::run_until_cancelled;
34 :
35 : project_git_version!(GIT_VERSION);
36 :
37 0 : fn cli() -> clap::Command {
38 0 : clap::Command::new("Neon proxy/router")
39 0 : .version(GIT_VERSION)
40 0 : .arg(
41 0 : Arg::new("listen")
42 0 : .short('l')
43 0 : .long("listen")
44 0 : .help("listen for incoming client connections on ip:port")
45 0 : .default_value("127.0.0.1:4432"),
46 0 : )
47 0 : .arg(
48 0 : Arg::new("listen-tls")
49 0 : .long("listen-tls")
50 0 : .help("listen for incoming client connections on ip:port, requiring TLS to compute")
51 0 : .default_value("127.0.0.1:4433"),
52 0 : )
53 0 : .arg(
54 0 : Arg::new("tls-key")
55 0 : .short('k')
56 0 : .long("tls-key")
57 0 : .help("path to TLS key for client postgres connections")
58 0 : .required(true),
59 0 : )
60 0 : .arg(
61 0 : Arg::new("tls-cert")
62 0 : .short('c')
63 0 : .long("tls-cert")
64 0 : .help("path to TLS cert for client postgres connections")
65 0 : .required(true),
66 0 : )
67 0 : .arg(
68 0 : Arg::new("dest")
69 0 : .short('d')
70 0 : .long("destination")
71 0 : .help("append this domain zone to the SNI hostname to get the destination address")
72 0 : .required(true),
73 0 : )
74 0 : }
75 :
76 0 : pub async fn run() -> anyhow::Result<()> {
77 0 : let _logging_guard = crate::logging::init().await?;
78 0 : let _panic_hook_guard = utils::logging::replace_panic_hook_with_tracing_panic_hook();
79 0 : let _sentry_guard = init_sentry(Some(GIT_VERSION.into()), &[]);
80 0 :
81 0 : Metrics::install(Arc::new(ThreadPoolMetrics::new(0)));
82 0 :
83 0 : let args = cli().get_matches();
84 0 : let destination: String = args
85 0 : .get_one::<String>("dest")
86 0 : .expect("string argument defined")
87 0 : .parse()?;
88 :
89 : // Configure TLS
90 0 : let tls_config = match (
91 0 : args.get_one::<String>("tls-key"),
92 0 : args.get_one::<String>("tls-cert"),
93 : ) {
94 0 : (Some(key_path), Some(cert_path)) => parse_tls(key_path.as_ref(), cert_path.as_ref())?,
95 0 : _ => bail!("tls-key and tls-cert must be specified"),
96 : };
97 :
98 0 : let compute_tls_config =
99 0 : Arc::new(crate::tls::client_config::compute_client_config_with_root_certs()?);
100 :
101 : // Start listening for incoming client connections
102 0 : let proxy_address: SocketAddr = args
103 0 : .get_one::<String>("listen")
104 0 : .expect("listen argument defined")
105 0 : .parse()?;
106 0 : let proxy_address_compute_tls: SocketAddr = args
107 0 : .get_one::<String>("listen-tls")
108 0 : .expect("listen-tls argument defined")
109 0 : .parse()?;
110 :
111 0 : info!("Starting sni router on {proxy_address}");
112 0 : info!("Starting sni router on {proxy_address_compute_tls}");
113 0 : let proxy_listener = TcpListener::bind(proxy_address).await?;
114 0 : let proxy_listener_compute_tls = TcpListener::bind(proxy_address_compute_tls).await?;
115 :
116 0 : let cancellation_token = CancellationToken::new();
117 0 : let dest = Arc::new(destination);
118 0 :
119 0 : let main = tokio::spawn(task_main(
120 0 : dest.clone(),
121 0 : tls_config.clone(),
122 0 : None,
123 0 : proxy_listener,
124 0 : cancellation_token.clone(),
125 0 : ))
126 0 : .map(crate::error::flatten_err);
127 0 :
128 0 : let main_tls = tokio::spawn(task_main(
129 0 : dest,
130 0 : tls_config,
131 0 : Some(compute_tls_config),
132 0 : proxy_listener_compute_tls,
133 0 : cancellation_token.clone(),
134 0 : ))
135 0 : .map(crate::error::flatten_err);
136 0 : let signals_task = tokio::spawn(crate::signals::handle(cancellation_token, || {}));
137 0 :
138 0 : // the signal task cant ever succeed.
139 0 : // the main task can error, or can succeed on cancellation.
140 0 : // we want to immediately exit on either of these cases
141 0 : let main = futures::future::try_join(main, main_tls);
142 0 : let signal = match futures::future::select(signals_task, main).await {
143 0 : Either::Left((res, _)) => crate::error::flatten_err(res)?,
144 0 : Either::Right((res, _)) => {
145 0 : res?;
146 0 : return Ok(());
147 : }
148 : };
149 :
150 : // maintenance tasks return `Infallible` success values, this is an impossible value
151 : // so this match statically ensures that there are no possibilities for that value
152 : match signal {}
153 0 : }
154 :
155 0 : pub(super) fn parse_tls(
156 0 : key_path: &Path,
157 0 : cert_path: &Path,
158 0 : ) -> anyhow::Result<Arc<rustls::ServerConfig>> {
159 0 : let key = {
160 0 : let key_bytes = std::fs::read(key_path).context("TLS key file")?;
161 :
162 0 : let mut keys = rustls_pemfile::pkcs8_private_keys(&mut &key_bytes[..]).collect_vec();
163 0 :
164 0 : ensure!(keys.len() == 1, "keys.len() = {} (should be 1)", keys.len());
165 : PrivateKeyDer::Pkcs8(
166 0 : keys.pop()
167 0 : .expect("keys should not be empty")
168 0 : .context(format!(
169 0 : "Failed to read TLS keys at '{}'",
170 0 : key_path.display()
171 0 : ))?,
172 : )
173 : };
174 :
175 0 : let cert_chain_bytes = std::fs::read(cert_path).context(format!(
176 0 : "Failed to read TLS cert file at '{}.'",
177 0 : cert_path.display()
178 0 : ))?;
179 :
180 0 : let cert_chain: Vec<_> = {
181 0 : rustls_pemfile::certs(&mut &cert_chain_bytes[..])
182 0 : .try_collect()
183 0 : .with_context(|| {
184 0 : format!(
185 0 : "Failed to read TLS certificate chain from bytes from file at '{}'.",
186 0 : cert_path.display()
187 0 : )
188 0 : })?
189 : };
190 :
191 0 : let tls_config =
192 0 : rustls::ServerConfig::builder_with_provider(Arc::new(ring::default_provider()))
193 0 : .with_protocol_versions(&[&rustls::version::TLS13, &rustls::version::TLS12])
194 0 : .context("ring should support TLS1.2 and TLS1.3")?
195 0 : .with_no_client_auth()
196 0 : .with_single_cert(cert_chain, key)?
197 0 : .into();
198 0 :
199 0 : Ok(tls_config)
200 0 : }
201 :
202 0 : pub(super) async fn task_main(
203 0 : dest_suffix: Arc<String>,
204 0 : tls_config: Arc<rustls::ServerConfig>,
205 0 : compute_tls_config: Option<Arc<rustls::ClientConfig>>,
206 0 : listener: tokio::net::TcpListener,
207 0 : cancellation_token: CancellationToken,
208 0 : ) -> anyhow::Result<()> {
209 0 : // When set for the server socket, the keepalive setting
210 0 : // will be inherited by all accepted client sockets.
211 0 : socket2::SockRef::from(&listener).set_keepalive(true)?;
212 :
213 0 : let connections = tokio_util::task::task_tracker::TaskTracker::new();
214 :
215 0 : while let Some(accept_result) =
216 0 : run_until_cancelled(listener.accept(), &cancellation_token).await
217 : {
218 0 : let (socket, peer_addr) = accept_result?;
219 :
220 0 : let session_id = uuid::Uuid::new_v4();
221 0 : let tls_config = Arc::clone(&tls_config);
222 0 : let dest_suffix = Arc::clone(&dest_suffix);
223 0 : let compute_tls_config = compute_tls_config.clone();
224 0 :
225 0 : connections.spawn(
226 0 : async move {
227 0 : socket
228 0 : .set_nodelay(true)
229 0 : .context("failed to set socket option")?;
230 :
231 0 : info!(%peer_addr, "serving");
232 0 : let ctx = RequestContext::new(
233 0 : session_id,
234 0 : ConnectionInfo {
235 0 : addr: peer_addr,
236 0 : extra: None,
237 0 : },
238 0 : crate::metrics::Protocol::SniRouter,
239 0 : "sni",
240 0 : );
241 0 : handle_client(ctx, dest_suffix, tls_config, compute_tls_config, socket).await
242 0 : }
243 0 : .unwrap_or_else(|e| {
244 0 : // Acknowledge that the task has finished with an error.
245 0 : error!("per-client task finished with an error: {e:#}");
246 0 : })
247 0 : .instrument(tracing::info_span!("handle_client", ?session_id)),
248 : );
249 : }
250 :
251 0 : connections.close();
252 0 : drop(listener);
253 0 :
254 0 : connections.wait().await;
255 :
256 0 : info!("all client connections have finished");
257 0 : Ok(())
258 0 : }
259 :
260 0 : async fn ssl_handshake<S: AsyncRead + AsyncWrite + Unpin>(
261 0 : ctx: &RequestContext,
262 0 : raw_stream: S,
263 0 : tls_config: Arc<rustls::ServerConfig>,
264 0 : ) -> anyhow::Result<TlsStream<S>> {
265 0 : let (mut stream, msg) = PqStream::parse_startup(Stream::from_raw(raw_stream)).await?;
266 0 : match msg {
267 : FeStartupPacket::SslRequest { direct: None } => {
268 0 : let raw = stream.accept_tls().await?;
269 :
270 0 : Ok(raw
271 0 : .upgrade(tls_config, !ctx.has_private_peer_addr())
272 0 : .await?)
273 : }
274 0 : unexpected => {
275 0 : info!(
276 : ?unexpected,
277 0 : "unexpected startup packet, rejecting connection"
278 : );
279 0 : Err(stream.throw_error(TlsRequired, None).await)?
280 : }
281 : }
282 0 : }
283 :
284 0 : async fn handle_client(
285 0 : ctx: RequestContext,
286 0 : dest_suffix: Arc<String>,
287 0 : tls_config: Arc<rustls::ServerConfig>,
288 0 : compute_tls_config: Option<Arc<rustls::ClientConfig>>,
289 0 : stream: impl AsyncRead + AsyncWrite + Unpin,
290 0 : ) -> anyhow::Result<()> {
291 0 : let mut tls_stream = ssl_handshake(&ctx, stream, tls_config).await?;
292 :
293 : // Cut off first part of the SNI domain
294 : // We receive required destination details in the format of
295 : // `{k8s_service_name}--{k8s_namespace}--{port}.non-sni-domain`
296 0 : let sni = tls_stream
297 0 : .get_ref()
298 0 : .1
299 0 : .server_name()
300 0 : .ok_or(anyhow!("SNI missing"))?;
301 0 : let dest: Vec<&str> = sni
302 0 : .split_once('.')
303 0 : .context("invalid SNI")?
304 : .0
305 0 : .splitn(3, "--")
306 0 : .collect();
307 0 : let port = dest[2].parse::<u16>().context("invalid port")?;
308 0 : let destination = format!("{}.{}.{}:{}", dest[0], dest[1], dest_suffix, port);
309 0 :
310 0 : info!("destination: {}", destination);
311 :
312 0 : let mut client = tokio::net::TcpStream::connect(&destination).await?;
313 :
314 0 : let client = if let Some(compute_tls_config) = compute_tls_config {
315 0 : info!("upgrading TLS");
316 :
317 : // send SslRequest
318 0 : client
319 0 : .write_all(b"\x00\x00\x00\x08\x04\xd2\x16\x2f")
320 0 : .await?;
321 :
322 : // wait for S/N respons
323 0 : let mut resp = b'N';
324 0 : client.read_exact(std::slice::from_mut(&mut resp)).await?;
325 :
326 : // error if not S
327 0 : ensure!(resp == b'S', "compute refused TLS");
328 :
329 : // upgrade to TLS.
330 0 : let domain = DnsName::try_from(destination)?;
331 0 : let domain = rustls::pki_types::ServerName::DnsName(domain);
332 0 : let client = TlsConnector::from(compute_tls_config)
333 0 : .connect(domain, client)
334 0 : .await?;
335 0 : Connection::Tls(client)
336 : } else {
337 0 : Connection::Raw(client)
338 : };
339 :
340 : // doesn't yet matter as pg-sni-router doesn't report analytics logs
341 0 : ctx.set_success();
342 0 : ctx.log_connect();
343 0 :
344 0 : // Starting from here we only proxy the client's traffic.
345 0 : info!("performing the proxy pass...");
346 :
347 0 : let res = match client {
348 0 : Connection::Raw(mut c) => copy_bidirectional_client_compute(&mut tls_stream, &mut c).await,
349 0 : Connection::Tls(mut c) => copy_bidirectional_client_compute(&mut tls_stream, &mut c).await,
350 : };
351 :
352 0 : match res {
353 0 : Ok(_) => Ok(()),
354 0 : Err(ErrorSource::Client(err)) => Err(err).context("client"),
355 0 : Err(ErrorSource::Compute(err)) => Err(err).context("compute"),
356 : }
357 0 : }
358 :
359 : #[allow(clippy::large_enum_variant)]
360 : enum Connection {
361 : Raw(tokio::net::TcpStream),
362 : Tls(tokio_rustls::client::TlsStream<tokio::net::TcpStream>),
363 : }
|