1#[cfg(feature = "quic")]
9mod quic_view;
10
11use std::{convert::Infallible, sync::Arc, time::Duration};
12
13use rama_core::error::ErrorExt as _;
14use rama_http::layer::upgrade::UpgradeLayer;
15use serde::Serialize;
16use serde_json::json;
17
18#[cfg(feature = "quic")]
19use self::quic_view::{EchoH3, EchoQuic, EchoQuicConnection};
20use crate::{
21 Layer, Service,
22 cli::{DEFAULT_CONNECTION_GRACE, ForwardKind, connection_scope},
23 combinators::{Either, Either3},
24 error::{BoxError, BoxErrorExt, ErrorContext},
25 extensions::ExtensionsRef,
26 graceful::WeakScope,
27 http::{
28 BodyLimitLayer, HeaderValue, Request, Response, Version,
29 body::util::BodyExt,
30 convert::curl,
31 core::h2::frame::EarlyFrameCapture,
32 fingerprint::{AkamaiH2, Ja4H},
33 header::USER_AGENT,
34 headers::{AltSvc, exotic::XClacksOverhead},
35 layer::{
36 required_header::AddRequiredResponseHeadersLayer, set_header::SetResponseHeaderLayer,
37 trace::TraceLayer,
38 },
39 proto::h2::PseudoHeaderOrder,
40 server::HttpServer,
41 service::web::{extract::Json, response::IntoResponse},
42 ws::handshake::{
43 matcher::WebSocketMatcher,
44 server::{WebSocketAcceptor, WebSocketEchoService},
45 },
46 },
47 layer::{
48 ConsumeErrLayer, LimitLayer,
49 limit::policy::{ConcurrentPolicy, RateLimitReached, RatePolicy, UnlimitedPolicy},
50 },
51 net::{
52 AuthorityInputExt, Protocol, ProtocolInputExt,
53 address::ip::geo::IpGeoDb,
54 forwarded::ForwardedClientExt as _,
55 stream::{
56 SocketInfo,
57 layer::{ThrottleLayer, ThrottleMode},
58 },
59 },
60 proxy::haproxy::server::HaProxyLayer,
61 service::service_fn,
62 tcp::TcpStream,
63 telemetry::tracing,
64 ua::{
65 UserAgent,
66 layer::classifier::UserAgentClassifierLayer,
67 profile::{
68 analysis::fingerprint::{RecordedFingerprintCache, RecordedFingerprints},
69 selection::database::UserAgentDatabase,
70 },
71 },
72 utils::{octets::mib, rate::Rate},
73};
74#[cfg(feature = "quic")]
75use crate::{
76 http::proto::h3::observation::{H3RequestObservation, ObservationLimits, SettingsStatus},
77 quic::{self, QuicConnectionInfo, proto::capture::QuicObservation},
78};
79
80core::cfg_select! {
81 feature = "boring" => {
82 use crate::tls::boring::server::TlsAcceptorLayer;
83 }
84 feature = "rustls" => {
85 use crate::tls::rustls::server::TlsAcceptorLayer;
86 }
87 _ => {}
88}
89
90#[cfg(any(feature = "rustls", feature = "boring"))]
91use crate::{
92 tls::{
93 client::{ClientHelloExtension, ECHClientHello},
94 fingerprint::{Ja3, Ja4, PeetPrint},
95 server::{ServerClientHellos, TlsServerConfig},
96 },
97 ua::profile::analysis::fingerprint::RecordedTlsFingerprint,
98};
99
100#[derive(Debug, Clone)]
101pub struct EchoServiceBuilder<H> {
104 concurrent_limit: usize,
105 rate_limit: Option<Rate>,
106 throttle: Option<Rate>,
107 body_limit: usize,
108 timeout: Duration,
109 timeout_grace: Duration,
110 forward: Option<ForwardKind>,
111
112 #[cfg(any(feature = "rustls", feature = "boring"))]
113 tls_server_config: Option<TlsServerConfig>,
114 #[cfg(any(feature = "rustls", feature = "boring"))]
115 store_outer_client_hello: bool,
116
117 http_version: Option<Version>,
118 http2_observation: bool,
119 #[cfg(feature = "quic")]
120 http3_observation: Option<ObservationLimits>,
121
122 ws_support: bool,
123
124 alt_svc: Option<AltSvc>,
125
126 http_service_builder: H,
127
128 uadb: Option<std::sync::Arc<UserAgentDatabase>>,
129
130 geo_db: Option<std::sync::Arc<IpGeoDb>>,
131}
132
133impl Default for EchoServiceBuilder<()> {
134 fn default() -> Self {
135 Self {
136 concurrent_limit: 0,
137 rate_limit: None,
138 throttle: None,
139 body_limit: mib(1),
140 timeout: Duration::ZERO,
141 timeout_grace: DEFAULT_CONNECTION_GRACE,
142 forward: None,
143
144 #[cfg(any(feature = "rustls", feature = "boring"))]
145 tls_server_config: None,
146 #[cfg(any(feature = "rustls", feature = "boring"))]
147 store_outer_client_hello: false,
148
149 http_version: None,
150 http2_observation: false,
151 #[cfg(feature = "quic")]
152 http3_observation: None,
153
154 ws_support: false,
155
156 alt_svc: None,
157
158 http_service_builder: (),
159
160 uadb: None,
161
162 geo_db: None,
163 }
164 }
165}
166
167impl EchoServiceBuilder<()> {
168 #[must_use]
170 pub fn new() -> Self {
171 Self::default()
172 }
173}
174
175impl<H> EchoServiceBuilder<H> {
176 crate::utils::macros::generate_set_and_with! {
177 pub fn concurrent(mut self, limit: usize) -> Self {
181 self.concurrent_limit = limit;
182 self
183 }
184 }
185
186 crate::utils::macros::generate_set_and_with! {
187 pub fn rate_limit(mut self, rate: Option<Rate>) -> Self {
190 self.rate_limit = rate;
191 self
192 }
193 }
194
195 crate::utils::macros::generate_set_and_with! {
196 pub fn throttle(mut self, rate: Option<Rate>) -> Self {
199 self.throttle = rate;
200 self
201 }
202 }
203
204 crate::utils::macros::generate_set_and_with! {
205 pub fn body_limit(mut self, limit: usize) -> Self {
207 self.body_limit = limit;
208 self
209 }
210 }
211
212 crate::utils::macros::generate_set_and_with! {
213 pub fn timeout(mut self, timeout: Duration) -> Self {
218 self.timeout = timeout;
219 self
220 }
221 }
222
223 crate::utils::macros::generate_set_and_with! {
224 pub fn timeout_grace(mut self, timeout_grace: Duration) -> Self {
229 self.timeout_grace = timeout_grace;
230 self
231 }
232 }
233
234 crate::utils::macros::generate_set_and_with! {
235 pub fn forward(mut self, kind: Option<ForwardKind>) -> Self {
247 self.forward = kind;
248 self
249 }
250 }
251
252 crate::utils::macros::generate_set_and_with! {
253 #[cfg(any(feature = "rustls", feature = "boring"))]
254 pub fn tls_server_config(mut self, cfg: Option<TlsServerConfig>) -> Self {
257 self.tls_server_config = cfg;
258 self
259 }
260 }
261
262 crate::utils::macros::generate_set_and_with! {
263 #[cfg(any(feature = "rustls", feature = "boring"))]
264 pub fn store_outer_client_hello(mut self, enabled: bool) -> Self {
267 self.store_outer_client_hello = enabled;
268 self
269 }
270 }
271
272 crate::utils::macros::generate_set_and_with! {
273 pub fn http_version(mut self, version: Option<Version>) -> Self {
275 self.http_version = version;
276 self
277 }
278 }
279
280 crate::utils::macros::generate_set_and_with! {
281 pub fn alt_svc(mut self, alt_svc: Option<AltSvc>) -> Self {
283 self.alt_svc = alt_svc;
284 self
285 }
286 }
287
288 #[cfg(feature = "quic")]
289 crate::utils::macros::generate_set_and_with! {
290 pub fn http3_observation(mut self, limits: Option<ObservationLimits>) -> Self {
292 self.http3_observation = limits;
293 self
294 }
295 }
296
297 crate::utils::macros::generate_set_and_with! {
298 pub fn http2_observation(mut self, enabled: bool) -> Self {
300 self.http2_observation = enabled;
301 self
302 }
303 }
304
305 pub fn with_http_layer<H2>(self, layer: H2) -> EchoServiceBuilder<(H, H2)> {
307 EchoServiceBuilder {
308 concurrent_limit: self.concurrent_limit,
309 rate_limit: self.rate_limit,
310 throttle: self.throttle,
311 body_limit: self.body_limit,
312 timeout: self.timeout,
313 timeout_grace: self.timeout_grace,
314 forward: self.forward,
315
316 #[cfg(any(feature = "rustls", feature = "boring"))]
317 tls_server_config: self.tls_server_config,
318 #[cfg(any(feature = "rustls", feature = "boring"))]
319 store_outer_client_hello: self.store_outer_client_hello,
320
321 http_version: self.http_version,
322 http2_observation: self.http2_observation,
323 #[cfg(feature = "quic")]
324 http3_observation: self.http3_observation,
325
326 ws_support: self.ws_support,
327
328 alt_svc: self.alt_svc,
329
330 http_service_builder: (self.http_service_builder, layer),
331
332 uadb: self.uadb,
333
334 geo_db: self.geo_db,
335 }
336 }
337
338 crate::utils::macros::generate_set_and_with! {
339 pub fn user_agent_database(
342 mut self,
343 db: Option<std::sync::Arc<UserAgentDatabase>>,
344 ) -> Self {
345 self.uadb = db;
346 self
347 }
348 }
349
350 crate::utils::macros::generate_set_and_with! {
351 pub fn geo_db(mut self, db: Option<std::sync::Arc<IpGeoDb>>) -> Self {
354 self.geo_db = db;
355 self
356 }
357 }
358
359 crate::utils::macros::generate_set_and_with! {
360 pub fn ws_support(
362 mut self,
363 support: bool,
364 ) -> Self {
365 self.ws_support = support;
366 self
367 }
368 }
369}
370
371impl<H> EchoServiceBuilder<H>
372where
373 H: Layer<EchoService, Service: Service<Request, Output = Response, Error = BoxError>>,
374{
375 pub fn build(
377 self,
378 scope: impl Into<WeakScope>,
379 ) -> Result<impl Service<TcpStream, Output = (), Error = Infallible>, BoxError> {
380 let scope = scope.into();
381 self.build_services(scope).map(|(tcp, _)| tcp)
382 }
383
384 #[cfg(feature = "quic")]
391 #[cfg_attr(docsrs, doc(cfg(feature = "quic")))]
392 pub fn build_with_http3(
393 self,
394 scope: impl Into<WeakScope>,
395 ) -> Result<
396 (
397 impl Service<TcpStream, Output = (), Error = Infallible>,
398 impl Service<quic::Connection, Output = (), Error = Infallible>,
399 ),
400 BoxError,
401 > {
402 let scope = scope.into();
403 self.build_services(scope)
404 }
405
406 fn build_services(
407 self,
408 scope: WeakScope,
409 ) -> Result<
410 (
411 impl Service<TcpStream, Output = (), Error = Infallible>,
412 impl super::MaybeHttp3Service,
413 ),
414 BoxError,
415 > {
416 let tcp_forwarded_layer = match &self.forward {
417 Some(ForwardKind::HaProxy) => Some(HaProxyLayer::default()),
418 _ => None,
419 };
420
421 let http_service = Arc::new(self.build_http(scope.clone()));
422
423 let connection_limit = LimitLayer::new(if self.concurrent_limit > 0 {
424 Either::A(ConcurrentPolicy::max(self.concurrent_limit))
425 } else {
426 Either::B(UnlimitedPolicy::new())
427 });
428 let connection_timeout = connection_scope(&scope, self.timeout, self.timeout_grace);
429
430 let throttle = self
432 .throttle
433 .map(|rate| ThrottleLayer::symmetric(ThrottleMode::per_conn(rate)));
434 let tcp_service_builder = (
435 ConsumeErrLayer::trace_as(tracing::Level::DEBUG),
436 connection_limit.clone(),
437 connection_timeout.clone(),
438 throttle.clone(),
439 tcp_forwarded_layer,
440 BodyLimitLayer::request_only(self.body_limit),
441 #[cfg(any(feature = "rustls", feature = "boring"))]
442 (self.store_outer_client_hello && self.tls_server_config.is_some())
443 .then_some(crate::tls::server::StoreOuterClientHelloLayer::new()),
444 #[cfg(any(feature = "rustls", feature = "boring"))]
445 self.tls_server_config
446 .map(|cfg| TlsAcceptorLayer::new(cfg).with_store_client_hello(true)),
447 );
448
449 let http_transport_service = match self.http_version {
450 Some(Version::HTTP_2) => Either3::A({
451 let mut http = HttpServer::new_h2(scope.clone());
452 http.h2_mut()
453 .set_observe_early_frames(self.http2_observation);
454 if self.ws_support {
455 http.h2_mut().set_enable_connect_protocol();
456 }
457 http.service(http_service.clone())
458 }),
459 Some(Version::HTTP_11 | Version::HTTP_10 | Version::HTTP_09) => {
460 Either3::B(HttpServer::new_http1(scope.clone()).service(http_service.clone()))
461 }
462 Some(version) => {
463 return Err(BoxError::from_static_str("unsupported http version")
464 .context_debug_field("version", version));
465 }
466 None => Either3::C({
467 let mut http = HttpServer::auto(scope.clone());
468 http.h2_mut()
469 .set_observe_early_frames(self.http2_observation);
470 if self.ws_support {
471 http.h2_mut().set_enable_connect_protocol();
472 }
473 http.service(http_service.clone())
474 }),
475 };
476
477 #[cfg(feature = "quic")]
478 let http3_service = {
479 let mut http3 = HttpServer::new_http3(scope);
480 http3.http3_mut().observation = self.http3_observation.map(Box::new);
482 http3.http3_mut().extended_connect = self.ws_support;
483 (
484 ConsumeErrLayer::trace_as(tracing::Level::DEBUG),
485 connection_limit,
486 connection_timeout,
487 throttle,
488 BodyLimitLayer::request_only(self.body_limit),
489 )
490 .into_layer(http3.service(http_service))
491 };
492 #[cfg(not(feature = "quic"))]
493 let http3_service = (
494 connection_limit,
495 connection_timeout,
496 throttle,
497 http_service,
498 scope,
499 );
500
501 Ok((
502 tcp_service_builder.into_layer(http_transport_service),
503 http3_service,
504 ))
505 }
506
507 pub fn build_http(
509 &self,
510 scope: WeakScope,
511 ) -> impl Service<Request, Output: IntoResponse, Error = Infallible> + use<H> {
512 let http_forwarded_layer = super::http_forwarded_layer(self.forward.as_ref());
513
514 let profiles = self.uadb.clone().map(|database| {
515 Arc::new(EchoProfiles {
516 fingerprints: RecordedFingerprintCache::new(&database),
517 database,
518 })
519 });
520
521 let geo_attribution = self.geo_db.as_ref().and_then(|db| {
523 let notices: Vec<_> = db.attributions().collect();
524 (!notices.is_empty()).then(|| crate::cli::service::geo::geo_attribution_layer(notices))
525 });
526
527 (
528 TraceLayer::new_for_http(),
529 SetResponseHeaderLayer::<XClacksOverhead>::if_not_present_default_typed(),
530 self.alt_svc
531 .clone()
532 .map(SetResponseHeaderLayer::if_not_present_typed),
533 AddRequiredResponseHeadersLayer::default(),
534 self.rate_limit.map(|rate| {
535 LimitLayer::new(RatePolicy::abort(rate)).with_error_into_response_fn(
536 |err: RateLimitReached| Ok::<_, Infallible>(err.into_response()),
537 )
538 }),
539 geo_attribution,
540 UserAgentClassifierLayer::new(),
541 ConsumeErrLayer::default(),
542 http_forwarded_layer,
543 self.ws_support.then(|| {
544 let acceptor = WebSocketAcceptor::default()
545 .with_protocols_flex(true)
546 .with_echo_protocols();
547 #[cfg(feature = "compression")]
548 let acceptor = acceptor.with_per_message_deflate_overwrite_extensions();
549 let profiles = profiles.clone();
550 UpgradeLayer::new_with_services(
551 scope,
552 WebSocketMatcher::default(),
553 service_fn(move |req: Request| {
555 let acceptor = acceptor.clone();
556 let report = fingerprint_headers(profiles.as_deref(), &req);
557 async move {
558 let mut accepted = acceptor.serve(req).await?;
559 let headers = accepted.response.headers_mut();
560 for (name, value) in report {
561 headers.insert(name, value);
562 }
563 Ok(accepted)
564 }
565 }),
566 ConsumeErrLayer::trace_as(tracing::Level::DEBUG)
567 .into_layer(WebSocketEchoService::default()),
568 )
569 }),
570 )
571 .into_layer(self.http_service_builder.layer(EchoService {
572 profiles,
573 geo_db: self.geo_db.clone(),
574 }))
575 }
576}
577
578#[derive(Debug, Clone)]
579#[non_exhaustive]
580pub struct EchoService {
582 profiles: Option<Arc<EchoProfiles>>,
583 geo_db: Option<std::sync::Arc<IpGeoDb>>,
584}
585
586#[derive(Debug)]
587struct EchoProfiles {
588 database: Arc<UserAgentDatabase>,
589 fingerprints: RecordedFingerprintCache,
590}
591
592impl EchoProfiles {
593 fn recorded(&self, ua: &str) -> Option<&RecordedFingerprints> {
594 self.fingerprints.get(&self.database, ua)
595 }
596}
597
598#[derive(Debug, Serialize)]
599struct CurlScripts {
600 unix: String,
601 powershell: String,
602}
603
604fn curl_scripts(
605 parts: &crate::http::request::Parts,
606 payload: &rama_core::bytes::Bytes,
607) -> Result<CurlScripts, curl::CurlPayloadRequiresStdin> {
608 let render = |compatibility| {
609 curl::try_cmd_string_for_request_parts_and_payload_with_options(
610 parts,
611 payload,
612 curl::CurlExportOptions::default().with_script_compatibility(compatibility),
613 &curl::CurlScriptPayloadMode::Inline,
614 )
615 };
616
617 Ok(CurlScripts {
618 unix: render(curl::CurlScriptCompatibility::Unix)?,
619 powershell: render(curl::CurlScriptCompatibility::PowerShell)?,
620 })
621}
622
623#[derive(Debug, Serialize)]
624struct FingerprintProfileData {
625 hash: String,
626 verbose: String,
627 matched: bool,
628}
629
630fn profile_fingerprint<'a, T: 'a>(
632 candidates: impl IntoIterator<Item = &'a T>,
633 is_match: impl Fn(&T) -> bool,
634 hash: impl Fn(&T) -> String,
635 verbose: impl Fn(&T) -> String,
636) -> Option<FingerprintProfileData> {
637 let mut first = None;
638 for candidate in candidates {
639 if is_match(candidate) {
640 return Some(FingerprintProfileData {
641 hash: hash(candidate),
642 verbose: verbose(candidate),
643 matched: true,
644 });
645 }
646 first.get_or_insert(candidate);
647 }
648 first.map(|candidate| FingerprintProfileData {
649 hash: hash(candidate),
650 verbose: verbose(candidate),
651 matched: false,
652 })
653}
654
655fn recorded_fingerprints<'a>(
657 profiles: Option<&'a EchoProfiles>,
658 req: &Request,
659) -> Option<&'a RecordedFingerprints> {
660 let ua = req.headers().get(USER_AGENT)?.to_str().ok()?;
661 profiles?.recorded(ua)
662}
663
664fn user_agent_view(req: &Request) -> serde_json::Value {
665 req.extensions()
666 .get_ref()
667 .map(|ua: &UserAgent| {
668 json!({
669 "user_agent": ua.header_str().to_owned(),
670 "kind": ua.info().map(|info| info.kind.to_string()),
671 "version": ua.info().and_then(|info| info.version),
672 "platform": ua.platform().map(|v| v.to_string()),
673 })
674 })
675 .unwrap_or_default()
676}
677
678fn ja4h_view(recorded: Option<&RecordedFingerprints>, req: &Request) -> Option<serde_json::Value> {
679 let ja4h = Ja4H::compute(req)
680 .inspect_err(|err| tracing::error!("ja4h compute failure: {err:?}"))
681 .ok()?;
682 let profile = recorded.and_then(|recorded| {
683 profile_fingerprint(
684 recorded.http.iter(),
685 |tgt| tgt.matches_client_shape(&ja4h),
686 |tgt| format!("{tgt}"),
687 |tgt| format!("{tgt:?}"),
688 )
689 });
690 Some(json!({
691 "hash": format!("{ja4h}"),
692 "verbose": format!("{ja4h:?}"),
693 "profile": profile,
694 }))
695}
696
697#[cfg(any(feature = "rustls", feature = "boring"))]
698fn recorded_tls(
699 recorded: Option<&RecordedFingerprints>,
700 version: Version,
701) -> &[RecordedTlsFingerprint] {
702 recorded.map_or(&[][..], |recorded| match version {
703 Version::HTTP_3 => &recorded.tls_quic[..],
704 _ => &recorded.tls[..],
705 })
706}
707
708#[cfg(any(feature = "rustls", feature = "boring"))]
709fn ja4_view(
710 hello: &crate::tls::client::ClientHello,
711 recorded_tls: &[RecordedTlsFingerprint],
712) -> Option<serde_json::Value> {
713 let ja4 = Ja4::compute_from_client_hello(hello)
714 .inspect_err(|err| tracing::trace!("ja4 computation: {err:?}"))
715 .ok()?;
716 let profile = profile_fingerprint(
717 recorded_tls.iter().filter_map(|tgt| tgt.ja4.as_ref()),
718 |tgt| tgt == &ja4,
719 |tgt| format!("{tgt}"),
720 |tgt| format!("{tgt:?}"),
721 );
722 Some(json!({
723 "hash": format!("{ja4}"),
724 "verbose": format!("{ja4:?}"),
725 "profile": profile,
726 }))
727}
728
729const FINGERPRINT_UA: &str = "x-rama-fingerprint-ua";
731const FINGERPRINT_HTTP_VERSION: &str = "x-rama-fingerprint-http-version";
732const FINGERPRINT_HTTP_METHOD: &str = "x-rama-fingerprint-http-method";
733const FINGERPRINT_JA4H: &str = "x-rama-fingerprint-ja4h";
734const FINGERPRINT_JA4H_VERBOSE: &str = "x-rama-fingerprint-ja4h-verbose";
735const FINGERPRINT_JA4H_PROFILE: &str = "x-rama-fingerprint-ja4h-profile";
736const FINGERPRINT_JA4H_MATCHED: &str = "x-rama-fingerprint-ja4h-matched";
737#[cfg(any(feature = "rustls", feature = "boring"))]
738const FINGERPRINT_JA4: &str = "x-rama-fingerprint-ja4";
739#[cfg(any(feature = "rustls", feature = "boring"))]
740const FINGERPRINT_JA4_PROFILE: &str = "x-rama-fingerprint-ja4-profile";
741#[cfg(any(feature = "rustls", feature = "boring"))]
742const FINGERPRINT_JA4_MATCHED: &str = "x-rama-fingerprint-ja4-matched";
743
744const MAX_FINGERPRINT_VALUE: usize = 4 * 1024;
746
747fn fingerprint_headers(
750 profiles: Option<&EchoProfiles>,
751 req: &Request,
752) -> Vec<(&'static str, HeaderValue)> {
753 let mut headers = Vec::new();
754 let mut push = |name: &'static str, value: Option<String>| {
755 let Some(value) = value else {
756 return;
757 };
758 if value.len() > MAX_FINGERPRINT_VALUE {
759 tracing::debug!(
760 header = name,
761 size = value.len(),
762 "fingerprint header left out: too large"
763 );
764 return;
765 }
766 match HeaderValue::try_from(value) {
767 Ok(value) => headers.push((name, value)),
768 Err(err) => tracing::debug!(header = name, %err, "fingerprint header left out"),
769 }
770 };
771 let text = |value: &serde_json::Value| value.as_str().map(ToOwned::to_owned);
772 let matched = |value: &serde_json::Value| value.as_bool().map(|matched| matched.to_string());
773
774 push(
775 FINGERPRINT_UA,
776 req.headers()
777 .get(USER_AGENT)
778 .and_then(|value| value.to_str().ok())
779 .map(ToOwned::to_owned),
780 );
781 push(
782 FINGERPRINT_HTTP_VERSION,
783 Some(format!("{:?}", req.version())),
784 );
785 push(
786 FINGERPRINT_HTTP_METHOD,
787 Some(req.method().as_str().to_owned()),
788 );
789 let recorded = recorded_fingerprints(profiles, req);
790 if let Some(ja4h) = ja4h_view(recorded, req) {
791 push(FINGERPRINT_JA4H, text(&ja4h["hash"]));
792 push(FINGERPRINT_JA4H_VERBOSE, text(&ja4h["verbose"]));
793 push(FINGERPRINT_JA4H_PROFILE, text(&ja4h["profile"]["hash"]));
794 push(
795 FINGERPRINT_JA4H_MATCHED,
796 matched(&ja4h["profile"]["matched"]),
797 );
798 }
799 #[cfg(any(feature = "rustls", feature = "boring"))]
800 if let Some(ja4) = ServerClientHellos::from_extensions(req.extensions())
801 .wire()
802 .and_then(|hello| ja4_view(hello, recorded_tls(recorded, req.version())))
803 {
804 push(FINGERPRINT_JA4, text(&ja4["hash"]));
805 push(FINGERPRINT_JA4_PROFILE, text(&ja4["profile"]["hash"]));
806 push(FINGERPRINT_JA4_MATCHED, matched(&ja4["profile"]["matched"]));
807 }
808 headers
809}
810
811impl Service<Request> for EchoService {
812 type Output = Response;
813 type Error = BoxError;
814
815 async fn serve(&self, req: Request) -> Result<Self::Output, Self::Error> {
816 let user_agent_info = user_agent_view(&req);
817
818 let authority = req
819 .authority()
820 .context("echo: resolve request authority")?
821 .to_string();
822 let scheme = req.protocol().unwrap_or(&Protocol::HTTP).to_string();
823
824 let ua_str = req
825 .headers()
826 .get(USER_AGENT)
827 .and_then(|h| h.to_str().ok())
828 .map(ToOwned::to_owned);
829 tracing::debug!(
830 user_agent.original = ua_str,
831 "echo request received from ua with ua header",
832 );
833
834 let recorded = recorded_fingerprints(self.profiles.as_deref(), &req);
835 let ja4h = ja4h_view(recorded, &req);
836
837 let (parts, body) = req.into_parts();
838
839 let body = body
840 .collect()
841 .await
842 .context("collect request body for echo purposes")?
843 .to_bytes();
844
845 let curl_request =
846 curl_scripts(&parts, &body).context("create curl command for echo response")?;
847
848 let headers: Vec<_> = parts
849 .headers
850 .into_ordered_iter()
851 .map(|(name, value)| {
852 (
853 name,
854 std::str::from_utf8(value.as_bytes())
855 .map(|s| s.to_owned())
856 .unwrap_or_else(|_| format!("0x{:x?}", value.as_bytes())),
857 )
858 })
859 .collect();
860
861 let body = crate::utils::fmt::hex(&body).to_string();
862
863 #[cfg(all(feature = "quic", any(feature = "rustls", feature = "boring")))]
864 let quic_completeness = parts
865 .extensions
866 .get_ref::<QuicObservation>()
867 .map(|value| value.completeness);
868 #[cfg(all(not(feature = "quic"), any(feature = "rustls", feature = "boring")))]
869 let quic_completeness = serde_json::Value::Null;
870
871 #[cfg(any(feature = "rustls", feature = "boring"))]
872 let tls_view = |hello: &crate::tls::client::ClientHello, compare_profiles: bool| {
873 let recorded = if compare_profiles { recorded } else { None };
874
875 let recorded_tls = recorded_tls(recorded, parts.version);
876 let ja4 = ja4_view(hello, recorded_tls);
877
878 let ja3 = Ja3::compute_from_client_hello(hello)
879 .inspect_err(|err| tracing::trace!("ja3 computation: {err:?}"))
880 .ok();
881
882 let profile_ja3 = ja3.as_ref().and_then(|src| {
883 profile_fingerprint(
884 recorded_tls.iter().filter_map(|tgt| tgt.ja3.as_ref()),
885 |tgt| tgt == src,
886 |tgt| format!("{tgt:x}"),
887 |tgt| format!("{tgt}"),
888 )
889 });
890
891 let ja3 = ja3.map(|ja3| {
892 json!({
893 "hash": format!("{ja3:x}"),
894 "verbose": format!("{ja3}"),
895 "profile": profile_ja3,
896 })
897 });
898
899 let peet = PeetPrint::compute_from_client_hello(hello)
900 .inspect_err(|err| tracing::trace!("peet computation: {err:?}"))
901 .ok();
902
903 let profile_peet = peet.as_ref().and_then(|src| {
904 profile_fingerprint(
905 recorded_tls.iter().filter_map(|tgt| tgt.peetprint.as_ref()),
906 |tgt| tgt == src,
907 |tgt| format!("{tgt}"),
908 |tgt| format!("{tgt:?}"),
909 )
910 });
911
912 let peet = peet.map(|peet| {
913 json!({
914 "hash": format!("{peet}"),
915 "verbose": format!("{peet:?}"),
916 "profile": profile_peet,
917 })
918 });
919
920 json!({
921 "transport": if parts.version == Version::HTTP_3 { "quic" } else { "tcp" },
922 "completeness": quic_completeness,
923 "header": {
924 "version": hello.protocol_version().to_string(),
925 "cipher_suites": hello
926 .cipher_suites().iter().map(|s| s.to_string()).collect::<Vec<_>>(),
927 "compression_algorithms": hello
928 .compression_algorithms().iter().map(|s| s.to_string()).collect::<Vec<_>>(),
929 },
930 "extensions": hello.extensions().iter().map(|extension| match extension {
931 ClientHelloExtension::ServerName(server_name) => json!({
932 "id": extension.id().to_string(),
933 "data": server_name.as_ref().map(ToString::to_string),
934 }),
935 ClientHelloExtension::SignatureAlgorithms(v) => json!({
936 "id": extension.id().to_string(),
937 "data": v.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
938 }),
939 ClientHelloExtension::SupportedVersions(v) => json!({
940 "id": extension.id().to_string(),
941 "data": v.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
942 }),
943 ClientHelloExtension::ApplicationLayerProtocolNegotiation(v) => json!({
944 "id": extension.id().to_string(),
945 "data": v.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
946 }),
947 ClientHelloExtension::ApplicationSettings{ protocols, .. } => json!({
948 "id": extension.id().to_string(),
949 "data": protocols.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
950 }),
951 ClientHelloExtension::SupportedGroups(v) => json!({
952 "id": extension.id().to_string(),
953 "data": v.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
954 }),
955 ClientHelloExtension::ECPointFormats(v) => json!({
956 "id": extension.id().to_string(),
957 "data": v.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
958 }),
959 ClientHelloExtension::CertificateCompression(v) => json!({
960 "id": extension.id().to_string(),
961 "data": v.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
962 }),
963 ClientHelloExtension::DelegatedCredentials(v) => json!({
964 "id": extension.id().to_string(),
965 "data": v.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
966 }),
967 ClientHelloExtension::RecordSizeLimit(v)
968 | ClientHelloExtension::ServerPaddingRequest(v) => json!({
969 "id": extension.id().to_string(),
970 "data": v.to_string(),
971 }),
972 ClientHelloExtension::EncryptedClientHello(ech) => match ech {
973 ECHClientHello::Outer(ech) => json!({
974 "id": extension.id().to_string(),
975 "data": {
976 "type": "outer",
977 "cipher_suite": {
978 "aead_id": ech.cipher_suite.aead_id.to_string(),
979 "kdf_id": ech.cipher_suite.kdf_id.to_string(),
980 },
981 "config_id": ech.config_id,
982 "enc": crate::utils::fmt::hex(&ech.enc).with_prefix(true).to_string(),
983 "payload": crate::utils::fmt::hex(&ech.payload).with_prefix(true).to_string(),
984 },
985 }),
986 ECHClientHello::Inner => json!({
987 "id": extension.id().to_string(),
988 "data": {
989 "type": "inner",
990 },
991 })
992
993 }
994 ClientHelloExtension::Opaque { id, data } => if data.is_empty() {
995 json!({
996 "id": id.to_string()
997 })
998 } else {
999 json!({
1000 "id": id.to_string(),
1001 "data": crate::utils::fmt::hex(data).with_prefix(true).to_string()
1002 })
1003 },
1004 }).collect::<Vec<_>>(),
1005 "ja3": ja3,
1006 "ja4": ja4,
1007 "peet": peet
1008 })
1009 };
1010 #[cfg(any(feature = "rustls", feature = "boring"))]
1011 let hellos = ServerClientHellos::from_extensions(&parts.extensions);
1012 #[cfg(any(feature = "rustls", feature = "boring"))]
1013 let ech_accepted = hellos.ech_accepted();
1014 #[cfg(any(feature = "rustls", feature = "boring"))]
1015 let tls_info = hellos.wire().map(|hello| tls_view(hello, true));
1016 #[cfg(any(feature = "rustls", feature = "boring"))]
1017 let tls_inner = hellos.ech_inner().map(|hello| tls_view(hello, false));
1018 #[cfg(not(any(feature = "rustls", feature = "boring")))]
1019 let (ech_accepted, tls_inner): (Option<bool>, Option<()>) = (None, None);
1020
1021 #[cfg(not(any(feature = "rustls", feature = "boring")))]
1022 let tls_info: Option<()> = None;
1023
1024 let mut h2 = None;
1025 if parts.version == Version::HTTP_2 {
1026 let early_frames = parts.extensions.get_ref::<EarlyFrameCapture>();
1027 let pseudo_headers = parts.extensions.get_ref::<PseudoHeaderOrder>();
1028 let akamai_h2 = AkamaiH2::compute(&parts.extensions)
1029 .inspect_err(|err| tracing::trace!("akamai h2 compute failure: {err:?}"))
1030 .ok()
1031 .map(|akamai| {
1032 json!({
1033 "hash": format!("{akamai}"),
1034 "verbose": format!("{akamai:?}"),
1035 })
1036 });
1037
1038 h2 = Some(json!({
1039 "early_frames": early_frames,
1040 "pseudo_headers": pseudo_headers,
1041 "akamai_h2": akamai_h2,
1042 }));
1043 }
1044
1045 #[cfg(feature = "quic")]
1046 let h3 = parts
1047 .extensions
1048 .get_ref::<H3RequestObservation>()
1049 .map(|observation| {
1050 EchoH3::from(observation.view(
1051 &observation.connection,
1052 SettingsStatus::Pending,
1053 parts.extensions.get_ref::<PseudoHeaderOrder>(),
1054 ))
1055 });
1056 #[cfg(feature = "quic")]
1057 let quic = parts
1058 .extensions
1059 .get_ref::<QuicObservation>()
1060 .map(EchoQuic::from);
1061 #[cfg(feature = "quic")]
1062 let quic_connection = parts
1063 .extensions
1064 .get_ref::<QuicConnectionInfo>()
1065 .map(EchoQuicConnection::from);
1066 #[cfg(not(feature = "quic"))]
1067 let (h3, quic, quic_connection) = (
1068 serde_json::Value::Null,
1069 serde_json::Value::Null,
1070 serde_json::Value::Null,
1071 );
1072
1073 let geo = self
1075 .geo_db
1076 .as_ref()
1077 .and_then(|db| {
1078 crate::net::client_ip::client_ip(&parts.extensions).and_then(|ip| db.resolve(ip))
1079 })
1080 .map(|info| serde_json::to_value(&info).unwrap_or_default())
1081 .unwrap_or(serde_json::Value::Null);
1082
1083 Ok(Json(json!({
1084 "ua": user_agent_info,
1085 "geo": geo,
1086 "http": {
1087 "version": format!("{:?}", parts.version),
1088 "scheme": scheme,
1089 "method": format!("{:?}", parts.method),
1090 "authority": authority,
1091 "path": parts.uri.path_or_root().into_owned(),
1092 "query": parts.uri.query().map(|q| q.as_encoded_str().into_owned()),
1093 "h2": h2,
1094 "h3": h3,
1095 "headers": headers,
1096 "payload": body,
1097 "ja4h": ja4h,
1098 "curl": curl_request,
1099 },
1100 "tls": tls_info,
1101 "tls_inner": tls_inner,
1102 "ech_accepted": ech_accepted,
1103 "quic": quic,
1104 "quic_connection": quic_connection,
1105 "socket_addr": parts.extensions.forwarded_client_socket_addr()
1106 .map(|addr| addr.to_string())
1107 .or_else(|| parts.extensions.forwarded_client_ip().map(|ip| ip.to_string()))
1108 .or_else(|| SocketInfo::ingress(&parts.extensions).map(|v| v.peer_addr().to_string())),
1109 }))
1110 .into_response())
1111 }
1112}
1113
1114#[cfg(test)]
1115mod tests {
1116 #[cfg(any(feature = "rustls", feature = "boring"))]
1117 use std::net::IpAddr;
1118
1119 use super::*;
1120 use crate::http::{Body, StatusCode};
1121 #[cfg(feature = "quic")]
1122 use crate::quic::proto::Version as QuicVersion;
1123 #[cfg(any(feature = "rustls", feature = "boring"))]
1124 use crate::{
1125 net::tls::ServerName,
1126 tls::{
1127 CipherSuite, CompressionAlgorithm, ProtocolVersion, SecureTransport,
1128 client::ClientHello,
1129 },
1130 };
1131
1132 #[cfg(any(feature = "rustls", feature = "boring"))]
1133 #[tokio::test]
1134 async fn an_ip_literal_server_name_is_echoed_as_its_address() {
1135 let request = Request::builder()
1136 .uri("https://10.20.30.40/")
1137 .body(Body::empty())
1138 .unwrap();
1139 request
1140 .extensions()
1141 .insert(SecureTransport::with_client_hello(ClientHello::new(
1142 ProtocolVersion::TLSv1_2,
1143 vec![CipherSuite::from(0x1301)],
1144 vec![CompressionAlgorithm::from(0)],
1145 vec![ClientHelloExtension::ServerName(Some(ServerName::from(
1146 IpAddr::from([10, 20, 30, 40]),
1147 )))],
1148 )));
1149 let response = EchoService {
1150 profiles: None,
1151 geo_db: None,
1152 }
1153 .serve(request)
1154 .await
1155 .unwrap();
1156 let bytes = response.into_body().collect().await.unwrap().to_bytes();
1157 let value: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
1158 assert_eq!(value["tls"]["extensions"][0]["data"], json!("10.20.30.40"));
1159 }
1160
1161 #[tokio::test]
1162 async fn binary_request_body_is_echoed_with_lossless_platform_curl_scripts() {
1163 let payload = rama_core::bytes::Bytes::from_static(b"\0\xfftail\n");
1164 let request = Request::builder()
1165 .method("POST")
1166 .uri("http://example.com/upload")
1167 .body(Body::from(payload))
1168 .unwrap();
1169
1170 let response = EchoService {
1171 profiles: None,
1172 geo_db: None,
1173 }
1174 .serve(request)
1175 .await
1176 .expect("echo binary request");
1177 assert_eq!(response.status(), StatusCode::OK);
1178
1179 let body = response
1180 .into_body()
1181 .collect()
1182 .await
1183 .expect("collect echo response")
1184 .to_bytes();
1185 let json: serde_json::Value = serde_json::from_slice(&body).expect("parse echo response");
1186
1187 assert_eq!(json["http"]["payload"], "00ff7461696c0a");
1188 let unix = json["http"]["curl"]["unix"]
1189 .as_str()
1190 .expect("Unix curl script");
1191 assert!(unix.contains("base64 -d"));
1192 assert!(unix.contains("--data-binary '@-'"));
1193 let powershell = json["http"]["curl"]["powershell"]
1194 .as_str()
1195 .expect("PowerShell curl script");
1196 assert!(powershell.contains("[Convert]::FromBase64String"));
1197 assert!(powershell.contains("--data-binary ('@' + $__ramaCurlPayload)"));
1198 }
1199
1200 #[cfg(feature = "quic")]
1201 #[tokio::test]
1202 async fn negotiated_quic_versions_are_echoed_without_capture() {
1203 let request = Request::builder()
1204 .version(Version::HTTP_3)
1205 .uri("https://example.test/")
1206 .body(Body::empty())
1207 .unwrap();
1208 request.extensions().insert(QuicConnectionInfo {
1209 version: QuicVersion::V2,
1210 original_version: QuicVersion::V1,
1211 early_data_keys_enabled: false,
1212 handshake_rtt: Duration::from_millis(10),
1213 handshake_mtu: 1200,
1214 });
1215 let response = EchoService {
1216 profiles: None,
1217 geo_db: None,
1218 }
1219 .serve(request)
1220 .await
1221 .unwrap();
1222 assert_eq!(response.status(), StatusCode::OK);
1223 let bytes = response.into_body().collect().await.unwrap().to_bytes();
1224 let value: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
1225 assert_eq!(
1226 value["quic_connection"],
1227 json!({
1228 "version": {"raw": "0x6b3343cf", "name": "v2"},
1229 "original_version": {"raw": "0x00000001", "name": "v1"},
1230 })
1231 );
1232 assert!(value["quic"].is_null());
1233 }
1234
1235 #[cfg(feature = "quic")]
1236 #[tokio::test]
1237 async fn observation_schema_distinguishes_absent_and_incomplete_h3() {
1238 for captured in [false, true] {
1239 let request = Request::builder()
1240 .version(Version::HTTP_3)
1241 .uri("https://example.test/")
1242 .header("user-agent", "custom/1")
1243 .body(Body::empty())
1244 .unwrap();
1245 if captured {
1246 request.extensions().insert(H3RequestObservation {
1247 stream_id: 0,
1248 connection: Arc::new(Default::default()),
1249 first_request: Arc::new(Default::default()),
1250 fields: Vec::new(),
1251 fields_complete: false,
1252 priority: None,
1253 });
1254 }
1255 let response = EchoService {
1256 profiles: None,
1257 geo_db: None,
1258 }
1259 .serve(request)
1260 .await
1261 .unwrap();
1262 let bytes = response.into_body().collect().await.unwrap().to_bytes();
1263 let value: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
1264 assert_eq!(value["http"]["version"], "HTTP/3.0");
1265 assert!(value["http"]["h2"].is_null());
1266 assert!(value["quic"].is_null());
1267 assert!(value["quic_connection"].is_null());
1268 assert!(value["tls"].is_null());
1269 let h3 = &value["http"]["h3"];
1270 if captured {
1271 assert_eq!(h3["settings_status"], "unavailable");
1272 assert!(h3["settings"].is_null());
1273 assert_eq!(h3["completeness"]["snapshot"], false);
1274 assert_eq!(h3["completeness"]["fields"], false);
1275 assert_eq!(h3["request_fields"], json!([]));
1276 } else {
1277 assert!(h3.is_null());
1278 }
1279 assert!(
1280 value["http"]["ja4h"]["verbose"]
1281 .as_str()
1282 .unwrap()
1283 .starts_with("ge30")
1284 );
1285 }
1286 }
1287}