├── .github ├── CODE_OF_CONDUCT.md └── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── lib └── .gitkeep └── static ├── .gitkeep └── img └── iptables-packet-flow-ng.png /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at trimstray@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | > _A real community, however, exists only when its members interact in a meaningful way that deepens their understanding of each other and leads to learning._ 4 | 5 | If you would like to support this project, have an interesting idea how to improve the operation of this tool, or if you found some errors - fork this, add your fixes, and add a pull request of your branch to the **master branch**. 6 | 7 | ## Using the issue tracker 8 | 9 | The [issue tracker](https://github.com/trimstray/iptables-essential/issues) is 10 | the preferred channel for bug reports, features requests and submitting pull requests, but please respect the following restrictions: 11 | 12 | * Please **do not** use the issue tracker for personal support requests (use 13 | [Stack Overflow](https://stackoverflow.com) or IRC) 14 | 15 | * Please **do not** derail or troll issues. Keep the discussion on topic and 16 | respect the opinions of others 17 | 18 | ## Signature of commit 19 | 20 | Moving forward all commits to this project must include a "signed-off-by" line indicating the name and email address of the contributor signing off on the change. To enable signatures add the following lines to `.git/hooks/prepare-commit-msg` : 21 | 22 | ``` 23 | SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/- signed-off-by: \1/p') 24 | grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1" 25 | ``` 26 | 27 | ## Pull requests 28 | 29 | When creating a pull request, please heed the following: 30 | 31 | - Base your code on the latest master branch to avoid manual merges 32 | - Code review may ensue in order to help shape your proposal 33 | - Explain the problem and your proposed solution 34 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 trimstray 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

Iptables Essentials: Common Firewall Rules and Commands

2 | 3 |
4 | 5 |

6 | 7 | Pull Requests 8 | 9 | 10 | MIT License 11 | 12 |

