44
55use axum:: {
66 extract:: { State , WebSocketUpgrade , ws} ,
7- http:: { StatusCode , Uri , header} ,
7+ http:: { HeaderMap , HeaderValue , StatusCode , Uri , header, uri :: Authority } ,
88 response:: { IntoResponse , Response } ,
99} ;
1010use std:: {
@@ -79,7 +79,11 @@ pub fn start<P: AsRef<Path>>(dir: P, ip: IpAddr, port: Option<u16>) -> crate::Re
7979 Ok ( address)
8080}
8181
82- async fn handler ( uri : Uri , state : State < ServerState > ) -> impl IntoResponse {
82+ async fn handler ( uri : Uri , headers : HeaderMap , state : State < ServerState > ) -> impl IntoResponse {
83+ if request_host ( & headers, & uri) . is_none_or ( |host| !is_allowed_host ( & host. 0 , & state. address ) ) {
84+ return forbidden ( ) ;
85+ }
86+
8387 // Frontend files should not contain query parameters. This seems to be how Vite handles it.
8488 let uri = uri. path ( ) ;
8589
@@ -92,7 +96,7 @@ async fn handler(uri: Uri, state: State<ServerState>) -> impl IntoResponse {
9296 let bytes = fs_read_scoped ( state. dir . join ( uri) , & state. dir )
9397 . or_else ( |_| fs_read_scoped ( state. dir . join ( format ! ( "{uri}.html" ) ) , & state. dir ) )
9498 . or_else ( |_| fs_read_scoped ( state. dir . join ( format ! ( "{uri}/index.html" ) ) , & state. dir ) )
95- . or_else ( |_| std :: fs :: read ( state. dir . join ( "index.html" ) ) ) ;
99+ . or_else ( |_| fs_read_scoped ( state. dir . join ( "index.html" ) , & state . dir ) ) ;
96100
97101 match bytes {
98102 Ok ( mut bytes) => {
@@ -110,21 +114,113 @@ async fn handler(uri: Uri, state: State<ServerState>) -> impl IntoResponse {
110114 }
111115}
112116
113- async fn ws_handler ( ws : WebSocketUpgrade , state : State < ServerState > ) -> Response {
117+ async fn ws_handler (
118+ ws : WebSocketUpgrade ,
119+ uri : Uri ,
120+ headers : HeaderMap ,
121+ state : State < ServerState > ,
122+ ) -> Response {
123+ let Some ( host) = request_host ( & headers, & uri) else {
124+ return forbidden ( ) . into_response ( ) ;
125+ } ;
126+ if !is_allowed_host ( & host. 0 , & state. address )
127+ || !is_allowed_origin ( headers. get ( header:: ORIGIN ) , & host)
128+ {
129+ return forbidden ( ) . into_response ( ) ;
130+ }
131+
114132 ws. on_upgrade ( move |mut ws| async move {
115133 let mut rx = state. tx . subscribe ( ) ;
116- while tokio:: select! {
117- _ = ws. recv( ) => return ,
118- fs_reload_event = rx. recv( ) => fs_reload_event. is_ok( ) ,
119- } {
120- let msg = ws:: Message :: Text ( r#"{"reload": true}"# . into ( ) ) ;
121- if ws. send ( msg) . await . is_err ( ) {
122- break ;
134+ loop {
135+ tokio:: select! {
136+ msg = ws. recv( ) => match msg {
137+ // the client disconnected
138+ None | Some ( Err ( _) ) | Some ( Ok ( ws:: Message :: Close ( _) ) ) => break ,
139+ // ignore any other client message, pings are answered automatically
140+ Some ( Ok ( _) ) => { }
141+ } ,
142+ fs_reload_event = rx. recv( ) => {
143+ if fs_reload_event. is_err( ) {
144+ break ;
145+ }
146+ let msg = ws:: Message :: Text ( r#"{"reload": true}"# . into( ) ) ;
147+ if ws. send( msg) . await . is_err( ) {
148+ break ;
149+ }
150+ }
123151 }
124152 }
125153 } )
126154}
127155
156+ fn forbidden ( ) -> ( StatusCode , [ ( header:: HeaderName , String ) ; 1 ] , Vec < u8 > ) {
157+ (
158+ StatusCode :: FORBIDDEN ,
159+ [ ( header:: CONTENT_TYPE , "text/plain" . into ( ) ) ] ,
160+ vec ! [ ] ,
161+ )
162+ }
163+
164+ /// Hostname (lowercase, without IPv6 brackets) and port of the request,
165+ /// read from the `Host` header or the request URI authority (HTTP/2).
166+ fn request_host ( headers : & HeaderMap , uri : & Uri ) -> Option < ( String , Option < u16 > ) > {
167+ match headers. get ( header:: HOST ) {
168+ Some ( host) => parse_authority ( host. to_str ( ) . ok ( ) ?. parse ( ) . ok ( ) ?) ,
169+ None => parse_authority ( uri. authority ( ) ?. clone ( ) ) ,
170+ }
171+ }
172+
173+ fn parse_authority ( authority : Authority ) -> Option < ( String , Option < u16 > ) > {
174+ let host = authority. host ( ) ;
175+ let host = host
176+ . strip_prefix ( '[' )
177+ . and_then ( |h| h. strip_suffix ( ']' ) )
178+ . unwrap_or ( host) ;
179+ if host. is_empty ( ) {
180+ return None ;
181+ }
182+ Some ( ( host. to_ascii_lowercase ( ) , authority. port_u16 ( ) ) )
183+ }
184+
185+ /// Only accept requests addressed to the server itself to prevent DNS rebinding attacks.
186+ fn is_allowed_host ( host : & str , address : & SocketAddr ) -> bool {
187+ // `localhost` and its subdomains always resolve to the loopback interface
188+ // (`tauri.localhost` is used by the dev proxy on Android and Windows)
189+ if host == "localhost" || host. ends_with ( ".localhost" ) {
190+ return true ;
191+ }
192+ match host. parse :: < IpAddr > ( ) {
193+ // an IP address can't be rebound
194+ Ok ( ip) => ip. is_loopback ( ) || ip == address. ip ( ) || address. ip ( ) . is_unspecified ( ) ,
195+ Err ( _) => false ,
196+ }
197+ }
198+
199+ /// Reject cross-site WebSocket connections.
200+ fn is_allowed_origin ( origin : Option < & HeaderValue > , host : & ( String , Option < u16 > ) ) -> bool {
201+ let Some ( origin) = origin else {
202+ return true ;
203+ } ;
204+ let Some ( origin) = origin. to_str ( ) . ok ( ) . and_then ( |o| url:: Url :: parse ( o) . ok ( ) ) else {
205+ return false ;
206+ } ;
207+ let Some ( origin_host) = origin. host_str ( ) else {
208+ return false ;
209+ } ;
210+ let origin_host = origin_host
211+ . strip_prefix ( '[' )
212+ . and_then ( |h| h. strip_suffix ( ']' ) )
213+ . unwrap_or ( origin_host)
214+ . to_ascii_lowercase ( ) ;
215+
216+ // Tauri pages served through the dev proxy on mobile (`tauri://localhost` or `http(s)://tauri.localhost`)
217+ if origin. scheme ( ) == "tauri" || origin_host == "tauri.localhost" {
218+ return true ;
219+ }
220+
221+ origin_host == host. 0 && origin. port_or_known_default ( ) == Some ( host. 1 . unwrap_or ( 80 ) )
222+ }
223+
128224fn inject_address ( html_bytes : Vec < u8 > , address : & SocketAddr ) -> Vec < u8 > {
129225 let document = tauri_utils:: html2:: parse_doc ( String :: from_utf8_lossy ( & html_bytes) . into_owned ( ) ) ;
130226
@@ -167,3 +263,109 @@ fn watch<F: Fn() + Send + 'static>(dir: PathBuf, handler: F) {
167263 }
168264 } ) ;
169265}
266+
267+ #[ cfg( test) ]
268+ mod tests {
269+ use super :: * ;
270+
271+ fn host_of ( host : & str ) -> Option < ( String , Option < u16 > ) > {
272+ let mut headers = HeaderMap :: new ( ) ;
273+ headers. insert ( header:: HOST , HeaderValue :: from_str ( host) . unwrap ( ) ) ;
274+ request_host ( & headers, & Uri :: from_static ( "/" ) )
275+ }
276+
277+ fn allowed ( host : & str , address : & str ) -> bool {
278+ let address: SocketAddr = address. parse ( ) . unwrap ( ) ;
279+ host_of ( host) . is_some_and ( |host| is_allowed_host ( & host. 0 , & address) )
280+ }
281+
282+ #[ test]
283+ fn parses_host_header ( ) {
284+ assert_eq ! (
285+ host_of( "127.0.0.1:1430" ) ,
286+ Some ( ( "127.0.0.1" . into( ) , Some ( 1430 ) ) )
287+ ) ;
288+ assert_eq ! ( host_of( "[::1]:1430" ) , Some ( ( "::1" . into( ) , Some ( 1430 ) ) ) ) ;
289+ assert_eq ! ( host_of( "LocalHost" ) , Some ( ( "localhost" . into( ) , None ) ) ) ;
290+ assert_eq ! ( host_of( "" ) , None ) ;
291+ assert_eq ! (
292+ request_host( & HeaderMap :: new( ) , & Uri :: from_static( "/" ) ) ,
293+ None
294+ ) ;
295+ assert_eq ! (
296+ request_host(
297+ & HeaderMap :: new( ) ,
298+ & Uri :: from_static( "http://127.0.0.1:1430/" )
299+ ) ,
300+ Some ( ( "127.0.0.1" . into( ) , Some ( 1430 ) ) )
301+ ) ;
302+ }
303+
304+ #[ test]
305+ fn host_check ( ) {
306+ let local = "127.0.0.1:1430" ;
307+ assert ! ( allowed( "127.0.0.1:1430" , local) ) ;
308+ assert ! ( allowed( "localhost:1430" , local) ) ;
309+ assert ! ( allowed( "[::1]:1430" , local) ) ;
310+ assert ! ( allowed( "tauri.localhost" , local) ) ;
311+ assert ! ( !allowed( "evil.com:1430" , local) ) ;
312+ assert ! ( !allowed( "localhost.evil.com" , local) ) ;
313+ assert ! ( !allowed( "192.168.1.10:1430" , local) ) ;
314+
315+ // mobile dev binds to the LAN address
316+ let lan = "192.168.1.10:1430" ;
317+ assert ! ( allowed( "192.168.1.10:1430" , lan) ) ;
318+ assert ! ( allowed( "127.0.0.1:1430" , lan) ) ;
319+ assert ! ( !allowed( "192.168.1.11:1430" , lan) ) ;
320+ assert ! ( !allowed( "evil.com:1430" , lan) ) ;
321+
322+ // the unspecified address accepts any IP but no domain
323+ let any = "0.0.0.0:1430" ;
324+ assert ! ( allowed( "192.168.1.11:1430" , any) ) ;
325+ assert ! ( !allowed( "evil.com:1430" , any) ) ;
326+ }
327+
328+ #[ test]
329+ fn origin_check ( ) {
330+ let host = ( "127.0.0.1" . to_string ( ) , Some ( 1430 ) ) ;
331+ let check =
332+ |origin : & str | is_allowed_origin ( Some ( & HeaderValue :: from_str ( origin) . unwrap ( ) ) , & host) ;
333+
334+ assert ! ( is_allowed_origin( None , & host) ) ;
335+ assert ! ( check( "http://127.0.0.1:1430" ) ) ;
336+ assert ! ( check( "tauri://localhost" ) ) ;
337+ assert ! ( check( "http://tauri.localhost" ) ) ;
338+ assert ! ( check( "https://tauri.localhost" ) ) ;
339+ assert ! ( !check( "http://127.0.0.1:3000" ) ) ;
340+ assert ! ( !check( "http://evil.com" ) ) ;
341+ assert ! ( !check( "null" ) ) ;
342+
343+ let ipv6 = ( "::1" . to_string ( ) , Some ( 1430 ) ) ;
344+ assert ! ( is_allowed_origin(
345+ Some ( & HeaderValue :: from_static( "http://[::1]:1430" ) ) ,
346+ & ipv6
347+ ) ) ;
348+
349+ let default_port = ( "localhost" . to_string ( ) , None ) ;
350+ assert ! ( is_allowed_origin(
351+ Some ( & HeaderValue :: from_static( "http://localhost" ) ) ,
352+ & default_port
353+ ) ) ;
354+ }
355+
356+ #[ test]
357+ fn fs_read_scoped_rejects_outside_scope ( ) {
358+ let dir = tempfile:: tempdir ( ) . unwrap ( ) ;
359+ let scope = dunce:: canonicalize ( dir. path ( ) ) . unwrap ( ) ;
360+ let inner = scope. join ( "dist" ) ;
361+ std:: fs:: create_dir ( & inner) . unwrap ( ) ;
362+ std:: fs:: write ( inner. join ( "index.html" ) , "inner" ) . unwrap ( ) ;
363+ std:: fs:: write ( scope. join ( "secret.txt" ) , "secret" ) . unwrap ( ) ;
364+
365+ assert_eq ! (
366+ fs_read_scoped( inner. join( "index.html" ) , & inner) . unwrap( ) ,
367+ b"inner"
368+ ) ;
369+ assert ! ( fs_read_scoped( inner. join( "../secret.txt" ) , & inner) . is_err( ) ) ;
370+ }
371+ }
0 commit comments