Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.
Rust desktop-appdiscorddiscord-clienteguielectron-alternativelightweightlinuxmacosnative-apprustwindows
Hardening: private folders, registry checks, https-only redirects, read-only CI (#40)
Needles4863c2541859
diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.ymlindex b59b9e6..0e99c25 100644--- a/.github/workflows/linux.yml+++ b/.github/workflows/linux.yml@@ -19,10 +19,10 @@ jobs:# The oldest supported Ubuntu with WebKitGTK 4.1: the binary then runs on# Ubuntu 22.04+, Debian 12+, Fedora 36+ and other distributions this new.runs-on: ubuntu-22.04- permissions:- contents: writesteps:- uses: actions/checkout@v7+ with:+ persist-credentials: false- name: Install the system librariesrun: |@@ -62,11 +62,28 @@ jobs:dist/*.tar.gzdist/*.tar.gz.sha256+ - name: Test+ run: cargo test --locked -p discord -p rencord -p voice -p rustcord++ release:+ # The only job that may write to the repository: it attaches what `build`+ # made, and runs nothing from the repository itself.+ needs: build+ # As before, the build is attached even when a later step of `build` (the+ # tests) failed. Without a build there is nothing to download, and this fails.+ if: ${{ !cancelled() && github.event_name == 'release' }}+ runs-on: ubuntu-latest+ permissions:+ contents: write+ steps:+ - uses: actions/download-artifact@v8+ with:+ name: rustcord-linux-x86_64+ path: dist+- name: Attach to the release- if: github.event_name == 'release'env:GH_TOKEN: ${{ github.token }}- run: gh release upload "${{ github.event.release.tag_name }}" dist/*.tar.gz dist/*.tar.gz.sha256 --clobber-- - name: Test- run: cargo test --locked -p discord -p rencord -p voice -p rustcord+ GH_REPO: ${{ github.repository }}+ TAG: ${{ github.event.release.tag_name }}+ run: gh release upload "$TAG" dist/*.tar.gz dist/*.tar.gz.sha256 --clobberdiff --git a/.github/workflows/macos.yml b/.github/workflows/macos.ymlindex 12de88b..654d602 100644--- a/.github/workflows/macos.yml+++ b/.github/workflows/macos.yml@@ -32,6 +32,8 @@ jobs:runs-on: ${{ matrix.runner }}steps:- uses: actions/checkout@v7+ with:+ persist-credentials: false- name: Install nasm# The H.264 decoder's assembly on Intel (it builds without, slower).@@ -67,6 +69,8 @@ jobs:runs-on: macos-15steps:- uses: actions/checkout@v7+ with:+ persist-credentials: false- uses: dtolnay/rust-toolchain@stable@@ -78,10 +82,10 @@ jobs:package:needs: buildruns-on: macos-15- permissions:- contents: writesteps:- uses: actions/checkout@v7+ with:+ persist-credentials: false- uses: actions/download-artifact@v8with:@@ -107,8 +111,24 @@ jobs:dist/*.dmgdist/*.dmg.sha256+ release:+ # The only job that may write to the repository: it attaches what `package`+ # made, and runs nothing from the repository itself. A failed smoke test+ # stops it, as before.+ needs: package+ if: github.event_name == 'release'+ runs-on: ubuntu-latest+ permissions:+ contents: write+ steps:+ - uses: actions/download-artifact@v8+ with:+ name: rustcord-macos-universal+ path: dist+- name: Attach to the release- if: github.event_name == 'release'env:GH_TOKEN: ${{ github.token }}- run: gh release upload "${{ github.event.release.tag_name }}" dist/*.dmg dist/*.dmg.sha256 --clobber+ GH_REPO: ${{ github.repository }}+ TAG: ${{ github.event.release.tag_name }}+ run: gh release upload "$TAG" dist/*.dmg dist/*.dmg.sha256 --clobberdiff --git a/README.md b/README.mdindex b59e5ed..a6b1a9e 100644--- a/README.md+++ b/README.md@@ -334,9 +334,11 @@ are declared with `SettingDef::{bool, text, select}` and RustCord draws their UI- **Blending in:** it presents itself to Discord as Discord's own web client, and paces itsrequests like it, because clients that stand out risk being flagged by Discord's anti-spam.- **Local data:** so your account opens instantly, a snapshot of it (servers, channels, DMs,- friends, read states; never the token) is kept in `%LOCALAPPDATA%\RustCord`, encrypted for- your Windows account, and deleted when you log out. On Linux it's in `~/.cache/rustcord`, on- macOS in `~/Library/Caches/dev.RustCord.RustCord`, and not encrypted there yet.+ friends, read states; never the token) and the newest messages of recently opened channels+ are kept in `%LOCALAPPDATA%\RustCord`, encrypted for your Windows account, and deleted when+ you log out. On Linux they're in `~/.cache/rustcord`, on macOS in+ `~/Library/Caches/dev.RustCord.RustCord`, in a folder only your user can open, but not+ encrypted there yet.<details><summary><b>Everything RustCord connects to</b></summary>diff --git a/apps/rustcord/src/app.rs b/apps/rustcord/src/app.rsindex 9f2fc7f..ac3013b 100644--- a/apps/rustcord/src/app.rs+++ b/apps/rustcord/src/app.rs@@ -2475,7 +2475,7 @@ impl RustCord {let (row, then, at) = known?;let (joined, seen) = (*row)?;// The service's clock, carried forward by how long ago it answered.- let now = then + at.elapsed().as_secs();+ let now = then.saturating_add(at.elapsed().as_secs());Some(crate::registry::Membership { joined, online: now.saturating_sub(seen) <= crate::registry::ONLINE_FOR_SECS })}diff --git a/apps/rustcord/src/cache.rs b/apps/rustcord/src/cache.rsindex 3192e4e..b0d9fdd 100644--- a/apps/rustcord/src/cache.rs+++ b/apps/rustcord/src/cache.rs@@ -5,10 +5,12 @@//! friends, read states), shown while the gateway is still connecting.//! (Images have their own cache in `net_images`.)//!-//! Both are kept per account (`accounts/<user ID>/` in the cache folder) and-//! sealed before they touch the disk (see [`seal`]): messages and the-//! account's servers and friends are private, and a file in the cache folder-//! is otherwise readable by whoever gets hold of the disk.+//! Both are kept per account (`accounts/<user ID>/` in the cache folder).+//! Messages and the account's servers and friends are private: on Windows+//! they are sealed before they touch the disk (see [`seal`]), as a file in the+//! cache folder is otherwise readable by whoever gets hold of the disk. On+//! Linux and macOS they are stored as is, in a folder only this user can open+//! (see [`make_folders_private`]).use discord::model::{Id, Message};use serde_json::Value;@@ -76,13 +78,42 @@ mod seal {}}- /// (Other systems have no equivalent wired up yet: stored as is.)+ /// (Other systems have no equivalent wired up yet: stored as is, in a+ /// folder only this user can open, see `make_folders_private`.)#[cfg(not(windows))]fn protect(data: &[u8], _seal: bool) -> Option<Vec<u8>> {Some(data.to_vec())}}+/// Create RustCord's two folders, this cache folder and the config folder+/// (saved accounts, settings, the log), and let only this user open them,+/// before anything is written there. Everything RustCord keeps is below them,+/// so nothing inside needs its own mode, and folders made by an earlier+/// version are tightened at the next start. Without this they get whatever+/// the umask gives, usually readable by every account on the machine. (On+/// Windows the profile folder is already the user's own, and the caches are+/// sealed, see [`seal`].)+pub fn make_folders_private() {+ #[cfg(unix)]+ {+ if let Some(d) = directories::ProjectDirs::from("dev", "RustCord", "RustCord") {+ for root in [d.cache_dir(), d.config_dir()] {+ make_private(root);+ }+ }+ }+}++/// Create `dir` if needed and set it to 0700 (best effort: RustCord still+/// starts if it can't).+#[cfg(unix)]+fn make_private(dir: &std::path::Path) {+ use std::os::unix::fs::PermissionsExt;+ let _ = std::fs::create_dir_all(dir);+ let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));+}+/// Remove what earlier versions left behind (at start-up, after the saved/// accounts were read).pub fn remove_stale() {@@ -298,6 +329,24 @@ mod tests {assert!(super::remove_tree(&root));}+ #[cfg(unix)]+ #[test]+ fn folders_are_private_to_this_user() {+ use std::os::unix::fs::PermissionsExt;+ fn mode(p: &std::path::Path) -> u32 {+ std::fs::metadata(p).unwrap().permissions().mode() & 0o777+ }+ let root = std::env::temp_dir().join(format!("rustcord-private-test-{}", std::process::id()));+ let dir = root.join("rustcord");+ super::make_private(&dir);+ assert_eq!(mode(&dir), 0o700);+ // A folder an earlier version left open is closed too.+ std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();+ super::make_private(&dir);+ assert_eq!(mode(&dir), 0o700);+ assert!(super::remove_tree(&root));+ }+#[test]fn sealed_data_opens_again_and_is_not_readable_on_disk() {let plain = br#"[{"id":"1","content":"a private message"}]"#;diff --git a/apps/rustcord/src/main.rs b/apps/rustcord/src/main.rsindex 3606c3d..d46d30f 100644--- a/apps/rustcord/src/main.rs+++ b/apps/rustcord/src/main.rs@@ -65,6 +65,8 @@ fn app_icon() -> egui::IconData {}fn main() -> eframe::Result<()> {+ // Before anything (the log, the saved accounts) is written there.+ cache::make_folders_private();#[cfg(target_os = "linux")]linux::prefer_x11();// The uninstaller's "delete my saved login": end every saved session atdiff --git a/apps/rustcord/src/net_images.rs b/apps/rustcord/src/net_images.rsindex d422c43..08d0964 100644--- a/apps/rustcord/src/net_images.rs+++ b/apps/rustcord/src/net_images.rs@@ -522,6 +522,8 @@ impl NetImages {.user_agent(concat!("RustCord/", env!("CARGO_PKG_VERSION"))).timeout(Duration::from_secs(30)).pool_max_idle_per_host(MAX_CONCURRENT)+ // Only https addresses are fetched; a redirect can't lead to http.+ .redirect(discord::http::https_only_redirects()).build().expect("image client");let root = directories::ProjectDirs::from("dev", "RustCord", "RustCord").map(|d| d.cache_dir().to_path_buf());diff --git a/apps/rustcord/src/registry.rs b/apps/rustcord/src/registry.rsindex 6294043..177a5ac 100644--- a/apps/rustcord/src/registry.rs+++ b/apps/rustcord/src/registry.rs@@ -41,8 +41,22 @@ pub const MAX_LOOKUP: usize = 50;pub fn url() -> Option<String> {let url = std::env::var("RUSTCORD_REGISTRY_URL").ok().or_else(|| BUILT_IN_URL.map(String::from))?;let url = url.trim().trim_end_matches('/');- let local = ["http://127.0.0.1", "http://localhost"].iter().any(|l| url.strip_prefix(l).is_some_and(|rest| rest.is_empty() || rest.starts_with(':')));- (url.starts_with("https://") || local).then(|| url.to_string())+ allowed(url).then(|| url.to_string())+}++/// Whether `url` may be the registry: https, or http only when the host is+/// exactly this PC, and never with a user name or password in it+/// (`http://127.0.0.1:[email protected]` goes to host.example).+fn allowed(url: &str) -> bool {+ let Ok(u) = url::Url::parse(url) else { return false };+ if !u.username().is_empty() || u.password().is_some() {+ return false;+ }+ match u.scheme() {+ "https" => u.host().is_some(),+ "http" => matches!(u.host_str(), Some("127.0.0.1" | "localhost")),+ _ => false,+ }}/// A user's row key: the hex SHA-256 of "rustcord-user:<id>".@@ -78,16 +92,38 @@ pub struct Membership {pub online: bool,}+/// The longest answer that is read. 50 keys answer in about 5 KB, so anything+/// near this isn't the registry's.+const MAX_ANSWER: usize = 64 * 1024;+fn client() -> Result<reqwest::Client, String> {- reqwest::Client::builder().timeout(Duration::from_secs(20)).user_agent("RustCord").build().map_err(|e| e.to_string())+ // The registry never redirects; following one could send the request to+ // another host, or over plain http.+ reqwest::Client::builder()+ .timeout(Duration::from_secs(20))+ .user_agent("RustCord")+ .redirect(reqwest::redirect::Policy::none())+ .build()+ .map_err(|e| e.to_string())}async fn post(client: &reqwest::Client, url: String, body: Value, asked: &[Id]) -> Result<Answer, String> {- let resp = client.post(url).json(&body).send().await.map_err(|e| e.to_string())?;+ let mut resp = client.post(url).json(&body).send().await.map_err(|e| e.to_string())?;if !resp.status().is_success() {return Err(format!("the registry answered {}", resp.status()));}- let v: Value = resp.json().await.map_err(|e| e.to_string())?;+ let too_long = || "the registry's answer is too long".to_string();+ if resp.content_length().is_some_and(|n| n > MAX_ANSWER as u64) {+ return Err(too_long());+ }+ let mut bytes = Vec::new();+ while let Some(chunk) = resp.chunk().await.map_err(|e| e.to_string())? {+ if bytes.len() + chunk.len() > MAX_ANSWER {+ return Err(too_long());+ }+ bytes.extend_from_slice(&chunk);+ }+ let v: Value = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?;Answer::parse(&v, asked).ok_or_else(|| "the registry sent something unreadable".to_string())}@@ -173,6 +209,22 @@ mod tests {assert!(k.chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()));}+ #[test]+ fn only_https_or_http_on_this_pc() {+ for ok in ["https://registry.example", "http://127.0.0.1:8787", "http://localhost:8787"] {+ assert!(allowed(ok), "{ok}");+ }+ for bad in [+ "http://127.0.0.1:[email protected]",+ "http://localhost.evil.example",+ "http://example.com",+ "https://user:[email protected]",+ "ftp://registry.example",+ ] {+ assert!(!allowed(bad), "{bad}");+ }+ }+/// Against a running registry (`node server/dev.mjs`, then/// `RUSTCORD_REGISTRY_URL=http://127.0.0.1:8787 cargo test -- --ignored registry`).#[tokio::test]diff --git a/apps/rustcord/src/rpc.rs b/apps/rustcord/src/rpc.rsindex 055697e..3c84af2 100644--- a/apps/rustcord/src/rpc.rs+++ b/apps/rustcord/src/rpc.rs@@ -100,6 +100,15 @@ wherelog::warn!("rpc: every discord-ipc socket is in use; Rich Presence is off");return;};+ // Only this user may connect. Without XDG_RUNTIME_DIR the socket sits in+ // a shared folder, and its mode would otherwise depend on the umask. Games+ // run as the same user, so nothing changes for them.+ {+ use std::os::unix::fs::PermissionsExt;+ if let Err(e) = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)) {+ log::warn!("rpc: could not make {} private: {e}", path.display());+ }+ }log::info!("rpc: serving Rich Presence on {}", path.display());let mut next = 1u64;loop {diff --git a/crates/discord/src/http.rs b/crates/discord/src/http.rsindex b9273f7..c9819fc 100644--- a/crates/discord/src/http.rs+++ b/crates/discord/src/http.rs@@ -283,6 +283,22 @@ pub fn account_locale() -> Option<String> {ACCOUNT_LOCALE.read().ok().and_then(|l| l.clone())}+/// Redirects for clients that fetch addresses from elsewhere (images, theme+/// files, uploads): those are checked to be https before the request, so a+/// redirect may not lead to plain http either. Otherwise reqwest's usual limit+/// of 10.+pub fn https_only_redirects() -> reqwest::redirect::Policy {+ reqwest::redirect::Policy::custom(|attempt| {+ if attempt.url().scheme() != "https" {+ attempt.error("redirected to an address that isn't https")+ } else if attempt.previous().len() > 10 {+ attempt.error("too many redirects")+ } else {+ attempt.follow()+ }+ })+}+fn discord_headers() -> reqwest::header::HeaderMap {use reqwest::header::{HeaderMap, HeaderValue};let mut h = HeaderMap::new();@@ -312,6 +328,7 @@ impl Http {let plain = Client::builder().user_agent(concat!("RustCord/", env!("CARGO_PKG_VERSION"))).timeout(Duration::from_secs(60))+ .redirect(https_only_redirects()).build().expect("failed to build HTTP client");Self { client, plain, token, spotify: Default::default() }diff --git a/server/registry.mjs b/server/registry.mjsindex b7890c9..812542c 100644--- a/server/registry.mjs+++ b/server/registry.mjs@@ -6,7 +6,8 @@// POST /v1/bye {"key": "<64 hex>"} hide that row (the badge setting, off)// POST /v1/lookup {"keys": ["<64 hex>", …]} are these RustCord users? (50 at most)//-// Every answer is {"now": <unix s>, "users": {"<key>": [joined, seen]}} with+// Requests are sent with content-type: application/json (anything else gets+// 415). Every answer is {"now": <unix s>, "users": {"<key>": [joined, seen]}} with// only the keys that were asked about (hello: your own). There is no way to// list the rows: you can only ask about a user whose ID you already have.//@@ -34,6 +35,11 @@ export async function handle(request, store, now = Math.floor(Date.now() / 1000)if (request.method !== "POST" || !["/v1/hello", "/v1/bye", "/v1/lookup"].includes(pathname)) {return json({ error: "not found" }, 404);}+ // A web page can make its visitors' browsers send text/plain POSTs to any+ // site without asking first; application/json needs a preflight, which this+ // service never answers, so browsers can't be used to write rows.+ const type = (request.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();+ if (type !== "application/json") return json({ error: "send application/json" }, 415);// 50 keys and their JSON wrapping: anything much longer isn't one of ours.const text = await request.text();if (text.length > 4096) return json({ error: "too long" }, 413);diff --git a/server/test.mjs b/server/test.mjsindex 34c8161..197fafb 100644--- a/server/test.mjs+++ b/server/test.mjs@@ -7,7 +7,8 @@ import { handle, memoryStore, MAX_LOOKUP } from "./registry.mjs";const A = "a".repeat(64);const B = "b".repeat(64);const C = "c".repeat(64);-const post = (path, body) => new Request(`http://x${path}`, { method: "POST", body: typeof body === "string" ? body : JSON.stringify(body) });+const post = (path, body, type = "application/json") =>+ new Request(`http://x${path}`, { method: "POST", headers: type ? { "content-type": type } : {}, body: typeof body === "string" ? body : JSON.stringify(body) });const get = (path) => new Request(`http://x${path}`);const call = async (store, now, path, body) => (await handle(post(path, body), store, now)).json();@@ -48,3 +49,13 @@ test("the rows can't be listed, and only hashed keys are accepted", async () =>}assert.equal(store.rows.size, 1);});++test("only JSON requests are read, so a web page can't write rows through a browser", async () => {+ const store = memoryStore();+ for (const type of [null, "text/plain", "text/plain;charset=UTF-8", "application/x-www-form-urlencoded"]) {+ assert.equal((await handle(post("/v1/hello", { key: A }, type), store, 1000)).status, 415, String(type));+ }+ assert.equal(store.rows.size, 0);+ assert.equal((await handle(post("/v1/hello", { key: A }, "Application/JSON; charset=utf-8"), store, 1000)).status, 200);+ assert.equal(store.rows.size, 1);+});