13 | 14 |
15 | 16 | ## :ballot_box_with_check: TODO 17 | 18 | - [ ] Add useful Iptables configuration examples 19 | - [x] Add useful Kernel Settings (sysctl) configuration 20 | - [ ] Add links to useful external resources 21 | - [x] Add advanced configuration examples, commands, rules 22 | 23 | **** 24 | 25 | ## Table of Contents 26 | 27 | - [Tools to help you configure Iptables](#tools-to-help-you-configure-iptables) 28 | - [Manuals/Howtos/Tutorials](#manualshowtostutorials) 29 | - [Useful Kernel Settings (sysctl) configuration](#useful-kernel-settings-sysctl-configuration) 30 | * [rp_filter](#rp_filter) 31 | * [log_martians](#log_martians) 32 | * [send_redirects](#send_redirects) 33 | * [accept_source_route](#accept_source_route) 34 | * [accept_redirects](#accept_redirects) 35 | * [tcp_syncookies](#tcp_syncookies) 36 | * [icmp_echo_ignore_broadcasts](#icmp_echo_ignore_broadcasts) 37 | * [ip_forward](#ip_forward) 38 | - [How it works?](#how-it-works) 39 | - [Iptables Rules](#iptables-rules) 40 | * [Saving Rules](#saving-rules) 41 | - [Debian Based](#debian-based) 42 | - [RedHat Based](#redhat-based) 43 | * [List out all of the active iptables rules with verbose](#list-out-all-of-the-active-iptables-rules-with-verbose) 44 | * [List out all of the active iptables rules with numeric lines and verbose](#list-out-all-of-the-active-iptables-rules-with-numeric-lines-and-verbose) 45 | * [Print out all of the active iptables rules](#print-out-all-of-the-active-iptables-rules) 46 | * [List Rules as Tables for INPUT chain](#list-rules-as-tables-for-input-chain) 47 | * [Print all of the rule specifications in the INPUT chain](#print-all-of-the-rule-specifications-in-the-input-chain) 48 | * [Show Packet Counts and Aggregate Size](#show-packet-counts-and-aggregate-size) 49 | * [To display INPUT or OUTPUT chain rules with numeric lines and verbose](#to-display-input-or-output-chain-rules-with-numeric-lines-and-verbose) 50 | * [Delete Rule by Chain and Number](#delete-rule-by-chain-and-number) 51 | * [Delete Rule by Specification](#delete-rule-by-specification) 52 | * [Flush All Rules, Delete All Chains, and Accept All](#flush-all-rules-delete-all-chains-and-accept-all) 53 | * [Flush All Chains](#flush-all-chains) 54 | * [Flush a Single Chain](#flush-a-single-chain) 55 | * [Insert Firewall Rules](#insert-firewall-rules) 56 | * [Allow Loopback Connections](#allow-loopback-connections) 57 | * [Allow Established and Related Incoming Connections](#allow-established-and-related-incoming-connections) 58 | * [Allow Established Outgoing Connections](#allow-established-outgoing-connections) 59 | * [Internal to External](#internal-to-external) 60 | * [Drop Invalid Packets](#drop-invalid-packets) 61 | * [Block an IP Address](#block-an-ip-address) 62 | * [Block and IP Address and Reject](#block-and-ip-address-and-reject) 63 | * [Block Connections to a Network Interface](#block-connections-to-a-network-interface) 64 | * [Allow All Incoming SSH](#allow-all-incoming-ssh) 65 | * [Allow Incoming SSH from Specific IP address or subnet](#allow-incoming-ssh-from-specific-ip-address-or-subnet) 66 | * [Allow Outgoing SSH](#allow-outgoing-ssh) 67 | * [Allow Incoming Rsync from Specific IP Address or Subnet](#allow-incoming-rsync-from-specific-ip-address-or-subnet) 68 | * [Allow All Incoming HTTP](#allow-all-incoming-http) 69 | * [Allow All Incoming HTTPS](#allow-all-incoming-https) 70 | * [Allow All Incoming HTTP and HTTPS](#allow-all-incoming-http-and-https) 71 | * [Allow MySQL from Specific IP Address or Subnet](#allow-mysql-from-specific-ip-address-or-subnet) 72 | * [Allow MySQL to Specific Network Interface](#allow-mysql-to-specific-network-interface) 73 | * [PostgreSQL from Specific IP Address or Subnet](#postgresql-from-specific-ip-address-or-subnet) 74 | * [Allow PostgreSQL to Specific Network Interface](#allow-postgresql-to-specific-network-interface) 75 | * [Block Outgoing SMTP Mail](#block-outgoing-smtp-mail) 76 | * [Allow All Incoming SMTP](#allow-all-incoming-smtp) 77 | * [Allow All Incoming IMAP](#allow-all-incoming-imap) 78 | * [Allow All Incoming IMAPS](#allow-all-incoming-imaps) 79 | * [Allow All Incoming POP3](#allow-all-incoming-pop3) 80 | * [Allow All Incoming POP3S](#allow-all-incoming-pop3s) 81 | * [Drop Private Network Address On Public Interface](#drop-private-network-address-on-public-interface) 82 | * [Drop All Outgoing to Facebook Networks](#drop-all-outgoing-to-facebook-networks) 83 | * [Log and Drop Packets](#log-and-drop-packets) 84 | * [Log and Drop Packets with Limited Number of Log Entries](#log-and-drop-packets-with-limited-number-of-log-entries) 85 | * [Drop or Accept Traffic From Mac Address](#drop-or-accept-traffic-from-mac-address) 86 | * [Block or Allow ICMP Ping Request](#block-or-allow-icmp-ping-request) 87 | * [Specifying Multiple Ports with `multiport`](#specifying-multiple-ports-with-multiport) 88 | * [Load Balancing with `random*` or `nth*`](#load-balancing-with-random-or-nth) 89 | * [Restricting the Number of Connections with `limit` and `iplimit*`](#restricting-the-number-of-connections-with-limit-and-iplimit) 90 | * [Maintaining a List of recent Connections to Match Against](#maintaining-a-list-of-recent-connections-to-match-against) 91 | * [Matching Against a `string*` in a Packet's Data Payload](#matching-against-a-string-in-a-packets-data-payload) 92 | * [Time-based Rules with `time*`](#time-based-rules-with-time) 93 | * [Packet Matching Based on TTL Values](#packet-matching-based-on-ttl-values) 94 | * [Protection against port scanning](#protection-against-port-scanning) 95 | * [SSH brute-force protection](#ssh-brute-force-protection) 96 | * [Syn-flood protection](#syn-flood-protection) 97 | - [Mitigating SYN Floods With SYNPROXY](#mitigating-syn-floods-with-synproxy) 98 | * [Block New Packets That Are Not SYN](#block-new-packets-that-are-not-syn) 99 | * [Force Fragments packets check](#force-fragments-packets-check) 100 | * [XMAS packets](#xmas-packets) 101 | * [Drop all NULL packets](#drop-all-null-packets) 102 | * [Block Uncommon MSS Values](#block-uncommon-mss-values) 103 | * [Block Packets With Bogus TCP Flags](#block-packets-with-bogus-tcp-flags) 104 | * [Block Packets From Private Subnets (Spoofing)](#block-packets-from-private-subnets-spoofing) 105 | - [Advanced configuration examples](#advanced-configuration-examples) 106 | * [Packet handling in Python using NFQUEUE target](#packet-handling-in-python-using-nfqueue-target) 107 | - [ACCEPT all packets from specific source on (filter:INPUT) and DROP everything else](#accept-all-packets-from-specific-source-on-filterinput-and-drop-everything-else) 108 | - [Write your own port knocking script to secure ssh access](#write-your-own-port-knocking-script-to-secure-ssh-access) 109 | 110 | **** 111 | 112 | ## Tools to help you configure Iptables 113 | 114 |

115 |   :small_orange_diamond: Shorewall - advanced gateway/firewall configuration tool for GNU/Linux.
116 |   :small_orange_diamond: Firewalld - provides a dynamically managed firewall.
117 |   :small_orange_diamond: UFW - default firewall configuration tool for Ubuntu.
118 |   :small_orange_diamond: FireHOL - offer simple and powerful configuration for all Linux firewall and traffic shaping requirements.
119 |

