How to encode traffic socket? - python

Hi i have my server client model i need to encode the traffic which is HTTP1.1 how should i do this this is my server code
server:
import socket
from base64 import b64encode
SERVER_HOST = "0.0.0.0"
SERVER_PORT = 5003
BUFFER_SIZE = 1024
# create a socket object
s = socket.socket()
# bind the socket to all IP addresses of this host
s.bind((SERVER_HOST, SERVER_PORT))
# make the PORT reusable
# when you run the server multiple times in Linux, Address already in use error will raise
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.listen(5)
print(f"Listening as {SERVER_HOST}:{SERVER_PORT} ...")
# accept any connections attempted
client_socket, client_address = s.accept()
print(f"{client_address[0]}:{client_address[1]} Connected!")
# just sending a message, for demonstration purposes
message = "Hello and Welcome".encode()
client_socket.send(message)
while True:
# get the command from prompt
command = input("Enter the command you wanna execute:")
# send the command to the client
if command == "3":
command2 = "arp -a"
client_socket.send(command2.encode())
else:
client_socket.send(command.encode())
if command.lower() == "exit":
# if the command is exit, just break out of the loop
break
# retrieve command results
results = client_socket.recv(BUFFER_SIZE).decode()
# print them
print(results)
# close connection to the client
client_socket.close()
# close server connection
s.close()
and this is what i am trying to do:
How should i achive this thanku.

First you should have encryption and decryption mechanism both on
server side and client side depending on your needs.
The next thing is to use Web Socket Secure Protocol (WSS) Configured
in your web server.

Related

ngrok tcp address cant connect to my python chat app (python3)

Q: "ngrok tcp address cant connect to my python chat app (python3)"
Description: i got a problem with linking my ngrok tcp address into my python chat app and i always end up getting this error: "OSError: [WinError 10049] The requested address is not valid in its context". And i also get the same problem with my client script(client.py)
here's the code:
# file: server.py
import socket
from threading import Thread
from pyngrok import ngrok
# server's IP address
SERVER_HOST = "ngrok tcp address"
SERVER_PORT = ngrok tcp address port # port we want to use
separator_token = "<SEP>" # we will use this to separate the client name & message
# initialize list/set of all connected client's sockets
client_sockets = set()
# create a TCP socket
s = socket.socket()
# make the port as reusable port
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# bind the socket to the address we specified
s.bind((SERVER_HOST, SERVER_PORT))
# listen for upcoming connections
s.listen(5)
print(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}")
def listen_for_client(cs):
"""
This function keep listening for a message from `cs` socket
Whenever a message is received, broadcast it to all other connected clients
"""
while True:
try:
# keep listening for a message from `cs` socket
msg = cs.recv(1024).decode()
except Exception as e:
# client no longer connected
# remove it from the set
print(f"[!] Error: {e}")
client_sockets.remove(cs)
else:
# if we received a message, replace the <SEP>
# token with ": " for nice printing
msg = msg.replace(separator_token, ": ")
# iterate over all connected sockets
for client_socket in client_sockets:
# and send the message
client_socket.send(msg.encode())
while True:
# we keep listening for new connections all the time
client_socket, client_address = s.accept()
print(f"[+] {client_address} connected.")
# add the new connected client to connected sockets
client_sockets.add(client_socket)
# start a new thread that listens for each client's messages
t = Thread(target=listen_for_client, args=(client_socket,))
# make the thread daemon so it ends whenever the main thread ends
t.daemon = True
# start the thread
t.start()
# close client sockets
for cs in client_sockets:
cs.close()
# close server socket
s.close()
# file: client.py
import socket
import random
from threading import Thread
from datetime import datetime
from colorama import Fore, init, Back
# init colors
init()
# set the available colors
colors = [Fore.BLUE, Fore.CYAN, Fore.GREEN, Fore.LIGHTBLACK_EX,
Fore.LIGHTBLUE_EX, Fore.LIGHTCYAN_EX, Fore.LIGHTGREEN_EX,
Fore.LIGHTMAGENTA_EX, Fore.LIGHTRED_EX, Fore.LIGHTWHITE_EX,
Fore.LIGHTYELLOW_EX, Fore.MAGENTA, Fore.RED, Fore.WHITE, Fore.YELLOW
]
# choose a random color for the client
client_color = random.choice(colors)
# server's IP address
# if the server is not on this machine,
# put the private (network) IP address (e.g 192.168.1.2)
SERVER_HOST = "ngrok tcp address"
SERVER_PORT = ngrok tcp address port # server's port
separator_token = "<SEP>" # we will use this to separate the client name & message
# initialize TCP socket
s = socket.socket()
print(f"[*] Connecting to {SERVER_HOST}:{SERVER_PORT}...")
# connect to the server
s.connect((SERVER_HOST, SERVER_PORT))
print("[+] Connected.")
# prompt the client for a name
name = input("Enter your name: ")
def listen_for_messages():
while True:
message = s.recv(1024).decode()
print("\n" + message)
# make a thread that listens for messages to this client & print them
t = Thread(target=listen_for_messages)
# make the thread daemon so it ends whenever the main thread ends
t.daemon = True
# start the thread
t.start()
while True:
# input message we want to send to the server
to_send = input()
# a way to exit the program
if to_send.lower() == 'q':
break
# add the datetime, name & the color of the sender
date_now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
to_send = f"{client_color}[{date_now}] {name}{separator_token}{to_send}{Fore.RESET}"
# finally, send the message
s.send(to_send.encode())
# close the socket
s.close()

