Skip to content

Commit 4e9337b

Browse files
committed
add mobile fallback platform verifier
Signed-off-by: 21pages <[email protected]>
1 parent 5b2f391 commit 4e9337b

File tree

6 files changed

+236
-10
lines changed

6 files changed

+236
-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: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
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) => {
60+
log::error!(
61+
"Both primary and fallback verifiers failed to verify server certificate, primary error: {:?}, fallback error: {:?}",
62+
primary_err,
63+
fallback_err
64+
);
65+
Err(primary_err)
66+
}
67+
}
68+
}
69+
}
70+
}
71+
72+
fn verify_tls12_signature(
73+
&self,
74+
message: &[u8],
75+
cert: &rustls_pki_types::CertificateDer<'_>,
76+
dss: &DigitallySignedStruct,
77+
) -> Result<HandshakeSignatureValid, TLSError> {
78+
// Both WebPkiServerVerifier and rustls_platform_verifier use the same signature verification implementation.
79+
// https://github.com/rustls/rustls/blob/1ee126adb3352a2dcd72420dcd6040351a6ddc1e/rustls/src/webpki/server_verifier.rs#L278
80+
// https://github.com/rustls/rustls/blob/1ee126adb3352a2dcd72420dcd6040351a6ddc1e/rustls/src/crypto/mod.rs#L17
81+
// https://github.com/rustls/rustls-platform-verifier/blob/1099f161bfc5e3ac7f90aad88b1bf788e72906cb/rustls-platform-verifier/src/verification/android.rs#L9
82+
// https://github.com/rustls/rustls-platform-verifier/blob/1099f161bfc5e3ac7f90aad88b1bf788e72906cb/rustls-platform-verifier/src/verification/apple.rs#L6
83+
self.primary.verify_tls12_signature(message, cert, dss)
84+
}
85+
86+
fn verify_tls13_signature(
87+
&self,
88+
message: &[u8],
89+
cert: &rustls_pki_types::CertificateDer<'_>,
90+
dss: &DigitallySignedStruct,
91+
) -> Result<HandshakeSignatureValid, TLSError> {
92+
// Same implementation as verify_tls12_signature.
93+
self.primary.verify_tls13_signature(message, cert, dss)
94+
}
95+
96+
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
97+
// Both WebPkiServerVerifier and rustls_platform_verifier use the same crypto provider,
98+
// so their supported signature schemes are identical.
99+
// https://github.com/rustls/rustls/blob/1ee126adb3352a2dcd72420dcd6040351a6ddc1e/rustls/src/webpki/server_verifier.rs#L172C52-L172C85
100+
// https://github.com/rustls/rustls-platform-verifier/blob/1099f161bfc5e3ac7f90aad88b1bf788e72906cb/rustls-platform-verifier/src/verification/android.rs#L327
101+
// https://github.com/rustls/rustls-platform-verifier/blob/1099f161bfc5e3ac7f90aad88b1bf788e72906cb/rustls-platform-verifier/src/verification/apple.rs#L304
102+
self.primary.supported_verify_schemes()
103+
}
104+
}
105+
106+
fn webpki_server_verifier(
107+
provider: Arc<rustls::crypto::CryptoProvider>,
108+
) -> ResultType<Arc<WebPkiServerVerifier>> {
109+
// Load root certificates from both bundled webpki_roots and system-native certificate stores.
110+
// This approach is consistent with how reqwest and tokio-tungstenite handle root certificates.
111+
// https://github.com/snapview/tokio-tungstenite/blob/35d110c24c9d030d1608ec964d70c789dfb27452/src/tls.rs#L95
112+
// https://github.com/seanmonstar/reqwest/blob/b126ca49da7897e5d676639cdbf67a0f6838b586/src/async_impl/client.rs#L643
113+
let mut root_cert_store = rustls::RootCertStore::empty();
114+
root_cert_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
115+
let rustls_native_certs::CertificateResult { certs, errors, .. } =
116+
rustls_native_certs::load_native_certs();
117+
if !errors.is_empty() {
118+
log::warn!("native root CA certificate loading errors: {errors:?}");
119+
}
120+
root_cert_store.add_parsable_certificates(certs);
121+
122+
// Build verifier using with_root_certificates behavior (WebPkiServerVerifier without CRLs).
123+
// Both reqwest and tokio-tungstenite use this approach.
124+
// https://github.com/seanmonstar/reqwest/blob/b126ca49da7897e5d676639cdbf67a0f6838b586/src/async_impl/client.rs#L749
125+
// https://github.com/snapview/tokio-tungstenite/blob/35d110c24c9d030d1608ec964d70c789dfb27452/src/tls.rs#L127
126+
// https://github.com/rustls/rustls/blob/1ee126adb3352a2dcd72420dcd6040351a6ddc1e/rustls/src/client/builder.rs#L47
127+
// with_root_certificates creates a WebPkiServerVerifier without revocation checking:
128+
// https://github.com/rustls/rustls/blob/1ee126adb3352a2dcd72420dcd6040351a6ddc1e/rustls/src/webpki/server_verifier.rs#L177
129+
// https://github.com/rustls/rustls/blob/1ee126adb3352a2dcd72420dcd6040351a6ddc1e/rustls/src/webpki/server_verifier.rs#L168
130+
// Default unknown_revocation_policy with builder_with_provider is Deny, so we set allow_unknown_revocation_status:
131+
// https://github.com/rustls/rustls/blob/1ee126adb3352a2dcd72420dcd6040351a6ddc1e/rustls/src/webpki/server_verifier.rs#L37
132+
// Note: build() only returns an error if the root certificate store is empty, which won't happen here.
133+
let verifier = rustls::client::WebPkiServerVerifier::builder_with_provider(
134+
Arc::new(root_cert_store),
135+
provider.clone(),
136+
)
137+
.allow_unknown_revocation_status()
138+
.build()
139+
.map_err(|e| anyhow::anyhow!(e))?;
140+
Ok(verifier)
141+
}
142+
143+
pub fn client_config() -> ResultType<ClientConfig> {
144+
// Use the default builder which uses the default protocol versions and crypto provider.
145+
// The with_protocol_versions API has been removed in rustls master branch:
146+
// https://github.com/rustls/rustls/pull/2599
147+
// This approach is consistent with tokio-tungstenite's usage:
148+
// https://github.com/snapview/tokio-tungstenite/blob/35d110c24c9d030d1608ec964d70c789dfb27452/src/tls.rs#L126
149+
let config_builder = rustls::ClientConfig::builder();
150+
let provider = config_builder.crypto_provider().clone();
151+
let webpki_verifier = webpki_server_verifier(provider.clone())?;
152+
#[cfg(any(target_os = "android", target_os = "ios"))]
153+
{
154+
match FallbackPlatformVerifier::with_platform_fallback(webpki_verifier.clone(), provider) {
155+
Ok(fallback_verifier) => {
156+
let config = config_builder
157+
.dangerous()
158+
.with_custom_certificate_verifier(Arc::new(fallback_verifier))
159+
.with_no_client_auth();
160+
Ok(config)
161+
}
162+
Err(e) => {
163+
log::error!(
164+
"Failed to create fallback verifier: {:?}, use webpki verifier instead",
165+
e
166+
);
167+
let config = config_builder
168+
.with_webpki_verifier(webpki_verifier)
169+
.with_no_client_auth();
170+
Ok(config)
171+
}
172+
}
173+
}
174+
#[cfg(not(any(target_os = "android", target_os = "ios")))]
175+
{
176+
let config = config_builder
177+
.with_webpki_verifier(webpki_verifier)
178+
.with_no_client_auth();
179+
Ok(config)
180+
}
181+
}

src/websocket.rs

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,45 @@ 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::warn!(
61+
"Failed to get client config: {:?}, fallback to default connector",
62+
e
63+
);
64+
None
65+
}
66+
};
67+
let (s, _) = timeout(
68+
Duration::from_millis(ms_timeout),
69+
connect_async_tls_with_config(request, None, false, connector),
70+
)
71+
.await??;
72+
stream = s;
73+
} else {
74+
let (s, _) =
75+
timeout(Duration::from_millis(ms_timeout), connect_async(request)).await??;
76+
stream = s;
77+
}
78+
}
79+
#[cfg(not(any(target_os = "android", target_os = "ios")))]
80+
{
81+
let (s, _) =
82+
timeout(Duration::from_millis(ms_timeout), connect_async(request)).await??;
83+
stream = s;
84+
}
4885

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

0 commit comments

Comments
 (0)