Skip to content

Commit 6e69a7a

Browse files
committed
add mobile fallback platform verifier
Signed-off-by: 21pages <[email protected]>
1 parent 7ae63b1 commit 6e69a7a

File tree

6 files changed

+226
-10
lines changed

6 files changed

+226
-10
lines changed

Cargo.toml

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,10 +59,14 @@ tokio-rustls = { version = "0.26", features = [
5959
"tls12",
6060
"ring",
6161
], default-features = false }
62-
rustls-platform-verifier = "0.5"
6362
rustls-pki-types = "1.11"
6463
tokio-tungstenite = { version = "0.26", features = ["rustls-tls-native-roots", "rustls-tls-webpki-roots"] }
6564
tungstenite = { version = "0.26", features = ["rustls-tls-native-roots", "rustls-tls-webpki-roots"] }
65+
rustls-native-certs = "0.8"
66+
webpki-roots = "1.0"
67+
68+
[target.'cfg(any(target_os = "android", target_os = "ios"))'.dependencies]
69+
rustls-platform-verifier = "0.6"
6670

6771
[target.'cfg(any(target_os = "macos", target_os = "windows"))'.dependencies]
6872
tokio-native-tls = "0.3"

src/config.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use std::{
55
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
66
ops::{Deref, DerefMut},
77
path::{Path, PathBuf},
8-
sync::{Mutex, RwLock},
8+
sync::{atomic::AtomicBool, Mutex, RwLock},
99
time::{Duration, Instant, SystemTime},
1010
};
1111

@@ -70,6 +70,7 @@ lazy_static::lazy_static! {
7070
pub static ref OVERWRITE_LOCAL_SETTINGS: RwLock<HashMap<String, String>> = Default::default();
7171
pub static ref HARD_SETTINGS: RwLock<HashMap<String, String>> = Default::default();
7272
pub static ref BUILTIN_SETTINGS: RwLock<HashMap<String, String>> = Default::default();
73+
pub static ref RUSTLS_PLATFORM_VERIFIER_INITIALIZED: AtomicBool = AtomicBool::new(false);
7374
}
7475

