1 use std::{cell::Ref, convert::Infallible, net::SocketAddr};
2 
3 use actix_utils::future::{err, ok, Ready};
4 use derive_more::{Display, Error};
5 use once_cell::sync::Lazy;
6 
7 use crate::{
8     dev::{AppConfig, Payload, RequestHead},
9     http::{
10         header::{self, HeaderName},
11         uri::{Authority, Scheme},
12     },
13     FromRequest, HttpRequest, ResponseError,
14 };
15 
16 static X_FORWARDED_FOR: Lazy<HeaderName> =
17     Lazy::new(|| HeaderName::from_static("x-forwarded-for"));
18 static X_FORWARDED_HOST: Lazy<HeaderName> =
19     Lazy::new(|| HeaderName::from_static("x-forwarded-host"));
20 static X_FORWARDED_PROTO: Lazy<HeaderName> =
21     Lazy::new(|| HeaderName::from_static("x-forwarded-proto"));
22 
23 /// Trim whitespace then any quote marks.
unquote(val: &str) -> &str24 fn unquote(val: &str) -> &str {
25     val.trim().trim_start_matches('"').trim_end_matches('"')
26 }
27 
28 /// Extracts and trims first value for given header name.
first_header_value<'a>(req: &'a RequestHead, name: &'_ HeaderName) -> Option<&'a str>29 fn first_header_value<'a>(req: &'a RequestHead, name: &'_ HeaderName) -> Option<&'a str> {
30     let hdr = req.headers.get(name)?.to_str().ok()?;
31     let val = hdr.split(',').next()?.trim();
32     Some(val)
33 }
34 
35 /// HTTP connection information.
36 ///
37 /// `ConnectionInfo` implements `FromRequest` and can be extracted in handlers.
38 ///
39 /// # Examples
40 /// ```
41 /// # use actix_web::{HttpResponse, Responder};
42 /// use actix_web::dev::ConnectionInfo;
43 ///
44 /// async fn handler(conn: ConnectionInfo) -> impl Responder {
45 ///     match conn.host() {
46 ///         "actix.rs" => HttpResponse::Ok().body("Welcome!"),
47 ///         "admin.actix.rs" => HttpResponse::Ok().body("Admin portal."),
48 ///         _ => HttpResponse::NotFound().finish()
49 ///     }
50 /// }
51 /// # let _svc = actix_web::web::to(handler);
52 /// ```
53 ///
54 /// # Implementation Notes
55 /// Parses `Forwarded` header information according to [RFC 7239][rfc7239] but does not try to
56 /// interpret the values for each property. As such, the getter methods on `ConnectionInfo` return
57 /// strings instead of IP addresses or other types to acknowledge that they may be
58 /// [obfuscated][rfc7239-63] or [unknown][rfc7239-62].
59 ///
60 /// If the older, related headers are also present (eg. `X-Forwarded-For`), then `Forwarded`
61 /// is preferred.
62 ///
63 /// [rfc7239]: https://datatracker.ietf.org/doc/html/rfc7239
64 /// [rfc7239-62]: https://datatracker.ietf.org/doc/html/rfc7239#section-6.2
65 /// [rfc7239-63]: https://datatracker.ietf.org/doc/html/rfc7239#section-6.3
66 #[derive(Debug, Clone, Default)]
67 pub struct ConnectionInfo {
68     scheme: String,
69     host: String,
70     realip_remote_addr: Option<String>,
71     remote_addr: Option<String>,
72 }
73 
74 impl ConnectionInfo {
75     /// Create *ConnectionInfo* instance for a request.
get<'a>(req: &'a RequestHead, cfg: &AppConfig) -> Ref<'a, Self>76     pub fn get<'a>(req: &'a RequestHead, cfg: &AppConfig) -> Ref<'a, Self> {
77         if !req.extensions().contains::<ConnectionInfo>() {
78             req.extensions_mut().insert(ConnectionInfo::new(req, cfg));
79         }
80         Ref::map(req.extensions(), |e| e.get().unwrap())
81     }
82 
new(req: &RequestHead, cfg: &AppConfig) -> ConnectionInfo83     fn new(req: &RequestHead, cfg: &AppConfig) -> ConnectionInfo {
84         let mut host = None;
85         let mut scheme = None;
86         let mut realip_remote_addr = None;
87 
88         for (name, val) in req
89             .headers
90             .get_all(&header::FORWARDED)
91             .into_iter()
92             .filter_map(|hdr| hdr.to_str().ok())
93             // "for=1.2.3.4, for=5.6.7.8; scheme=https"
94             .flat_map(|val| val.split(';'))
95             // ["for=1.2.3.4, for=5.6.7.8", " scheme=https"]
96             .flat_map(|vals| vals.split(','))
97             // ["for=1.2.3.4", " for=5.6.7.8", " scheme=https"]
98             .flat_map(|pair| {
99                 let mut items = pair.trim().splitn(2, '=');
100                 Some((items.next()?, items.next()?))
101             })
102         {
103             // [(name , val      ), ...                                    ]
104             // [("for", "1.2.3.4"), ("for", "5.6.7.8"), ("scheme", "https")]
105 
106             // taking the first value for each property is correct because spec states that first
107             // "for" value is client and rest are proxies; multiple values other properties have
108             // no defined semantics
109             //
110             // > In a chain of proxy servers where this is fully utilized, the first
111             // > "for" parameter will disclose the client where the request was first
112             // > made, followed by any subsequent proxy identifiers.
113             // --- https://datatracker.ietf.org/doc/html/rfc7239#section-5.2
114 
115             match name.trim().to_lowercase().as_str() {
116                 "for" => realip_remote_addr.get_or_insert_with(|| unquote(val)),
117                 "proto" => scheme.get_or_insert_with(|| unquote(val)),
118                 "host" => host.get_or_insert_with(|| unquote(val)),
119                 "by" => {
120                     // TODO: implement https://datatracker.ietf.org/doc/html/rfc7239#section-5.1
121                     continue;
122                 }
123                 _ => continue,
124             };
125         }
126 
127         let scheme = scheme
128             .or_else(|| first_header_value(req, &*X_FORWARDED_PROTO))
129             .or_else(|| req.uri.scheme().map(Scheme::as_str))
130             .or_else(|| Some("https").filter(|_| cfg.secure()))
131             .unwrap_or("http")
132             .to_owned();
133 
134         let host = host
135             .or_else(|| first_header_value(req, &*X_FORWARDED_HOST))
136             .or_else(|| req.headers.get(&header::HOST)?.to_str().ok())
137             .or_else(|| req.uri.authority().map(Authority::as_str))
138             .unwrap_or(cfg.host())
139             .to_owned();
140 
141         let realip_remote_addr = realip_remote_addr
142             .or_else(|| first_header_value(req, &*X_FORWARDED_FOR))
143             .map(str::to_owned);
144 
145         let remote_addr = req.peer_addr.map(|addr| addr.to_string());
146 
147         ConnectionInfo {
148             remote_addr,
149             scheme,
150             host,
151             realip_remote_addr,
152         }
153     }
154 
155     /// Scheme of the request.
156     ///
157     /// Scheme is resolved through the following headers, in this order:
158     ///
159     /// - Forwarded
160     /// - X-Forwarded-Proto
161     /// - Uri
162     #[inline]
scheme(&self) -> &str163     pub fn scheme(&self) -> &str {
164         &self.scheme
165     }
166 
167     /// Hostname of the request.
168     ///
169     /// Hostname is resolved through the following headers, in this order:
170     ///
171     /// - Forwarded
172     /// - X-Forwarded-Host
173     /// - Host
174     /// - Uri
175     /// - Server hostname
host(&self) -> &str176     pub fn host(&self) -> &str {
177         &self.host
178     }
179 
180     /// Remote address of the connection.
181     ///
182     /// Get remote_addr address from socket address.
remote_addr(&self) -> Option<&str>183     pub fn remote_addr(&self) -> Option<&str> {
184         self.remote_addr.as_deref()
185     }
186 
187     /// Real IP (remote address) of client that initiated request.
188     ///
189     /// The address is resolved through the following headers, in this order:
190     ///
191     /// - Forwarded
192     /// - X-Forwarded-For
193     /// - remote_addr name of opened socket
194     ///
195     /// # Security
196     /// Do not use this function for security purposes, unless you can ensure the Forwarded and
197     /// X-Forwarded-For headers cannot be spoofed by the client. If you want the client's socket
198     /// address explicitly, use [`HttpRequest::peer_addr()`][peer_addr] instead.
199     ///
200     /// [peer_addr]: crate::web::HttpRequest::peer_addr()
201     #[inline]
realip_remote_addr(&self) -> Option<&str>202     pub fn realip_remote_addr(&self) -> Option<&str> {
203         self.realip_remote_addr
204             .as_deref()
205             .or_else(|| self.remote_addr.as_deref())
206     }
207 }
208 
209 impl FromRequest for ConnectionInfo {
210     type Error = Infallible;
211     type Future = Ready<Result<Self, Self::Error>>;
212     type Config = ();
213 
from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future214     fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
215         ok(req.connection_info().clone())
216     }
217 }
218 
219 /// Extractor for peer's socket address.
220 ///
221 /// Also see [`HttpRequest::peer_addr`].
222 ///
223 /// # Examples
224 /// ```
225 /// # use actix_web::Responder;
226 /// use actix_web::dev::PeerAddr;
227 ///
228 /// async fn handler(peer_addr: PeerAddr) -> impl Responder {
229 ///     let socket_addr = peer_addr.0;
230 ///     socket_addr.to_string()
231 /// }
232 /// # let _svc = actix_web::web::to(handler);
233 /// ```
234 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Display)]
235 #[display(fmt = "{}", _0)]
236 pub struct PeerAddr(pub SocketAddr);
237 
238 impl PeerAddr {
239     /// Unwrap into inner `SocketAddr` value.
into_inner(self) -> SocketAddr240     pub fn into_inner(self) -> SocketAddr {
241         self.0
242     }
243 }
244 
245 #[derive(Debug, Display, Error)]
246 #[non_exhaustive]
247 #[display(fmt = "Missing peer address")]
248 pub struct MissingPeerAddr;
249 
250 impl ResponseError for MissingPeerAddr {}
251 
252 impl FromRequest for PeerAddr {
253     type Error = MissingPeerAddr;
254     type Future = Ready<Result<Self, Self::Error>>;
255     type Config = ();
256 
from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future257     fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
258         match req.peer_addr() {
259             Some(addr) => ok(PeerAddr(addr)),
260             None => {
261                 log::error!("Missing peer address.");
262                 err(MissingPeerAddr)
263             }
264         }
265     }
266 }
267 
268 #[cfg(test)]
269 mod tests {
270     use super::*;
271     use crate::test::TestRequest;
272 
273     const X_FORWARDED_FOR: &str = "x-forwarded-for";
274     const X_FORWARDED_HOST: &str = "x-forwarded-host";
275     const X_FORWARDED_PROTO: &str = "x-forwarded-proto";
276 
277     #[test]
info_default()278     fn info_default() {
279         let req = TestRequest::default().to_http_request();
280         let info = req.connection_info();
281         assert_eq!(info.scheme(), "http");
282         assert_eq!(info.host(), "localhost:8080");
283     }
284 
285     #[test]
host_header()286     fn host_header() {
287         let req = TestRequest::default()
288             .insert_header((header::HOST, "rust-lang.org"))
289             .to_http_request();
290 
291         let info = req.connection_info();
292         assert_eq!(info.scheme(), "http");
293         assert_eq!(info.host(), "rust-lang.org");
294         assert_eq!(info.realip_remote_addr(), None);
295     }
296 
297     #[test]
x_forwarded_for_header()298     fn x_forwarded_for_header() {
299         let req = TestRequest::default()
300             .insert_header((X_FORWARDED_FOR, "192.0.2.60"))
301             .to_http_request();
302         let info = req.connection_info();
303         assert_eq!(info.realip_remote_addr(), Some("192.0.2.60"));
304     }
305 
306     #[test]
x_forwarded_host_header()307     fn x_forwarded_host_header() {
308         let req = TestRequest::default()
309             .insert_header((X_FORWARDED_HOST, "192.0.2.60"))
310             .to_http_request();
311         let info = req.connection_info();
312         assert_eq!(info.host(), "192.0.2.60");
313         assert_eq!(info.realip_remote_addr(), None);
314     }
315 
316     #[test]
x_forwarded_proto_header()317     fn x_forwarded_proto_header() {
318         let req = TestRequest::default()
319             .insert_header((X_FORWARDED_PROTO, "https"))
320             .to_http_request();
321         let info = req.connection_info();
322         assert_eq!(info.scheme(), "https");
323     }
324 
325     #[test]
forwarded_header()326     fn forwarded_header() {
327         let req = TestRequest::default()
328             .insert_header((
329                 header::FORWARDED,
330                 "for=192.0.2.60; proto=https; by=203.0.113.43; host=rust-lang.org",
331             ))
332             .to_http_request();
333 
334         let info = req.connection_info();
335         assert_eq!(info.scheme(), "https");
336         assert_eq!(info.host(), "rust-lang.org");
337         assert_eq!(info.realip_remote_addr(), Some("192.0.2.60"));
338 
339         let req = TestRequest::default()
340             .insert_header((
341                 header::FORWARDED,
342                 "for=192.0.2.60; proto=https; by=203.0.113.43; host=rust-lang.org",
343             ))
344             .to_http_request();
345 
346         let info = req.connection_info();
347         assert_eq!(info.scheme(), "https");
348         assert_eq!(info.host(), "rust-lang.org");
349         assert_eq!(info.realip_remote_addr(), Some("192.0.2.60"));
350     }
351 
352     #[test]
forwarded_case_sensitivity()353     fn forwarded_case_sensitivity() {
354         let req = TestRequest::default()
355             .insert_header((header::FORWARDED, "For=192.0.2.60"))
356             .to_http_request();
357         let info = req.connection_info();
358         assert_eq!(info.realip_remote_addr(), Some("192.0.2.60"));
359     }
360 
361     #[test]
forwarded_weird_whitespace()362     fn forwarded_weird_whitespace() {
363         let req = TestRequest::default()
364             .insert_header((header::FORWARDED, "for= 1.2.3.4; proto= https"))
365             .to_http_request();
366         let info = req.connection_info();
367         assert_eq!(info.realip_remote_addr(), Some("1.2.3.4"));
368         assert_eq!(info.scheme(), "https");
369 
370         let req = TestRequest::default()
371             .insert_header((header::FORWARDED, "  for = 1.2.3.4  "))
372             .to_http_request();
373         let info = req.connection_info();
374         assert_eq!(info.realip_remote_addr(), Some("1.2.3.4"));
375     }
376 
377     #[test]
forwarded_for_quoted()378     fn forwarded_for_quoted() {
379         let req = TestRequest::default()
380             .insert_header((header::FORWARDED, r#"for="192.0.2.60:8080""#))
381             .to_http_request();
382         let info = req.connection_info();
383         assert_eq!(info.realip_remote_addr(), Some("192.0.2.60:8080"));
384     }
385 
386     #[test]
forwarded_for_ipv6()387     fn forwarded_for_ipv6() {
388         let req = TestRequest::default()
389             .insert_header((header::FORWARDED, r#"for="[2001:db8:cafe::17]:4711""#))
390             .to_http_request();
391         let info = req.connection_info();
392         assert_eq!(info.realip_remote_addr(), Some("[2001:db8:cafe::17]:4711"));
393     }
394 
395     #[test]
forwarded_for_multiple()396     fn forwarded_for_multiple() {
397         let req = TestRequest::default()
398             .insert_header((header::FORWARDED, "for=192.0.2.60, for=198.51.100.17"))
399             .to_http_request();
400         let info = req.connection_info();
401         // takes the first value
402         assert_eq!(info.realip_remote_addr(), Some("192.0.2.60"));
403     }
404 
405     #[test]
scheme_from_uri()406     fn scheme_from_uri() {
407         let req = TestRequest::get()
408             .uri("https://actix.rs/test")
409             .to_http_request();
410         let info = req.connection_info();
411         assert_eq!(info.scheme(), "https");
412     }
413 
414     #[test]
host_from_uri()415     fn host_from_uri() {
416         let req = TestRequest::get()
417             .uri("https://actix.rs/test")
418             .to_http_request();
419         let info = req.connection_info();
420         assert_eq!(info.host(), "actix.rs");
421     }
422 
423     #[test]
host_from_server_hostname()424     fn host_from_server_hostname() {
425         let mut req = TestRequest::get();
426         req.set_server_hostname("actix.rs");
427         let req = req.to_http_request();
428 
429         let info = req.connection_info();
430         assert_eq!(info.host(), "actix.rs");
431     }
432 
433     #[actix_rt::test]
conn_info_extract()434     async fn conn_info_extract() {
435         let req = TestRequest::default()
436             .uri("https://actix.rs/test")
437             .to_http_request();
438         let conn_info = ConnectionInfo::extract(&req).await.unwrap();
439         assert_eq!(conn_info.scheme(), "https");
440         assert_eq!(conn_info.host(), "actix.rs");
441     }
442 
443     #[actix_rt::test]
peer_addr_extract()444     async fn peer_addr_extract() {
445         let addr = "127.0.0.1:8080".parse().unwrap();
446         let req = TestRequest::default().peer_addr(addr).to_http_request();
447         let peer_addr = PeerAddr::extract(&req).await.unwrap();
448         assert_eq!(peer_addr, PeerAddr(addr));
449 
450         let req = TestRequest::default().to_http_request();
451         let res = PeerAddr::extract(&req).await;
452         assert!(res.is_err());
453     }
454 }
455