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 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
//! **Rust-based firewall for network drivers.**
//!
//! # Purpose
//!
//! This library is used to match network packets against a set of constraints (here called *firewall rules*)
//! with the aim of deciding whether to permit or deny incoming/outgoing traffic.
//!
//! Given a set of firewall rules and a network packet, the library will *inform* the user
//! about *how* to handle the packet.
//!
//! The library assumes that users are able to manipulate the stream of network packets in a way such
//! it's possible to take proper actions to allow or deny the forwarding of single packets
//! between the network card and the operating system; consequently, this framework is mainly intended
//! to be used at the level of *network drivers*.
//!
//! Each of the packets passed to the firewall will be logged both in standard output
//! and in a `SQLite` database with path `./log.sqlite`.
//!
//! # Firewall definition
//!
//! A new [`Firewall`] object is defined via the [`Firewall::new`] method, which accepts as parameter
//! the path of a file defining a collection of firewall rules.
//!
//! Each of the **rules** defined in the file is placed on a new line and has the following structure:
//! ``` txt
//! [+] DIRECTION ACTION [OPTIONS]
//! ```
//!
//! * Each rule can optionally be introduced by a `+` character; this will make the rule
//! have higher priority (quick rule).
//!
//! * `DIRECTION` can be either `IN` or `OUT` and represents the traffic directionality
//! (see [`FirewallDirection`]).
//!
//! * `ACTION` can be either `ACCEPT`, `DENY`, or `REJECT` and represents the action
//! associated with the rule (see [`FirewallAction`]).
//!
//! * For each rule, a list of **options** can be specified to match the desired traffic:
//! * `--dest`: destination IP addresses; the value is expressed in the form of a comma-separated
//! list of IP addresses, in which each entry can also represent an address range (using the `-` character).
//! * `--dport`: destination transport ports; the value is expressed in the form of a comma-separated
//! list of port numbers, in which each entry can also represent a port range (using the `:` character).
//! * `--icmp-type`: ICMP message type; the value is expressed as a number representing
//! a specific message type (see [here](https://www.iana.org/assignments/icmp-parameters/icmp-parameters.xhtml#icmp-parameters-types) for more info).
//! * `--proto`: Internet Protocol number; the value is expressed as a number representing
//! a specific protocol number (see [here](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml#protocol-numbers-1) for more info).
//! * `--source`: source IP addresses; the value is expressed in the form of a comma-separated
//! list of IP addresses, in which each entry can also represent an address range (using the `-` character).
//! * `--sport`: source transport ports; the value is expressed in the form of a comma-separated
//! list of port numbers, in which each entry can also represent a port range (using the `:` character).
//!
//! A **sample** firewall configuration file is reported in the following:
//!
//! ``` text
//! # Firewall rules (this is a comment line)
//!
//! IN REJECT --source 8.8.8.8
//! # Rules marked with '+' have higher priority
//! + IN ACCEPT --source 8.8.8.0-8.8.8.10 --sport 8
//! OUT ACCEPT --source 8.8.8.8,7.7.7.7 --dport 900:1000,1,2,3
//! OUT DENY
//! ```
//!
//! In case of invalid firewall configurations, a [`FirewallError`] will be returned.
//!
//! # Usage
//!
//! Once a [`Firewall`] has been defined, it can be used to determine which action to take for each
//! of the netwrok packets in transit.
//!
//! This is done by invoking [`Firewall::resolve_packet`], which will answer with the
//! action to take for the supplied packet.
//!
//! ```
//! use nullnet_firewall::{Firewall, FirewallDirection, FirewallAction};
//!
//! // build the firewall from the rules in a file
//! let firewall = Firewall::new("./samples/firewall.txt").unwrap();
//!
//! // here we suppose to have a packet to match against the firewall
//! let packet = [/* ... */];
//!
//! // determine action for packet, supposing incoming direction for packet
//! let action = firewall.resolve_packet(&packet, FirewallDirection::IN);
//!
//! // act accordingly
//! match action {
//! FirewallAction::ACCEPT => {/* ... */}
//! FirewallAction::DENY => {/* ... */}
//! FirewallAction::REJECT => {/* ... */}
//! }
//! ```
//!
//! An existing firewall can be temporarily [disabled](Firewall::disable),
//! its rules can be [updated](Firewall::update_rules),
//! and the default [input policy](Firewall::policy_in) and
//! [output policy](Firewall::policy_out) can
//! be overridden for packets that don't match any of the firewall rules.
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::sync::mpsc;
use std::sync::mpsc::{Receiver, Sender};
use std::thread;
pub use crate::data_link::DataLink;
use crate::fields::fields::Fields;
use crate::fields::ip_header::{get_dest, get_proto, get_source};
use crate::fields::transport_header::{get_dport, get_icmp_type, get_sport};
pub use crate::firewall_action::FirewallAction;
pub use crate::firewall_direction::FirewallDirection;
pub use crate::firewall_error::FirewallError;
use crate::firewall_rule::FirewallRule;
use crate::logs::log_entry::LogEntry;
use crate::logs::logger::log;
mod data_link;
mod fields;
mod firewall_action;
mod firewall_direction;
mod firewall_error;
mod firewall_option;
mod firewall_rule;
mod logs;
mod utils;
/// Object embedding a collection of firewall rules and policies to determine
/// the action to be taken for a given network packet.
///
/// A new `Firewall` can be created from a textual file listing a set of rules.
pub struct Firewall {
rules: Vec<FirewallRule>,
enabled: bool,
policy_in: FirewallAction,
policy_out: FirewallAction,
tx: Sender<LogEntry>,
data_link: DataLink,
log: bool,
}
impl Firewall {
const COMMENT: char = '#';
/// Instantiates a new [`Firewall`] from a file.
///
/// # Arguments
///
/// * `file_path` - The path of a file defining the firewall rules.
///
/// # Errors
///
/// Will return a [`FirewallError`] if the rules defined in the file are not properly formatted.
///
/// # Panics
///
/// Will panic if the supplied `file_path` does not exist or the user does not have
/// permission to read it.
///
/// # Examples
///
/// ```
/// use nullnet_firewall::Firewall;
///
/// let firewall = Firewall::new("./samples/firewall.txt").unwrap();
/// ```
///
/// Sample file content:
///
/// ``` txt
/// OUT REJECT --source 8.8.8.8 --sport 6700:6800,8080
/// OUT DENY --source 192.168.200.0-192.168.200.255 --sport 6700:6800,8080 --dport 1,2,2000
/// IN ACCEPT --source 2.1.1.2,2.1.1.3 --dest 2.1.1.1 --proto 1
/// IN REJECT --source 2.1.1.2 --dest 2.1.1.1 --proto 1 --icmp-type 8
/// OUT REJECT
/// IN ACCEPT
/// ```
pub fn new(file_path: &str) -> Result<Self, FirewallError> {
let (tx, rx): (Sender<LogEntry>, Receiver<LogEntry>) = mpsc::channel();
thread::Builder::new()
.name("logger".to_string())
.spawn(move || {
log(&rx);
})
.unwrap();
let mut firewall = Firewall {
rules: Vec::new(),
enabled: true,
policy_in: FirewallAction::default(),
policy_out: FirewallAction::default(),
tx,
data_link: DataLink::default(),
log: true,
};
firewall.update_rules(file_path)?;
Ok(firewall)
}
/// Returns the action to be taken for a supplied network packet,
/// according to rules defined for the [`Firewall`].
///
/// # Arguments
///
/// * `packet` - Raw network packet bytes, including headers and payload.
///
/// * `direction` - The network packet direction (incoming or outgoing).
///
/// # Panics
///
/// Will panic if the logger routine of the firewall aborts for some reason.
///
/// # Examples
///
/// ```
/// use nullnet_firewall::{Firewall, FirewallDirection, FirewallAction};
///
/// let firewall = Firewall::new("./samples/firewall.txt").unwrap();
///
/// // here we suppose to have a packet to match against the firewall
/// let packet = [/* ... */];
///
/// // determine action for packet, supposing incoming direction for packet
/// let action = firewall.resolve_packet(&packet, FirewallDirection::IN);
///
/// // act accordingly
/// match action {
/// FirewallAction::ACCEPT => {/* ... */}
/// FirewallAction::DENY => {/* ... */}
/// FirewallAction::REJECT => {/* ... */}
/// }
/// ```
#[must_use]
pub fn resolve_packet(&self, packet: &[u8], direction: FirewallDirection) -> FirewallAction {
if !self.enabled {
return FirewallAction::ACCEPT;
}
let mut action_opt = None;
// structure the packet as a set of relevant fields
let fields = Fields::new(packet, self.data_link);
// determine action for packet
for rule in &self.rules {
if rule.matches_packet(&fields, &direction) {
if rule.quick {
action_opt = Some(rule.action);
break;
} else if action_opt.is_none() {
action_opt = Some(rule.action);
}
}
}
let action = action_opt.unwrap_or(match direction {
FirewallDirection::IN => self.policy_in,
FirewallDirection::OUT => self.policy_out,
});
if self.log {
// send the log entry to the logger thread
let log_entry = LogEntry::new(&fields, direction, action);
self.tx
.send(log_entry)
.expect("the firewall logger routine aborted");
}
action
}
/// Updates the rules of a previously instantiated [`Firewall`].
///
/// # Arguments
///
/// * `file_path` - The path of a file defining the firewall rules.
///
/// # Errors
///
/// Will return a [`FirewallError`] if the rules defined in the file are not properly formatted.
///
/// # Panics
///
/// Will panic if the supplied `file_path` does not exist or the user does not have
/// permission to read it.
///
/// # Examples
///
/// ```
/// use nullnet_firewall::Firewall;
///
/// let mut firewall = Firewall::new("./samples/firewall.txt").unwrap();
///
/// /* ... */
///
/// firewall.update_rules("./samples/firewall_for_tests_1.txt");
/// ```
pub fn update_rules(&mut self, file_path: &str) -> Result<(), FirewallError> {
let mut rules = Vec::new();
let file = File::open(file_path).unwrap();
for firewall_rule_str in BufReader::new(file)
.lines()
.flatten()
.map(|l| l.trim().to_owned())
.filter(|l| !l.starts_with(Self::COMMENT) && !l.is_empty())
{
rules.push(FirewallRule::new(&firewall_rule_str)?);
}
self.rules = rules;
Ok(())
}
/// Disables an existing [`Firewall`].
///
/// This will make all the network packets be accepted
/// regardless of the rules defined for the firewall.
///
/// # Examples
///
/// ```
/// use nullnet_firewall::{Firewall, FirewallAction, FirewallDirection};
///
/// let mut firewall = Firewall::new("./samples/firewall.txt").unwrap();
///
/// // here we suppose to have a packet to match against the firewall
/// let packet = [/* ... */];
///
/// // disable the firewall
/// firewall.disable();
///
/// // a disabled firewall will accept everything
/// assert_eq!(
/// firewall.resolve_packet(&packet, FirewallDirection::IN),
/// FirewallAction::ACCEPT
/// );
/// ```
pub fn disable(&mut self) {
self.enabled = false;
}
/// Enables an existing [`Firewall`].
///
/// When a new firewall is created, it's enabled by default.
///
/// When the firewall is enabled, the actions to take for network packets are determined
/// according to the specified rules.
///
/// # Examples
///
/// ```
/// use nullnet_firewall::Firewall;
///
/// // a new firewall is enabled by default
/// let mut firewall = Firewall::new("./samples/firewall.txt").unwrap();
///
/// // disable the firewall
/// firewall.disable();
///
/// /* ... */
///
/// // enable the firewall again
/// firewall.enable();
/// ```
pub fn enable(&mut self) {
self.enabled = true;
}
/// Sets the input policy for an existing [`Firewall`].
///
/// # Arguments
///
/// * `policy` - The policy to use for incoming packets that don't match any of the specified rules.
///
/// # Examples
///
/// ```
/// use nullnet_firewall::{Firewall, FirewallAction};
///
/// let mut firewall = Firewall::new("./samples/firewall.txt").unwrap();
///
/// // set the firewall input policy
/// firewall.policy_in(FirewallAction::DENY);
/// ```
pub fn policy_in(&mut self, policy: FirewallAction) {
self.policy_in = policy;
}
/// Sets the output policy for an existing [`Firewall`].
///
/// # Arguments
///
/// * `policy` - The policy to use for outgoing packets that don't match any of the specified rules.
///
/// # Examples
///
/// ```
/// use nullnet_firewall::{Firewall, FirewallAction};
///
/// let mut firewall = Firewall::new("./samples/firewall.txt").unwrap();
///
/// // set the firewall output policy
/// firewall.policy_out(FirewallAction::ACCEPT);
/// ```
pub fn policy_out(&mut self, policy: FirewallAction) {
self.policy_out = policy;
}
/// Sets the [`DataLink`] type for an existing [`Firewall`].
///
/// As default, a firewall will try to parse packets considering them Ethernet frames; if different kinds of packets
/// want to be inspected, it's necessary to set the corresponding data link type via this method.
///
/// # Arguments
///
/// * `data_link` - The data link type that'll be used to parse packets.
///
/// # Examples
///
/// ```
/// use nullnet_firewall::{DataLink, Firewall};
///
/// let mut firewall = Firewall::new("./samples/firewall.txt").unwrap();
///
/// // let the firewall know that submitted packets start with an IP header
/// firewall.data_link(DataLink::RawIP);
/// ```
pub fn data_link(&mut self, data_link: DataLink) {
self.data_link = data_link;
}
/// Enables or disables logging.
///
/// If enabled (default) packets will be printed in stdout and will be logged into a DB.
///
/// # Arguments
///
/// * `log` - Whether the log activity should be enabled or not.
///
/// # Examples
///
/// ```
/// use nullnet_firewall::{Firewall};
///
/// let mut firewall = Firewall::new("./samples/firewall.txt").unwrap();
///
/// // disable logging
/// firewall.log(false);
/// ```
pub fn log(&mut self, log: bool) {
self.log = log;
}
}
#[cfg(test)]
mod tests {
use std::sync::mpsc;
use std::sync::mpsc::{Receiver, Sender};
use crate::utils::raw_packets::test_packets::{
ARP_PACKET, ICMP_PACKET, TCP_PACKET, UDP_IPV6_PACKET,
};
use crate::{DataLink, Firewall, LogEntry};
use crate::{FirewallAction, FirewallDirection, FirewallRule};
const TEST_FILE_1: &str = "./samples/firewall_for_tests_1.txt";
const TEST_FILE_2: &str = "./samples/firewall_for_tests_2.txt";
const TEST_FILE_3: &str = "./samples/firewall_for_tests_3.txt";
#[test]
fn test_new_firewall_from_file_1() {
let rules = vec![
FirewallRule::new("OUT REJECT --source 192.168.200.135 --sport 6700:6800,8080").unwrap(),
FirewallRule::new("OUT REJECT --source 192.168.200.135 --sport 6700:6800,8080 --dport 1,2,2000").unwrap(),
FirewallRule::new("+ OUT DENY --source 192.168.200.135-192.168.200.140 --sport 6700:6800,8080 --dport 1,2,2000").unwrap(),
FirewallRule::new("OUT REJECT --source 192.168.200.135 --sport 6750:6800,8080 --dest 192.168.200.21 --dport 1,2,2000").unwrap(),
FirewallRule::new("IN ACCEPT --source 2.1.1.2 --dest 2.1.1.1 --proto 1 --icmp-type 8").unwrap(),
FirewallRule::new("+ IN REJECT --source 2.1.1.2 --dest 2.1.1.1 --proto 1 --icmp-type 8").unwrap(),
FirewallRule::new("IN ACCEPT --source 2.1.1.2 --dest 2.1.1.1 --proto 1 --icmp-type 9").unwrap(),
FirewallRule::new("IN ACCEPT --source 2.1.1.2 --dest 2.1.1.1 --proto 58 --icmp-type 8").unwrap(),
FirewallRule::new("OUT REJECT").unwrap(),
FirewallRule::new("IN ACCEPT").unwrap(),
];
let mut firewall_from_file = Firewall::new(TEST_FILE_1).unwrap();
assert_eq!(firewall_from_file.rules, rules);
assert!(firewall_from_file.enabled);
assert_eq!(firewall_from_file.policy_out, FirewallAction::default());
assert_eq!(firewall_from_file.policy_in, FirewallAction::default());
firewall_from_file.disable();
firewall_from_file.policy_in(FirewallAction::DENY);
firewall_from_file.policy_out(FirewallAction::REJECT);
assert!(!firewall_from_file.enabled);
assert_eq!(firewall_from_file.policy_in, FirewallAction::DENY);
assert_eq!(firewall_from_file.policy_out, FirewallAction::REJECT);
firewall_from_file.enable();
assert!(firewall_from_file.enabled);
}
#[test]
fn test_firewall_determine_action_for_packets_file_1() {
let mut firewall = Firewall::new(TEST_FILE_1).unwrap();
firewall.policy_in(FirewallAction::DENY);
firewall.policy_out(FirewallAction::ACCEPT);
assert_eq!(firewall.data_link, DataLink::Ethernet);
// tcp packet
assert_eq!(
firewall.resolve_packet(&TCP_PACKET, FirewallDirection::IN),
FirewallAction::ACCEPT
);
assert_eq!(
firewall.resolve_packet(&TCP_PACKET, FirewallDirection::OUT),
FirewallAction::DENY
);
// icmp packet
assert_eq!(
firewall.resolve_packet(&ICMP_PACKET, FirewallDirection::IN),
FirewallAction::REJECT
);
assert_eq!(
firewall.resolve_packet(&ICMP_PACKET, FirewallDirection::OUT),
FirewallAction::REJECT
);
// arp packet
assert_eq!(
firewall.resolve_packet(&ARP_PACKET, FirewallDirection::IN),
FirewallAction::ACCEPT
);
assert_eq!(
firewall.resolve_packet(&ARP_PACKET, FirewallDirection::OUT),
FirewallAction::REJECT
);
}
#[test]
fn test_firewall_determine_action_for_packets_file_1_with_data_link_raw_ip() {
let mut firewall = Firewall::new(TEST_FILE_1).unwrap();
firewall.data_link(DataLink::RawIP);
firewall.policy_in(FirewallAction::DENY);
firewall.policy_out(FirewallAction::ACCEPT);
assert_eq!(firewall.data_link, DataLink::RawIP);
// tcp packet
assert_eq!(
firewall.resolve_packet(&TCP_PACKET[14..], FirewallDirection::IN),
FirewallAction::ACCEPT
);
assert_eq!(
firewall.resolve_packet(&TCP_PACKET[14..], FirewallDirection::OUT),
FirewallAction::DENY
);
// icmp packet
assert_eq!(
firewall.resolve_packet(&ICMP_PACKET[14..], FirewallDirection::IN),
FirewallAction::REJECT
);
assert_eq!(
firewall.resolve_packet(&ICMP_PACKET[14..], FirewallDirection::OUT),
FirewallAction::REJECT
);
}
#[test]
fn test_firewall_determine_action_for_packets_file_2() {
let mut firewall = Firewall::new(TEST_FILE_2).unwrap();
firewall.policy_in(FirewallAction::DENY);
firewall.policy_out(FirewallAction::ACCEPT);
// tcp packet
assert_eq!(
firewall.resolve_packet(&TCP_PACKET, FirewallDirection::IN),
FirewallAction::DENY
);
assert_eq!(
firewall.resolve_packet(&TCP_PACKET, FirewallDirection::OUT),
FirewallAction::DENY
);
// icmp packet
assert_eq!(
firewall.resolve_packet(&ICMP_PACKET, FirewallDirection::IN),
FirewallAction::ACCEPT
);
assert_eq!(
firewall.resolve_packet(&ICMP_PACKET, FirewallDirection::OUT),
FirewallAction::ACCEPT
);
// arp packet
assert_eq!(
firewall.resolve_packet(&ARP_PACKET, FirewallDirection::IN),
FirewallAction::DENY
);
assert_eq!(
firewall.resolve_packet(&ARP_PACKET, FirewallDirection::OUT),
FirewallAction::ACCEPT
);
}
#[test]
fn test_firewall_determine_action_for_packets_file_3() {
let mut firewall = Firewall::new(TEST_FILE_3).unwrap();
// ipv6 packet
assert_eq!(
firewall.resolve_packet(&UDP_IPV6_PACKET, FirewallDirection::IN),
FirewallAction::DENY
);
assert_eq!(
firewall.resolve_packet(&UDP_IPV6_PACKET, FirewallDirection::OUT),
FirewallAction::ACCEPT
);
// tcp packet
assert_eq!(
firewall.resolve_packet(&TCP_PACKET, FirewallDirection::IN),
FirewallAction::default()
);
assert_eq!(
firewall.resolve_packet(&TCP_PACKET, FirewallDirection::OUT),
FirewallAction::default()
);
// change default policies
firewall.policy_in(FirewallAction::DENY);
firewall.policy_out(FirewallAction::REJECT);
// ipv6 packet
assert_eq!(
firewall.resolve_packet(&UDP_IPV6_PACKET, FirewallDirection::IN),
FirewallAction::DENY
);
assert_eq!(
firewall.resolve_packet(&UDP_IPV6_PACKET, FirewallDirection::OUT),
FirewallAction::ACCEPT
);
// tcp packet
assert_eq!(
firewall.resolve_packet(&TCP_PACKET, FirewallDirection::IN),
FirewallAction::DENY
);
assert_eq!(
firewall.resolve_packet(&TCP_PACKET, FirewallDirection::OUT),
FirewallAction::REJECT
);
}
#[test]
fn test_firewall_determine_action_for_packets_while_disabled() {
let mut firewall = Firewall::new(TEST_FILE_1).unwrap();
firewall.policy_in(FirewallAction::REJECT); // doesn't matter
firewall.policy_out(FirewallAction::REJECT); // doesn't matter
firewall.disable(); // always accept
// tcp packet
assert_eq!(
firewall.resolve_packet(&TCP_PACKET, FirewallDirection::IN),
FirewallAction::ACCEPT
);
assert_eq!(
firewall.resolve_packet(&TCP_PACKET, FirewallDirection::OUT),
FirewallAction::ACCEPT
);
// icmp packet
assert_eq!(
firewall.resolve_packet(&ICMP_PACKET, FirewallDirection::IN),
FirewallAction::ACCEPT
);
assert_eq!(
firewall.resolve_packet(&ICMP_PACKET, FirewallDirection::OUT),
FirewallAction::ACCEPT
);
// arp packet
assert_eq!(
firewall.resolve_packet(&ARP_PACKET, FirewallDirection::IN),
FirewallAction::ACCEPT
);
assert_eq!(
firewall.resolve_packet(&ARP_PACKET, FirewallDirection::OUT),
FirewallAction::ACCEPT
);
}
#[test]
fn test_firewall_rules_precedence() {
let (tx, _rx): (Sender<LogEntry>, Receiver<LogEntry>) = mpsc::channel();
let mut firewall = Firewall {
rules: vec![],
enabled: true,
policy_in: Default::default(),
policy_out: Default::default(),
tx,
data_link: Default::default(),
log: true,
};
let rules_1 = vec![
// no quick, first match wins
FirewallRule::new("OUT DENY --source 192.168.200.135 --sport 6700:6800,8080").unwrap(),
FirewallRule::new("OUT ACCEPT --source 192.168.200.135 --sport 6700:6800,8080")
.unwrap(),
FirewallRule::new("OUT REJECT --source 192.168.200.135 --sport 6700:6800,8080")
.unwrap(),
];
firewall = Firewall {
rules: rules_1,
..firewall
};
assert_eq!(
firewall.resolve_packet(&TCP_PACKET, FirewallDirection::OUT),
FirewallAction::DENY
);
assert_eq!(
firewall.resolve_packet(&TCP_PACKET, FirewallDirection::IN),
FirewallAction::default()
);
let rules_2 = vec![
// quick match wins
FirewallRule::new("+ OUT DENY --source 192.168.200.135 --sport 6700:6800,8080")
.unwrap(),
FirewallRule::new("OUT ACCEPT --source 192.168.200.135 --sport 6700:6800,8080")
.unwrap(),
FirewallRule::new("OUT REJECT --source 192.168.200.135 --sport 6700:6800,8080")
.unwrap(),
];
firewall = Firewall {
rules: rules_2,
..firewall
};
assert_eq!(
firewall.resolve_packet(&TCP_PACKET, FirewallDirection::OUT),
FirewallAction::DENY
);
let rules_3 = vec![
// quick match wins even if after other matches
FirewallRule::new("OUT DENY --source 192.168.200.135 --sport 6700:6800,8080").unwrap(),
FirewallRule::new("OUT ACCEPT --source 192.168.200.135 --sport 6700:6800,8080")
.unwrap(),
FirewallRule::new("+ OUT REJECT --source 192.168.200.135 --sport 6700:6800,8080")
.unwrap(),
];
firewall = Firewall {
rules: rules_3,
..firewall
};
assert_eq!(
firewall.resolve_packet(&TCP_PACKET, FirewallDirection::OUT),
FirewallAction::REJECT
);
let rules_4 = vec![
// first quick match wins
FirewallRule::new("OUT DENY --source 192.168.200.135 --sport 6700:6800,8080").unwrap(),
FirewallRule::new("+ OUT ACCEPT --source 192.168.200.135 --sport 6700:6800,8080")
.unwrap(),
FirewallRule::new("+ OUT REJECT --source 192.168.200.135 --sport 6700:6800,8080")
.unwrap(),
];
firewall = Firewall {
rules: rules_4,
..firewall
};
assert_eq!(
firewall.resolve_packet(&TCP_PACKET, FirewallDirection::OUT),
FirewallAction::ACCEPT
);
let rules_5 = vec![
// only quick rules, first wins
FirewallRule::new("+ OUT DENY --source 192.168.200.135 --sport 6700:6800,8080")
.unwrap(),
FirewallRule::new("+ OUT ACCEPT --source 192.168.200.135 --sport 6700:6800,8080")
.unwrap(),
FirewallRule::new("+ OUT REJECT --source 192.168.200.135 --sport 6700:6800,8080")
.unwrap(),
];
firewall = Firewall {
rules: rules_5,
..firewall
};
assert_eq!(
firewall.resolve_packet(&TCP_PACKET, FirewallDirection::OUT),
FirewallAction::DENY
);
}
#[test]
fn test_update_firewall_rules() {
let rules_before_update = vec![
FirewallRule::new("OUT REJECT --source 192.168.200.135 --sport 6700:6800,8080").unwrap(),
FirewallRule::new("OUT REJECT --source 192.168.200.135 --sport 6700:6800,8080 --dport 1,2,2000").unwrap(),
FirewallRule::new("+ OUT DENY --source 192.168.200.135-192.168.200.140 --sport 6700:6800,8080 --dport 1,2,2000").unwrap(),
FirewallRule::new("OUT REJECT --source 192.168.200.135 --sport 6750:6800,8080 --dest 192.168.200.21 --dport 1,2,2000").unwrap(),
FirewallRule::new("IN ACCEPT --source 2.1.1.2 --dest 2.1.1.1 --proto 1 --icmp-type 8").unwrap(),
FirewallRule::new("+ IN REJECT --source 2.1.1.2 --dest 2.1.1.1 --proto 1 --icmp-type 8").unwrap(),
FirewallRule::new("IN ACCEPT --source 2.1.1.2 --dest 2.1.1.1 --proto 1 --icmp-type 9").unwrap(),
FirewallRule::new("IN ACCEPT --source 2.1.1.2 --dest 2.1.1.1 --proto 58 --icmp-type 8").unwrap(),
FirewallRule::new("OUT REJECT").unwrap(),
FirewallRule::new("IN ACCEPT").unwrap(),
];
let rules_after_update = vec![
FirewallRule::new("OUT REJECT --dest 3ffe:507:0:1:200:86ff:fe05:800-3ffe:507:0:1:200:86ff:fe05:08dd --sport 545:560,43,53").unwrap(),
FirewallRule::new("+ OUT ACCEPT --dest 3ffe:507:0:1:200:86ff:fe05:800-3ffe:507:0:1:200:86ff:fe05:08dd --sport 545:560,43,53").unwrap(),
FirewallRule::new("OUT DENY --dest 3ffe:507:0:1:200:86ff:fe05:800-3ffe:507:0:1:200:86ff:fe05:08dd --proto 17 --sport 545:560,43,53 --dport 2396").unwrap(),
FirewallRule::new("OUT REJECT --dest 3ffe:507:0:1:200:86ff:fe05:800-3ffe:507:0:1:200:86ff:fe05:08dd --proto 17 --sport 545:560,43,53 --dport 2395").unwrap(),
FirewallRule::new("IN DENY --sport 40:49,53").unwrap(),
FirewallRule::new("IN REJECT --sport 40:49,53 --source 3ffe:501:4819::41,3ffe:501:4819::42").unwrap(),
];
let mut firewall = Firewall::new(TEST_FILE_1).unwrap();
assert_eq!(firewall.rules, rules_before_update);
assert!(firewall.enabled);
assert_eq!(firewall.policy_in, FirewallAction::ACCEPT);
assert_eq!(firewall.policy_out, FirewallAction::ACCEPT);
// update the rules
firewall.update_rules(TEST_FILE_3).unwrap();
assert_eq!(firewall.rules, rules_after_update);
assert!(firewall.enabled);
assert_eq!(firewall.policy_in, FirewallAction::ACCEPT);
assert_eq!(firewall.policy_out, FirewallAction::ACCEPT);
}
#[test]
fn test_log_disable() {
let mut firewall = Firewall::new(TEST_FILE_1).unwrap();
assert!(firewall.log);
firewall.log(false);
assert!(!firewall.log);
firewall.log(true);
assert!(firewall.log);
}
}