Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ away from home (`compose.tailscale.yaml`).
|---|---|---|
| `LISTEN` | `0.0.0.0:8443` | |
| `TLS` | `self-signed` | `self-signed`, `off` behind a proxy, or `cert.pem,key.pem` |
| `TLS_NAMES` | | Names and addresses the page is opened at, for the self-signed certificate |
| `TLS_NAMES` | | Domains the page is opened at. It answers only to these, IP addresses and names no public DNS holds (`localhost`, `desk`, `.local`, `.home.arpa`, `.internal`); with your own certificate and none listed, to any name. The self-signed certificate covers them too |
| `PUNKTFUNK_HOSTS` | | Hosts mDNS cannot find: `name=address[:port][#fingerprint]`, comma-separated |
| `DISCOVER` | on | `0` turns the mDNS browse off |
| `ADD_HOSTS` | on | `0` stops the page reaching a host typed by address. Set it when the page is reachable from outside your network |
Expand Down
9 changes: 6 additions & 3 deletions deploy/compose.proxy.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@
# The page's origin is your proxy's domain: add it to each host's Browser origins (console,
# Streaming, advanced), or leave that list empty to allow any page.
#
# On networks that block UDP the page streams through this server. For that, the proxy must
# pass the browser's Host header through unchanged, or the stream is refused. The host then
# sees every such stream as coming from the proxy's address, so it treats it as local.
# On networks that block UDP the page streams through this server. The host then sees every
# such stream as coming from the proxy's address, so it treats it as local.
services:
punktfunk-web:
image: git.unom.io/unom/punktfunk-client-web:latest
Expand All @@ -15,6 +14,10 @@ services:
environment:
TLS: "off"
LISTEN: 0.0.0.0:8080
# Your proxy's domain. The page answers only to addresses, local names and the names here.
# The proxy must pass the browser's Host header through unchanged (nginx:
# `proxy_set_header Host $host;`), or the page's own requests are refused.
TLS_NAMES: play.example.com
# PUNKTFUNK_HOSTS: desk=192.168.1.21
volumes:
- punktfunk-web:/data
Expand Down
3 changes: 3 additions & 0 deletions deploy/compose.tailscale.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ services:
environment:
TLS: "off"
LISTEN: 127.0.0.1:8080
# This machine's tailnet name. The page answers only to addresses, local names and the
# names here; `tailscale serve` passes the browser's Host header through, as it must.
TLS_NAMES: punktfunk.your-tailnet.ts.net
PUNKTFUNK_HOSTS: desk=100.64.0.5
volumes:
- punktfunk-web:/data
Expand Down
20 changes: 1 addition & 19 deletions server/src/bridge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,6 @@ async fn open(
req: Request,
) -> Response {
let (mut parts, _) = req.into_parts();
if !same_origin(&parts) {
return StatusCode::FORBIDDEN.into_response();
}
let addr = match addr {
Ok(a) => a,
Err(status) => return status.into_response(),
Expand Down Expand Up @@ -120,21 +117,6 @@ async fn open(
.on_upgrade(move |socket| session(socket, target, host, slot))
}

/// The `wake` route's rule, and an `Origin`, when sent, that names this server: a page on another
/// site that could open the bridge could drive a host it has no right to.
fn same_origin(parts: &Parts) -> bool {
if header_str(parts, "sec-fetch-site") == Some("cross-site") {
return false;
}
let Some(origin) = header_str(parts, header::ORIGIN.as_str()) else {
return true;
};
let own = proxy::own_authority(&parts.uri, &parts.headers);
let theirs = origin.split_once("://").map(|(_, authority)| authority);
own.zip(theirs)
.is_some_and(|(a, b)| a.eq_ignore_ascii_case(b))
}

fn header_str<'a>(parts: &'a Parts, name: &str) -> Option<&'a str> {
parts.headers.get(name).and_then(|v| v.to_str().ok())
}
Expand Down Expand Up @@ -418,7 +400,7 @@ mod tests {
pin: None,
};
let hosts = Hosts::new(vec![desk], &dir, true).unwrap();
let app = crate::router(hosts, dir);
let app = crate::router(hosts, dir, None);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let at = listener.local_addr().unwrap();
tokio::spawn(async move {
Expand Down
35 changes: 34 additions & 1 deletion server/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ pub const MGMT_PORT: u16 = 47990;
pub struct Config {
pub listen: SocketAddr,
pub tls: Tls,
/// Names the self-signed certificate is issued for, beyond `localhost`.
/// Names the page is opened at: the only names it answers to besides addresses and local
/// ones, and the self-signed certificate's beyond `localhost`.
pub tls_names: Vec<String>,
pub hosts: Vec<Listed>,
/// Browse mDNS for hosts. Needs the container on the host's network to see anything.
Expand Down Expand Up @@ -76,6 +77,20 @@ impl Config {
data: get("DATA_DIR").unwrap_or_else(|| "data".into()).into(),
})
}

/// The names the page answers to besides addresses and local names. None to check with the
/// operator's certificate and no `TLS_NAMES`: a browser that trusts it refuses other names.
pub fn names(&self) -> crate::origin::Names {
if matches!(self.tls, Tls::Files { .. }) && self.tls_names.is_empty() {
return None;
}
let names = self.tls_names.iter();
Some(
names
.map(|n| n.trim_end_matches('.').to_ascii_lowercase())
.collect(),
)
}
}

