1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
//! Searches for a contiguous array of bytes determined by a given pattern. The pattern can include //! supported wildcard characters, as seen below. //! //! ## Wildcards //! * `?` match any byte //! //! ## Example Patterns //! * `fe 00 68 98` - matches only `fe 00 68 98` //! * `8d 11 ? ? 8f` - could match `8d 11 9e ef 8f` or `8d 11 0 0 8f` for example //! //! ## Example Usage //! The [`scan`] function is used to scan for a pattern within the output of a [`Read`]. Using a //! [`Cursor`](std::io::Cursor) to scan within a byte array in memory could look as follows: //! //! ```rust //! use patternscan::scan; //! use std::io::Cursor; //! //! let bytes = [0x10, 0x20, 0x30, 0x40, 0x50]; //! let pattern = "20 30 40"; //! let locs = scan(Cursor::new(bytes), &pattern).unwrap(); // Will equal vec![1], the index of //! // the pattern //! ``` //! //! Any struct implementing [`Read`] can be passed as the reader which should be scanned for //! ocurrences of a pattern, so one could scan for a byte sequence within an executable as follows: //! //! ```ignore //! use patternscan::scan; //! use std::fs::File; //! //! let reader = File::open("somebinary.exe").unwrap(); //! let instruction = "A3 ? ? ? ?"; //! let locs = scan(reader, &instruction).unwrap(); //! ``` //! //! For more example uses of this module, see the //! [tests](https://github.com/lewisclark/patternscan/blob/master/src/lib.rs#L128) use std::fmt::{self, Display}; use std::io::Read; use std::str::FromStr; /// Size of chunks to be read from `reader` when looking for patterns. /// /// In [`Matches`] (which in turn is used in [`scan`] and [`scan_first_match`]), bytes are read /// from the provided [`Read`] type into a fixed-size internal buffer. The length of this buffer is /// given by `CHUNK_SIZE`. pub const CHUNK_SIZE: usize = 0x800; /// Scan for any instances of `pattern` in the bytes read by `reader`. /// /// Returns a [`Result`] containing a vector of indices of the start of each match within the /// bytes. If no matches are found, this vector will be empty. Returns an [`Error`] if an error was /// encountered while scanning, which could occur if the pattern is invalid (i.e: contains /// something other than 8-bit hex values and wildcards), or if the reader encounters an error. pub fn scan(reader: impl Read, pattern: &str) -> Result<Vec<usize>, Error> { let matches = Matches::from_pattern_str(reader, pattern)?; matches.collect() } /// Scan for the first instance of `pattern` in the bytes read by `reader`. /// /// This function should be used instead of [`scan`] if you just want to test whether a byte string /// contains a given pattern, or just find the first instance, as it returns as soon as the first /// match is found, and will therefore be more efficient for these purposes in long strings where /// the pattern occurs early. /// /// Returns a [`Result`] containing an [`Option`]. This Option will contain `Some(index)` if the /// pattern was found, where `index` is the index of the first match, and `None` if the pattern /// was not found. Returns an [`Error`] if an error was encountered while scanning, which could /// occur if the pattern is invalid (i.e: contains something other than 8-bit hex values and /// wildcards), or if the reader encounters an error. pub fn scan_first_match(reader: impl Read, pattern: &str) -> Result<Option<usize>, Error> { let mut matches = Matches::from_pattern_str(reader, pattern)?; matches.next().transpose() } /// Determine whether a byte slice matches a pattern. pub fn pattern_matches(bytes: &[u8], pattern: &Pattern) -> bool { if bytes.len() < pattern.len() { false } else { pattern == bytes } } /// Represents an error which occurred while scanning for a pattern. #[derive(Debug)] pub struct Error { /// String detailing the error e: String, } impl Error { pub fn new(e: String) -> Self { Self { e } } } impl Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "Pattern scan error: {}", self.e) } } impl std::error::Error for Error {} /// Represents a single byte in a search pattern. #[derive(PartialEq, Eq)] pub enum PatternByte { Byte(u8), Any, } impl FromStr for PatternByte { type Err = Error; /// Create an instance of [`PatternByte`] from a string. /// /// This string should either be a hexadecimal byte, or a "?". Will return an error if the /// string is not a "?", or it cannot be converted into an 8-bit integer when interpreted as /// hexadecimal. fn from_str(s: &str) -> Result<Self, Error> { if s == "?" { Ok(Self::Any) } else { let n = match u8::from_str_radix(s, 16) { Ok(n) => Ok(n), Err(e) => Err(Error::new(format!("from_str_radix failed: {}", e))), }?; Ok(Self::Byte(n)) } } } impl PartialEq<u8> for PatternByte { fn eq(&self, other: &u8) -> bool { match self { PatternByte::Any => true, PatternByte::Byte(b) => b == other, } } } /// Represents a pattern to search for in a byte string. #[derive(PartialEq, Eq)] pub struct Pattern { bytes: Vec<PatternByte>, } impl Pattern { fn new(bytes: Vec<PatternByte>) -> Self { Self { bytes } } fn len(&self) -> usize { self.bytes.len() } } impl FromStr for Pattern { type Err = Error; fn from_str(s: &str) -> Result<Self, Error> { let mut bytes = Vec::new(); for segment in s.split_ascii_whitespace() { bytes.push(PatternByte::from_str(segment)?); } Ok(Self::new(bytes)) } } impl PartialEq<[u8]> for Pattern { fn eq(&self, other: &[u8]) -> bool { Iterator::zip(self.bytes.iter(), other.iter()).all(|(pb, b)| pb == b) } } /// Iterator over locations of matches for a pattern found within a byte string. /// /// This struct implements the actual logic for pattern matching, and is used by the [`scan`] and /// [`scan_first_match`] functions to locate matches. The values returned by the iterator are /// indices of locations of the pattern matches within the byte string produced by `reader`. /// /// The byte string which the pattern should be searched against is read from `reader` in /// [`CHUNK_SIZE`] chunks, when required by the iterator. /// /// ## Example Usage /// ```rust /// use patternscan; /// use std::io::Cursor; /// /// let bytes = [0x10, 0x20, 0x30, 0x40]; /// let reader = Cursor::new(bytes); /// let pattern = patternscan::Matches::from_pattern_str(reader, "20 30").unwrap(); /// let match_indices: Result<Vec<usize>, _> = pattern.collect(); /// let match_indices = match_indices.unwrap(); /// ``` pub struct Matches<R: Read> { /// Reader from which the byte string to search will be read. pub reader: R, /// Pattern to search for in the byte string. pub pattern: Pattern, // Internal state, would be nice to reduce this somehow bytes_buf: [u8; CHUNK_SIZE], last_bytes_read: usize, abs_position: usize, rel_position: usize, } impl<R: Read> Matches<R> { /// Create a new instance of [`Matches`] from an instance of [`Pattern`]. /// /// `reader` should be some [`Read`] type which will produce a byte string to search. `pattern` /// should be a [`Pattern`] to search for. pub fn from_pattern(mut reader: R, pattern: Pattern) -> Result<Self, Error> { // Constraint imposed due to the method used to detect matches over chunk boundaries. We // might want to increase the chunk size to account for this? if 2 * pattern.len() > CHUNK_SIZE { return Err(Error::new(format!( "Pattern too long: It can be at most {} bytes", CHUNK_SIZE / 2 ))); } // Perform initial read into the bytes buffer on creation // Might be more idiomatic to only perform a read once we're stepping through the iterator, // I'm not sure, but this ensures that the state of the struct when an instance is created // is reasonable. let mut bytes_buf = [0; CHUNK_SIZE]; let bytes_read = reader .read(&mut bytes_buf) .map_err(|e| Error::new(format!("Failed to read bytes: {}", e)))?; Ok(Self { reader, pattern, bytes_buf, last_bytes_read: bytes_read, abs_position: 0, rel_position: 0, }) } /// Create a new instance of [`Matches`] from a string pattern. pub fn from_pattern_str(reader: R, pattern: &str) -> Result<Self, Error> { let pattern = Pattern::from_str(pattern)?; Self::from_pattern(reader, pattern) } } impl<R: Read> Iterator for Matches<R> { type Item = Result<usize, Error>; fn next(&mut self) -> Option<Self::Item> { loop { if self.rel_position == CHUNK_SIZE - self.pattern.len() { // This block is what allows us to detect matches over chunk boundaries. // When we're close enough to a boundary that a pattern match could overrun, we // copy the final bytes in the buffer to the start of the buffer, then read into // the rest of the buffer. let len = self.pattern.len(); let boundary_bytes = &self.bytes_buf[CHUNK_SIZE - len..].to_owned(); self.bytes_buf[..len].copy_from_slice(&boundary_bytes); self.last_bytes_read = match self.reader.read(&mut self.bytes_buf[len..]) { Ok(b) => b, Err(e) => return Some(Err(Error::new(format!("Failed to read bytes: {}", e)))), }; self.rel_position = 0; } if self.rel_position == self.last_bytes_read + self.pattern.len() { break; } for i in self.rel_position..self.last_bytes_read + self.pattern.len() { if i == CHUNK_SIZE - self.pattern.len() { break; } self.abs_position += 1; self.rel_position += 1; if pattern_matches(&self.bytes_buf[i..], &self.pattern) { return Some(Ok(self.abs_position - 1)); } } if self.last_bytes_read == 0 { break; } } None } } // Tests #[cfg(test)] mod tests { use std::io::Cursor; #[test] fn simple_scan_start() { let bytes = [0x10, 0x20, 0x30, 0x40, 0x50]; let pattern = "10 20 30"; assert_eq!(crate::scan(Cursor::new(bytes), &pattern).unwrap(), vec![0]); } #[test] fn simple_scan_middle() { let bytes = [0x10, 0x20, 0x30, 0x40, 0x50]; let pattern = "20 30 40"; assert_eq!(crate::scan(Cursor::new(bytes), &pattern).unwrap(), vec![1]); } #[test] fn scan_bad_exceeds() { let bytes = [0x10, 0x20, 0x30, 0x40, 0x50]; let pattern = "40 50 60"; assert_eq!(crate::scan(Cursor::new(bytes), &pattern).unwrap(), vec![]); } #[test] fn scan_exists() { let bytes = [0xff, 0xfe, 0x7c, 0x88, 0xfd, 0x90, 0x00]; let pattern = "fe 7c 88 fd 90 0"; assert_eq!(crate::scan(Cursor::new(bytes), &pattern).unwrap(), vec![1]); } #[test] fn scan_exists_multiple_q() { let bytes = [0xff, 0xfe, 0x7c, 0x88, 0xfd, 0x90, 0x00]; let pattern = "fe ? ? ? 90"; assert_eq!(crate::scan(Cursor::new(bytes), &pattern).unwrap(), vec![1]); } #[test] fn scan_exists_multiple_q_starts() { let bytes = [0xff, 0xfe, 0x7c, 0x88, 0xfd, 0x90, 0x00]; let pattern = "? ? ? ? fd"; assert_eq!(crate::scan(Cursor::new(bytes), &pattern).unwrap(), vec![0]); } #[test] fn scan_nexists_1() { let bytes = [0xff, 0xfe, 0x7c, 0x88, 0xfd, 0x90, 0x00]; let pattern = "78 90 cc dd fe"; assert_eq!(crate::scan(Cursor::new(bytes), &pattern).unwrap(), vec![]); } #[test] fn scan_nexists_2() { let bytes = [0xff, 0xfe, 0x7c, 0x88, 0xfd, 0x90, 0x00]; let pattern = "fe 7c 88 fd 90 1"; assert_eq!(crate::scan(Cursor::new(bytes), &pattern).unwrap(), vec![]); } #[test] fn scan_pattern_larger_than_bytes() { let bytes = [0xff, 0xfe, 0x7c, 0x88, 0xfd, 0x90, 0x00]; let pattern = "fe 7c 88 fd 90 0 1"; assert_eq!(crate::scan(Cursor::new(bytes), &pattern).unwrap(), vec![]); } #[test] fn scan_multiple_instances_of_pattern() { let bytes = [0x10, 0x20, 0x30, 0x10, 0x20, 0x30]; let pattern = "10 20 30"; assert_eq!( crate::scan(Cursor::new(bytes), &pattern).unwrap(), vec![0, 3] ); } #[test] fn scan_multiple_instances_q() { let bytes = [0x10, 0x20, 0x30, 0x10, 0x40, 0x30]; let pattern = "10 ? 30"; assert_eq!( crate::scan(Cursor::new(bytes), &pattern).unwrap(), vec![0, 3] ); } #[test] fn scan_rejects_invalid_pattern() { let bytes = [0x10, 0x20, 0x30]; let pattern = "10 fff 20"; assert!(crate::scan(Cursor::new(bytes), &pattern).is_err()); } #[test] fn scan_first_match_simple_start() { let bytes = [0x10, 0x20, 0x30, 0x40, 0x50]; let pattern = "10 20 30"; assert_eq!( crate::scan_first_match(Cursor::new(bytes), &pattern) .unwrap() .unwrap(), 0 ); } #[test] fn scan_first_match_simple_middle() { let bytes = [0x10, 0x20, 0x30, 0x40, 0x50]; let pattern = "20 30 40"; assert_eq!( crate::scan_first_match(Cursor::new(bytes), &pattern) .unwrap() .unwrap(), 1 ); } #[test] fn scan_first_match_no_match() { let bytes = [0x10, 0x20, 0x30, 0x40, 0x50]; let pattern = "10 11 12"; assert!(crate::scan_first_match(Cursor::new(bytes), &pattern) .unwrap() .is_none()); } #[test] fn find_across_chunk_boundary() { let mut bytes = vec![0; super::CHUNK_SIZE - 2]; bytes.push(0xaa); bytes.push(0xbb); bytes.push(0xcc); bytes.push(0xdd); let pattern = "aa bb cc dd"; assert!(crate::scan_first_match(Cursor::new(bytes), &pattern) .unwrap() .is_some()) } #[test] fn correct_index_noninitial_chunk() { let mut bytes = vec![0; super::CHUNK_SIZE]; bytes.push(0xaa); bytes.push(0xbb); bytes.push(0xcc); bytes.push(0xdd); let pattern = "aa bb cc dd"; assert_eq!( crate::scan_first_match(Cursor::new(bytes), &pattern) .unwrap() .unwrap(), super::CHUNK_SIZE ); } }