Showing posts with label infosec. Show all posts
Showing posts with label infosec. Show all posts

ETHICAL HACKING


Elements of Information Security:
Confidentiality:
Assurance that the information is accessible only to those authorized to have access. Confidentiality breaches may occur due to improper data handling or a hacking attempt.

Integrity:
The trustworthiness of data or resources in terms of preventing improper and unauthorized access. Assurance that information can be relied upon to be sufficiently accurate for its purpose.

Availability:
Assurance that the systems responsible for delivering, storing and processing information are accessible when required by the authorized users.

Level of security in any system can be defined by the strength of three components,
Security
Functionality
Usability

Effects of Hacking:
Damage to information and theft of information
Attackers may steal corporate secrets and sell them to competitors, compromise critical financial information, and leak to the rivals.

Who is a Hacker?
Intelligent individuals with excellent computer skills, with the ability to create and explore into the computer’s software and hardware.
For some hackers, hacking is a hobby to see how many computers or networks they can compromise.
Their intention can either be to gain knowledge or to poke around to do illegal things.
Some do hacking with malicious intent behind their escapades, like stealing business data, credit card information, social security numbers, email passwords etc.


Hacker Classes:
Black Hats: Individuals with extraordinary computing skills, resorting to malicious or destructive activities and are also known as crackers.
White Hats: Individuals professing hacker skills and using them for defensive purpose and are also known as security analysts.
Gray Hats: Individuals who work both offensively and defensively at various times.
Suicide Hackers: Individuals who aim to bring down critical infrastructure for a “cause” and are not worried about facing 30 years in jail for their actions.

Hacktivism:
Hacktivism is an act of promoting a political agenda by hacking, especially by defacing or disabling website.
Common targets include government agencies, multinational corporations, or any other entity perceived as bad or wrong by these groups or individuals.
It remain a fact, however, that gaining unauthorized access is a crime, no matter what the intention is.

Hacking Phases:
Reconnaissance:
- Reconnaissance refers to the preparatory phase where an attacker seeks to gather information about a target prior to launching an attack.
- Reconnaissance target range may include the target organization’s clients, employees, operations, network and systems.
- Passive Reconnaissance: Passive reconnaissance involves acquiring information without directly interacting with the target. Eg., Searching public records or news releases.
- Active Reconnaissance: Active reconnaissance involves interacting with the target directly by any means. Eg., Telephone calls to the help desk or technical department.

Scanning
- Pre-Attack Phase: Scanning refer to the pre-attack phase when the attacker scans the network for specific information on the basis of information gathered during reconnaissance.
- Port Scanner: Scanning can include use of dialers, port scanners, network mapping, sweeping, vulnerability scanners, etc.
- Extract Information: Attackers extract information such as computer name, IP address and user accounts to launch attack.

Gaining Access
- Gaining access refers to the point where the attacker obtains access to the operating system or applications on the computer or network.
- The attacker can escalate privileges to obtain complete control of the system. In the process, intermediate systems that are connected to it are also compromised.
- The attacker can gain access at the operating system level, application level, or network level.

Maintaining Access
- Maintaining access refers to the phase when the attacker tries to retain his or her ownership of the system.
- Attackers may prevent the system from being owned by the other attackers by securing their exclusive access with Backdoors, Rootkits, or Trojans.
- Attackers use the compromised system to launch further attacks.

Clearing Track
- Covering tracks refers to the activities carried out by an attacker to hide malicious acts.
- The attacker’s intentions include: Continuing access to the victim’s system, remaining unnoticed and uncaught, deleting evidence that might lead to his prosecution.
- The attacker overwrites the server, system and application logs to avoid suspicion.

Why Ethical hacking is necessary?
As hacking involves creating thinking, vulnerability testing and security audits cannot ensure that the network is secure.
To achieve this, organizations need to implement a “defense in depth” strategy by penetrating into their network to estimate vulnerabilities and expose them.
Ethical hacking is necessary because it allows the countering of attacks from malicious hackers by anticipating methods they can use to break into a system.

Scope and Limitations of Ethical Hacking:
- Ethical hacking is a crucial component of risk assessment, auditing, counterfraud, best practices and good governance.
- It is used to identify risks and highlight the remedial actions and also reduces information and communications technology costs by resolving those vulnerabilities.