120 | 121 | ## Manuals/Howtos/Tutorials 122 | 123 |

124 |   :small_orange_diamond: Best practices: iptables - by Major Hayden
125 |   :small_orange_diamond: An In-Depth Guide to Iptables, the Linux Firewall
126 |   :small_orange_diamond: Advanced Features of netfilter/iptables
127 |   :small_orange_diamond: Linux Firewalls Using iptables
128 |   :small_orange_diamond: Debugging iptables and common firewall pitfalls?
129 |   :small_orange_diamond: Netfilter Hacking HOWTO
130 |   :small_orange_diamond: Per-IP rate limiting with iptables
131 |

132 | 133 | ## Useful Kernel Settings (sysctl) Configuration 134 | 135 | ##### rp_filter 136 | 137 | > _Disable routing triangulation. Respond to queries out the same interface, not another. Also protects against IP spoofing._ 138 | 139 | ```bash 140 | cat << EOF >> /etc/sysctl.d/40-custom.conf 141 | net/ipv4/conf/all/rp_filter = 1 142 | EOF 143 | ``` 144 | 145 | - [rp_filter and LPIC-3 Linux Security](https://www.theurbanpenguin.com/rp_filter-and-lpic-3-linux-security/) 146 | - [Linux kernel rp_filter settings (Reverse path filtering)](https://www.slashroot.in/linux-kernel-rpfilter-settings-reverse-path-filtering) 147 | - [Reverse Path Filtering](http://tldp.org/HOWTO/Adv-Routing-HOWTO/lartc.kernel.rpf.html) 148 | 149 | ##### log_martians 150 | 151 | > _Enable logging of packets with malformed IP addresses._ 152 | 153 | ```bash 154 | cat << EOF >> /etc/sysctl.d/40-custom.conf 155 | net/ipv4/conf/all/log_martians = 1 156 | EOF 157 | ``` 158 | 159 | - [What is the usefulness of logging of martians packet?](https://serverfault.com/questions/570980/what-is-the-usefulness-of-logging-of-martians-packet-e-g-net-ipv4-conf-all-lo) 160 | 161 | ##### send_redirects 162 | 163 | > _Disables sending of all IPv4 ICMP redirected packets on all interfaces._ 164 | 165 | ```bash 166 | cat << EOF >> /etc/sysctl.d/40-custom.conf 167 | net/ipv4/conf/all/send_redirects = 0 168 | EOF 169 | ``` 170 | 171 | - [Disable source routing](https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/security_guide/sect-security_guide-server_security-disable-source-routing) 172 | - [What are ICMP redirects and should they be blocked?](https://askubuntu.com/questions/118273/what-are-icmp-redirects-and-should-they-be-blocked) 173 | 174 | ##### accept_source_route 175 | 176 | > _Disable source routed packets (packets with the Strict Source Route (SSR) or Loose Source Routing (LSR) option set)._ 177 | 178 | ```bash 179 | cat << EOF >> /etc/sysctl.d/40-custom.conf 180 | net/ipv4/conf/all/accept_source_route = 0 181 | EOF 182 | ``` 183 | 184 | - [Disable source routing](https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/security_guide/sect-security_guide-server_security-disable-source-routing) 185 | - [The system must not accept IPv4 source-routed packets by default.](https://www.stigviewer.com/stig/red_hat_enterprise_linux_6/2017-12-08/finding/V-38529) 186 | 187 | ##### accept_redirects 188 | 189 | > _Disable acceptance of ICMP redirects._ 190 | 191 | ```bash 192 | cat << EOF >> /etc/sysctl.d/40-custom.conf 193 | net/ipv4/conf/all/accept_redirects = 0 194 | EOF 195 | ``` 196 | 197 | - [What are ICMP redirects and should they be blocked?](https://askubuntu.com/questions/118273/what-are-icmp-redirects-and-should-they-be-blocked) 198 | - [The Red Hat Enterprise Linux operating system must ignore Internet Protocol version 4 (IPv4) Internet Control Message Protocol (ICMP) redirect messages.](https://www.stigviewer.com/stig/red_hat_enterprise_linux_7/2018-11-28/finding/V-73175) 199 | 200 | ##### tcp_syncookies 201 | 202 | > _Turn on SYN-flood protections (protection from Denial of Service (DOS) attacks)._ 203 | 204 | ```bash 205 | cat << EOF >> /etc/sysctl.d/40-custom.conf 206 | net/ipv4/tcp_syncookies = 1 207 | EOF 208 | ``` 209 | 210 | - [Hardening your TCP/IP Stack Against SYN Floods](https://www.ndchost.com/wiki/server-administration/hardening-tcpip-syn-flood) 211 | - [Linux: Turn On TCP SYN Cookie Protection](https://www.cyberciti.biz/faq/enable-tcp-syn-cookie-protection/) 212 | - [Better alternative for tcp_syncookies in Linux](https://serverfault.com/questions/705504/better-alternative-for-tcp-syncookies-in-linux) 213 | 214 | ##### icmp_echo_ignore_broadcasts 215 | 216 | > _Disable responding to ping broadcasts._ 217 | 218 | ```bash 219 | cat << EOF >> /etc/sysctl.d/40-custom.conf 220 | net/ipv4/icmp_echo_ignore_broadcasts = 1 221 | EOF 222 | ``` 223 | 224 | - [What is ICMP broadcast good for?](https://superuser.com/questions/306065/what-is-icmp-broadcast-good-for) 225 | - [The system must not respond to ICMPv4 sent to a broadcast address.](https://www.stigviewer.com/stig/red_hat_enterprise_linux_6/2018-11-28/finding/V-38535) 226 | 227 | ##### ip_forward 228 | 229 | > _Enable IP routing. Required if your firewall is protecting a network, NAT included._ 230 | 231 | ```bash 232 | cat << EOF >> /etc/sysctl.d/40-custom.conf 233 | net/ipv4/ip_forward = 1 234 | EOF 235 | ``` 236 | 237 | - [Introduction to routers](http://linux-training.be/security/ch10.html) 238 | - [How to Enable IP Forwarding in Linux](http://www.ducea.com/2006/08/01/how-to-enable-ip-forwarding-in-linux/) 239 | - [What is kernel ip forwarding?](https://unix.stackexchange.com/questions/14056/what-is-kernel-ip-forwarding) 240 | 241 | ## How it works? 242 | 243 |

