yexuanyang commented on code in PR #3547: URL: https://github.com/apache/hertzbeat/pull/3547#discussion_r2283963164
########## mcp-servers/mcp-bash-server/src/common/validator.rs: ########## @@ -0,0 +1,470 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +//! Command validation module for security enforcement +//! +//! This module provides command validation functionality to prevent execution +//! of dangerous commands and operations based on configurable blacklists. + +use std::ffi::OsStr; +use tracing::debug; + +use crate::{common::config::Whitelist, config::Blacklist}; +use rmcp::model::{ErrorCode, ErrorData}; +use tracing::error; + +/// Command validator that checks commands against security blacklists +/// Prevents execution of dangerous commands and operations +#[derive(Debug, Clone)] +pub struct Validator { + /// Security blacklist configuration containing forbidden commands and operations + blacklist: Blacklist, + /// Security whitelist configuration containing secure commands + whitelist: Whitelist, +} + +impl Validator { + /// Create a new validator with the specified blacklist configuration + pub fn new(blacklist: Blacklist, whitelist: Whitelist) -> Self { + Validator { + blacklist, + whitelist, + } + } + + /// Validate a command against the security blacklist and whitelist + /// Returns Ok(()) if command is safe, Err(ErrorData) if command is blocked + /// + /// Security Logic: + /// 1. All commands are denied by default + /// 2. Blacklist has higher priority than whitelist + /// 3. If command matches any blacklist pattern (exact or regex), deny + /// 4. If command doesn't match blacklist and matches whitelist (exact or regex), allow + /// 5. Otherwise, deny + pub fn is_unsafe_command(&self, args: Vec<&OsStr>) -> Result<(), ErrorData> { + // Handle empty command - deny by default + if args.is_empty() { + return Err(ErrorData::invalid_request( + "Empty command not allowed".to_string(), + None, + )); + } + + let full_cmd = args.join(OsStr::new(" ")).into_string().map_err(|_| { Review Comment: Is it feasible to change the function parameter from Vec<&OsStr> to &str? ########## mcp-servers/mcp-bash-server/src/common/validator.rs: ########## @@ -0,0 +1,470 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +//! Command validation module for security enforcement +//! +//! This module provides command validation functionality to prevent execution +//! of dangerous commands and operations based on configurable blacklists. + +use std::ffi::OsStr; +use tracing::debug; + +use crate::{common::config::Whitelist, config::Blacklist}; +use rmcp::model::{ErrorCode, ErrorData}; +use tracing::error; + +/// Command validator that checks commands against security blacklists +/// Prevents execution of dangerous commands and operations +#[derive(Debug, Clone)] +pub struct Validator { + /// Security blacklist configuration containing forbidden commands and operations + blacklist: Blacklist, + /// Security whitelist configuration containing secure commands + whitelist: Whitelist, +} + +impl Validator { + /// Create a new validator with the specified blacklist configuration + pub fn new(blacklist: Blacklist, whitelist: Whitelist) -> Self { + Validator { + blacklist, + whitelist, + } + } + + /// Validate a command against the security blacklist and whitelist + /// Returns Ok(()) if command is safe, Err(ErrorData) if command is blocked + /// + /// Security Logic: + /// 1. All commands are denied by default + /// 2. Blacklist has higher priority than whitelist + /// 3. If command matches any blacklist pattern (exact or regex), deny + /// 4. If command doesn't match blacklist and matches whitelist (exact or regex), allow + /// 5. Otherwise, deny + pub fn is_unsafe_command(&self, args: Vec<&OsStr>) -> Result<(), ErrorData> { + // Handle empty command - deny by default + if args.is_empty() { + return Err(ErrorData::invalid_request( + "Empty command not allowed".to_string(), + None, + )); + } + + let full_cmd = args.join(OsStr::new(" ")).into_string().map_err(|_| { + ErrorData::new( + ErrorCode::INTERNAL_ERROR, + "Convert OsStr to String failed!", + None, + ) + })?; + Review Comment: ```suggestion let full_cmd = args.to_string(); ``` ########## mcp-servers/mcp-bash-server/src/common/validator.rs: ########## @@ -0,0 +1,470 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +//! Command validation module for security enforcement +//! +//! This module provides command validation functionality to prevent execution +//! of dangerous commands and operations based on configurable blacklists. + +use std::ffi::OsStr; +use tracing::debug; + +use crate::{common::config::Whitelist, config::Blacklist}; +use rmcp::model::{ErrorCode, ErrorData}; +use tracing::error; + +/// Command validator that checks commands against security blacklists +/// Prevents execution of dangerous commands and operations +#[derive(Debug, Clone)] +pub struct Validator { + /// Security blacklist configuration containing forbidden commands and operations + blacklist: Blacklist, + /// Security whitelist configuration containing secure commands + whitelist: Whitelist, +} + +impl Validator { + /// Create a new validator with the specified blacklist configuration + pub fn new(blacklist: Blacklist, whitelist: Whitelist) -> Self { + Validator { + blacklist, + whitelist, + } + } + + /// Validate a command against the security blacklist and whitelist + /// Returns Ok(()) if command is safe, Err(ErrorData) if command is blocked + /// + /// Security Logic: + /// 1. All commands are denied by default + /// 2. Blacklist has higher priority than whitelist + /// 3. If command matches any blacklist pattern (exact or regex), deny + /// 4. If command doesn't match blacklist and matches whitelist (exact or regex), allow + /// 5. Otherwise, deny + pub fn is_unsafe_command(&self, args: Vec<&OsStr>) -> Result<(), ErrorData> { + // Handle empty command - deny by default + if args.is_empty() { + return Err(ErrorData::invalid_request( + "Empty command not allowed".to_string(), + None, + )); + } + + let full_cmd = args.join(OsStr::new(" ")).into_string().map_err(|_| { + ErrorData::new( + ErrorCode::INTERNAL_ERROR, + "Convert OsStr to String failed!", + None, + ) + })?; + + debug!("Validating command: {}", full_cmd); + + // First check blacklist - if any match, deny immediately + // Check blacklist exact commands - match against the full command + for blacklisted_cmd in &self.blacklist.commands { + if &full_cmd == blacklisted_cmd { + error!( + "Command blocked by blacklist exact match: {}, full command: {}", + blacklisted_cmd, full_cmd + ); + return Err(ErrorData::invalid_request( + format!("Command blocked by blacklist: {blacklisted_cmd}"), + None, + )); + } + } + + // Check blacklist regex patterns + for pattern in &self.blacklist.regex { + match regex::Regex::new(pattern) { + Ok(regex) => { + if regex.is_match(&full_cmd) { + error!( + "Command blocked by blacklist regex pattern: {}, full command: {}", + pattern, full_cmd + ); + return Err(ErrorData::invalid_request( + format!("Command blocked by blacklist pattern: {pattern}"), + None, + )); + } + } + Err(e) => { + error!( + "Invalid regex pattern in blacklist: {}, error: {}", + pattern, e + ); + } + } + } + + // Now check whitelist - if any match, allow + // Check whitelist exact commands + if self.whitelist.commands.contains(&full_cmd) { + debug!("Command allowed by whitelist exact match: {}", full_cmd); + return Ok(()); + } + + // Check whitelist regex patterns + for pattern in &self.whitelist.regex { + match regex::Regex::new(pattern) { + Ok(regex) => { + if regex.is_match(&full_cmd) { + debug!("Command allowed by whitelist regex pattern: {}", pattern); + return Ok(()); + } + } + Err(e) => { + error!( + "Invalid regex pattern in whitelist: {}, error: {}", + pattern, e + ); + } + } + } + + // Handle nested shell commands (e.g., bash -c "command") + if let Ok(available_shells_string) = std::fs::read_to_string("/etc/shells") { + let available_shells = available_shells_string.split('\n'); + let mut is_shell = false; + for shell in available_shells { + if shell.contains(&args[0].to_string_lossy().to_string()) { + is_shell = true; + } + } + if is_shell && args.len() >= 2 && args[1] == OsStr::new("-c") { + // pattern is "<shell> -c '<command>'", check the command again + if args.len() >= 3 { + let inner_args: Vec<&OsStr> = args[2] + .to_str() + .map(|s| s.split_whitespace().map(OsStr::new).collect()) + .unwrap_or_default(); + return self.is_unsafe_command(inner_args); + } + } + } + + // Default deny - command didn't match whitelist + error!("Command denied - not in whitelist: {full_cmd}"); + Err(ErrorData::invalid_request( + format!("Command not allowed: {full_cmd}"), + None, + )) Review Comment: ```suggestion // Default deny - command didn't match whitelist error!("Command denied - not in whitelist: {full_cmd}"); Err(ErrorData::invalid_request( format!("Command not allowed: {full_cmd}"), None, )) ``` -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