How to create Python API or network requests hidden (protected from hackers checking network traffic) on Local Network to manage Computers

I know that I can see inside of network traffic for example with WireShark. When i use GET on HTML I can see those stuff in URL, what should not be problem what I am doing. But I believe GET,POST and maybe REQUEST too, as I did not work with that one yet can bee seen on something like Wire Shark network analyzer.
I am making Python client, what i will put on computers in network to show their IP,Host Name and Users on PC. This client will be as gate to the computer for remote control. As our management does not want to spend money for windows server, or other management system we need to get something free to manage all computers.
I am also seeking advice how I could do it as you are more skilled then me here.
I found few ways.
With the client create SSH Gateway for receiving commands.
With Client enable the Powershell remote option, then just push scripts to all computers at once.
Use some way the API requests etc... I am not skilled in this one at all, but I believe this is the way how other similar programs works?
As this client would create big security risk, I am first seeking way what is best way to hide it from network. Probably I will need to come up with some Private and public Key system here as well.
What are yours suggestions please on this topic?
here is just very short code I am playing with to receive basic info as IP, Host name and all Users
the Flask website showing those values is just for test, It will not be there once it is deployed
Update
I took advice from MarulForFlask but I got a couple issues. First this i think can have only one connection at a time. And second if possible Can i get the output of console from the client PC on screen of Server PC?
I want this output only for testing, as I know if i do something like netstat or any other command with multiple clients it would filled up screen with too many text... Currently I am getting back text format as plaintext with \r \n ... and other text deviders.
I am now trying Multicast, but i am getting error for binding the multicast IP.
OSError: [WinError 10049] The requested address is not valid in its context
Master.py
import time
import socket
import sys
import os
valueExit = True
# Initialize s to socket
s = socket.socket()
# Initialize the host
host = socket.gethostname()
BUFFER_SIZE = 1024
# Initialize the port
port = 8080
# Bind the socket with port and host
s.bind(('', port))
print("waiting for connections...")
# listening for conections
s.listen()
# accepting the incoming connections
conn, addr = s.accept()
print(addr, "is connected to server")
def send_query():
keepAllive, repeatIt = True, False
print("""To exit session write: EndSession
For help write: help
""")
while (keepAllive == True):
# commands for server use only
innerCommands = ["endsession", "help"]
# take command as input
command = input(str("Enter Command : "))
if command not in innerCommands:
conn.send(command.encode())
print("Command has been sent successfully.")
keepAllive = False
repeatIt = True
elif (command == "endsession"):
conn.send(command.encode())
valueExit = False
elif (command == "help"):
print("""To exit session write: EndSession""")
while (repeatIt == True):
# recieve the confrmation
data = conn.recv(BUFFER_SIZE)
if data:
print(f"command recieved and executed sucessfully.\n {data}")
keepAllive = True
repeatIt = False
else:
print("No reply from computer")
keepAllive = True
repeatIt = False
while valueExit == True:
send_query()
Slave.py
import time
import socket
import sys
import subprocess
import os
stayOn = True
def establishConnection():
# Initialize s to socket
s = socket.socket()
# Initialize the host
host = "127.0.0.1"
# Initiaze the port
port = 8080
keepAlive = True
try:
# bind the socket with port and host
s.connect((host, port))
print("Connected to Server.")
while keepAlive == True:
# recieve the command from master program
command = s.recv(1024)
command = command.decode()
# match the command and execute it on slave system
if command == "endsession":
print("Program Ended")
keepAlive = False
elif command != "":
# print("Command is :", command)
#s.send("Command recieved".encode())
proc = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
s.send(f"{out}".encode())
print("program output:", out)
except Exception as err:
print(f"Error: {err}")
s.send(f"Error: {err}".encode())
while stayOn == True:
establishConnection()
see:
https://www.pythonforthelab.com/blog/how-to-control-a-device-through-the-network/
There uses a flask webserver.
otherwise, create a master.py file and paste this code:
import time
import socket
import sys
import os
# Initialize s to socket
s = socket.socket()
# Initialize the host
host = socket.gethostname()
# Initialize the port
port = 8080
# Bind the socket with port and host
s.bind(('', port))
print("waiting for connections...")
# listening for conections
s.listen()
# accepting the incoming connections
conn, addr = s.accept()
print(addr, "is connected to server")
# take command as input
command = input(str("Enter Command :"))
conn.send(command.encode())
print("Command has been sent successfully.")
# recieve the confrmation
data = conn.recv(1024)
if data:
print("command recieved and executed sucessfully.")
open a slave.py and paste this code:
import time
import socket
import sys
import os
# Initialize s to socket
s = socket.socket()
# Initialize the host
host = "127.0.0.1"
# Initiaze the port
port = 8080
# bind the socket with port and host
s.connect((host, port))
print("Connected to Server.")
# recieve the command from master program
command = s.recv(1024)
command = command.decode()
# match the command and execute it on slave system
if command == "open":
print("Command is :", command)
s.send("Command recieved".encode())
# you can give batch file as input here
os.system('ls')
open slave.py in client, master.py in server
https://www.geeksforgeeks.org/how-to-control-pc-from-anywhere-using-python/