244 | Master 246 |

247 | 248 | ## Iptables Rules 249 | 250 | #### Saving Rules 251 | 252 | ###### Debian Based 253 | 254 | ```bash 255 | netfilter-persistent save 256 | ``` 257 | 258 | ###### RedHat Based 259 | 260 | ```bash 261 | service iptables save 262 | ``` 263 | 264 | #### List out all of the active iptables rules with verbose 265 | 266 | ```bash 267 | iptables -n -L -v 268 | ``` 269 | 270 | #### List out all of the active iptables rules with numeric lines and verbose 271 | 272 | ```bash 273 | iptables -n -L -v --line-numbers 274 | ``` 275 | 276 | #### Print out all of the active iptables rules 277 | 278 | ```bash 279 | iptables -S 280 | ``` 281 | 282 | #### List Rules as Tables for INPUT chain 283 | 284 | ```bash 285 | iptables -L INPUT 286 | ``` 287 | 288 | #### Print all of the rule specifications in the INPUT chain 289 | 290 | ```bash 291 | iptables -S INPUT 292 | ``` 293 | 294 | #### Show Packet Counts and Aggregate Size 295 | 296 | ```bash 297 | iptables -L INPUT -v 298 | ``` 299 | 300 | #### To display INPUT or OUTPUT chain rules with numeric lines and verbose 301 | 302 | ```bash 303 | iptables -L INPUT -n -v 304 | iptables -L OUTPUT -n -v --line-numbers 305 | ``` 306 | 307 | #### Delete Rule by Chain and Number 308 | 309 | ```bash 310 | iptables -D INPUT 10 311 | ``` 312 | 313 | #### Delete Rule by Specification 314 | 315 | ```bash 316 | iptables -D INPUT -m conntrack --ctstate INVALID -j DROP 317 | ``` 318 | 319 | #### Flush All Rules, Delete All Chains, and Accept All 320 | 321 | ```bash 322 | iptables -P INPUT ACCEPT 323 | iptables -P FORWARD ACCEPT 324 | iptables -P OUTPUT ACCEPT 325 | 326 | iptables -t nat -F 327 | iptables -t mangle -F 328 | iptables -F 329 | iptables -X 330 | ``` 331 | 332 | #### Flush All Chains 333 | 334 | ```bash 335 | iptables -F 336 | ``` 337 | 338 | #### Flush a Single Chain 339 | 340 | ```bash 341 | iptables -F INPUT 342 | ``` 343 | 344 | #### Insert Firewall Rules 345 | 346 | ```bash 347 | iptables -I INPUT 2 -s 202.54.1.2 -j DROP 348 | ``` 349 | 350 | #### Allow Loopback Connections 351 | 352 | ```bash 353 | iptables -A INPUT -i lo -j ACCEPT 354 | iptables -A OUTPUT -o lo -j ACCEPT 355 | ``` 356 | 357 | #### Allow Established and Related Incoming Connections 358 | 359 | ```bash 360 | iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT 361 | ``` 362 | 363 | #### Allow Established Outgoing Connections 364 | 365 | ```bash 366 | iptables -A OUTPUT -m conntrack --ctstate ESTABLISHED -j ACCEPT 367 | ``` 368 | 369 | #### Internal to External 370 | 371 | ```bash 372 | iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT 373 | ``` 374 | 375 | #### Drop Invalid Packets 376 | 377 | ```bash 378 | iptables -A INPUT -m conntrack --ctstate INVALID -j DROP 379 | ``` 380 | 381 | #### Block an IP Address 382 | 383 | ```bash 384 | iptables -A INPUT -s 192.168.252.10 -j DROP 385 | ``` 386 | 387 | #### Block and IP Address and Reject 388 | 389 | ```bash 390 | iptables -A INPUT -s 192.168.252.10 -j REJECT 391 | ``` 392 | 393 | #### Block Connections to a Network Interface 394 | 395 | ```bash 396 | iptables -A INPUT -i eth0 -s 192.168.252.10 -j DROP 397 | ``` 398 | 399 | #### Allow All Incoming SSH 400 | 401 | ```bash 402 | iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT 403 | iptables -A OUTPUT -p tcp --sport 22 -m conntrack --ctstate ESTABLISHED -j ACCEPT 404 | ``` 405 | 406 | #### Allow Incoming SSH from Specific IP address or subnet 407 | 408 | ```bash 409 | iptables -A INPUT -p tcp -s 192.168.240.0/24 --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT 410 | iptables -A OUTPUT -p tcp --sport 22 -m conntrack --ctstate ESTABLISHED -j ACCEPT 411 | ``` 412 | 413 | #### Allow Outgoing SSH 414 | 415 | ```bash 416 | iptables -A OUTPUT -p tcp --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT 417 | iptables -A INPUT -p tcp --sport 22 -m conntrack --ctstate ESTABLISHED -j ACCEPT 418 | ``` 419 | 420 | #### Allow Incoming Rsync from Specific IP Address or Subnet 421 | 422 | ```bash 423 | iptables -A INPUT -p tcp -s 192.168.240.0/24 --dport 873 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT 424 | iptables -A OUTPUT -p tcp --sport 873 -m conntrack --ctstate ESTABLISHED -j ACCEPT 425 | ``` 426 | 427 | #### Allow All Incoming HTTP 428 | 429 | ```bash 430 | iptables -A INPUT -p tcp --dport 80 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT 431 | iptables -A OUTPUT -p tcp --sport 80 -m conntrack --ctstate ESTABLISHED -j ACCEPT 432 | ``` 433 | 434 | #### Allow All Incoming HTTPS 435 | 436 | ```bash 437 | iptables -A INPUT -p tcp --dport 443 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT 438 | iptables -A OUTPUT -p tcp --sport 443 -m conntrack --ctstate ESTABLISHED -j ACCEPT 439 | ``` 440 | 441 | #### Allow All Incoming HTTP and HTTPS 442 | 443 | ```bash 444 | iptables -A INPUT -p tcp -m multiport --dports 80,443 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT 445 | iptables -A OUTPUT -p tcp -m multiport --dports 80,443 -m conntrack --ctstate ESTABLISHED -j ACCEPT 446 | ``` 447 | 448 | #### Allow MySQL from Specific IP Address or Subnet 449 | 450 | ```bash 451 | iptables -A INPUT -p tcp -s 192.168.240.0/24 --dport 3306 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT 452 | iptables -A OUTPUT -p tcp --sport 3306 -m conntrack --ctstate ESTABLISHED -j ACCEPT 453 | ``` 454 | 455 | #### Allow MySQL to Specific Network Interface 456 | 457 | ```bash 458 | iptables -A INPUT -i eth1 -p tcp --dport 3306 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT 459 | iptables -A OUTPUT -o eth1 -p tcp --sport 3306 -m conntrack --ctstate ESTABLISHED -j ACCEPT 460 | ``` 461 | 462 | #### PostgreSQL from Specific IP Address or Subnet 463 | 464 | ```bash 465 | iptables -A INPUT -p tcp -s 192.168.240.0/24 --dport 5432 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT 466 | iptables -A OUTPUT -p tcp --sport 5432 -m conntrack --ctstate ESTABLISHED -j ACCEPT 467 | ``` 468 | 469 | #### Allow PostgreSQL to Specific Network Interface 470 | 471 | ```bash 472 | iptables -A INPUT -i eth1 -p tcp --dport 5432 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT 473 | iptables -A OUTPUT -o eth1 -p tcp --sport 5432 -m conntrack --ctstate ESTABLISHED -j ACCEPT 474 | ``` 475 | 476 | #### Block Outgoing SMTP Mail 477 | 478 | ```bash 479 | iptables -A OUTPUT -p tcp --dport 25 -j REJECT 480 | ``` 481 | 482 | #### Allow All Incoming SMTP 483 | 484 | ```bash 485 | iptables -A INPUT -p tcp --dport 25 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT 486 | iptables -A OUTPUT -p tcp --sport 25 -m conntrack --ctstate ESTABLISHED -j ACCEPT 487 | ``` 488 | 489 | #### Allow All Incoming IMAP 490 | 491 | ```bash 492 | iptables -A INPUT -p tcp --dport 143 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT 493 | iptables -A OUTPUT -p tcp --sport 143 -m conntrack --ctstate ESTABLISHED -j ACCEPT 494 | ``` 495 | 496 | #### Allow All Incoming IMAPS 497 | 498 | ```bash 499 | iptables -A INPUT -p tcp --dport 993 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT 500 | iptables -A OUTPUT -p tcp --sport 993 -m conntrack --ctstate ESTABLISHED -j ACCEPT 501 | ``` 502 | 503 | #### Allow All Incoming POP3 504 | 505 | ```bash 506 | iptables -A INPUT -p tcp --dport 110 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT 507 | iptables -A OUTPUT -p tcp --sport 110 -m conntrack --ctstate ESTABLISHED -j ACCEPT 508 | ``` 509 | 510 | #### Allow All Incoming POP3S 511 | 512 | ```bash 513 | iptables -A INPUT -p tcp --dport 995 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT 514 | iptables -A OUTPUT -p tcp --sport 995 -m conntrack --ctstate ESTABLISHED -j ACCEPT 515 | ``` 516 | 517 | #### Drop Private Network Address On Public Interface 518 | 519 | ```bash 520 | iptables -A INPUT -i eth1 -s 192.168.0.0/24 -j DROP 521 | iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j DROP 522 | ``` 523 | 524 | #### Drop All Outgoing to Facebook Networks 525 | 526 | Get Facebook AS: 527 | 528 | ```bash 529 | whois -h v4.whois.cymru.com " -v $(host facebook.com | grep "has address" | cut -d " " -f4)" | tail -n1 | awk '{print $1}' 530 | ``` 531 | 532 | Drop: 533 | 534 | ```bash 535 | for i in $(whois -h whois.radb.net -- '-i origin AS32934' | grep "^route:" | cut -d ":" -f2 | sed -e 's/^[ \t]*//' | sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4 | cut -d ":" -f2 | sed 's/$/;/') ; do 536 | 537 | iptables -A OUTPUT -s "$i" -j REJECT 538 | 539 | done 540 | ``` 541 | 542 | #### Log and Drop Packets 543 | 544 | ```bash 545 | iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j LOG --log-prefix "IP_SPOOF A: " 546 | iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j DROP 547 | ``` 548 | 549 | By default everything is logged to `/var/log/messages` file: 550 | 551 | ```bash 552 | tail -f /var/log/messages 553 | grep --color 'IP SPOOF' /var/log/messages 554 | ``` 555 | 556 | #### Log and Drop Packets with Limited Number of Log Entries 557 | 558 | ```bash 559 | iptables -A INPUT -i eth1 -s 10.0.0.0/8 -m limit --limit 5/m --limit-burst 7 -j LOG --log-prefix "IP_SPOOF A: " 560 | iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j DROP 561 | ``` 562 | 563 | #### Drop or Accept Traffic From Mac Address 564 | 565 | ```bash 566 | iptables -A INPUT -m mac --mac-source 00:0F:EA:91:04:08 -j DROP 567 | iptables -A INPUT -p tcp --destination-port 22 -m mac --mac-source 00:0F:EA:91:04:07 -j ACCEPT 568 | ``` 569 | 570 | #### Block or Allow ICMP Ping Request 571 | 572 | ```bash 573 | iptables -A INPUT -p icmp --icmp-type echo-request -j DROP 574 | iptables -A INPUT -i eth1 -p icmp --icmp-type echo-request -j DROP 575 | ``` 576 | 577 | #### Specifying Multiple Ports with `multiport` 578 | 579 | ```bash 580 | iptables -A INPUT -i eth0 -p tcp -m state --state NEW -m multiport --dports ssh,smtp,http,https -j ACCEPT 581 | ``` 582 | 583 | #### Load Balancing with `random*` or `nth*` 584 | 585 | ```bash 586 | _ips=("172.31.250.10" "172.31.250.11" "172.31.250.12" "172.31.250.13") 587 | 588 | for ip in "${_ips[@]}" ; do 589 | iptables -A PREROUTING -i eth0 -p tcp --dport 80 -m state --state NEW -m nth --counter 0 --every 4 --packet 0 \ 590 | -j DNAT --to-destination ${ip}:80 591 | done 592 | ``` 593 | 594 | or 595 | 596 | ```bash 597 | _ips=("172.31.250.10" "172.31.250.11" "172.31.250.12" "172.31.250.13") 598 | 599 | for ip in "${_ips[@]}" ; do 600 | iptables -A PREROUTING -i eth0 -p tcp --dport 80 -m state --state NEW -m random --average 25 \ 601 | -j DNAT --to-destination ${ip}:80 602 | done 603 | ``` 604 | 605 | #### Restricting the Number of Connections with `limit` and `iplimit*` 606 | 607 | ```bash 608 | iptables -A FORWARD -m state --state NEW -p tcp -m multiport --dport http,https -o eth0 -i eth1 \ 609 | -m limit --limit 20/hour --limit-burst 5 -j ACCEPT 610 | ``` 611 | 612 | or 613 | 614 | ```bash 615 | iptables -A INPUT -p tcp -m state --state NEW --dport http -m iplimit --iplimit-above 5 -j DROP 616 | ``` 617 | 618 | #### Maintaining a List of recent Connections to Match Against 619 | 620 | ```bash 621 | iptables -A FORWARD -m recent --name portscan --rcheck --seconds 100 -j DROP 622 | iptables -A FORWARD -p tcp -i eth0 --dport 443 -m recent --name portscan --set -j DROP 623 | ``` 624 | 625 | #### Matching Against a `string*` in a Packet's Data Payload 626 | 627 | ```bash 628 | iptables -A FORWARD -m string --string '.com' -j DROP 629 | iptables -A FORWARD -m string --string '.exe' -j DROP 630 | ``` 631 | 632 | #### Time-based Rules with `time*` 633 | 634 | ```bash 635 | iptables -A FORWARD -p tcp -m multiport --dport http,https -o eth0 -i eth1 \ 636 | -m time --timestart 21:30 --timestop 22:30 --days Mon,Tue,Wed,Thu,Fri -j ACCEPT 637 | ``` 638 | 639 | #### Packet Matching Based on TTL Values 640 | 641 | ```bash 642 | iptables -A INPUT -s 1.2.3.4 -m ttl --ttl-lt 40 -j REJECT 643 | ``` 644 | 645 | #### Protection against port scanning 646 | 647 | ```bash 648 | iptables -N port-scanning 649 | iptables -A port-scanning -p tcp --tcp-flags SYN,ACK,FIN,RST RST -m limit --limit 1/s --limit-burst 2 -j RETURN 650 | iptables -A port-scanning -j DROP 651 | ``` 652 | 653 | #### SSH brute-force protection 654 | 655 | ```bash 656 | iptables -A INPUT -p tcp --dport ssh -m conntrack --ctstate NEW -m recent --set 657 | iptables -A INPUT -p tcp --dport ssh -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 10 -j DROP 658 | ``` 659 | 660 | #### Syn-flood protection 661 | 662 | ```bash 663 | iptables -N syn_flood 664 | 665 | iptables -A INPUT -p tcp --syn -j syn_flood 666 | iptables -A syn_flood -m limit --limit 1/s --limit-burst 3 -j RETURN 667 | iptables -A syn_flood -j DROP 668 | 669 | iptables -A INPUT -p icmp -m limit --limit 1/s --limit-burst 1 -j ACCEPT 670 | 671 | iptables -A INPUT -p icmp -m limit --limit 1/s --limit-burst 1 -j LOG --log-prefix PING-DROP: 672 | iptables -A INPUT -p icmp -j DROP 673 | 674 | iptables -A OUTPUT -p icmp -j ACCEPT 675 | ``` 676 | 677 | ##### Mitigating SYN Floods With SYNPROXY 678 | 679 | ```bash 680 | iptables -t raw -A PREROUTING -p tcp -m tcp --syn -j CT --notrack 681 | iptables -A INPUT -p tcp -m tcp -m conntrack --ctstate INVALID,UNTRACKED -j SYNPROXY --sack-perm --timestamp --wscale 7 --mss 1460 682 | iptables -A INPUT -m conntrack --ctstate INVALID -j DROP 683 | ``` 684 | 685 | #### Block New Packets That Are Not SYN 686 | 687 | ```bash 688 | iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP 689 | ``` 690 | 691 | or 692 | 693 | ```bash 694 | iptables -t mangle -A PREROUTING -p tcp ! --syn -m conntrack --ctstate NEW -j DROP 695 | ``` 696 | 697 | #### Force Fragments packets check 698 | 699 | ```bash 700 | iptables -A INPUT -f -j DROP 701 | ``` 702 | 703 | #### XMAS packets 704 | 705 | ```bash 706 | iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP 707 | ``` 708 | 709 | #### Drop all NULL packets 710 | 711 | ```bash 712 | iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP 713 | ``` 714 | 715 | #### Block Uncommon MSS Values 716 | 717 | ```bash 718 | iptables -t mangle -A PREROUTING -p tcp -m conntrack --ctstate NEW -m tcpmss ! --mss 536:65535 -j DROP 719 | ``` 720 | 721 | #### Block Packets With Bogus TCP Flags 722 | 723 | ```bash 724 | iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j DROP 725 | iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,SYN FIN,SYN -j DROP 726 | iptables -t mangle -A PREROUTING -p tcp --tcp-flags SYN,RST SYN,RST -j DROP 727 | iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,RST FIN,RST -j DROP 728 | iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,ACK FIN -j DROP 729 | iptables -t mangle -A PREROUTING -p tcp --tcp-flags ACK,URG URG -j DROP 730 | iptables -t mangle -A PREROUTING -p tcp --tcp-flags ACK,FIN FIN -j DROP 731 | iptables -t mangle -A PREROUTING -p tcp --tcp-flags ACK,PSH PSH -j DROP 732 | iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL ALL -j DROP 733 | iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL NONE -j DROP 734 | iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL FIN,PSH,URG -j DROP 735 | iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL SYN,FIN,PSH,URG -j DROP 736 | iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG -j DROP 737 | ``` 738 | 739 | #### Block Packets From Private Subnets (Spoofing) 740 | 741 | ```bash 742 | _subnets=("224.0.0.0/3" "169.254.0.0/16" "172.16.0.0/12" "192.0.2.0/24" "192.168.0.0/16" "10.0.0.0/8" "0.0.0.0/8" "240.0.0.0/5") 743 | 744 | for _sub in "${_subnets[@]}" ; do 745 | iptables -t mangle -A PREROUTING -s "$_sub" -j DROP 746 | done 747 | iptables -t mangle -A PREROUTING -s 127.0.0.0/8 ! -i lo -j DROP 748 | ``` 749 | 750 | ## Advanced configuration examples 751 | 752 | ### Packet handling in Python using NFQUEUE target 753 | 754 | > _This target passes the packet to userspace using the nfnetlink_queue handler. The packet is put into the queue identified by its 16-bit queue number. Userspace can inspect and modify the packet if desired. Userspace must then drop or reinject the packet into the kernel._ 755 | 756 | #### ACCEPT all packets from specific source on (filter:INPUT) and DROP everything else 757 | 758 | > _This rule forwards all filter:INPUT packets to queue 1 with NFQUEUE target._ 759 | 760 | ```bash 761 | iptables -A INPUT -j NFQUEUE --queue-num 1 762 | ``` 763 | 764 | > _Script to bind to netfilter queue 1 and handle packets._ 765 | 766 | ```python 767 | #!/usr/bin/python3 768 | 769 | from netfilterqueue import NetfilterQueue 770 | from scapy.all import * 771 | 772 | def packetanalyzer(pkt): 773 | ip=IP(pkt.get_payload()) 774 | if(ip.src=="192.168.122.1"): 775 | print(f"New packet from {ip.src}") 776 | pkt.accept() 777 | else: 778 | pkt.drop() 779 | 780 | nfqueue=NetfilterQueue() 781 | nfqueue.bind(1, packetanalyzer) 782 | nfqueue.run() 783 | ``` 784 | 785 | #### Write your own port knocking script to secure ssh access 786 | 787 | > _DROP all ssh requests and send secret port requests to user-space with NFQUEUE target._ 788 | 789 | ```bash 790 | iptables -t filter -I INPUT -p tcp --dport 22 -j DROP 791 | iptables -t raw -I PREROUTING -p tcp --sport 65534 --dport 65535 -j NFQUEUE --queue-num 1 792 | ``` 793 | 794 | > _This script capture packet from netfilter queue 1 and check SOURCEPORT and SECRETPORT for port knocking and allow source to connect to ssh for EXPIRETIME, default is 30 minutes. 795 | 796 | ```python 797 | #!/usr/bin/python3 798 | 799 | from os import system 800 | from netfilterqueue import NetfilterQueue 801 | from scapy.layers.inet import IP 802 | from time import time 803 | 804 | SOURCEPORT=65534 805 | SECRETPORT=65535 806 | EXPIRETIME=30 807 | ALLOWED={} 808 | 809 | def portknocking(pkt): 810 | packet=IP(pkt.get_payload()) 811 | currtime=time() 812 | for item in list(ALLOWED): 813 | if(currtime-ALLOWED[item] >= EXPIRETIME*60): 814 | del ALLOWED[item] 815 | if(packet.sport==SOURCEPORT and packet.dport==SECRETPORT and packet.src not in ALLOWED): 816 | print(f"Port {packet.dport} knocked by {packet.src}:{packet.sport}") 817 | system(f"iptables -I INPUT -p tcp --dport 22 -s {packet.src} -j ACCEPT") 818 | system(f"echo 'iptables -D INPUT -p tcp --dport 22 -s {packet.src} -j ACCEPT' | at now + {EXPIRETIME} minutes") 819 | ALLOWED[packet.src]=time() 820 | pkt.drop() 821 | 822 | nfqueue=NetfilterQueue() 823 | nfqueue.bind(1, portknocking) 824 | 825 | try: 826 | nfqueue.run() 827 | except KeyboardInterrupt: 828 | print("\nExit with Keyboard Interrupt") 829 | ``` 830 | 831 | > _To knocking port and allow ssh connections from your computer just execute this command:_ 832 | 833 | ```bash 834 | nc -p 65534 SERVER 65535 835 | ``` 836 | -------------------------------------------------------------------------------- /lib/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trimstray/iptables-essentials/02a83e46d3e00f4291ae8303ddabc93d4aa4d227/lib/.gitkeep -------------------------------------------------------------------------------- /static/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trimstray/iptables-essentials/02a83e46d3e00f4291ae8303ddabc93d4aa4d227/static/.gitkeep -------------------------------------------------------------------------------- /static/img/iptables-packet-flow-ng.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trimstray/iptables-essentials/02a83e46d3e00f4291ae8303ddabc93d4aa4d227/static/img/iptables-packet-flow-ng.png --------------------------------------------------------------------------------