Skip to content

An open-source cross-platform alternative to AirDrop

fix: anonymous sender fingerprint (#3754)

Tien Nam Do0d9060eeebc2
diff --git a/AGENTS.md b/AGENTS.md
index 28a150cb..dd638fb5 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -114,7 +114,7 @@ Save targets are decided in Dart (`prepareFileSaveTarget`) and written by Rust:
Server event `ip`s are `PeerIp` (IP + IPv6 scope): a link-local peer renders as `fe80::1%3`, which the HTTP client accepts back as a host, so event ips stay dialable.
-TLS uses per-device on-the-fly certificates with **mandatory client certificates** (optional while the web pages are served, so browsers can connect); the peer identity is the uppercase-hex SHA-256 of the client cert DER, and `Register` is simply not emitted when a payload's claimed fingerprint disagrees with the cert. Prefer `event.certFingerprint ?? event.info.fingerprint` — the payload fallback only exists for encryption-off mode.
+TLS uses per-device on-the-fly certificates with **mandatory client certificates** (optional while the web pages are served, so browsers can connect); the peer identity is the uppercase-hex SHA-256 of the client cert DER, and `Register` is simply not emitted when a payload's claimed fingerprint disagrees with the cert or no cert was presented; `prepare-upload` with a cert whose fingerprint disagrees with the claim is rejected with 403. Use `PrepareUpload`'s `sender_fingerprint` (Dart: `event.senderFingerprint`), never `info.fingerprint`: it is the cert fingerprint on TLS, the self-reported one only in encryption-off mode, and `null` for a cert-less TLS client (a browser while the web pages are served) — such a sender is anonymous and must never match a favorite.
Both the receive pin and the web-send pin are fixed at server start, so changing either restarts the server.
@@ -127,6 +127,8 @@ Integration mirrors the HTTP server: `multicast::start` takes a `MulticastConfig
UDP is **announce-only**: responses go back over HTTP as a unicast register request to the announcing device.
+The discovery store (`packages/core/src/discovery/store.rs`) dedupes devices by fingerprint. Over plain HTTP a fingerprint is only claimed, so once a device is reached over (pinned) HTTPS it is `verified`: its HTTP channels are dropped and later HTTP observations of that fingerprint are ignored, otherwise anyone could route transfers to a known device through an unpinned HTTP channel.
+
One socket is bound per interface IPv4 address (`SO_REUSEPORT`/`SO_REUSEADDR` + `IP_MULTICAST_IF`), because a single socket only sends on one interface. Multicast loopback stays on so that instances on one host see each other; own messages are dropped by fingerprint. IPv6 is a LocalSend extension (group `ff12::fd3a:e420`, `DEFAULT_MULTICAST_GROUP_V6`), enabled by setting `group_v6`: one `IPV6_V6ONLY` socket per interface, joined by interface index. `Discovered` carries the source's scope ID (interface index), which link-local IPv6 sources need for the HTTP answer.
### i18n
diff --git a/app/lib/provider/network/server/controller/receive_controller.dart b/app/lib/provider/network/server/controller/receive_controller.dart
index 9f1c0da8..21f2894c 100644
--- a/app/lib/provider/network/server/controller/receive_controller.dart
+++ b/app/lib/provider/network/server/controller/receive_controller.dart
@@ -83,10 +83,14 @@ class ReceiveController {
for (final entry in event.files.entries) entry.key: entry.value.toDart(),
};
- // The fingerprint of the sender's mTLS certificate cannot be spoofed, unlike the
- // self-reported fingerprint in the JSON payload which is only used as fallback
- // when encryption is disabled.
- final senderFingerprint = event.certFingerprint ?? event.info.fingerprint;
+ // Never use the self-reported fingerprint in the JSON payload: the server provides
+ // the one proven by the sender's mTLS certificate (or, with encryption disabled, the
+ // self-reported one). It is null for an anonymous sender (e.g. a browser on the
+ // receive-via-link page), which must never be treated as a favorite.
+ final senderFingerprint = event.senderFingerprint;
+ final senderFavorite = senderFingerprint == null
+ ? null
+ : server.ref.read(favoritesProvider).firstWhereOrNull((e) => e.fingerprint == senderFingerprint);
_logger.info('Session Id: $sessionId');
_logger.info('Destination Directory: $destinationDir');
@@ -96,8 +100,8 @@ class ReceiveController {
session: ReceiveSessionState(
sessionId: sessionId,
status: SessionStatus.waiting,
- sender: event.info.toDevice(event.ip, withChannel: false).copyWith(fingerprint: senderFingerprint),
- senderAlias: server.ref.read(favoritesProvider).firstWhereOrNull((e) => e.fingerprint == senderFingerprint)?.alias ?? event.info.alias,
+ sender: event.info.toDevice(event.ip, withChannel: false).copyWith(fingerprint: senderFingerprint ?? ''),
+ senderAlias: senderFavorite?.alias ?? event.info.alias,
files: {
for (final file in files.values)
file.id: ReceivingFile(
@@ -128,11 +132,8 @@ class ReceiveController {
bool quickSave = settings.quickSave && server.getState().session?.isMessageRequest != true;
final quickSaveFromFavorites = settings.quickSaveFromFavorites && server.getState().session?.isMessageRequest != true;
- if (quickSaveFromFavorites) {
- final bool isFavorite = server.ref.read(favoritesProvider).any((e) => e.fingerprint == senderFingerprint);
- if (isFavorite) {
- quickSave = true;
- }
+ if (quickSaveFromFavorites && senderFavorite != null) {
+ quickSave = true;
}
if (server.getState().webUpload && settings.receiveViaLinkAutoAccept && server.getState().session?.isMessageRequest != true) {
// The upload page (receive via link) is being served and requests should be accepted automatically.
@@ -188,7 +189,8 @@ class ReceiveController {
return ReceivePageVm(
status: session?.status,
sender: session?.sender ?? Device.empty,
- showSenderInfo: true,
+ // An anonymous sender (empty fingerprint) has nothing to verify.
+ showSenderInfo: session == null || session.sender.fingerprint.isNotEmpty,
files: session?.files.values.map((f) => f.file).toList() ?? [],
message: message,
onAccept: () async {
@@ -415,7 +417,7 @@ class ReceiveController {
// the session to stay open.
bool quickSave = settings.quickSave && !hasError && server.getState().session?.isMessageRequest != true;
final quickSaveFromFavorites = settings.quickSaveFromFavorites && !hasError && server.getState().session?.isMessageRequest != true;
- if (quickSaveFromFavorites) {
+ if (quickSaveFromFavorites && session.sender.fingerprint.isNotEmpty) {
final bool isFavorite = server.ref.read(favoritesProvider).any((e) => e.fingerprint == session.sender.fingerprint);
if (isFavorite) {
quickSave = true;
diff --git a/app/lib/util/favorites.dart b/app/lib/util/favorites.dart
index c3f72215..f12c5ddf 100644
--- a/app/lib/util/favorites.dart
+++ b/app/lib/util/favorites.dart
@@ -4,12 +4,16 @@ import 'package:localsend_isolates/model/device.dart';
extension FavoriteDevicesExt on Iterable<FavoriteDevice> {
/// Returns the favorite device with the given [device] or null if not found.
+ /// A device without fingerprint (e.g. an anonymous sender) is never a favorite.
FavoriteDevice? findDevice(Device device) {
+ if (device.fingerprint.isEmpty) {
+ return null;
+ }
return firstWhereOrNull((e) => e.fingerprint == device.fingerprint);
}
/// Returns true if the list contains the given [device].
bool containsDevice(Device device) {
- return any((e) => e.fingerprint == device.fingerprint);
+ return findDevice(device) != null;
}
}
diff --git a/cli/src/app/devices.rs b/cli/src/app/devices.rs
index ebe7f6ff..b95b1123 100644
--- a/cli/src/app/devices.rs
+++ b/cli/src/app/devices.rs
@@ -220,6 +220,7 @@ mod tests {
download: false,
},
confirmed: true,
+ verified: true,
channels: [
(channel("10.0.0.10"), failed),
(channel("fe80::1%3"), untested),
diff --git a/cli/src/app/receive.rs b/cli/src/app/receive.rs
index 6ff66d16..4521d2c6 100644
--- a/cli/src/app/receive.rs
+++ b/cli/src/app/receive.rs
@@ -3,7 +3,6 @@
use super::App;
use super::sending::MAX_MESSAGE_BYTES;
-use super::web_link::WebMode;
use crate::sanitize;
use crate::ui::Category;
use crate::util::{self, SpeedMeter};
@@ -33,6 +32,9 @@ pub(super) struct PendingReceive {
pub(super) session_id: String,
pub(super) alias: String,
pub(super) sender: SenderTarget,
+ /// Whether `sender.fingerprint` is proven by a client certificate.
+ /// Only verified senders can be paired.
+ pub(super) verified: bool,
pub(super) files: HashMap<String, FileDto>,
pub(super) decision_tx: oneshot::Sender<PrepareUploadDecisionV2>,
}
@@ -130,12 +132,30 @@ impl App {
session_id,
ip,
info,
- cert_fingerprint,
+ sender_fingerprint,
files,
decision_tx,
} => {
+ // Queued by a server that has since been stopped (e.g. a web
+ // mode toggle): the sender is gone, and `verified` below would
+ // be judged against the new mode.
+ if decision_tx.is_closed() {
+ return;
+ }
+
+ // While a web page is served, the server runs without TLS (see
+ // `restart_server`), so the fingerprint is only self-reported
+ // and any sender could claim to be a paired device. Otherwise
+ // it is proven by the client certificate, and core rejects a
+ // request whose `info` claims another one.
+ let verified = self.web.is_none() && sender_fingerprint.is_some();
+
// The sender is clearly reachable; make sure it has a slot.
- self.device_confirmed(ip.to_string(), info.clone());
+ // Only a proven `info` may enter the store: a claim could
+ // rename a known device or attach a channel to it.
+ if verified {
+ self.device_confirmed(ip.to_string(), info.clone());
+ }
let alias = sanitize::single_line(&info.alias);
if let Some(message) = message_of(&files) {
@@ -156,10 +176,10 @@ impl App {
host: ip.to_string(),
port: info.port,
protocol: info.protocol,
- fingerprint: cert_fingerprint.unwrap_or_else(|| info.fingerprint.clone()),
+ fingerprint: sender_fingerprint.unwrap_or_else(|| info.fingerprint.clone()),
};
- if self.storage.paired.contains(&sender.fingerprint) {
+ if verified && self.storage.paired.contains(&sender.fingerprint) {
let ids: HashSet<String> = files.keys().cloned().collect();
if decision_tx
.send(PrepareUploadDecisionV2::Accept(ids))
@@ -190,11 +210,11 @@ impl App {
sorted.len() - MAX_LISTED_FILES
));
}
- // Web senders have no stable identity worth pairing: the
- // fingerprint is an unverified payload value.
- let prompt = match self.web {
- Some(WebMode::Receive) => "\nAccept? Y/N",
- _ => "\nAccept? Y/N/P (P = accept and pair)",
+ // Unverified senders have no stable identity worth pairing:
+ // the fingerprint is a self-reported payload value.
+ let prompt = match verified {
+ false => "\nAccept? Y/N",
+ true => "\nAccept? Y/N/P (P = accept and pair)",
};
lines.push(prompt.to_string());
self.ui.log(Category::Receive, &lines.join("\n"));
@@ -202,6 +222,7 @@ impl App {
session_id,
alias,
sender,
+ verified,
files,
decision_tx,
});
@@ -457,11 +478,9 @@ impl App {
Category::Receive,
&format!("{}: You accepted", pending.alias),
);
- // While "receive via link" is on, P was not offered; a stray
- // press still accepts, but never pairs.
- if matches!(answer, Answer::AcceptAndPair)
- && !matches!(self.web, Some(WebMode::Receive))
- {
+ // P was not offered for an unverified sender; a stray press
+ // still accepts, but never pairs.
+ if matches!(answer, Answer::AcceptAndPair) && pending.verified {
let channels = self
.discovery
.device_by_fingerprint(&pending.sender.fingerprint)
diff --git a/cli/src/app/target.rs b/cli/src/app/target.rs
index 68da19f4..49e7d360 100644
--- a/cli/src/app/target.rs
+++ b/cli/src/app/target.rs
@@ -98,6 +98,7 @@ mod tests {
download: false,
},
confirmed: true,
+ verified: true,
channels: HashMap::from([(
channel,
ChannelState {
diff --git a/packages/core/src/discovery/mod.rs b/packages/core/src/discovery/mod.rs
index 2afca4ec..2dba8d63 100644
--- a/packages/core/src/discovery/mod.rs
+++ b/packages/core/src/discovery/mod.rs
@@ -223,8 +223,10 @@ impl DiscoveryState {
let (event, merged) =
self.store
.observe(device, observation, announcement, SystemTime::now());
- let is_new = matches!(event, DiscoveryEvent::Discovered { .. });
- self.emit(event);
+ let is_new = matches!(event, Some(DiscoveryEvent::Discovered { .. }));
+ if let Some(event) = event {
+ self.emit(event);
+ }
(is_new, merged)
}
@@ -468,6 +470,9 @@ impl DiscoveryHandle {
/// ([`ClientError::is_unreachable`]), not requests that the device
/// answered with an error.
///
+ /// A request over HTTPS must have been pinned to `fingerprint`: its
+ /// success verifies the device ([`StatefulDevice::verified`]).
+ ///
/// Returns `false` when no device has the fingerprint.
pub fn report_outbound(
&self,
@@ -481,7 +486,9 @@ impl DiscoveryHandle {
.report_outbound(fingerprint, channel, result, SystemTime::now());
match event {
Some(event) => {
- self.state.emit(event);
+ if let Some(event) = event {
+ self.state.emit(event);
+ }
true
}
None => false,
diff --git a/packages/core/src/discovery/store.rs b/packages/core/src/discovery/store.rs
index 57dafcc3..7593463c 100644
--- a/packages/core/src/discovery/store.rs
+++ b/packages/core/src/discovery/store.rs
@@ -56,6 +56,19 @@ pub struct StatefulDevice {
/// offered as a transfer target.
pub confirmed: bool,
+ /// Whether the device's fingerprint is proven: this device reached it
+ /// over a channel that authenticates the peer
+ /// ([`DeviceChannel::authenticates`], i.e. HTTPS).
+ ///
+ /// From then on, observations over channels that do not authenticate
+ /// the peer (plain HTTP, where the fingerprint is only claimed) are
+ /// ignored, and such channels are dropped. Otherwise anyone could attach
+ /// a channel to the device by claiming its fingerprint, and a transfer
+ /// to the device would go to them without the certificate pin ever
+ /// being checked. A device that switches to plain HTTP is therefore
+ /// only seen again once the store is recreated.
+ pub verified: bool,
+
/// Every channel the device was observed on, with what is known about
/// each direction.
pub channels: HashMap<DeviceChannel, ChannelState>,
@@ -232,6 +245,11 @@ impl StatefulDevice {
},
);
+ if matches!(observation, Observation::Reached) && device.channel.authenticates() {
+ self.verified = true;
+ self.channels.retain(|channel, _| channel.authenticates());
+ }
+
if let Observation::Failed(error) = observation {
// A failed request carries no verified information: what a
// confirmed device said about itself must not be replaced by
@@ -318,6 +336,12 @@ impl StatefulDevice {
}
}
+ /// Whether an observation over `channel` must be ignored, see
+ /// [`StatefulDevice::verified`].
+ fn ignores(&self, channel: &DeviceChannel) -> bool {
+ self.verified && !channel.authenticates()
+ }
+
fn log(&mut self, timestamp: SystemTime, event: DeviceLogEvent) {
self.logs.push(DeviceLog { timestamp, event });
if self.logs.len() > MAX_LOGS {
@@ -352,6 +376,16 @@ impl DeviceChannel {
}
}
+ /// Whether a successful request over the channel authenticates the peer,
+ /// i.e. proves that it holds the fingerprint it claims: HTTPS requests
+ /// are pinned to the fingerprint (the hash of the peer's certificate),
+ /// while plain HTTP has nothing to verify it with.
+ pub fn authenticates(&self) -> bool {
+ match self {
+ DeviceChannel::Http(http) => http.protocol == ProtocolType::Https,
+ }
+ }
+
/// Whether two channels address the same endpoint, so that a
/// re-confirmation updates the known channel instead of adding one.
fn same_endpoint(&self, other: &DeviceChannel) -> bool {
@@ -433,13 +467,16 @@ impl DeviceStore {
/// [`DiscoveryEvent::Updated`] afterwards. A failure yields `Updated`
/// for a confirmed device and [`DiscoveryEvent::Unreachable`] otherwise;
/// an unknown device then enters the store unconfirmed.
+ ///
+ /// Yields no event when the observation is ignored because it does not
+ /// authenticate a verified device ([`StatefulDevice::verified`]).
pub(super) fn observe(
&self,
device: DiscoveredDevice,
observation: Observation,
announcement: Option<Announcement>,
timestamp: SystemTime,
- ) -> (DiscoveryEvent, StatefulDevice) {
+ ) -> (Option<DiscoveryEvent>, StatefulDevice) {
let mut devices = self.devices.lock().unwrap();
let index = match devices
.iter()
@@ -450,6 +487,7 @@ impl DeviceStore {
devices.push(StatefulDevice {
device: device.clone(),
confirmed: false,
+ verified: false,
channels: HashMap::new(),
logs: Vec::new(),
});
@@ -458,6 +496,15 @@ impl DeviceStore {
};
let known = &mut devices[index];
+ if known.ignores(&device.channel) {
+ tracing::debug!(
+ "Ignoring an unauthenticated observation of verified device {}: {:?}",
+ known.device.alias,
+ device.channel
+ );
+ return (None, known.clone());
+ }
+
if let Some(announcement) = announcement {
known.log(
announcement.timestamp,
@@ -467,23 +514,27 @@ impl DeviceStore {
);
}
let event = known.apply(device, observation, timestamp);
- (event, known.clone())
+ (Some(event), known.clone())
}
/// Merges the outcome of a request sent to a known device over
/// `channel` into the store, like [`DeviceStore::observe`]. Returns
- /// `None` when no device has the fingerprint.
+ /// `None` when no device has the fingerprint, and `Some(None)` when the
+ /// outcome is ignored like in [`DeviceStore::observe`].
pub(super) fn report_outbound(
&self,
fingerprint: &str,
channel: DeviceChannel,
result: Result<(), String>,
timestamp: SystemTime,
- ) -> Option<DiscoveryEvent> {
+ ) -> Option<Option<DiscoveryEvent>> {
let mut devices = self.devices.lock().unwrap();
let known = devices
.iter_mut()
.find(|known| known.device.fingerprint == fingerprint)?;
+ if known.ignores(&channel) {
+ return Some(None);
+ }
let device = DiscoveredDevice {
channel,
@@ -493,7 +544,7 @@ impl DeviceStore {
Ok(()) => Observation::Reached,
Err(error) => Observation::Failed(error),
};
- Some(known.apply(device, observation, timestamp))
+ Some(Some(known.apply(device, observation, timestamp)))
}
/// All confirmed devices in the order they were first observed.
@@ -557,6 +608,7 @@ mod tests {
store
.observe(device, Observation::Reached, None, SystemTime::now())
.0
+ .expect("the observation was ignored")
}
/// `device` reached this device.
@@ -564,6 +616,7 @@ mod tests {
store
.observe(device, Observation::ReachedUs, None, SystemTime::now())
.0
+ .expect("the observation was ignored")
}
/// This device could not reach `device`.
@@ -576,6 +629,7 @@ mod tests {
SystemTime::now(),
)
.0
+ .expect("the observation was ignored")
}
fn channel_host(channel: &DeviceChannel) -> &str {
@@ -947,7 +1001,7 @@ mod tests {
match event {
// The device stays confirmed: only the ranking of its channels
// changed.
- Some(DiscoveryEvent::Updated { device }) => {
+ Some(Some(DiscoveryEvent::Updated { device })) => {
assert_eq!(device.alias, "Alias of a");
assert_eq!(channel_host(&device.channel), "192.168.0.10");
}
@@ -960,7 +1014,7 @@ mod tests {
);
let event = store.report_outbound("a", channel("192.168.0.10", 53317), Ok(()), now);
- assert!(matches!(event, Some(DiscoveryEvent::Updated { .. })));
+ assert!(matches!(event, Some(Some(DiscoveryEvent::Updated { .. }))));
let known = store.by_fingerprint("a").unwrap();
assert_eq!(
state_of(&known, "192.168.0.10").outbound,
@@ -1140,4 +1194,94 @@ mod tests {
);
assert!(store.by_fingerprint("c").is_none());
}
+
+ fn http_device(fingerprint: &str, host: &str) -> DiscoveredDevice {
+ DiscoveredDevice {
+ channel: DeviceChannel::Http(HttpChannel {
+ host: host.to_string(),
+ port: 53317,
+ protocol: ProtocolType::Http,
+ }),
+ ..device(fingerprint, host)
+ }
+ }
+
+ fn observe(
+ store: &DeviceStore,
+ device: DiscoveredDevice,
+ observation: Observation,
+ ) -> Option<DiscoveryEvent> {
+ store
+ .observe(device, observation, None, SystemTime::now())
+ .0
+ }
+
+ /// Plain HTTP proves nothing about the fingerprint, so once a device is
+ /// verified over HTTPS, nobody can attach an HTTP channel to it by
+ /// claiming its fingerprint (GHSA-hxmj-fjxh-v795).
+ #[test]
+ fn test_http_observations_of_a_verified_device_are_ignored() {
+ let store = DeviceStore::new();
+ reach(&store, device("a", "192.168.0.10"));
+ assert!(store.by_fingerprint("a").unwrap().verified);
+
+ for observation in [
+ Observation::Reached,
+ Observation::ReachedUs,
+ Observation::Failed("connection refused".to_string()),
+ ] {
+ let event = observe(&store, http_device("a", "192.168.0.66"), observation);
+ assert!(event.is_none(), "expected no event, got {event:?}");
+ }
+ let event = store.report_outbound(
+ "a",
+ http_device("a", "192.168.0.66").channel,
+ Ok(()),
+ SystemTime::now(),
+ );
+ assert!(matches!(event, Some(None)), "expected no event, got {event:?}");
+
+ let known = store.by_fingerprint("a").unwrap();
+ assert_eq!(ranked_hosts(&known), ["192.168.0.10"]);
+ assert_eq!(known.device.alias, "Alias of a");
+ }
+
+ /// HTTP channels attached before the device was verified are dropped
+ /// with the verification, so they cannot outrank the proven ones.
+ #[test]
+ fn test_verification_drops_http_channels() {
+ let store = DeviceStore::new();
+ reach(&store, http_device("a", "192.168.0.66"));
+ assert!(!store.by_fingerprint("a").unwrap().verified);
+
+ reach(&store, device("a", "192.168.0.10"));
+
+ let known = store.by_fingerprint("a").unwrap();
+ assert!(known.verified);
+ assert_eq!(ranked_hosts(&known), ["192.168.0.10"]);
+ }
+
+ /// A device that only uses plain HTTP is never verified and keeps
+ /// working as before.
+ #[test]
+ fn test_unverified_device_keeps_http_channels() {
+ let store = DeviceStore::new();
+ reach(&store, http_device("a", "192.168.0.10"));
+ reached_by(&store, http_device("a", "10.0.0.10"));
+
+ let known = store.by_fingerprint("a").unwrap();
+ assert!(!known.verified);
+ assert_eq!(known.channels.len(), 2);
+ }
+
+ /// Only this device reaching the peer over HTTPS verifies it: an
+ /// inbound request merely claims its channel.
+ #[test]
+ fn test_inbound_https_does_not_verify() {
+ let store = DeviceStore::new();
+ reached_by(&store, device("a", "192.168.0.10"));
+ fail(&store, device("a", "10.0.0.10"));
+
+ assert!(!store.by_fingerprint("a").unwrap().verified);
+ }
}
diff --git a/packages/core/src/http/server/mod.rs b/packages/core/src/http/server/mod.rs
index a4981698..e96f858a 100644
--- a/packages/core/src/http/server/mod.rs
+++ b/packages/core/src/http/server/mod.rs
@@ -504,6 +504,7 @@ async fn serve_connection(
let (_, server_connection) = tls_stream.get_ref();
RequestClientInfo {
ip: PeerIp::from_remote_addr(&remote_addr),
+ tls: true,
// No certificate when client auth is optional (web pages served)
// and the client (e.g. a browser) did not present one.
cert: server_connection
@@ -519,6 +520,7 @@ async fn serve_connection(
None => {
let client_info = RequestClientInfo {
ip: PeerIp::from_remote_addr(&remote_addr),
+ tls: false,
cert: None,
};
serve_http(tcp_stream, client_info, app_state).await
@@ -576,16 +578,30 @@ pub struct RequestClientInfo {
/// The IP address of the client, including the IPv6 scope when present.
ip: PeerIp,
+ /// Whether the connection uses TLS.
+ tls: bool,
+
/// The client certificate in DER format.
+ /// `None` without TLS, or on TLS when the client presented no certificate
+ /// (only possible while the web pages are served).
cert: Option<Vec<u8>>,
}
impl RequestClientInfo {
- /// The SHA-256 fingerprint (uppercase hex) of the client certificate
- /// verified during the mTLS handshake.
- /// `None` when the server runs without TLS.
- fn cert_fingerprint(&self) -> Option<String> {
- self.cert.as_deref().map(fingerprint_from_cert_der)
+ /// The fingerprint identifying the client, given the one it `claimed`:
+ /// - TLS with a client certificate: the SHA-256 fingerprint (uppercase hex)
+ /// of that certificate, verified during the mTLS handshake.
+ /// - Plain HTTP: the claimed fingerprint, as there is nothing to verify it
+ /// against (encryption is turned off).
+ /// - TLS without a client certificate (e.g. a browser while the web pages
+ /// are served): `None`, the client is anonymous. Its claimed fingerprint
+ /// must not be trusted, otherwise it could impersonate any device.
+ fn sender_fingerprint(&self, claimed: &str) -> Option<String> {
+ match (&self.cert, self.tls) {
+ (Some(cert), _) => Some(fingerprint_from_cert_der(cert)),
+ (None, false) => Some(claimed.to_string()),
+ (None, true) => None,
+ }
}
fn extract_public_key(&self) -> Option<String> {
diff --git a/packages/core/src/http/server/v2.rs b/packages/core/src/http/server/v2.rs
index 41fc33e2..48b11d96 100644
--- a/packages/core/src/http/server/v2.rs
+++ b/packages/core/src/http/server/v2.rs
@@ -31,7 +31,8 @@ pub enum ServerEventV2 {
///
/// On TLS, this event is only emitted when `info.fingerprint` matches the
/// SHA-256 fingerprint of the client certificate verified during the mTLS
- /// handshake, so the fingerprint cannot be spoofed.
+ /// handshake, so the fingerprint cannot be spoofed. Clients without a
+ /// certificate are ignored.
Register {
/// The IP address of the remote device.
ip: PeerIp,
@@ -54,13 +55,23 @@ pub enum ServerEventV2 {
ip: PeerIp,
/// The device information of the sender.
+ ///
+ /// On TLS with a client certificate, `info.fingerprint` matches
+ /// `sender_fingerprint` (up to case): the request is rejected
+ /// otherwise. Without one, `info` is self-reported.
info: RegisterDtoV2,
- /// The SHA-256 fingerprint (uppercase hex) of the sender's client
- /// certificate verified during the mTLS handshake. Unlike
- /// `info.fingerprint`, this value cannot be spoofed.
- /// `None` when the server runs without TLS.
- cert_fingerprint: Option<String>,
+ /// The fingerprint identifying the sender. Use this instead of
+ /// `info.fingerprint`, which is self-reported.
+ ///
+ /// On TLS, the SHA-256 fingerprint (uppercase hex) of the sender's
+ /// client certificate verified during the mTLS handshake, so it cannot
+ /// be spoofed. Without TLS, the self-reported `info.fingerprint`.
+ ///
+ /// `None` when the sender presented no client certificate on TLS (e.g. a
+ /// browser while the web pages are served): the sender is anonymous and
+ /// must not be treated as a known device.
+ sender_fingerprint: Option<String>,
/// The offered files, mapped by file ID.
files: HashMap<String, FileDto>,
@@ -161,9 +172,9 @@ pub(crate) async fn register(
// On TLS, only trust registrations whose claimed fingerprint is proven
// by the client certificate of the mTLS handshake.
- let fingerprint_valid = match client_info.cert_fingerprint() {
- Some(cert_fingerprint) => payload.fingerprint.to_ascii_uppercase() == cert_fingerprint,
- None => true,
+ let fingerprint_valid = match client_info.sender_fingerprint(&payload.fingerprint) {
+ Some(fingerprint) => payload.fingerprint.eq_ignore_ascii_case(&fingerprint),
+ None => false,
};
if let Some(v2) = &state.v2 {
@@ -185,7 +196,7 @@ pub(crate) async fn register(
}
} else {
tracing::warn!(
- "Ignoring register from {}: claimed fingerprint does not match the client certificate",
+ "Ignoring register from {}: claimed fingerprint is not proven by a client certificate",
client_info.ip
);
}
@@ -255,6 +266,21 @@ pub(crate) async fn prepare_upload(
file.file_name = filename::normalize(&file.file_name);
}
+ // Like `register`: a sender with a client certificate must claim the
+ // fingerprint of that certificate, so that `info` cannot pass itself off
+ // as another device. Plain HTTP and anonymous senders have nothing to
+ // check the claim against.
+ let sender_fingerprint = client_info.sender_fingerprint(&payload.info.fingerprint);
+ if sender_fingerprint
+ .as_deref()
+ .is_some_and(|fingerprint| !payload.info.fingerprint.eq_ignore_ascii_case(fingerprint))
+ {
+ return Err(AppError::Message(
+ StatusCode::FORBIDDEN,
+ "Fingerprint does not match the client certificate".to_string(),
+ ));
+ }
+
let session_id = Uuid::new_v4().to_string();
let cancelled = CancellationToken::new();
@@ -282,7 +308,7 @@ pub(crate) async fn prepare_upload(
session_id: session_id.clone(),
ip: client_info.ip,
info: payload.info,
- cert_fingerprint: client_info.cert_fingerprint(),
+ sender_fingerprint,
files: payload.files.clone(),
decision_tx,
};
diff --git a/packages/core/tests/v2_server.rs b/packages/core/tests/v2_server.rs
index 3a2714c9..26bf0f74 100644
--- a/packages/core/tests/v2_server.rs
+++ b/packages/core/tests/v2_server.rs
@@ -2,6 +2,7 @@
use bytes::Bytes;
use futures_util::StreamExt;
+use localsend::crypto::cert::fingerprint_from_cert_der;
use localsend::crypto::hash::sha256_hex;
use localsend::http::client::{ClientError, LsHttpClient, LsHttpClientV2};
use localsend::http::dto_v2::{PrepareUploadRequestDtoV2, RegisterDtoV2};
@@ -1292,6 +1293,9 @@ async fn test_prepare_upload_aborted_by_sender_disconnect_tls() {
let client =
LsHttpClientV2::try_new(&sender_key.serialize_pem(), &sender_cert.pem(), None, None)
.unwrap();
+ // On TLS, the sender must claim the fingerprint of its certificate.
+ let mut request = prepare_upload_request(&[file_dto("file-a", "a.bin", 5)]);
+ request.info.fingerprint = fingerprint_from_cert_der(sender_cert.der());
let cancel = CancellationToken::new();
tokio::spawn({
let cancel = cancel.clone();
@@ -1306,7 +1310,7 @@ async fn test_prepare_upload_aborted_by_sender_disconnect_tls() {
"127.0.0.1",
port,
None,
- prepare_upload_request(&[file_dto("file-a", "a.bin", 5)]),
+ request,
None,
cancel,
)
diff --git a/packages/core/tests/v2_tls_pinning.rs b/packages/core/tests/v2_tls_pinning.rs
index 285074ce..744e427e 100644
--- a/packages/core/tests/v2_tls_pinning.rs
+++ b/packages/core/tests/v2_tls_pinning.rs
@@ -42,6 +42,10 @@ struct TestServer {
port: u16,
/// Requests that reached the application layer.
prepare_uploads: Arc<Mutex<Vec<String>>>,
+ /// The `sender_fingerprint` of every `PrepareUpload` event.
+ sender_fingerprints: Arc<Mutex<Vec<Option<String>>>>,
+ /// The claimed fingerprint of every `Register` event.
+ registers: Arc<Mutex<Vec<String>>>,
/// Uploaded file contents, mapped by file ID.
received: Arc<Mutex<Vec<(String, Vec<u8>)>>>,
_stop_tx: oneshot::Sender<()>,
@@ -57,19 +61,30 @@ async fn start_tls_server(identity: &Identity) -> TestServer {
async fn start_tls_server_with_web(identity: &Identity, web: WebConfig) -> TestServer {
let _ = tracing_subscriber::fmt().with_test_writer().try_init();
let prepare_uploads: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
+ let sender_fingerprints: Arc<Mutex<Vec<Option<String>>>> = Arc::new(Mutex::new(Vec::new()));
+ let registers: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
let received: Arc<Mutex<Vec<(String, Vec<u8>)>>> = Arc::new(Mutex::new(Vec::new()));
let (event_tx, mut event_rx) = mpsc::channel::<ServerEventV2>(16);
tokio::spawn({
let prepare_uploads = prepare_uploads.clone();
+ let sender_fingerprints = sender_fingerprints.clone();
+ let registers = registers.clone();
let received = received.clone();
async move {
while let Some(event) = event_rx.recv().await {
match event {
+ ServerEventV2::Register { info, .. } => {
+ registers.lock().await.push(info.fingerprint);
+ }
ServerEventV2::PrepareUpload {
- files, decision_tx, ..
+ sender_fingerprint,
+ files,
+ decision_tx,
+ ..
} => {
+ sender_fingerprints.lock().await.push(sender_fingerprint);
prepare_uploads
.lock()
.await
@@ -134,6 +149,8 @@ async fn start_tls_server_with_web(identity: &Identity, web: WebConfig) -> TestS
TestServer {
port: handle.port(),
prepare_uploads,
+ sender_fingerprints,
+ registers,
received,
_stop_tx: stop_tx,
}
@@ -273,6 +290,12 @@ async fn test_transfer_with_matching_fingerprint() {
let received = server.received.lock().await;
assert_eq!(received.len(), 1);
assert_eq!(received[0].1, content);
+
+ // The sender is identified by its client certificate.
+ assert_eq!(
+ *server.sender_fingerprints.lock().await,
+ vec![Some(sender.fingerprint.clone())]
+ );
}
/// The peer presents a valid self-signed certificate, but not the one that was
@@ -430,3 +453,117 @@ async fn test_register_without_pin_returns_public_key() {
assert!(response.public_key.is_some());
assert_eq!(response.body.fingerprint, server_identity.fingerprint);
}
+
+/// A browser-like client without a client certificate while the web pages are
+/// served. It must not be able to pass itself off as a known device by
+/// claiming that device's fingerprint (GHSA-hxmj-fjxh-v795).
+#[tokio::test]
+async fn test_client_without_cert_cannot_claim_fingerprint() {
+ let server_identity = generate_identity();
+ let favorite = generate_identity();
+ let server = start_tls_server_with_web(
+ &server_identity,
+ WebConfig {
+ mode: WebMode::Upload,
+ ..WebConfig::default()
+ },
+ )
+ .await;
+
+ let attacker = localsend::reqwest::Client::builder()
+ .use_rustls_tls()
+ .danger_accept_invalid_certs(true)
+ .build()
+ .unwrap();
+ let base = format!("https://127.0.0.1:{}/api/localsend/v2", server.port);
+
+ // A register claiming the favorite's fingerprint is answered, but ignored.
+ let response = attacker
+ .post(format!("{base}/register"))
+ .body(serde_json::to_string(&sender_info(&favorite.fingerprint)).unwrap())
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(response.status().as_u16(), 200);
+
+ // Register events are delivered in order: once the authenticated one
+ // arrives, the anonymous one would have arrived before it.
+ let peer = generate_identity();
+ client(&peer, Some(&server_identity.fingerprint))
+ .register(
+ ProtocolType::Https,
+ "127.0.0.1",
+ server.port,
+ sender_info(&peer.fingerprint),
+ )
+ .await
+ .expect("register with client certificate should succeed");
+ tokio::time::timeout(std::time::Duration::from_secs(5), async {
+ while server.registers.lock().await.is_empty() {
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
+ }
+ })
+ .await
+ .expect("the authenticated register should arrive");
+ assert_eq!(*server.registers.lock().await, vec![peer.fingerprint.clone()]);
+
+ // A prepare-upload still reaches the application (browsers upload this
+ // way), but as an anonymous sender, not as the claimed favorite.
+ let files = vec![file_dto("file-1", 10)];
+ let response = attacker
+ .post(format!("{base}/prepare-upload"))
+ .body(serde_json::to_string(&prepare_upload_request(&favorite, &files)).unwrap())
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(response.status().as_u16(), 200);
+ assert_eq!(*server.sender_fingerprints.lock().await, vec![None]);
+}
+
+/// A sender with a valid client certificate that claims another device's
+/// fingerprint in its payload: the claim is disproven by the certificate, so
+/// the request is rejected instead of passing `info` on as that device.
+#[tokio::test]
+async fn test_prepare_upload_rejected_when_claim_disagrees_with_cert() {
+ let server_identity = generate_identity();
+ let sender = generate_identity();
+ let impersonated = generate_identity();
+ let server = start_tls_server(&server_identity).await;
+ let client = client(&sender, Some(&server_identity.fingerprint));
+
+ let files = vec![file_dto("file-1", 10)];
+ let result = client
+ .prepare_upload(
+ ProtocolType::Https,
+ "127.0.0.1",
+ server.port,
+ None,
+ prepare_upload_request(&impersonated, &files),
+ None,
+ CancellationToken::new(),
+ )
+ .await;
+
+ match result {
+ Err(ClientError::StatusCode(err)) => assert_eq!(err.status, 403),
+ Err(err) => panic!("expected 403, got {err:?}"),
+ Ok(_) => panic!("expected 403, got success"),
+ }
+ assert!(server.prepare_uploads.lock().await.is_empty());
+
+ // The claim is compared case-insensitively.
+ let mut request = prepare_upload_request(&sender, &files);
+ request.info.fingerprint = sender.fingerprint.to_lowercase();
+ client
+ .prepare_upload(
+ ProtocolType::Https,
+ "127.0.0.1",
+ server.port,
+ None,
+ request,
+ None,
+ CancellationToken::new(),
+ )
+ .await
+ .expect("a lowercase claim of the own fingerprint should be accepted");
+}
diff --git a/packages/localsend_isolates/lib/rust/api/server.dart b/packages/localsend_isolates/lib/rust/api/server.dart
index c119a38b..4f325fbf 100644
--- a/packages/localsend_isolates/lib/rust/api/server.dart
+++ b/packages/localsend_isolates/lib/rust/api/server.dart
@@ -191,11 +191,13 @@ sealed class RsServerEvent with _$RsServerEvent {
required String ip,
required RegisterDtoV2 info,
- /// The SHA-256 fingerprint (uppercase hex) of the sender's client
- /// certificate verified during the mTLS handshake. Unlike
- /// `info.fingerprint`, this value cannot be spoofed.
- /// `None` when the server runs without TLS.
- String? certFingerprint,
+ /// The fingerprint identifying the sender. Use this instead of
+ /// `info.fingerprint`, which is self-reported.
+ /// On TLS, the fingerprint of the verified client certificate, so it
+ /// cannot be spoofed. Without TLS, the self-reported `info.fingerprint`.
+ /// `None` when the sender presented no client certificate on TLS (e.g. a
+ /// browser on the receive-via-link page): the sender is anonymous.
+ String? senderFingerprint,
required Map<String, FileDto> files,
}) = RsServerEvent_PrepareUpload;
diff --git a/packages/localsend_isolates/lib/rust/api/server.freezed.dart b/packages/localsend_isolates/lib/rust/api/server.freezed.dart
index 8d1e6fee..861f5136 100644
--- a/packages/localsend_isolates/lib/rust/api/server.freezed.dart
+++ b/packages/localsend_isolates/lib/rust/api/server.freezed.dart
@@ -143,11 +143,11 @@ return listenerFailed(_that);case _:
/// }
/// ```
-@optionalTypeArgs TResult maybeWhen<TResult extends Object?>({TResult Function( String ip, RegisterDtoV2 info)? register,TResult Function( String sessionId, String ip, RegisterDtoV2 info, String? certFingerprint, Map<String, FileDto> files)? prepareUpload,TResult Function( String sessionId, String fileId, FileDto file)? fileUpload,TResult Function( String sessionId, SessionEndReasonV2 reason)? sessionEnd,TResult Function( String sessionId)? prepareUploadAborted,TResult Function( String ip, String sessionId)? cancelReceived,TResult Function( String ip, String sessionId, String? userAgent)? webPrepareDownload,TResult Function( String sessionId, String fileId, FileDto file)? webFileDownload,TResult Function( List<String> args)? show_,TResult Function( String error)? listenerFailed,required TResult orElse(),}) {final _that = this;
+@optionalTypeArgs TResult maybeWhen<TResult extends Object?>({TResult Function( String ip, RegisterDtoV2 info)? register,TResult Function( String sessionId, String ip, RegisterDtoV2 info, String? senderFingerprint, Map<String, FileDto> files)? prepareUpload,TResult Function( String sessionId, String fileId, FileDto file)? fileUpload,TResult Function( String sessionId, SessionEndReasonV2 reason)? sessionEnd,TResult Function( String sessionId)? prepareUploadAborted,TResult Function( String ip, String sessionId)? cancelReceived,TResult Function( String ip, String sessionId, String? userAgent)? webPrepareDownload,TResult Function( String sessionId, String fileId, FileDto file)? webFileDownload,TResult Function( List<String> args)? show_,TResult Function( String error)? listenerFailed,required TResult orElse(),}) {final _that = this;
switch (_that) {
case RsServerEvent_Register() when register != null:
return register(_that.ip,_that.info);case RsServerEvent_PrepareUpload() when prepareUpload != null:
-return prepareUpload(_that.sessionId,_that.ip,_that.info,_that.certFingerprint,_that.files);case RsServerEvent_FileUpload() when fileUpload != null:
+return prepareUpload(_that.sessionId,_that.ip,_that.info,_that.senderFingerprint,_that.files);case RsServerEvent_FileUpload() when fileUpload != null:
return fileUpload(_that.sessionId,_that.fileId,_that.file);case RsServerEvent_SessionEnd() when sessionEnd != null:
return sessionEnd(_that.sessionId,_that.reason);case RsServerEvent_PrepareUploadAborted() when prepareUploadAborted != null:
return prepareUploadAborted(_that.sessionId);case RsServerEvent_CancelReceived() when cancelReceived != null:
@@ -173,11 +173,11 @@ return listenerFailed(_that.error);case _:
/// }
/// ```
-@optionalTypeArgs TResult when<TResult extends Object?>({required TResult Function( String ip, RegisterDtoV2 info) register,required TResult Function( String sessionId, String ip, RegisterDtoV2 info, String? certFingerprint, Map<String, FileDto> files) prepareUpload,required TResult Function( String sessionId, String fileId, FileDto file) fileUpload,required TResult Function( String sessionId, SessionEndReasonV2 reason) sessionEnd,required TResult Function( String sessionId) prepareUploadAborted,required TResult Function( String ip, String sessionId) cancelReceived,required TResult Function( String ip, String sessionId, String? userAgent) webPrepareDownload,required TResult Function( String sessionId, String fileId, FileDto file) webFileDownload,required TResult Function( List<String> args) show_,required TResult Function( String error) listenerFailed,}) {final _that = this;
+@optionalTypeArgs TResult when<TResult extends Object?>({required TResult Function( String ip, RegisterDtoV2 info) register,required TResult Function( String sessionId, String ip, RegisterDtoV2 info, String? senderFingerprint, Map<String, FileDto> files) prepareUpload,required TResult Function( String sessionId, String fileId, FileDto file) fileUpload,required TResult Function( String sessionId, SessionEndReasonV2 reason) sessionEnd,required TResult Function( String sessionId) prepareUploadAborted,required TResult Function( String ip, String sessionId) cancelReceived,required TResult Function( String ip, String sessionId, String? userAgent) webPrepareDownload,required TResult Function( String sessionId, String fileId, FileDto file) webFileDownload,required TResult Function( List<String> args) show_,required TResult Function( String error) listenerFailed,}) {final _that = this;
switch (_that) {
case RsServerEvent_Register():
return register(_that.ip,_that.info);case RsServerEvent_PrepareUpload():
-return prepareUpload(_that.sessionId,_that.ip,_that.info,_that.certFingerprint,_that.files);case RsServerEvent_FileUpload():
+return prepareUpload(_that.sessionId,_that.ip,_that.info,_that.senderFingerprint,_that.files);case RsServerEvent_FileUpload():
return fileUpload(_that.sessionId,_that.fileId,_that.file);case RsServerEvent_SessionEnd():
return sessionEnd(_that.sessionId,_that.reason);case RsServerEvent_PrepareUploadAborted():
return prepareUploadAborted(_that.sessionId);case RsServerEvent_CancelReceived():
@@ -199,11 +199,11 @@ return listenerFailed(_that.error);}
/// }
/// ```
-@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({TResult? Function( String ip, RegisterDtoV2 info)? register,TResult? Function( String sessionId, String ip, RegisterDtoV2 info, String? certFingerprint, Map<String, FileDto> files)? prepareUpload,TResult? Function( String sessionId, String fileId, FileDto file)? fileUpload,TResult? Function( String sessionId, SessionEndReasonV2 reason)? sessionEnd,TResult? Function( String sessionId)? prepareUploadAborted,TResult? Function( String ip, String sessionId)? cancelReceived,TResult? Function( String ip, String sessionId, String? userAgent)? webPrepareDownload,TResult? Function( String sessionId, String fileId, FileDto file)? webFileDownload,TResult? Function( List<String> args)? show_,TResult? Function( String error)? listenerFailed,}) {final _that = this;
+@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({TResult? Function( String ip, RegisterDtoV2 info)? register,TResult? Function( String sessionId, String ip, RegisterDtoV2 info, String? senderFingerprint, Map<String, FileDto> files)? prepareUpload,TResult? Function( String sessionId, String fileId, FileDto file)? fileUpload,TResult? Function( String sessionId, SessionEndReasonV2 reason)? sessionEnd,TResult? Function( String sessionId)? prepareUploadAborted,TResult? Function( String ip, String sessionId)? cancelReceived,TResult? Function( String ip, String sessionId, String? userAgent)? webPrepareDownload,TResult? Function( String sessionId, String fileId, FileDto file)? webFileDownload,TResult? Function( List<String> args)? show_,TResult? Function( String error)? listenerFailed,}) {final _that = this;
switch (_that) {
case RsServerEvent_Register() when register != null:
return register(_that.ip,_that.info);case RsServerEvent_PrepareUpload() when prepareUpload != null:
-return prepareUpload(_that.sessionId,_that.ip,_that.info,_that.certFingerprint,_that.files);case RsServerEvent_FileUpload() when fileUpload != null:
+return prepareUpload(_that.sessionId,_that.ip,_that.info,_that.senderFingerprint,_that.files);case RsServerEvent_FileUpload() when fileUpload != null:
return fileUpload(_that.sessionId,_that.fileId,_that.file);case RsServerEvent_SessionEnd() when sessionEnd != null:
return sessionEnd(_that.sessionId,_that.reason);case RsServerEvent_PrepareUploadAborted() when prepareUploadAborted != null:
return prepareUploadAborted(_that.sessionId);case RsServerEvent_CancelReceived() when cancelReceived != null:
@@ -291,18 +291,20 @@ as RegisterDtoV2,
class RsServerEvent_PrepareUpload extends RsServerEvent {
- const RsServerEvent_PrepareUpload({required this.sessionId, required this.ip, required this.info, this.certFingerprint, required final Map<String, FileDto> files}): _files = files,super._();
+ const RsServerEvent_PrepareUpload({required this.sessionId, required this.ip, required this.info, this.senderFingerprint, required final Map<String, FileDto> files}): _files = files,super._();
/// The session ID the upload session will have when the request is accepted.
final String sessionId;
final String ip;
final RegisterDtoV2 info;
-/// The SHA-256 fingerprint (uppercase hex) of the sender's client
-/// certificate verified during the mTLS handshake. Unlike
-/// `info.fingerprint`, this value cannot be spoofed.
-/// `None` when the server runs without TLS.
- final String? certFingerprint;
+/// The fingerprint identifying the sender. Use this instead of
+/// `info.fingerprint`, which is self-reported.
+/// On TLS, the fingerprint of the verified client certificate, so it
+/// cannot be spoofed. Without TLS, the self-reported `info.fingerprint`.
+/// `None` when the sender presented no client certificate on TLS (e.g. a
+/// browser on the receive-via-link page): the sender is anonymous.
+ final String? senderFingerprint;
final Map<String, FileDto> _files;
Map<String, FileDto> get files {
if (_files is EqualUnmodifiableMapView) return _files;
@@ -321,16 +323,16 @@ $RsServerEvent_PrepareUploadCopyWith<RsServerEvent_PrepareUpload> get copyWith =
@override
bool operator ==(Object other) {
- return identical(this, other) || (other.runtimeType == runtimeType&&other is RsServerEvent_PrepareUpload&&(identical(other.sessionId, sessionId) || other.sessionId == sessionId)&&(identical(other.ip, ip) || other.ip == ip)&&(identical(other.info, info) || other.info == info)&&(identical(other.certFingerprint, certFingerprint) || other.certFingerprint == certFingerprint)&&const DeepCollectionEquality().equals(other._files, _files));
+ return identical(this, other) || (other.runtimeType == runtimeType&&other is RsServerEvent_PrepareUpload&&(identical(other.sessionId, sessionId) || other.sessionId == sessionId)&&(identical(other.ip, ip) || other.ip == ip)&&(identical(other.info, info) || other.info == info)&&(identical(other.senderFingerprint, senderFingerprint) || other.senderFingerprint == senderFingerprint)&&const DeepCollectionEquality().equals(other._files, _files));
}
@override
-int get hashCode => Object.hash(runtimeType,sessionId,ip,info,certFingerprint,const DeepCollectionEquality().hash(_files));
+int get hashCode => Object.hash(runtimeType,sessionId,ip,info,senderFingerprint,const DeepCollectionEquality().hash(_files));
@override
String toString() {
- return 'RsServerEvent.prepareUpload(sessionId: $sessionId, ip: $ip, info: $info, certFingerprint: $certFingerprint, files: $files)';
+ return 'RsServerEvent.prepareUpload(sessionId: $sessionId, ip: $ip, info: $info, senderFingerprint: $senderFingerprint, files: $files)';
}
@@ -341,7 +343,7 @@ abstract mixin class $RsServerEvent_PrepareUploadCopyWith<$Res> implements $RsSe
factory $RsServerEvent_PrepareUploadCopyWith(RsServerEvent_PrepareUpload value, $Res Function(RsServerEvent_PrepareUpload) _then) = _$RsServerEvent_PrepareUploadCopyWithImpl;
@useResult
$Res call({
- String sessionId, String ip, RegisterDtoV2 info, String? certFingerprint, Map<String, FileDto> files
+ String sessionId, String ip, RegisterDtoV2 info, String? senderFingerprint, Map<String, FileDto> files
});
@@ -358,12 +360,12 @@ class _$RsServerEvent_PrepareUploadCopyWithImpl<$Res>
/// Create a copy of RsServerEvent
/// with the given fields replaced by the non-null parameter values.
-@pragma('vm:prefer-inline') $Res call({Object? sessionId = null,Object? ip = null,Object? info = null,Object? certFingerprint = freezed,Object? files = null,}) {
+@pragma('vm:prefer-inline') $Res call({Object? sessionId = null,Object? ip = null,Object? info = null,Object? senderFingerprint = freezed,Object? files = null,}) {
return _then(RsServerEvent_PrepareUpload(
sessionId: null == sessionId ? _self.sessionId : sessionId // ignore: cast_nullable_to_non_nullable
as String,ip: null == ip ? _self.ip : ip // ignore: cast_nullable_to_non_nullable
as String,info: null == info ? _self.info : info // ignore: cast_nullable_to_non_nullable
-as RegisterDtoV2,certFingerprint: freezed == certFingerprint ? _self.certFingerprint : certFingerprint // ignore: cast_nullable_to_non_nullable
+as RegisterDtoV2,senderFingerprint: freezed == senderFingerprint ? _self.senderFingerprint : senderFingerprint // ignore: cast_nullable_to_non_nullable
as String?,files: null == files ? _self._files : files // ignore: cast_nullable_to_non_nullable
as Map<String, FileDto>,
));
diff --git a/packages/localsend_isolates/lib/rust/frb_generated.dart b/packages/localsend_isolates/lib/rust/frb_generated.dart
index a7d25cca..f34fe4f7 100644
--- a/packages/localsend_isolates/lib/rust/frb_generated.dart
+++ b/packages/localsend_isolates/lib/rust/frb_generated.dart
@@ -3338,7 +3338,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
sessionId: dco_decode_String(raw[1]),
ip: dco_decode_String(raw[2]),
info: dco_decode_box_autoadd_register_dto_v_2(raw[3]),
- certFingerprint: dco_decode_opt_String(raw[4]),
+ senderFingerprint: dco_decode_opt_String(raw[4]),
files: dco_decode_Map_String_file_dto_None(raw[5]),
);
case 2:
@@ -4805,13 +4805,13 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
var var_sessionId = sse_decode_String(deserializer);
var var_ip = sse_decode_String(deserializer);
var var_info = sse_decode_box_autoadd_register_dto_v_2(deserializer);
- var var_certFingerprint = sse_decode_opt_String(deserializer);
+ var var_senderFingerprint = sse_decode_opt_String(deserializer);
var var_files = sse_decode_Map_String_file_dto_None(deserializer);
return RsServerEvent_PrepareUpload(
sessionId: var_sessionId,
ip: var_ip,
info: var_info,
- certFingerprint: var_certFingerprint,
+ senderFingerprint: var_senderFingerprint,
files: var_files,
);
case 2:
@@ -6262,14 +6262,14 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi {
sessionId: final sessionId,
ip: final ip,
info: final info,
- certFingerprint: final certFingerprint,
+ senderFingerprint: final senderFingerprint,
files: final files,
):
sse_encode_i_32(1, serializer);
sse_encode_String(sessionId, serializer);
sse_encode_String(ip, serializer);
sse_encode_box_autoadd_register_dto_v_2(info, serializer);
- sse_encode_opt_String(certFingerprint, serializer);
+ sse_encode_opt_String(senderFingerprint, serializer);
sse_encode_Map_String_file_dto_None(files, serializer);
case RsServerEvent_FileUpload(sessionId: final sessionId, fileId: final fileId, file: final file):
sse_encode_i_32(2, serializer);
@@ -6714,7 +6714,8 @@ class RsDiscoveryImpl extends RustOpaque implements RsDiscovery {
/// emitted on [RsDiscovery::listen].
///
/// Only the inbound direction of the address is confirmed: an address
- /// new to the device is stored with [RsOutbound::Untested].
+ /// new to the device is stored with [RsOutbound::Untested] and dialed
+ /// back in the background, whose outcome is emitted as well.
Future<void> observeInbound({required RsDiscoveredDevice device}) =>
RustLib.instance.api.crateApiDiscoveryRsDiscoveryObserveInbound(that: this, device: device);
diff --git a/packages/localsend_isolates/lib/src/isolate/child/server_isolate.dart b/packages/localsend_isolates/lib/src/isolate/child/server_isolate.dart
index 735fab01..90b18db7 100644
--- a/packages/localsend_isolates/lib/src/isolate/child/server_isolate.dart
+++ b/packages/localsend_isolates/lib/src/isolate/child/server_isolate.dart
@@ -195,11 +195,17 @@ class HttpServerPrepareUploadEvent extends HttpServerEvent {
final String ip;
final RegisterDtoV2 info;
- /// The SHA-256 fingerprint (uppercase hex) of the sender's client
- /// certificate verified during the mTLS handshake. Unlike
- /// [RegisterDtoV2.fingerprint], this value cannot be spoofed.
- /// `null` when the server runs without TLS.
- final String? certFingerprint;
+ /// The fingerprint identifying the sender. Use this instead of
+ /// [RegisterDtoV2.fingerprint], which is self-reported.
+ ///
+ /// On TLS, the fingerprint of the sender's client certificate verified during
+ /// the mTLS handshake, so it cannot be spoofed. Without TLS (encryption off),
+ /// the self-reported [RegisterDtoV2.fingerprint].
+ ///
+ /// `null` when the sender presented no client certificate on TLS (e.g. a
+ /// browser on the receive-via-link page): the sender is anonymous and must
+ /// not be treated as a known device.
+ final String? senderFingerprint;
final Map<String, FileDto> files;
@@ -207,7 +213,7 @@ class HttpServerPrepareUploadEvent extends HttpServerEvent {
required this.sessionId,
required this.ip,
required this.info,
- required this.certFingerprint,
+ required this.senderFingerprint,
required this.files,
});
}
@@ -456,7 +462,7 @@ Future<void> setupHttpServerIsolate(
switch (event) {
case RsServerEvent_Register(:final ip, :final info):
emit(HttpServerRegisterEvent(ip: ip, info: info));
- case RsServerEvent_PrepareUpload(:final sessionId, :final ip, :final info, :final certFingerprint, :final files):
+ case RsServerEvent_PrepareUpload(:final sessionId, :final ip, :final info, :final senderFingerprint, :final files):
// The Rust server is the authority on the single-session
// invariant: a new request means the old session is over.
holder.session = null;
@@ -465,7 +471,7 @@ Future<void> setupHttpServerIsolate(
sessionId: sessionId,
ip: ip,
info: info,
- certFingerprint: certFingerprint,
+ senderFingerprint: senderFingerprint,
files: files,
),
);
diff --git a/packages/localsend_isolates/rust/src/api/server.rs b/packages/localsend_isolates/rust/src/api/server.rs
index aa165615..db4de7d7 100644
--- a/packages/localsend_isolates/rust/src/api/server.rs
+++ b/packages/localsend_isolates/rust/src/api/server.rs
@@ -41,11 +41,13 @@ pub enum RsServerEvent {
session_id: String,
ip: String,
info: RegisterDtoV2,
- /// The SHA-256 fingerprint (uppercase hex) of the sender's client
- /// certificate verified during the mTLS handshake. Unlike
- /// `info.fingerprint`, this value cannot be spoofed.
- /// `None` when the server runs without TLS.
- cert_fingerprint: Option<String>,
+ /// The fingerprint identifying the sender. Use this instead of
+ /// `info.fingerprint`, which is self-reported.
+ /// On TLS, the fingerprint of the verified client certificate, so it
+ /// cannot be spoofed. Without TLS, the self-reported `info.fingerprint`.
+ /// `None` when the sender presented no client certificate on TLS (e.g. a
+ /// browser on the receive-via-link page): the sender is anonymous.
+ sender_fingerprint: Option<String>,
files: HashMap<String, FileDto>,
},
@@ -371,7 +373,7 @@ impl RsHttpServer {
session_id,
ip,
info,
- cert_fingerprint,
+ sender_fingerprint,
files,
decision_tx,
} => {
@@ -380,7 +382,7 @@ impl RsHttpServer {
session_id,
ip: ip.to_string(),
info,
- cert_fingerprint,
+ sender_fingerprint,
files,
})
.is_ok()
diff --git a/packages/localsend_isolates/rust/src/frb_generated.rs b/packages/localsend_isolates/rust/src/frb_generated.rs
index d821146e..11db9bdd 100644
--- a/packages/localsend_isolates/rust/src/frb_generated.rs
+++ b/packages/localsend_isolates/rust/src/frb_generated.rs
@@ -4858,7 +4858,7 @@ impl SseDecode for crate::api::server::RsServerEvent {
let mut var_sessionId = <String>::sse_decode(deserializer);
let mut var_ip = <String>::sse_decode(deserializer);
let mut var_info = <crate::api::server::RegisterDtoV2>::sse_decode(deserializer);
- let mut var_certFingerprint = <Option<String>>::sse_decode(deserializer);
+ let mut var_senderFingerprint = <Option<String>>::sse_decode(deserializer);
let mut var_files =
<std::collections::HashMap<String, crate::api::model::FileDto>>::sse_decode(
deserializer,
@@ -4867,7 +4867,7 @@ impl SseDecode for crate::api::server::RsServerEvent {
session_id: var_sessionId,
ip: var_ip,
info: var_info,
- cert_fingerprint: var_certFingerprint,
+ sender_fingerprint: var_senderFingerprint,
files: var_files,
};
}
@@ -6400,14 +6400,14 @@ impl flutter_rust_bridge::IntoDart for crate::api::server::RsServerEvent {
session_id,
ip,
info,
- cert_fingerprint,
+ sender_fingerprint,
files,
} => [
1.into_dart(),
session_id.into_into_dart().into_dart(),
ip.into_into_dart().into_dart(),
info.into_into_dart().into_dart(),
- cert_fingerprint.into_into_dart().into_dart(),
+ sender_fingerprint.into_into_dart().into_dart(),
files.into_into_dart().into_dart(),
]
.into_dart(),
@@ -7871,14 +7871,14 @@ impl SseEncode for crate::api::server::RsServerEvent {
session_id,
ip,
info,
- cert_fingerprint,
+ sender_fingerprint,
files,
} => {
<i32>::sse_encode(1, serializer);
<String>::sse_encode(session_id, serializer);
<String>::sse_encode(ip, serializer);
<crate::api::server::RegisterDtoV2>::sse_encode(info, serializer);
- <Option<String>>::sse_encode(cert_fingerprint, serializer);
+ <Option<String>>::sse_encode(sender_fingerprint, serializer);
<std::collections::HashMap<String, crate::api::model::FileDto>>::sse_encode(
files, serializer,
);