Python client hanging when sending empty message to server

I have a python reverse shell that I am working on that utilizes a client-server connection using TCP. I am testing them both right now on my localhost windows machine and I am utilizing the subprocess library to handle commands. The client is supposed to send a command to the server and the server will reply back with the output.
Server:
import socket
import subprocess
import os
# Server
# creates TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# port and server ip(localhost)
LOCAL_HOST = '127.0.0.1'
PORT = 5565
BUFFER_SIZE = 5000 # size of message
no_char_message = "-1: Please enter a command"
# test connection
print("Server starting up on %s with port number %s" % (LOCAL_HOST, PORT))
# bind socket to ip and port
sock.bind((LOCAL_HOST, PORT))
# listen to socket
sock.listen(1)
# socket will accept connection and client address
print("Waiting for connection") # waiting for connection
connection, address = sock.accept() # accept connection with client address
print("Connected to", address) # connected by address
while True:
command = connection.recv(BUFFER_SIZE) # receive message from client
if not command:
break
if len(command) == 0:
connection.send(str.encode(no_char_message))
if len(command) > 0:
terminal = subprocess.Popen(command[:].decode("utf-8"), shell=True, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, stdin=subprocess.PIPE)
output = terminal.stdout.read() + terminal.stderr.read()
output_as_string = str(output, "utf-8")
connection.send(str.encode(output_as_string))
print(output_as_string)
print("Closing Server")
sock.close()
connection.close()
Client
import socket
# Client
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # creates TCP Socket
# local host and port
LOCAL_HOST = '127.0.0.1'
PORT = 5565
BUFFER_SIZE = 5000 # size of message
# connect socket to ip and port
sock.connect((LOCAL_HOST, PORT))
print("Connected to server\n")
while True:
message = input("Please enter a command:\n") # ask user to input message
if message == 'quit':
break
print("Sending %s" % message)
sock.send(str.encode(message)) # send message
command = str(sock.recv(BUFFER_SIZE), "utf-8") # receive message
print("received %s" % command)
print("closing connection with server")
sock.close()
The issue is when I send an empty message to the server it hangs and just says sending in the terminal and the server never receives anything. I am not sure what is causing this but I am assuming the pipes are being blocked or that I am not handling this correctly.
I want the server to return an error message to the client rather than handle the message error in the client itself.
I tried checking the condition if the length of the command is 0 and handling it with an error message but it did not work and still hangs.
The program also seems to hang when I try for example the date command.
In general, how do I handle the condition if a command is not recognized, empty or doesn't execute successfully?
TCP has no concept of an empty message. TCP has no concept of a message at all, it knows only bytes. Thus, if you call send with an empty string it will simply send nothing (not an empty packet but no packet at all) to the server which means that there is nothing for the server to receive - it will still block while waiting for data. In other words: there is no empty command, there is simply no comment at all.
if len(command) == 0:
This will not check for an empty message (which again does not exist) but will trigger if the client closes the connection. Any check for an empty command had to be done at the client already.

