diff --git a/Cargo.lock b/Cargo.lock index 4b1f7f1..9cfd4b4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -274,9 +274,9 @@ checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] name = "chacha20" -version = "0.10.1" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", "cpufeatures 0.3.0", diff --git a/src/cdp.rs b/src/cdp.rs index a71f386..e8435d7 100644 --- a/src/cdp.rs +++ b/src/cdp.rs @@ -1422,7 +1422,7 @@ impl Executor for CdpExecutor { } } -fn fetch_json_targets(config: &CdpConfig) -> Result { +fn discover_websocket_url(config: &CdpConfig) -> Result { let mut stream = TcpStream::connect_timeout(&config.endpoint(), MAX_IO_TIMEOUT) .map_err(|_| CdpError::Protocol)?; stream @@ -1486,11 +1486,7 @@ fn fetch_json_targets(config: &CdpConfig) -> Result { if body.len() != content_length { return Err(CdpError::Protocol); } - serde_json::from_slice(&body).map_err(|_| CdpError::Protocol) -} - -fn discover_websocket_url(config: &CdpConfig) -> Result { - let targets = fetch_json_targets(config)?; + let targets: Value = serde_json::from_slice(&body).map_err(|_| CdpError::Protocol)?; let mut matches = targets .as_array() .ok_or(CdpError::Protocol)? @@ -1681,14 +1677,8 @@ fn endpoint_owner_process_ids(port: u16, process_id: u32) -> Result Result, CdpError> { +fn list_all_process_ids() -> Result, CdpError> { const MAX_PROCESS_COUNT: usize = 1024 * 1024; - const MAX_DESCRIPTOR_BYTES: usize = 16 * 1024 * 1024; - const SOCKET_INFO_BYTES: usize = 792; - const PROC_PIDFDSOCKETINFO: i32 = 3; - const SOCKINFO_TCP: i32 = 2; - const TCP_LISTEN: i32 = 1; - let capacity = unsafe { libc::proc_listallpids(std::ptr::null_mut(), 0) }; let capacity = usize::try_from(capacity) .ok() @@ -1707,89 +1697,111 @@ fn endpoint_owner_process_ids(port: u16, _process_id: u32) -> Result 0) { - let descriptor_bytes = unsafe { - libc::proc_pidinfo( - process_id, - libc::PROC_PIDLISTFDS, - 0, - std::ptr::null_mut(), - 0, - ) - }; - let Ok(descriptor_bytes) = usize::try_from(descriptor_bytes) else { - continue; - }; - if descriptor_bytes == 0 || descriptor_bytes > MAX_DESCRIPTOR_BYTES { + process_ids.truncate(count); + Ok(process_ids) +} + +#[cfg(target_os = "macos")] +fn process_has_tcp_listen_socket(process_id: i32, port: u16) -> Result { + const MAX_DESCRIPTOR_BYTES: usize = 16 * 1024 * 1024; + const SOCKET_INFO_BYTES: usize = 792; + const PROC_PIDFDSOCKETINFO: i32 = 3; + const SOCKINFO_TCP: i32 = 2; + const TCP_LISTEN: i32 = 1; + + let descriptor_bytes = unsafe { + libc::proc_pidinfo( + process_id, + libc::PROC_PIDLISTFDS, + 0, + std::ptr::null_mut(), + 0, + ) + }; + let Ok(descriptor_bytes) = usize::try_from(descriptor_bytes) else { + return Ok(false); + }; + if descriptor_bytes == 0 || descriptor_bytes > MAX_DESCRIPTOR_BYTES { + return Ok(false); + } + let descriptor_capacity = descriptor_bytes + .checked_add(64 * 8) + .filter(|bytes| *bytes <= MAX_DESCRIPTOR_BYTES) + .ok_or(CdpError::StaleTarget)?; + let mut descriptors = vec![0u8; descriptor_capacity]; + let requested = i32::try_from(descriptors.len()).map_err(|_| CdpError::StaleTarget)?; + let written = unsafe { + libc::proc_pidinfo( + process_id, + libc::PROC_PIDLISTFDS, + 0, + descriptors.as_mut_ptr().cast(), + requested, + ) + }; + let Ok(written) = usize::try_from(written) else { + return Ok(false); + }; + if written >= descriptors.len() || written % 8 != 0 { + return Err(CdpError::StaleTarget); + } + #[allow(clippy::chunks_exact_to_as_chunks)] + for descriptor in descriptors[..written].chunks_exact(8) { + let file_descriptor = + i32::from_ne_bytes(descriptor[..4].try_into().map_err(|_| CdpError::Protocol)?); + let descriptor_type = u32::from_ne_bytes( + descriptor[4..8] + .try_into() + .map_err(|_| CdpError::Protocol)?, + ); + if descriptor_type != libc::PROX_FDTYPE_SOCKET as u32 { continue; } - let descriptor_capacity = descriptor_bytes - .checked_add(64 * 8) - .filter(|bytes| *bytes <= MAX_DESCRIPTOR_BYTES) - .ok_or(CdpError::StaleTarget)?; - let mut descriptors = vec![0u8; descriptor_capacity]; - let requested = i32::try_from(descriptors.len()).map_err(|_| CdpError::StaleTarget)?; + let mut socket = [0u8; SOCKET_INFO_BYTES]; let written = unsafe { - libc::proc_pidinfo( + libc::proc_pidfdinfo( process_id, - libc::PROC_PIDLISTFDS, - 0, - descriptors.as_mut_ptr().cast(), - requested, + file_descriptor, + PROC_PIDFDSOCKETINFO, + socket.as_mut_ptr().cast(), + SOCKET_INFO_BYTES as i32, ) }; - let Ok(written) = usize::try_from(written) else { + if written != SOCKET_INFO_BYTES as i32 + || i32::from_ne_bytes(socket[256..260].try_into().unwrap_or_default()) != SOCKINFO_TCP + || i32::from_ne_bytes(socket[344..348].try_into().unwrap_or_default()) != TCP_LISTEN + || socket[288] & 1 == 0 + || socket[324..328] != Ipv4Addr::LOCALHOST.octets() + || u16::from_be_bytes(socket[268..270].try_into().unwrap_or_default()) != port + { continue; - }; - if written >= descriptors.len() || written % 8 != 0 { - return Err(CdpError::StaleTarget); } - for descriptor in descriptors[..written].as_chunks::<8>().0 { - let file_descriptor = - i32::from_ne_bytes(descriptor[..4].try_into().map_err(|_| CdpError::Protocol)?); - let descriptor_type = u32::from_ne_bytes( - descriptor[4..8] - .try_into() - .map_err(|_| CdpError::Protocol)?, - ); - if descriptor_type != libc::PROX_FDTYPE_SOCKET as u32 { - continue; - } - let mut socket = [0u8; SOCKET_INFO_BYTES]; - let written = unsafe { - libc::proc_pidfdinfo( - process_id, - file_descriptor, - PROC_PIDFDSOCKETINFO, - socket.as_mut_ptr().cast(), - SOCKET_INFO_BYTES as i32, - ) - }; - if written != SOCKET_INFO_BYTES as i32 - || i32::from_ne_bytes(socket[256..260].try_into().unwrap_or_default()) - != SOCKINFO_TCP - || i32::from_ne_bytes(socket[344..348].try_into().unwrap_or_default()) != TCP_LISTEN - || socket[288] & 1 == 0 - || socket[324..328] != Ipv4Addr::LOCALHOST.octets() - || u16::from_be_bytes(socket[268..270].try_into().unwrap_or_default()) != port - { - continue; - } + return Ok(true); + } + Ok(false) +} + +#[cfg(target_os = "macos")] +fn endpoint_owner_process_ids(port: u16, _process_id: u32) -> Result, CdpError> { + let process_ids = list_all_process_ids()?; + let mut owners = BTreeSet::new(); + for process_id in process_ids.into_iter().filter(|id| *id > 0) { + if process_has_tcp_listen_socket(process_id, port)? { owners.insert(u32::try_from(process_id).map_err(|_| CdpError::Protocol)?); - break; } } Ok(owners) } #[cfg(windows)] -fn get_extended_tcp_table() -> Result, CdpError> { +fn endpoint_owner_process_ids(port: u16, _process_id: u32) -> Result, CdpError> { const AF_INET: u32 = 2; const ERROR_INSUFFICIENT_BUFFER: u32 = 122; const MAX_TABLE_BYTES: usize = 16 * 1024 * 1024; const NO_ERROR: u32 = 0; + const TCP_LISTEN: u32 = 2; const TCP_TABLE_OWNER_PID_LISTENER: i32 = 3; + const TCP_ROW_BYTES: usize = 24; #[link(name = "iphlpapi")] unsafe extern "system" { @@ -1840,16 +1852,6 @@ fn get_extended_tcp_table() -> Result, CdpError> { if written > table.len() || written < 4 { return Err(CdpError::Protocol); } - table.truncate(written); - Ok(table) -} - -#[cfg(windows)] -fn endpoint_owner_process_ids(port: u16, _process_id: u32) -> Result, CdpError> { - const TCP_LISTEN: u32 = 2; - const TCP_ROW_BYTES: usize = 24; - - let table = get_extended_tcp_table()?; let row_count = u32::from_ne_bytes(table[..4].try_into().map_err(|_| CdpError::Protocol)?) as usize; if 4usize @@ -1858,17 +1860,13 @@ fn endpoint_owner_process_ids(port: u16, _process_id: u32) -> Result table.len()) + .is_none_or(|required| required > written) { return Err(CdpError::Protocol); } let mut owners = BTreeSet::new(); - for row in table[4..] - .as_chunks::() - .0 - .iter() - .take(row_count) - { + #[allow(clippy::chunks_exact_to_as_chunks)] + for row in table[4..].chunks_exact(TCP_ROW_BYTES).take(row_count) { if u32::from_ne_bytes(row[..4].try_into().map_err(|_| CdpError::Protocol)?) == TCP_LISTEN && row[4..8] == Ipv4Addr::LOCALHOST.octets() && u16::from_be_bytes(row[8..10].try_into().map_err(|_| CdpError::Protocol)?) == port @@ -2762,44 +2760,6 @@ mod tests { } } - fn interactive_request( - operation_id: &str, - action: Action, - target: TargetRef, - verification: VerificationPolicy, - ) -> ActionRequest { - ActionRequest { - protocol_version: PROTOCOL_VERSION, - action_version: PROTOCOL_VERSION, - target_version: PROTOCOL_VERSION, - verification_version: PROTOCOL_VERSION, - operation_id: operation_id.to_string(), - subject: "subject".to_string(), - session_id: "session".to_string(), - authority: SignedAuthority { - grant: AuthorityGrant { - protocol_version: PROTOCOL_VERSION, - issuer: "host".to_string(), - key_id: "key".to_string(), - operation_id: operation_id.to_string(), - subject: "subject".to_string(), - session_id: "session".to_string(), - risk: SafetyClass::Reversible, - expires_at_ms: i64::MAX, - policy_generation: "generation".to_string(), - action_hash: "0".repeat(64), - }, - signature: "0".repeat(128), - }, - action, - target, - interaction_mode: crate::InteractionMode::Interactive, - deadline_at_ms: i64::MAX, - verification, - safety: SafetyClass::Reversible, - } - } - #[test] fn only_exact_local_channel_is_accepted() { let process_id = std::process::id(); @@ -3837,14 +3797,38 @@ mod tests { )), ]); drop(channel); - let request = interactive_request( - "cdp-set-value", - Action::SetValue { + let request = ActionRequest { + protocol_version: PROTOCOL_VERSION, + action_version: PROTOCOL_VERSION, + target_version: PROTOCOL_VERSION, + verification_version: PROTOCOL_VERSION, + operation_id: "cdp-set-value".to_string(), + subject: "subject".to_string(), + session_id: "session".to_string(), + authority: SignedAuthority { + grant: AuthorityGrant { + protocol_version: PROTOCOL_VERSION, + issuer: "host".to_string(), + key_id: "key".to_string(), + operation_id: "cdp-set-value".to_string(), + subject: "subject".to_string(), + session_id: "session".to_string(), + risk: SafetyClass::Reversible, + expires_at_ms: i64::MAX, + policy_generation: "generation".to_string(), + action_hash: "0".repeat(64), + }, + signature: "0".repeat(128), + }, + action: Action::SetValue { value: value.to_string(), }, - TargetRef::Element { target }, - VerificationPolicy::TargetValueHash { sha256: value_hash }, - ); + target: TargetRef::Element { target }, + interaction_mode: crate::InteractionMode::Interactive, + deadline_at_ms: i64::MAX, + verification: VerificationPolicy::TargetValueHash { sha256: value_hash }, + safety: SafetyClass::Reversible, + }; let directory = tempfile::tempdir().expect("temporary directory"); crate::restrict_directory(directory.path()).expect("restrict temporary directory"); let report = Engine::new( diff --git a/src/lib.rs b/src/lib.rs index ee9a91b..eaee624 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,3 @@ -#![allow(unknown_lints)] -#![allow(clippy::chunks_exact_to_as_chunks)] #![allow(clippy::collapsible_if, clippy::needless_return)] use std::collections::BTreeMap; use std::fs::{File, OpenOptions}; @@ -130,17 +128,6 @@ pub enum DeliveryRoute { Unknown, } -impl DeliveryRoute { - pub fn as_str(&self) -> &'static str { - match self { - DeliveryRoute::TargetAddressed => "targetAddressed", - DeliveryRoute::Pointer => "pointer", - DeliveryRoute::PerProcessEvent => "perProcessEvent", - DeliveryRoute::Unknown => "unknown", - } - } -} - #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub enum BackgroundSupport { @@ -1267,11 +1254,69 @@ impl NativeRuntime { } #[cfg(windows)] { - return windows_native_press(_key, _count, _delay_ms); + use windows::Win32::UI::Input::KeyboardAndMouse::*; + + let vk = win_key_code(_key).ok_or(NativeError)?; + + for i in 0.._count { + if i > 0 { + if let Some(delay) = _delay_ms { + std::thread::sleep(std::time::Duration::from_millis(delay)); + } + } + let down = INPUT { + r#type: INPUT_KEYBOARD, + Anonymous: INPUT_0 { + ki: KEYBDINPUT { + wVk: vk, + wScan: 0, + dwFlags: KEYBD_EVENT_FLAGS::default(), + time: 0, + dwExtraInfo: 0, + }, + }, + }; + let up = INPUT { + r#type: INPUT_KEYBOARD, + Anonymous: INPUT_0 { + ki: KEYBDINPUT { + wVk: vk, + wScan: 0, + dwFlags: KEYEVENTF_KEYUP, + time: 0, + dwExtraInfo: 0, + }, + }, + }; + let _ = unsafe { SendInput(&[down, up], std::mem::size_of::() as i32) }; + } + return Ok(()); } #[cfg(target_os = "macos")] { - return macos_native_press(_key, _count, _delay_ms); + if !native_permissions() + .get("accessibility") + .and_then(serde_json::Value::as_bool) + .unwrap_or(false) + { + return Err(NativeError); + } + let code = mac_key_name_code(_key) + .or_else(|| { + _key.chars() + .next() + .and_then(|ch| mac_key_code(ch.to_ascii_lowercase())) + }) + .ok_or(NativeError)?; + for i in 0.._count { + if i > 0 + && let Some(delay) = _delay_ms + { + std::thread::sleep(std::time::Duration::from_millis(delay)); + } + let _ = mac_post_key(code, 0); + } + Ok(()) } #[cfg(not(any(target_os = "macos", target_os = "linux", windows)))] Err(NativeError) @@ -6759,7 +6804,7 @@ impl Drop for LedgerLock { } } -fn validate_request_versions(request: &ActionRequest) -> Result<(), ProtocolError> { +fn validate_request(request: &ActionRequest) -> Result<(), ProtocolError> { if request.protocol_version != PROTOCOL_VERSION || request.action_version != PROTOCOL_VERSION || request.target_version != PROTOCOL_VERSION @@ -6770,10 +6815,6 @@ fn validate_request_versions(request: &ActionRequest) -> Result<(), ProtocolErro "unsupported protocol version".to_string(), )); } - Ok(()) -} - -fn validate_request_identifiers(request: &ActionRequest) -> Result<(), ProtocolError> { for (name, value) in [ ("operation_id", request.operation_id.as_str()), ("subject", request.subject.as_str()), @@ -6788,10 +6829,6 @@ fn validate_request_identifiers(request: &ActionRequest) -> Result<(), ProtocolE return Err(ProtocolError::InvalidRequest(format!("invalid {name}"))); } } - Ok(()) -} - -fn validate_request_action_and_target(request: &ActionRequest) -> Result<(), ProtocolError> { let auxiliary = matches!( request.action, Action::Screenshot { .. } @@ -6840,10 +6877,6 @@ fn validate_request_action_and_target(request: &ActionRequest) -> Result<(), Pro "action requires a fenced semantic element target".to_string(), )); } - Ok(()) -} - -fn validate_request_verification(request: &ActionRequest) -> Result<(), ProtocolError> { validate_verification(&request.verification)?; match (&request.action, &request.verification) { (Action::SetValue { value }, VerificationPolicy::TargetValueHash { sha256 }) @@ -6903,14 +6936,6 @@ fn validate_request_verification(request: &ActionRequest) -> Result<(), Protocol Ok(()) } -fn validate_request(request: &ActionRequest) -> Result<(), ProtocolError> { - validate_request_versions(request)?; - validate_request_identifiers(request)?; - validate_request_action_and_target(request)?; - validate_request_verification(request)?; - Ok(()) -} - fn target_provenance_is_valid(target: &TargetRef) -> bool { match target { TargetRef::Coordinates { @@ -7874,78 +7899,6 @@ fn default_ledger_path_with_env(get_env: impl Fn(&str) -> Option, -) -> Result<(), NativeError> { - use windows::Win32::UI::Input::KeyboardAndMouse::*; - - let vk = win_key_code(_key).ok_or(NativeError)?; - - for i in 0.._count { - if i > 0 { - if let Some(delay) = _delay_ms { - std::thread::sleep(std::time::Duration::from_millis(delay)); - } - } - let down = INPUT { - r#type: INPUT_KEYBOARD, - Anonymous: INPUT_0 { - ki: KEYBDINPUT { - wVk: vk, - wScan: 0, - dwFlags: KEYBD_EVENT_FLAGS::default(), - time: 0, - dwExtraInfo: 0, - }, - }, - }; - let up = INPUT { - r#type: INPUT_KEYBOARD, - Anonymous: INPUT_0 { - ki: KEYBDINPUT { - wVk: vk, - wScan: 0, - dwFlags: KEYEVENTF_KEYUP, - time: 0, - dwExtraInfo: 0, - }, - }, - }; - let _ = unsafe { SendInput(&[down, up], std::mem::size_of::() as i32) }; - } - Ok(()) -} - -#[cfg(target_os = "macos")] -fn macos_native_press(_key: &str, _count: u32, _delay_ms: Option) -> Result<(), NativeError> { - if !native_permissions() - .get("accessibility") - .and_then(serde_json::Value::as_bool) - .unwrap_or(false) - { - return Err(NativeError); - } - let code = mac_key_name_code(_key) - .or_else(|| { - _key.chars() - .next() - .and_then(|ch| mac_key_code(ch.to_ascii_lowercase())) - }) - .ok_or(NativeError)?; - for i in 0.._count { - if i > 0 - && let Some(delay) = _delay_ms - { - std::thread::sleep(std::time::Duration::from_millis(delay)); - } - let _ = mac_post_key(code, 0); - } - Ok(()) -} - #[cfg(test)] mod tests { use super::{ @@ -8109,15 +8062,6 @@ mod tests { ); } - #[test] - fn test_delivery_route_as_str() { - use super::DeliveryRoute; - assert_eq!(DeliveryRoute::TargetAddressed.as_str(), "targetAddressed"); - assert_eq!(DeliveryRoute::Pointer.as_str(), "pointer"); - assert_eq!(DeliveryRoute::PerProcessEvent.as_str(), "perProcessEvent"); - assert_eq!(DeliveryRoute::Unknown.as_str(), "unknown"); - } - #[cfg(target_os = "macos")] #[test] fn macos_semantic_scroll_names_one_page_action_per_direction() { diff --git a/src/main.rs b/src/main.rs index 133a787..2280417 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,3 @@ -#![allow(unknown_lints)] -#![allow(clippy::chunks_exact_to_as_chunks)] use std::io; use std::path::PathBuf; use std::process::ExitCode;