7576
lazy_static::lazy_static! {

src/lib.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,10 +57,14 @@ pub use toml;
5757
pub use uuid;
5858
pub mod fingerprint;
5959
pub use flexi_logger;
60-
pub mod websocket;
6160
pub mod stream;
61+
pub mod websocket;
62+
#[cfg(any(target_os = "android", target_os = "ios"))]
63+
pub use rustls_platform_verifier;
6264
pub use stream::Stream;
6365
pub use whoami;
66+
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
67+
pub mod verifier;
6468

6569
pub type SessionID = uuid::Uuid;
6670

src/proxy.rs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,6 @@ const MAXIMUM_RESPONSE_HEADERS: usize = 16;
5656
const DEFINE_TIME_OUT: u64 = 600;
5757

5858
pub trait IntoUrl {
59-
6059
// Besides parsing as a valid `Url`, the `Url` must be a valid
6160
// `http::Uri`, in that it makes sense to use in a network request.
6261
fn into_url(self) -> Result<Url, ProxyError>;
@@ -456,14 +455,14 @@ impl Proxy {
456455
T: IntoTargetAddr<'a>,
457456
{
458457
use std::convert::TryFrom;
459-
let verifier = rustls_platform_verifier::tls_config();
460-
let url_domain = self.intercept.get_domain()?;
461458

459+
let url_domain = self.intercept.get_domain()?;
462460
let domain = rustls_pki_types::ServerName::try_from(url_domain.as_str())
463461
.map_err(|e| ProxyError::AddressResolutionFailed(e.to_string()))?
464462
.to_owned();
465-
466-
let tls_connector = TlsConnector::from(std::sync::Arc::new(verifier));
463+
let client_config = crate::verifier::client_config()
464+
.map_err(|e| ProxyError::IoError(std::io::Error::other(e)))?;
465+
let tls_connector = TlsConnector::from(std::sync::Arc::new(client_config));
467466
let stream = tls_connector.connect(domain, io).await?;
468467
self.http_connect(stream, target).await
469468
}

src/verifier.rs

Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
use crate::ResultType;
2+
#[cfg(any(target_os = "android", target_os = "ios"))]
3+
use rustls_pki_types::{ServerName, UnixTime};
4+
use std::sync::Arc;
5+
use tokio_rustls::rustls::{self, client::WebPkiServerVerifier, ClientConfig};
6+
#[cfg(any(target_os = "android", target_os = "ios"))]
7+
use tokio_rustls::rustls::{
8+
client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
9+
DigitallySignedStruct, Error as TLSError, SignatureScheme,
10+
};
11+
12+
/// A certificate verifier that tries a primary verifier first,
13+
/// and falls back to a platform verifier if the primary fails.
14+
#[cfg(any(target_os = "android", target_os = "ios"))]
15+
#[derive(Debug)]
16+
struct FallbackPlatformVerifier {
17+
primary: Arc<dyn ServerCertVerifier>,
18+
fallback: Arc<dyn ServerCertVerifier>,
19+
}
20+
21+
#[cfg(any(target_os = "android", target_os = "ios"))]
22+
impl FallbackPlatformVerifier {
23+
fn with_platform_fallback(
24+
primary: Arc<dyn ServerCertVerifier>,
25+
provider: Arc<rustls::crypto::CryptoProvider>,
26+
) -> Result<Self, TLSError> {
27+
let fallback = Arc::new(rustls_platform_verifier::Verifier::new(provider)?);
28+
Ok(Self { primary, fallback })
29+
}
30+
}
31+
32+
#[cfg(any(target_os = "android", target_os = "ios"))]
33+
impl ServerCertVerifier for FallbackPlatformVerifier {
34+
fn verify_server_cert(
35+
&self,
36+
end_entity: &rustls_pki_types::CertificateDer<'_>,
37+
intermediates: &[rustls_pki_types::CertificateDer<'_>],
38+
server_name: &ServerName<'_>,
39+
ocsp_response: &[u8],
40+
now: UnixTime,
41+
) -> Result<ServerCertVerified, TLSError> {
42+
match self.primary.verify_server_cert(
43+
end_entity,
44+
intermediates,
45+
server_name,
46+
ocsp_response,
47+
now,
48+
) {
49+
Ok(verified) => Ok(verified),
50+
Err(primary_err) => {
51+
match self.fallback.verify_server_cert(
52+
end_entity,
53+
intermediates,
54+
server_name,
55+
ocsp_response,
56+
now,
57+
) {
58+
Ok(verified) => Ok(verified),
59+
Err(_fallback_err) => Err(primary_err),
60+
}
61+
}
62+
}
63+
}
64+
65+
fn verify_tls12_signature(
66+
&self,
67+
message: &[u8],
68+
cert: &rustls_pki_types::CertificateDer<'_>,
69+
dss: &DigitallySignedStruct,
70+
) -> Result<HandshakeSignatureValid, TLSError> {
71+
// Both WebPkiServerVerifier and rustls_platform_verifier use the same signature verification implementation.
72+
// https://github.com/rustls/rustls/blob/1ee126adb3352a2dcd72420dcd6040351a6ddc1e/rustls/src/webpki/server_verifier.rs#L278
73+
// https://github.com/rustls/rustls/blob/1ee126adb3352a2dcd72420dcd6040351a6ddc1e/rustls/src/crypto/mod.rs#L17
74+
// https://github.com/rustls/rustls-platform-verifier/blob/1099f161bfc5e3ac7f90aad88b1bf788e72906cb/rustls-platform-verifier/src/verification/android.rs#L9
75+
// https://github.com/rustls/rustls-platform-verifier/blob/1099f161bfc5e3ac7f90aad88b1bf788e72906cb/rustls-platform-verifier/src/verification/apple.rs#L6
76+
self.primary.verify_tls12_signature(message, cert, dss)
77+
}
78+
79+
fn verify_tls13_signature(
80+
&self,
81+
message: &[u8],
82+
cert: &rustls_pki_types::CertificateDer<'_>,
83+
dss: &DigitallySignedStruct,
84+
) -> Result<HandshakeSignatureValid, TLSError> {
85+
// Same implementation as verify_tls12_signature.
86+
self.primary.verify_tls13_signature(message, cert, dss)
87+
}
88+
89+
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
90+
// Both WebPkiServerVerifier and rustls_platform_verifier use the same crypto provider,
91+
// so their supported signature schemes are identical.
92+
// https://github.com/rustls/rustls/blob/1ee126adb3352a2dcd72420dcd6040351a6ddc1e/rustls/src/webpki/server_verifier.rs#L172C52-L172C85
93+
// https://github.com/rustls/rustls-platform-verifier/blob/1099f161bfc5e3ac7f90aad88b1bf788e72906cb/rustls-platform-verifier/src/verification/android.rs#L327
94+
// https://github.com/rustls/rustls-platform-verifier/blob/1099f161bfc5e3ac7f90aad88b1bf788e72906cb/rustls-platform-verifier/src/verification/apple.rs#L304
95+
self.primary.supported_verify_schemes()
96+
}
97+
}
98+
99+
fn webpki_server_verifier(
100+
provider: Arc<rustls::crypto::CryptoProvider>,
101+
) -> ResultType<Arc<WebPkiServerVerifier>> {
102+
// Load root certificates from both bundled webpki_roots and system-native certificate stores.
103+
// This approach is consistent with how reqwest and tokio-tungstenite handle root certificates.
104+
// https://github.com/snapview/tokio-tungstenite/blob/35d110c24c9d030d1608ec964d70c789dfb27452/src/tls.rs#L95
105+
// https://github.com/seanmonstar/reqwest/blob/b126ca49da7897e5d676639cdbf67a0f6838b586/src/async_impl/client.rs#L643
106+
let mut root_cert_store = rustls::RootCertStore::empty();
107+
root_cert_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
108+
let rustls_native_certs::CertificateResult { certs, errors, .. } =
109+
rustls_native_certs::load_native_certs();
110+
if !errors.is_empty() {
111+
log::warn!("native root CA certificate loading errors: {errors:?}");
112+
}
113+
root_cert_store.add_parsable_certificates(certs);
114+
115+
// Build verifier using with_root_certificates behavior (WebPkiServerVerifier without CRLs).
116+
// Both reqwest and tokio-tungstenite use this approach.
117+
// https://github.com/seanmonstar/reqwest/blob/b126ca49da7897e5d676639cdbf67a0f6838b586/src/async_impl/client.rs#L749
118+
// https://github.com/snapview/tokio-tungstenite/blob/35d110c24c9d030d1608ec964d70c789dfb27452/src/tls.rs#L127
119+
// https://github.com/rustls/rustls/blob/1ee126adb3352a2dcd72420dcd6040351a6ddc1e/rustls/src/client/builder.rs#L47
120+
// with_root_certificates creates a WebPkiServerVerifier without revocation checking:
121+
// https://github.com/rustls/rustls/blob/1ee126adb3352a2dcd72420dcd6040351a6ddc1e/rustls/src/webpki/server_verifier.rs#L177
122+
// https://github.com/rustls/rustls/blob/1ee126adb3352a2dcd72420dcd6040351a6ddc1e/rustls/src/webpki/server_verifier.rs#L168
123+
// Default unknown_revocation_policy with builder_with_provider is Deny, so we set allow_unknown_revocation_status:
124+
// https://github.com/rustls/rustls/blob/1ee126adb3352a2dcd72420dcd6040351a6ddc1e/rustls/src/webpki/server_verifier.rs#L37
125+
// Note: build() only returns an error if the root certificate store is empty, which won't happen here.
126+
let verifier = rustls::client::WebPkiServerVerifier::builder_with_provider(
127+
Arc::new(root_cert_store),
128+
provider.clone(),
129+
)
130+
.allow_unknown_revocation_status()
131+
.build()
132+
.map_err(|e| anyhow::anyhow!(e))?;
133+
Ok(verifier)
134+
}
135+
136+
pub fn client_config() -> ResultType<ClientConfig> {
137+
// Use the default builder which automatically selects protocol versions and crypto provider.
138+
// The with_protocol_versions API has been removed in rustls master branch:
139+
// https://github.com/rustls/rustls/pull/2599
140+
// This approach is consistent with tokio-tungstenite's usage:
141+
// https://github.com/snapview/tokio-tungstenite/blob/35d110c24c9d030d1608ec964d70c789dfb27452/src/tls.rs#L126
142+
let config_builder = rustls::ClientConfig::builder();
143+
let provider = config_builder.crypto_provider().clone();
144+
let webpki_verifier = webpki_server_verifier(provider.clone())?;
145+
#[cfg(any(target_os = "android", target_os = "ios"))]
146+
{
147+
match FallbackPlatformVerifier::with_platform_fallback(webpki_verifier.clone(), provider) {
148+
Ok(fallback_verifier) => {
149+
let config = config_builder
150+
.dangerous()
151+
.with_custom_certificate_verifier(Arc::new(fallback_verifier))
152+
.with_no_client_auth();
153+
Ok(config)
154+
}
155+
Err(e) => {
156+
log::error!(
157+
"Failed to create fallback verifier: {:?}, use webpki verifier instead",
158+
e
159+
);
160+
let config = config_builder
161+
.with_webpki_verifier(webpki_verifier)
162+
.with_no_client_auth();
163+
Ok(config)
164+
}
165+
}
166+
}
167+
#[cfg(not(any(target_os = "android", target_os = "ios")))]
168+
{
169+
let config = config_builder
170+
.with_webpki_verifier(webpki_verifier)
171+
.with_no_client_auth();
172+
Ok(config)
173+
}
174+
}

src/websocket.rs

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,42 @@ impl WsFramedStream {
4343
.into_client_request()
4444
.map_err(|e| Error::new(ErrorKind::Other, e))?;
4545

46-
let (stream, _) =
47-
timeout(Duration::from_millis(ms_timeout), connect_async(request)).await??;
46+
let stream;
47+
#[cfg(any(target_os = "android", target_os = "ios"))]
48+
{
49+
let is_wss = url_str.starts_with("wss://");
50+
let rustls_platform_verifier_ready = !cfg!(target_os = "android")
51+
|| crate::config::RUSTLS_PLATFORM_VERIFIER_INITIALIZED
52+
.load(std::sync::atomic::Ordering::Relaxed);
53+
if is_wss && rustls_platform_verifier_ready {
54+
use std::sync::Arc;
55+
use tokio_tungstenite::{connect_async_tls_with_config, Connector};
56+
57+
let connector = match crate::verifier::client_config() {
58+
Ok(client_config) => Some(Connector::Rustls(Arc::new(client_config))),
59+
Err(e) => {
60+
log::error!("get_client_config failed: {:?}", e);
61+
None
62+
}
63+
};
64+
let (s, _) = timeout(
65+
Duration::from_millis(ms_timeout),
66+
connect_async_tls_with_config(request.clone(), None, false, connector),
67+
)
68+
.await??;
69+
stream = s;
70+
} else {
71+
let (s, _) =
72+
timeout(Duration::from_millis(ms_timeout), connect_async(request)).await??;
73+
stream = s;
74+
}
75+
}
76+
#[cfg(not(any(target_os = "android", target_os = "ios")))]
77+
{
78+
let (s, _) =
79+
timeout(Duration::from_millis(ms_timeout), connect_async(request)).await??;
80+
stream = s;
81+
}
4882

4983
let addr = match stream.get_ref() {
5084
MaybeTlsStream::Plain(tcp) => tcp.peer_addr()?,

0 commit comments

Comments
 (0)