Python Socket, how do i choose between s.send and conn.send?

def send_Button():
try:
myMsg = "ME: " + text.get()
msg = text.get()
conn.send(msg) ###
textBox.insert(END, myMsg + "\n")
textEntry.delete(0, END)
textBox.yview_pickplace("end")
except NameError:
myMsg = "ME: " + text.get()
msg = text.get()
conn.send(msg) ###
textBox.insert(END, myMsg + "\n")
textEntry.delete(0, END)
textBox.yview_pickplace("end")
This program uses the tkinter module with socket in python2.7. My program allows for you to either connect to a server to chat with or host a server for others to connect to you, but whenever I try and test it out then the lines with the '###' on always bring up an error and it doesn't work, the error which comes up is: "NameError: global name 'conn' is not defined" OR "error: [Errno 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied".
Any help please?
I think that you are trying to get the program to act as a Client or as a Server just changing s.send() to conn.send() saddly it isn't that simple.
Socket Initializzation
The socket have to be initialized before sending or receiving data.
For a client usually it's something like this.
send_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # Create the socket
send_socket.connect((serverIp, serverPort)) # Connect to the server
send_socket.send(data) # Send the data to the server
And like this for a Server:
listen_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # Create the socket
listen_socket.bind(("0.0.0.0", port)) # Set the socket to accept client from every interface on the port port
listen_socket.listen(1) # Put the server on listen on the port setted before
accept_socket, addr = self.listen_socket.accept() # when a client connect return the socket to talk with it
data = self.accept_socket.recv(buffer_size) # Receive data form the client of max size buffer_size
Docs examples
From your question I guess that with s.send() and conn.send() you are talking about
this example from the python 2.7 socket docs
Here are four minimal example programs using the TCP/IP protocol: a server that echoes all data that it receives back (servicing only one client), and a client using it. Note that a server must perform the sequence socket(), bind(), listen(), accept() (possibly repeating the accept() to service more than one client), while a client only needs the sequence socket(), connect(). Also note that the server does not sendall()/recv() on the socket it is listening on but on the new socket returned by accept().
Client
Echo client program
import socket
HOST = 'daring.cwi.nl' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
the client is pretty stright forward, it create the socket s and then after using s.connect() it just send data through it.
Server
The server one is where there there are both s and conn
Echo server program
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
conn.close()
in this one first of all we create a socket s on which the server will listen and then using s.accept() it will wait till a client connect to the server and then return the conn which is the socket of the connected client.
So to receive or send data to the client you have to use conn.
Notes
As said in the documentation in these two example the server accept only one client. So if you want to deal with multiple clients you have to repeat the accept step and possibly generate a new Thread for each client so that other clients don't have to wait for each others.

How to connect to server, listen for arbitrary time and send back data

I'm trying to:
Connect to a server/port
Listen for x seconds
Receive user input
Send user input to server
Go back to step 2
So far, I've written the following code, but it's not working properly receiving input after the first send. Any help would be greatly appreciated.
import socket
import select
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('domain.com', 1234))
client_socket.setblocking(0)
timeout = 5
while True:
while True:
ready = select.select([client_socket], [], [], timeout)
if ready[0]:
data = client_socket.recv(4096)
print data
else:
break
data = raw_input("Enter input:")
client_socket.send(data)
You need to have separate server side code and client side code. This article has been referred.
Server binds to a port and listens for clients
server.py
import select
import socket
# Create a TCP/IP socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(0)
# Bind the socket to the port
server_address = ('localhost', 1234)
server.bind(server_address)
# Listen for incoming connections
server.listen(5)
# Sockets from which we expect to read
inputs = [ server ]
# Sockets to which we expect to write
outputs = [ ]
while inputs:
readable, writable, exceptional = select.select(inputs, outputs, inputs)
# Handle inputs
for s in readable:
if s is server:
# A "readable" server socket is ready to accept a connection
connection, client_address = s.accept()
connection.setblocking(0)
inputs.append(connection)
else:
data = s.recv(1024)
if data:
print "Receiving data from client"
print data
else:
inputs.remove(s)
s.close()
Client first establishes a connection with the server and then keeps on sending user input to the server.
client.py
import socket
server_address = ('domain.com', 1234)
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(server_address)
while True:
data = raw_input("Enter input:")
sock.send(data)
Open terminal.
Run server in background:
python server.py &
Run client after that:
python client.py

Categories