/// A switch that is on unless set: `0`, `false`, `no` or `off` turn it off. A value it does not
Expand Down Expand Up @@ -205,4 +220,22 @@ mod tests {
let off = Config::from_lookup(|k| (k == "TLS").then(|| "off".into())).unwrap();
assert!(matches!(off.tls, Tls::Off));
}

#[test]
fn only_the_operators_certificate_alone_checks_no_name() {
let names = |tls: &str, names: &str| {
let env = [("TLS", tls), ("TLS_NAMES", names)];
let get = |k: &str| env.iter().find(|e| e.0 == k && !e.1.is_empty());
Config::from_lookup(|k| get(k).map(|e| e.1.into()))
.unwrap()
.names()
.map(|n| n.to_vec())
};
assert_eq!(names("c.pem,k.pem", ""), None);
let play = Some(vec!["play.example.com".to_string()]);
assert_eq!(names("c.pem,k.pem", "Play.Example.com."), play);
assert_eq!(names("off", "play.example.com"), play);
assert_eq!(names("off", ""), Some(Vec::new()));
assert_eq!(names("self-signed", ""), Some(Vec::new()));
}
}
30 changes: 12 additions & 18 deletions server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@
mod bridge;
mod config;
mod hosts;
mod origin;
mod proxy;
mod tls;

use axum::extract::{Path, Request, State};
use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
use axum::http::{header, HeaderValue, StatusCode};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use axum::routing::{any, get, post};
Expand All @@ -40,7 +41,7 @@ async fn main() -> anyhow::Result<()> {
if cfg.discover {
hosts::discover(hosts.clone());
}
let app = router(hosts, cfg.dist.clone());
let app = router(hosts, cfg.dist.clone(), cfg.names());

let handle = axum_server::Handle::new();
tokio::spawn(shutdown(handle.clone()));
Expand Down Expand Up @@ -68,18 +69,22 @@ async fn main() -> anyhow::Result<()> {
Ok(())
}

pub(crate) fn router(hosts: Arc<Hosts>, dist: PathBuf) -> Router {
/// Every route but the static files answers only this server's own page; every response, the
/// files included, answers only the names in `names`.
pub(crate) fn router(hosts: Arc<Hosts>, dist: PathBuf, names: origin::Names) -> Router {
Router::new()
.route("/config.json", get(config_json))
.route("/h/{id}/{*rest}", any(proxy::listed))
.route("/a/{target}/{*rest}", any(proxy::typed))
.route("/wake/{id}", post(wake))
.route("/w/{id}", get(bridge::listed))
.route("/wa/{target}", get(bridge::typed))
.route_layer(axum::middleware::from_fn(origin::own_page))
.with_state(hosts)
.layer(Extension(Arc::new(Semaphore::new(bridge::SESSIONS))))
.fallback_service(tower_http::services::ServeDir::new(dist))
.layer(axum::middleware::from_fn(cache))
.layer(axum::middleware::from_fn_with_state(names, origin::guard))
}

/// The hosts the page lists, and whether it may reach others by address through `/a/`. `api` and
Expand All @@ -102,19 +107,8 @@ async fn config_json(State(state): State<Arc<Hosts>>) -> impl IntoResponse {
}

/// Wake a listed host: a magic packet to every MAC it announced while awake, from this machine,
/// which is on the host's network where a browser cannot send one. Only this page may ask, not one
/// on another site: a cross-site request is refused.
async fn wake(
State(state): State<Arc<Hosts>>,
Path(id): Path<String>,
headers: HeaderMap,
) -> StatusCode {
if headers
.get("sec-fetch-site")
.is_some_and(|v| v == "cross-site")
{
return StatusCode::FORBIDDEN;
}
/// which is on the host's network where a browser cannot send one.
async fn wake(State(state): State<Arc<Hosts>>, Path(id): Path<String>) -> StatusCode {
let Some(host) = state.get(&id) else {
return StatusCode::NOT_FOUND;
};
Expand Down Expand Up @@ -196,7 +190,7 @@ mod tests {
};
for add in [true, false] {
let hosts = crate::Hosts::new(vec![desk.clone()], &dir, add).unwrap();
let res = crate::router(hosts, dir.clone())
let res = crate::router(hosts, dir.clone(), None)
.oneshot(Request::get("/config.json").body(Body::empty()).unwrap())
.await
.unwrap();
Expand Down Expand Up @@ -229,7 +223,7 @@ mod tests {
.unwrap()
};
let status = |req: Request<Body>| {
let app = crate::router(hosts.clone(), dir.clone());
let app = crate::router(hosts.clone(), dir.clone(), None);
async move { app.oneshot(req).await.unwrap().status() }
};
assert_eq!(status(wake("/wake/desk", "cross-site")).await, 403);
Expand Down
Loading
Loading