- An ethical hacker thus can only help the organization to better understand their security system, but it is up to the organization to place the right guards on the network.
- However, unless the business first know what it is at that they are looking for and why they are hiring outside vendor to hack systems in the first place, chances are there would not be much to gain from the experience.

Essential Terminologies:
Hack Value: It is the notion among hackers that something is worth doing or is interesting.

Target of Evaluation:
An IT system, product, or component that is identified/subjected to a required security evaluation.

Attack:
An assault on the system security derived from an intelligent threat. An attack is any action violating security.

Exploit:
A defined way to breach the security of an IT system through vulnerability.

A zero-day:
A computer threat that tries to exploit computer application vulnerabilities that are unknown to others or undisclosed to the software developer.

Security:
A state of well-being of information and infrastructure in which the possibility of theft, tempering and disruption of information and services is kept low or tolerable.

Threat:
An action or event that might compromise security. A threat is a potential violation of security.

Vulnerability:
Existence of a weakness, design or implementation error that can lead to an unexpected and undesirable event compromising the security of the system.

Daisy Chaining:
Hackers who get away with database theft usually complete their task, then backtrack to cover their tracks by destroying logs, etc.


STEGOSUITE

StegoSuite:
Stegosuite  is a graphical steganography tool to easily hide information in image files. It allows the embedding of text messages and multiple files of any type. In addition, the embedded data is encrypted using AES. Currently supported file types are BMP,  GIF,  JPG and PNG.
Features:
  • BMP, GIF and JPG supported
  • AES encryption of embedded data
  • Automatic avoidance of homogenous areas (only embed data in noisy areas)
  • Embed text messages and multiple files of any type
  • Easy to use 

Experiment:


MENTALIST

