leejunyoung5819 wayland-android-remote
공개Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)
| 1 | //! 가짜 기기 서버 자체 점검. 최소한의 TLS 클라이언트로 인증·PING·비디오 채널을 확인한다. |
| 2 | |
| 3 | mod common; |
| 4 | |
| 5 | use std::net::SocketAddr; |
| 6 | use std::sync::Arc; |
| 7 | use std::time::Duration; |
| 8 | |
| 9 | use common::fake_device::{FakeDevice, FakeDeviceConfig, PendingPolicy}; |
| 10 | use ed25519_dalek::{Signer, SigningKey}; |
| 11 | use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; |
| 12 | use rustls::crypto::CryptoProvider; |
| 13 | use rustls::pki_types::{CertificateDer, ServerName, UnixTime}; |
| 14 | use rustls::{DigitallySignedStruct, HandshakeKind, SignatureScheme}; |
| 15 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 16 | use tokio::net::TcpStream; |
| 17 | use tokio_rustls::TlsConnector; |
| 18 | use tokio_rustls::client::TlsStream; |
| 19 | use wayland_android_remote::net::{FramedError, FramedStream}; |
| 20 | use wayland_android_remote::protocol::{ |
| 21 | AuthGrant, AuthHello, AuthResponse, AuthResult, AuthResultCode, AuthStatus, ChannelAttach, |
| 22 | ChannelKind, CodecMask, Message, VIDEO_HEADER_LEN, VideoCodec, VideoConfigRequest, |
| 23 | VideoPacketHeader, auth_signing_message, cert_fingerprint, error_code, |
| 24 | }; |
| 25 | |
| 26 | const TIMEOUT: Duration = Duration::from_secs(5); |
| 27 | |
| 28 | /// 인증서 지문만 고정하고, TLS 1.3 핸드셰이크 서명은 정상 검증한다. |
| 29 | #[derive(Debug)] |
| 30 | struct PinnedVerifier { |
| 31 | provider: Arc<CryptoProvider>, |
| 32 | fingerprint: [u8; 32], |
| 33 | } |
| 34 | |
| 35 | impl ServerCertVerifier for PinnedVerifier { |
| 36 | fn verify_server_cert( |
| 37 | &self, |
| 38 | end_entity: &CertificateDer<'_>, |
| 39 | _intermediates: &[CertificateDer<'_>], |
| 40 | _server_name: &ServerName<'_>, |
| 41 | _ocsp: &[u8], |
| 42 | _now: UnixTime, |
| 43 | ) -> Result<ServerCertVerified, rustls::Error> { |
| 44 | if cert_fingerprint(end_entity) == self.fingerprint { |
| 45 | Ok(ServerCertVerified::assertion()) |
| 46 | } else { |
| 47 | Err(rustls::Error::General("인증서 지문 불일치".into())) |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | fn verify_tls12_signature( |
| 52 | &self, |
| 53 | _message: &[u8], |
| 54 | _cert: &CertificateDer<'_>, |
| 55 | _dss: &DigitallySignedStruct, |
| 56 | ) -> Result<HandshakeSignatureValid, rustls::Error> { |
| 57 | Err(rustls::Error::General("TLS 1.2 미지원".into())) |
| 58 | } |
| 59 | |
| 60 | fn verify_tls13_signature( |
| 61 | &self, |
| 62 | message: &[u8], |
| 63 | cert: &CertificateDer<'_>, |
| 64 | dss: &DigitallySignedStruct, |
| 65 | ) -> Result<HandshakeSignatureValid, rustls::Error> { |
| 66 | rustls::crypto::verify_tls13_signature( |
| 67 | message, |
| 68 | cert, |
| 69 | dss, |
| 70 | &self.provider.signature_verification_algorithms, |
| 71 | ) |
| 72 | } |
| 73 | |
| 74 | fn supported_verify_schemes(&self) -> Vec<SignatureScheme> { |
| 75 | self.provider |
| 76 | .signature_verification_algorithms |
| 77 | .supported_schemes() |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | type Conn = FramedStream<TlsStream<TcpStream>>; |
| 82 | |
| 83 | /// 최소 테스트 클라이언트. 같은 ClientConfig를 재사용해 TLS 세션 재개를 시험한다. |
| 84 | struct Client { |
| 85 | addr: SocketAddr, |
| 86 | connector: TlsConnector, |
| 87 | key: SigningKey, |
| 88 | cert_sha256: [u8; 32], |
| 89 | } |
| 90 | |
| 91 | impl Client { |
| 92 | fn new(device: &FakeDevice) -> Self { |
| 93 | let provider = Arc::new(rustls::crypto::ring::default_provider()); |
| 94 | let verifier = PinnedVerifier { |
| 95 | provider: provider.clone(), |
| 96 | fingerprint: device.cert_sha256(), |
| 97 | }; |
| 98 | let config = rustls::ClientConfig::builder_with_provider(provider) |
| 99 | .with_protocol_versions(&[&rustls::version::TLS13]) |
| 100 | .unwrap() |
| 101 | .dangerous() |
| 102 | .with_custom_certificate_verifier(Arc::new(verifier)) |
| 103 | .with_no_client_auth(); |
| 104 | let mut secret = [0u8; 32]; |
| 105 | getrandom::fill(&mut secret).unwrap(); |
| 106 | Self { |
| 107 | addr: device.addr(), |
| 108 | connector: TlsConnector::from(Arc::new(config)), |
| 109 | key: SigningKey::from_bytes(&secret), |
| 110 | cert_sha256: device.cert_sha256(), |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | fn public_key(&self) -> [u8; 32] { |
| 115 | self.key.verifying_key().to_bytes() |
| 116 | } |
| 117 | |
| 118 | async fn connect(&self) -> Conn { |
| 119 | let tcp = TcpStream::connect(self.addr).await.unwrap(); |
| 120 | tcp.set_nodelay(true).unwrap(); |
| 121 | let name = ServerName::try_from("android-remote-device").unwrap(); |
| 122 | FramedStream::new(self.connector.connect(name, tcp).await.unwrap()) |
| 123 | } |
| 124 | |
| 125 | /// AUTH_HELLO → AUTH_CHALLENGE → AUTH_RESPONSE → AUTH_RESULT. |
| 126 | async fn auth_with(&self, corrupt_signature: bool) -> (Conn, AuthStatus, AuthResult) { |
| 127 | let mut conn = self.connect().await; |
| 128 | let hello = AuthHello { |
| 129 | public_key: self.public_key(), |
| 130 | hostname: "smoke-test".to_owned(), |
| 131 | }; |
| 132 | conn.send(&Message::AuthHello(hello)).await.unwrap(); |
| 133 | let Message::AuthChallenge(ch) = read(&mut conn).await else { |
| 134 | panic!("AUTH_CHALLENGE 아님"); |
| 135 | }; |
| 136 | let mut signature = self |
| 137 | .key |
| 138 | .sign(&auth_signing_message(&ch.nonce, &self.cert_sha256)) |
| 139 | .to_bytes(); |
| 140 | if corrupt_signature { |
| 141 | signature[0] ^= 0xFF; |
| 142 | } |
| 143 | conn.send(&Message::AuthResponse(AuthResponse { signature })) |
| 144 | .await |
| 145 | .unwrap(); |
| 146 | let Message::AuthResult(result) = read(&mut conn).await else { |
| 147 | panic!("AUTH_RESULT 아님"); |
| 148 | }; |
| 149 | (conn, ch.status, result) |
| 150 | } |
| 151 | |
| 152 | async fn auth(&self) -> (Conn, AuthStatus, AuthResult) { |
| 153 | self.auth_with(false).await |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | async fn read(conn: &mut Conn) -> Message { |
| 158 | tokio::time::timeout(TIMEOUT, conn.read_message()) |
| 159 | .await |
| 160 | .expect("응답 시간 초과") |
| 161 | .expect("읽기 실패") |
| 162 | .1 |
| 163 | } |
| 164 | |
| 165 | /// 상대가 데이터 없이 연결을 닫았는지 확인한다. |
| 166 | async fn assert_closed(conn: &mut Conn) { |
| 167 | let res = tokio::time::timeout(TIMEOUT, conn.read_message()) |
| 168 | .await |
| 169 | .expect("닫히지 않음"); |
| 170 | assert!( |
| 171 | matches!(res, Err(FramedError::Closed) | Err(FramedError::Io(_))), |
| 172 | "{res:?}" |
| 173 | ); |
| 174 | } |
| 175 | |
| 176 | async fn start(config: FakeDeviceConfig) -> FakeDevice { |
| 177 | FakeDevice::start("127.0.0.1:0".parse().unwrap(), config) |
| 178 | .await |
| 179 | .unwrap() |
| 180 | } |
| 181 | |
| 182 | async fn read_video_packet(stream: &mut TlsStream<TcpStream>) -> (VideoPacketHeader, Vec<u8>) { |
| 183 | let mut header = [0u8; VIDEO_HEADER_LEN]; |
| 184 | tokio::time::timeout(TIMEOUT, stream.read_exact(&mut header)) |
| 185 | .await |
| 186 | .expect("비디오 패킷 시간 초과") |
| 187 | .unwrap(); |
| 188 | let header = VideoPacketHeader::decode(&header).unwrap(); |
| 189 | let mut data = vec![0u8; header.data_len as usize]; |
| 190 | stream.read_exact(&mut data).await.unwrap(); |
| 191 | (header, data) |
| 192 | } |
| 193 | |
| 194 | #[tokio::test] |
| 195 | async fn pending_then_whitelisted() { |
| 196 | let device = start(FakeDeviceConfig::default()).await; |
| 197 | let client = Client::new(&device); |
| 198 | |
| 199 | let (conn, status, result) = client.auth().await; |
| 200 | assert_eq!(status, AuthStatus::PendingUser); |
| 201 | assert_eq!(result.result, AuthResultCode::Ok); |
| 202 | assert_eq!(result.grant, AuthGrant::Always); |
| 203 | assert_ne!(result.session_token, [0; 32]); |
| 204 | assert_eq!(result.daemon_version, 1); |
| 205 | assert_eq!(device.approval_prompts(), 1); |
| 206 | assert_eq!(device.whitelist(), vec![client.public_key()]); |
| 207 | drop(conn); |
| 208 | |
| 209 | let (conn, status, result) = client.auth().await; |
| 210 | assert_eq!(status, AuthStatus::Approved); |
| 211 | assert_eq!(result.result, AuthResultCode::Ok); |
| 212 | assert_eq!(result.grant, AuthGrant::Always); |
| 213 | assert_eq!(device.approval_prompts(), 1); |
| 214 | // 두 번째 연결은 TLS 1.3 세션 재개. |
| 215 | assert_eq!( |
| 216 | conn.get_ref().get_ref().1.handshake_kind(), |
| 217 | Some(HandshakeKind::Resumed) |
| 218 | ); |
| 219 | device.shutdown(); |
| 220 | } |
| 221 | |
| 222 | #[tokio::test] |
| 223 | async fn bad_signature_rejected() { |
| 224 | let device = start(FakeDeviceConfig::default()).await; |
| 225 | let client = Client::new(&device); |
| 226 | let (mut conn, _, result) = client.auth_with(true).await; |
| 227 | assert_eq!(result.result, AuthResultCode::SignatureInvalid); |
| 228 | assert_eq!(result.grant, AuthGrant::None); |
| 229 | assert_eq!(result.session_token, [0; 32]); |
| 230 | assert_closed(&mut conn).await; |
| 231 | assert_eq!(device.approval_prompts(), 0); |
| 232 | assert!(device.whitelist().is_empty()); |
| 233 | } |
| 234 | |
| 235 | #[tokio::test] |
| 236 | async fn reject_and_once_policies() { |
| 237 | let after = Duration::from_millis(10); |
| 238 | let device = start(FakeDeviceConfig { |
| 239 | pending: PendingPolicy::Reject { after }, |
| 240 | ..FakeDeviceConfig::default() |
| 241 | }) |
| 242 | .await; |
| 243 | let (mut conn, _, result) = Client::new(&device).auth().await; |
| 244 | assert_eq!(result.result, AuthResultCode::Rejected); |
| 245 | assert_eq!(result.grant, AuthGrant::None); |
| 246 | assert_closed(&mut conn).await; |
| 247 | |
| 248 | let device = start(FakeDeviceConfig { |
| 249 | pending: PendingPolicy::ApproveOnce { after }, |
| 250 | ..FakeDeviceConfig::default() |
| 251 | }) |
| 252 | .await; |
| 253 | let (_conn, _, result) = Client::new(&device).auth().await; |
| 254 | assert_eq!(result.result, AuthResultCode::Ok); |
| 255 | assert_eq!(result.grant, AuthGrant::Once); |
| 256 | assert!(device.whitelist().is_empty()); |
| 257 | } |
| 258 | |
| 259 | #[tokio::test] |
| 260 | async fn unauthenticated_first_frame() { |
| 261 | let device = start(FakeDeviceConfig::default()).await; |
| 262 | let mut conn = Client::new(&device).connect().await; |
| 263 | conn.send(&Message::VideoRequestKeyframe).await.unwrap(); |
| 264 | let Message::Error(err) = read(&mut conn).await else { |
| 265 | panic!("ERROR 아님"); |
| 266 | }; |
| 267 | assert_eq!(err.code, error_code::UNAUTHENTICATED); |
| 268 | assert_closed(&mut conn).await; |
| 269 | } |
| 270 | |
| 271 | #[tokio::test] |
| 272 | async fn ping_config_and_video() { |
| 273 | let device = start(FakeDeviceConfig { |
| 274 | video_frames: 3, |
| 275 | ..FakeDeviceConfig::default() |
| 276 | }) |
| 277 | .await; |
| 278 | let client = Client::new(&device); |
| 279 | let (mut control, _, result) = client.auth().await; |
| 280 | let token = result.session_token; |
| 281 | |
| 282 | control.send_with_seq(&Message::Ping, 0xBEEF).await.unwrap(); |
| 283 | let (seq, msg) = tokio::time::timeout(TIMEOUT, control.read_message()) |
| 284 | .await |
| 285 | .unwrap() |
| 286 | .unwrap(); |
| 287 | assert_eq!((seq, msg), (0xBEEF, Message::Pong)); |
| 288 | |
| 289 | let req = VideoConfigRequest { |
| 290 | max_size: 1920, |
| 291 | max_fps: 0, |
| 292 | codecs: CodecMask::ALL, |
| 293 | bitrate: 8_000_000, |
| 294 | }; |
| 295 | control |
| 296 | .send(&Message::VideoConfigRequest(req)) |
| 297 | .await |
| 298 | .unwrap(); |
| 299 | let Message::VideoConfig(cfg) = read(&mut control).await else { |
| 300 | panic!("VIDEO_CONFIG 아님"); |
| 301 | }; |
| 302 | assert_eq!(cfg.codec, VideoCodec::H265); |
| 303 | assert_eq!((cfg.width, cfg.height), (864, 1920)); |
| 304 | assert_eq!((cfg.fps, cfg.bitrate, cfg.config_gen), (60, 8_000_000, 1)); |
| 305 | assert_eq!((cfg.display_width, cfg.display_height), (1080, 2400)); |
| 306 | |
| 307 | let mut video = client.connect().await; |
| 308 | let attach = ChannelAttach { |
| 309 | kind: ChannelKind::Video, |
| 310 | session_token: token, |
| 311 | }; |
| 312 | video.send(&Message::ChannelAttach(attach)).await.unwrap(); |
| 313 | let mut video = video.into_inner(); |
| 314 | let (h, data) = read_video_packet(&mut video).await; |
| 315 | assert!(h.is_config && !h.is_keyframe && h.pts_us == 0 && h.config_gen == 1); |
| 316 | assert!(!data.is_empty()); |
| 317 | let (h, _) = read_video_packet(&mut video).await; |
| 318 | assert!(!h.is_config && h.is_keyframe && h.config_gen == 1); |
| 319 | let (h, _) = read_video_packet(&mut video).await; |
| 320 | assert!(!h.is_config && h.pts_us == 16_666); |
| 321 | |
| 322 | // 같은 토큰 재사용은 데이터 없이 닫힌다. |
| 323 | let mut again = client.connect().await; |
| 324 | again.send(&Message::ChannelAttach(attach)).await.unwrap(); |
| 325 | let mut again = again.into_inner(); |
| 326 | let mut buf = [0u8; 1]; |
| 327 | let n = tokio::time::timeout(TIMEOUT, again.read(&mut buf)) |
| 328 | .await |
| 329 | .expect("닫히지 않음") |
| 330 | .unwrap_or(0); |
| 331 | assert_eq!(n, 0); |
| 332 | |
| 333 | // 제어 연결이 끝나면 비디오 채널도 닫힌다. |
| 334 | drop(control); |
| 335 | let mut rest = Vec::new(); |
| 336 | tokio::time::timeout(TIMEOUT, video.read_to_end(&mut rest)) |
| 337 | .await |
| 338 | .expect("비디오 채널이 닫히지 않음") |
| 339 | .ok(); |
| 340 | let _ = video.shutdown().await; |
| 341 | } |