Mentalist is a graphical tool for custom wordlist generation. It utilizes common human paradigms for constructing passwords and can output the full wordlist as well as rules compatible with [Hashcat](https://hashcat.net/hashcat) and [John the Ripper](http://www.openwall.com/john).

Experiment:


CUPP


CUPP(Common  User  Passwords Profiler) is tool to generate wordlist from common user profiler. The most common form of authentication is the combination of a username and a password or passphrase. If both match values stored within a locally stored table, the user is authenticated  for  a  connection.  Password  strength  is  a measure of the difficulty involved in guessing or breaking the password through cryptographic techniques or library-based automated testing of alternate values.
       A weak password can also be one that is easily guessed by someone profiling the user, such as a birthday, nickname, address, name of a  pet or relative,or a common word such as God, love, money or password. From a social engineering you can obtain information to use with the CUPP, this way the tool can create a very effective dictionary for brute force attacks or dictionary attacks.


Author: Muris Kurgas | j0rgan@remote-exploit.org

Example:



CEWL

CeWL (Custom Word List generator) is a ruby app which spiders a given URL, up to a specified depth, and returns a list of words which can then be used for password crackers such as John the Ripper. 
Optionally, CeWL can follow external links. CeWL can also create a list of email addresses found in mailto links. These email addresses can be used as usernames in  brute  forceactions.
CeWL is pronounced "cool" and it is written in ruby!

Author: Robin Wood <robin@digi.ninja>

 dfs

CRUNCH

Dictionary attack: Dictionary attack is an attempted entry in a digital system which uses a precompiled list of possible passwords rather entering them one at a time. Basically, it an evolved and advanced form of trial and error as it brings result fast and is efficient.

Crunch can create a wordlist based on criteria you specify. The output from crunch can be sent to the screen, file, or to another program. The best thing is about crunch is you can use it both offline and online.

crunch <min-len> <max-len> [<charset string>] [options]

The required parameters are: 
min-len
The minimum length string you want crunch to start at. This option is required even for parameters that won't use the value.
max-len
The maximum length string you want crunch to end at. This option is required even for parameters that won't use the value.  
charset string 
You may specify character sets for crunch to use on the command line or if you leave it blank crunch will use the default character sets. The order MUST BE lower case characters, upper case characters, numbers, and then symbols. If you don't follow this order you will not get the results you want. You MUST specify either values for the character type or a plus sign. NOTE: If you want to include the space character in your character set you must escape it using the \ character or enclose your character set in quotes i.e. "abc ". See the examples 3, 11, 12, and 13 for examples.



OPTIONS
-b number[type]
Specifies the size of the output file, only works if -o START is used

-c number
Specifies the number of lines to write to output file, only works if -o START is used

-d numbersymbol
Limits the number of duplicate characters. -d 2@ limits the lower case alphabet to output like aab and aac. aaa would not be generated as that is 3 consecutive letters of a

-e string
Specifies when crunch should stop early

-f /path/to/charset.lst charset-name
Specifies a character set from the charset.lst

-i Inverts
The output so instead of aaa,aab,aac,aad, etc you get
aaa,baa,caa,daa,aba,bba, etc

-l literals
When you use the -t option this option tells crunch which symbols should be treated as literals. This will allow you to use the placeholders as letters in the pattern. The -l option should be the same length as the -t option

-m Merged with -p. Please use -p instead

-o wordlist.txt
Specifies the file to write the output to, eg: wordlist.txt

-p charset OR -p word1 word2 ...
Tells crunch to generate words that don't have repeating characters. By default crunch will generate a wordlist size of #of_chars_in_charset ^ max_length. This option will instead generate #of_chars_in_charset!. The ! stands for factorial.
For example say the charset is abc and max length is 4.. Crunch will by default generate 3^4 = 81 words. This option will instead generate 3! = 3x2x1 = 6 words (abc, acb, bac, bca, cab, cba). THIS MUST BE THE LAST OPTION! This option CANNOT be used with -s and it ignores min and max length however you must still specify two numbers.

-q filename.txt
Tells crunch to read filename.txt and permute what is read. This is like the -p option except it gets the input from file‐name.txt.

-r resume
Tells crunch to resume generate words from where it left off. -r only works if you use -o. You must use the same command as the original command used to generate the words. The only exception to this is the -s option. If your original command used the -s option you MUST remove it before you resume the session. Just add -r to the end of the original command.

-s startblock
Specifies a starting string, eg: 03god22fs

-t @,%^
Specifies a pattern, eg: @@god@@@@ where the only the @'s, ,'s, %'s, and ^'s will change. @ will insert lower case characters, will insert upper case characters % will insert numbers ^ will insert symbols

-u
The -u option disables the print percentage thread. This should be the last option.

-z gzip, bzip2, lzma, and 7z
Compresses the output from the -o option. Valid parameters are gzip, bzip2, lzma, and 7z. gzip is the fastest but the compression is minimal. bzip2 is a little slower than gzip but has better compression. 7z is slowest but has the best compression.


EXAMPLES

Example 1

crunch 1 8
crunch will display a wordlist that starts at a and ends at zzzzzzzz

Example 2
crunch 1 6 abcdefg
crunch will display a wordlist using the character set abcdefg that starts at a and ends at gggggg

Example 3
crunch 1 6 abcdefg\
there is a space at the end of the character string. In order for crunch to use the space you will need to escape it using the \ character. In this example you could also put quotes around the letters and not need the \, i.e. "abcdefg ". Crunch will display a wordlist using the character set abcdefg that starts at a and ends at (6 spaces)

Example 4
crunch 1 8 -f charset.lst mixalpha-numeric-all-space -o wordlist.txt
crunch will use the mixalpha-numeric-all-space character set from charset.lst and will write the wordlist to a file named wordlist.txt. The file will start with a and end with " "

Example 5
crunch 8 8 -f charset.lst mixalpha-numeric-all-space -o wordlist.txt -t @@dog@@@ -s cbdogaaa crunch should generate a 8 character wordlist using the mixalpha-number-all-space character set from charset.lst and will write the wordlist to a file named wordlist.txt. The file will start at cbdogaaa and end at " dog "

Example 6
crunch 2 3 -f charset.lst ualpha -s BB
crunch with start generating a wordlist at BB and end with ZZZ. This is useful if you have to stop generating a wordlist in the middle. Just do a tail wordlist.txt and set the -s parameter to the next word in the sequence. Be sure to rename the original wordlist BEFORE you begin as crunch will overwrite the existing wordlist.

Example 7
crunch 4 5 -p abc
The numbers aren't processed but are needed.
crunch will generate abc, acb, bac, bca, cab, cba.

Example 8
crunch 4 5 -p dog cat bird
The numbers aren't processed but are needed.
crunch will generate birdcatdog, birddogcat, catbirddog, catdogbird, dogbirdcat, dogcatbird.

Example 9
crunch 1 5 -o START -c 6000 -z bzip2
crunch will generate bzip2 compressed files with each file containing 6000 words. The filenames of the compressed files will be first_word-last_word.txt.bz2

Example 10
crunch 4 5 -b 20mib -o START
will generate 4 files: aaaa-gvfed.txt, gvfee-ombqy.txt, ombqz-wcydt.txt, wcydu-zzzzz.txt the first three files are 20MBs (real power of 2 MegaBytes) and the last file is 11MB.

Example 11
crunch 3 3 abc + 123 !@# -t @%^
will generate a 3 character long word with a character as the first character, and number as the second character, and a symbol for the third character. The order in which you specify the characters you want is important. You must specify the order as lower case character, upper case character, number, and symbol. If you aren't going to use a particular character set you use a plus sign as a placeholder. As you can see I am not using the upper case character set so I am using the plus sign placeholder. The above will start at a1! and end at c3#

Example 12
crunch 3 3 abc + 123 !@# -t ^%@
will generate 3 character words starting with !1a and ending with #3c

Example 13
crunch 4 4 + + 123 + -t %%@^
the plus sign (+) is a place holder so you can specify a character set for the character type. crunch will use the default character set for the character type when crunch encounters a + (plus sign) on the command line. You must either specify values for each character type or use the plus sign. I.E. if you have two characters types you MUST either specify values for each type or use a plus sign. So in this example the character sets will be:
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
123
!@#$%^&*()-_+=~`[]{}|\:;"'<>,.?/
there is a space at the end of the above string the output will start at 11a! and end at "33z ". The quotes show the space at the end of the string.

Example 14
crunch 5 5 -t ddd@@ -o j -p dog cat bird
any character other than one of the following: @,%^ is the placeholder for the words to permute. The @,%^ symbols have the same function as -t. If you want to use @,%^ in your output you can use the -l option to specify which character you want crunch to treat as a literal.
So the results are
birdcatdogaa
birdcatdogab
birdcatdogac
<skipped>
dogcatbirdzy
dogcatbirdzz

Example 15
crunch 7 7 -t p@ss,%^ -l a@aaaaa
crunch will now treat the @ symbol as a literal character and not replace the character with a uppercase letter. this will generate
p@ssA0!
p@ssA0@
p@ssA0#
p@ssA0$
<skipped>
p@ssZ9

Example 16
crunch 5 5 -s @4#S2 -t @%^,2 -e @8 Q2 -l @dddd -b 10KB -o START
crunch will generate 5 character strings starting with @4#S2 and ending at @8 Q2. The output will be broken into 10KB sized files named for the files starting and ending strings.

Example 17
crunch 5 5 -d 2@ -t @@@%%
crunch will generate 5 character strings staring with aab00 and ending at zzy99. Notice that aaa and zzz are not present.

Example 18
crunch 10 10 -t @@@^%%%%^^ -d 2@ -d 3% -b 20mb -o START
crunch will generate 10 character strings starting with aab!0001!! and ending at zzy 9998 The output will be written to 20mb files.

Example 19
crunch 8 8 -d 2@
crunch will generate 8 characters that limit the same number of lower case characters to 2. Crunch will start at aabaabaa and end at
zzyzzyzz.

Example 20
crunch 4 4 -f unicode_test.lst japanese -t @@%% -l @xdd
crunch will load some Japanese characters from the unicode_test character set file. The output will start at @日00 and end at @語99.

STEGHIDE

Steganography is the practice of concealing a file, message, image, or video within another file, message, image, or video.
In digital steganography, electronic communications may include steganographic coding inside of a transport layer, such as a document file, image file, program or protocol. Media files are ideal for steganographic transmission because of their large size.
Steghide:
Steghide is a steganography program that is able to hide data in various kinds of image- and audio-files. The color- respectivly sample-frequencies are not changed thus making the embedding resistant against first-order statistical tests.

       Features include the compression of the embedded data, encryption of the embedded data  and  automatic  integrity  checking  using  a checksum.  The JPEG, BMP, WAV and AU file formats are supported for use as cover file. There are no restrictions on the format of the secret data.

       Steghide uses a graph-theoretic approach to steganography. You do not need to know anything about graph theory to  use  steghide  and you  can  safely  skip the rest of this paragraph if you are not interested in the technical details. The embedding algorithm roughly works as follows: At first, the secret data is compressed and encrypted. Then a sequence of positions of pixels in the cover file is created  based on a pseudo-random number generator initialized with the passphrase (the secret data will be embedded in the pixels at these positions). Of these positions those that do not need to be changed (because they already contain the correct value by  chance) are  sorted  out. Then a graph-theoretic matching algorithm finds pairs of positions such that exchanging their values has the effect of embedding the corresponding part of the secret data. If the algorithm cannot find any more such pairs all exchanges  are  actually performed. The  pixels at the remaining positions (the positions that are not part of such a pair) are also modified to contain the embedded data (but this is done by overwriting them, not by exchanging them with other pixels).  The fact that (most of)  the  embedding  is done by exchanging pixel values implies that the first-order statistics (i.e. the number of times a color occurs in the picture) is not changed. For audio files the algorithm is the same, except that audio samples are used instead of pixels.

       The default encryption algorithm is Rijndael with a key size of 128 bits (which is AES - the advanced  encryption  standard)  in  the cipher  block chaining mode. If you do not trust this combination for whatever reason feel free to choose another algorithm/mode combination (information about all possible algorithms and modes is displayed by the encinfo command).  The checksum is calculated using the CRC32 algorithm.

Features:

  • compression of embedded data
  • encryption of embedded data
  • embedding of a checksum to verify the integrity of the extraced data
  • support for JPEG, BMP, WAV and AU files


Experiment:




PROXY CHAINS

A proxy or proxy server is a dedicated computer or software system running on a computer which acts as an intermediary between an end device, such as a computer and another server which a client is requesting any services from. By connecting to the Internet through proxies, the client IP address will not be shown but rather the IP of the proxy server.
Built-in anonymity service in Kali Linux and or others penetration testing based systems, it is Proxychains.

Proxychain is one of the tool to provide function called proxy. It supports different proxy types with dynamic or random option.

Proxychain Features:
  • Support SOCKS5, SOCKS4, and HTTP CONNECT proxy servers.
  • Proxychains can be mixed up with a different proxy types in a list
  • Proxychains also supports any kinds of chaining option methods, like: random, which takes a random proxy in the list stored in a configuration file, or chaining proxies in the exact order list, different proxies are separated by a new line in a file. There is also a dynamic option, that lets Proxychains go through the live only proxies, it will exclude the dead or unreachable proxies, the dynamic option often called smart option.
  • Proxychains can be used with servers, like squid, sendmail, etc.
  • Proxychains is capable to do DNS resolving through proxy.
  • Proxychains can handle any TCP client application, ie., nmap, telnet.

Author: Net Creature, Proxy Labs

FIREWALK

Firewalk is an active reconnaissance network security tool that attempts to determine what layer 4 protocols a given IP forwarding device will pass. Firewalk works by sending out TCP or UDP packets with a TTL one greater than the targeted gateway. If the gateway allows the traffic, it will forward the packets to the next hop where they will expire and elicit an ICMP_TIME_EXCEEDED message. If the gateway hostdoes not allow the traffic, it will likely drop the packets on the floor and we will see no response.
To get the correct IP TTL that will result in expired packets one beyond the gateway we need to ramp up hop-counts. We do this in the same manner that traceroute works. Once we have the gateway hopcount (at that point the scan is said to be `bound`) we can begin our scan.

It is significant to note the fact that the ultimate destination host does not have to be reached. It just needs to be somewhere downstream, on the other side of the gateway, from the scanning host.




METASPLOIT ARCHITECTURE


Metasploit is written in Ruby!!          Metasploit is case-insensitive!!

In Kali Linux, Metasploit is provided in the metasploit-framework package and is installed in the /usr/share/metasploit-framework directory.


Data:

The data directory contains editable files used by Metasploit to store binaries required for certain exploits, wordlists, images, and more. 
Documentation:

As its name suggests, the documentation directory contains the available documentation for the framework. 
Lib:

The lib directory contains the ‘meat’ of the framework code base. 
Modules:

The modules directory is where you will find the actual MSF modules for exploits, auxiliary and post modules, payloads, encoders, and nop generators.
Plugins:

Metasploit includes many plugins, which you will find in this directory. 
Scripts:

The scripts directory contains Meterpreter and other scripts.
Tools:

The tools directory has various useful command-line utilities.




Metasploit Libraries:
There are a number of MSF libraries that allow us to run our exploits without having to write additional code for rudimentary tasks, such as HTTP requests or encoding of payloads. Some of the most important libraries are outlined below.

Rex:

* The basic library for most tasks

* Handles sockets, protocols, text transformations, and others

* SSL, SMB, HTTP, XOR, Base64, Unicode

Msf::Core:

* Provides the ‘basic’ API

* Defines the Metasploit Framework

Msf::Base:

* Provides the ‘friendly’ API

* Provides simplified APIs for use in the Framework


Metasploit Modules and Locations:

Almost all of your interaction with Metasploit will be through its many modules, which it looks for in two locations. The first is the primary module store under /usr/share/metasploit-framework/modules/ and the second, which is where you will store custom modules, is under your home directory at ~/.msf4/modules/.
All Metasploit modules are organized into separate directories, according to their purpose. An basic overview of the various types of Metasploit modules is shown below.

In the Metasploit Framework, exploit modules are defined as modules that use payloads.
  Auxiliary modules include port scanners, fuzzers, sniffers, and more.

Payloads, Encoders, Nops:

Payloads consist of code that runs remotely, while encoders ensure that payloads make it to their destination intact. Nops keep the payload sizes consistent across exploit attempts.
 


Loading Additional Module Trees:

Metasploit gives you the option to load modules either at runtime or after msfconsole has already been started. Pass the -m option when running msfconsole to load additional modules at runtime:
If you need to load additional modules from with msfconsole, use the loadpath command:
A Quick Diversion into Ruby:
* Every Class only has one parent
* A class may include many Modules
* Modules can add new methods
* Modules can overload old methods
* Metasploit modules inherit Msf::Module and include mixins to add features.

Metasploit Mixins and Plugins:
Mixins are quite simply, the reason why Ruby rocks.
* Mixins include one class into another  
* This is both different and similar to inheritanc
*  Mixins can override a class’ methods

Mixins can add new features and allows modules to have different ‘flavors’.
* Protocol specific (HTTP, SMB)
* Behaviour-specific (brute force)
* connect() is implemented by the TCP mixin
* connect() is then overloaded by FTP, SMB and others

Mixins can change behavior.
* The scanner mixin overloads run()
* Scanner changes run() for run_host() and run_range
* It calls these in parallel based on the THREADS setting
* The BruteForce mixin is similar

Plugins work directly with the API.
* They manipulate the framework as a whole
* Plugins hook into the event subsystem
* They automate specific tasks that would be tedious to do manually

Plugins only work in the msfconsole.
* Plugins can add new console commands
* They extend the overall Framework functionality

ARP TABLES

ARP Tables:
          ARP stands for Address Resolution Protocol, is a telecommunication protocol used for resolution of network layer addresses into link layer addresses.
          It is used to setup and maintain the tables of ARP rules in the Linux Kernel. These rules will inspect ARP frames.

NETFILTER

Netfilter is a host-based firewall for Linux based operating systems. It is included as part of Linux distribution and it is activated by default. This firewall is controlled by the program called iptables. Netfilter filtering takes place at kernel level, before a program can even process the data from the network packet.
Iptables/Ip6tables - administration tool for IPv4/IPv6 packet filtering and NAT
Author: Rusty Russell
Developer(s): Netfilter Core Team
Original release: 1998

Tables:
  • Filter Table: Used for normal filtering of traffic based on rules defined by user
     Chains Used: INPUT CHAIN/OUTPUT CHAIN/FORWARD CHAIN
  • NAT Table: Iptable can be used for Network Address Translation purpose. This table contains rules related to NAT
     Chains Used: PREROUTING/OUTPUT/POST ROUTING
  • Mangle Table: Rules in this table can be used to modified the packets based on user given criteria. User can modify the TTL, MMS value, Terms of service(like., which traffic should be given more priority, etc)
     Chains Used: PREROUTING/OUTPUT/INPUT/POSTROUTING/FORWARD
  • Raw Table: Primarily used to add no connection tracking rules
  • Security: Used for mandatory access control networking rules
Chains:
  • PREROUTING Chain: It is used to add rules which define actions that need to be taken before a routing decision is made by a kernel
  • INPUT Chain: It is used for rules which are applicable to the traffic/packets coming towards the server
  • OUTPUT Chain: It is used for rules which need to be applied on outgoing traffic/packets from server
  • FORWARD Chain: It is used for adding rules related to forwarding an IP packet
  • POST ROUTING Chain: It is used for adding rules which will define actions that need to be taken after a routing decision which is taken by the kernel
Targets:
  • ACCEPT
  • DROP
  • REJECT
  • LOG
  • QUEUE
  • RETURN 
Usage: 
       iptables -[ACD] chain rule-specification [options]
       iptables -I chain [rulenum] rule-specification [options]
       iptables -R chain rulenum rule-specification [options]
       iptables -D chain rulenum [options]
       iptables -[LS] [chain [rulenum]] [options]
       iptables -[FZ] [chain] [options]
       iptables -[NX] chain
       iptables -E old-chain-name new-chain-name
       iptables -P chain target [options]
       iptables -h (print this help information)

Commands:
Either long or short options are allowed.
  --append  -A chain        Append to chain
  --check   -C chain        Check for the existence of a rule
  --delete  -D chain        Delete matching rule from chain
  --delete  -D chain rulenum
                Delete rule rulenum (1 = first) from chain
  --insert  -I chain [rulenum]
                Insert in chain as rulenum (default 1=first)
  --replace -R chain rulenum
                Replace rule rulenum (1 = first) in chain
  --list    -L [chain [rulenum]]
                List the rules in a chain or all chains
  --list-rules -S [chain [rulenum]]
                Print the rules in a chain or all chains
  --flush   -F [chain]        Delete all rules in  chain or all chains
  --zero    -Z [chain [rulenum]]
                Zero counters in chain or all chains
  --new     -N chain        Create a new user-defined chain
  --delete-chain
            -X [chain]        Delete a user-defined chain
  --policy  -P chain target
                Change policy on chain to target
  --rename-chain
            -E old-chain new-chain
                Change chain name, (moving any references)
Options:
    --ipv4    -4        Nothing (line is ignored by ip6tables-restore)
    --ipv6    -6        Error (line is ignored by iptables-restore)
[!] --protocol    -p proto    protocol: by number or name, eg. `tcp'
[!] --source    -s address[/mask][...]
                source specification
[!] --destination -d address[/mask][...]
                destination specification
[!] --in-interface -i input name[+]
                network interface name ([+] for wildcard)
 --jump    -j target
                target for rule (may load target extension)
  --goto      -g chain
                              jump to chain with no return
  --match    -m match
                extended match (may load extension)
  --numeric    -n        numeric output of addresses and ports
[!] --out-interface -o output name[+]
                network interface name ([+] for wildcard)
  --table    -t table    table to manipulate (default: `filter')
  --verbose    -v        verbose mode
  --wait    -w [seconds]    maximum wait to acquire xtables lock before give up
  --wait-interval -W [usecs]    wait time to try to acquire xtables lock
                default is 1 second
  --line-numbers        print line numbers when listing
  --exact    -x        expand numbers (display exact values)
[!] --fragment    -f        match second or further fragments only
  --modprobe=<command>        try to insert modules using this command
  --set-counters PKTS BYTES    set the counter during insert/append
[!] --version    -V        print package version


Configuration file

sudo vi /etc/sysconfig/iptables

sudo service iptables status

sudo service iptables start

sudo service iptables stop

sudo service iptables status

sudo iptables -L or sudo iptables –list

iptables -L INPUT or iptables -L OUTPUT

with line-numbers and numeric

iptables -L –line-numbers --numeric

delete rules with line-number

iptables –delete INPUT 2

create a new chain

iptables –new MOHAN-INPUT

iptables –new MOHAN-OUTPUT

check rule is already exists

iptables -t filter -C INPUT -p tcp –dport 80 -j DROP

deleting chain

iptables -X MOHAN-INPUT

iptables -X MOHAN-OUTPUT
 

inserting rule with line-number

iptables -t filter -I INPUT 2 -p tcp –dport 25 -m state –state NEW,ESTABLISHED -j ACCEPT

replacing a rule with line-number

iptables -t filter -R INPUT 2 -p tcp –dport 25 -j ACCEPT

flushing iptables

iptables -F

renaming chain name

iptables E MOHAN-INPUT M-INPUT

used full forms and short forms

iptables –table filter –append INPUT –in-interface eno16777736 –protocol tcp –source 172.20.10.3 –dport 22 -m state –state NEW,ESTABLISHED –jump ACCEPT

iptables -t filter -A INPUT -i eno16777736 -p tcp -s 172.20.10.3/24 –dport 22 -m state –state NEW,ESTABLISHED -j ACCEPT