C ++ - 将代码注入运行进程(使用DLL)

时间:2017-04-22 09:06:52

标签: java c++ dll-injection

我正在尝试使用Dll注入更改正在运行的java进程中int的值。

我的Dll:

#include <stdio.h>
#include <windows.h>
#include <iostream>
#include <fstream>
#include <jni.h>

using namespace std;

BOOL APIENTRY DllMain(HMODULE hDLL, DWORD Reason, LPVOID Reserved)
{
    HMODULE m_hDllInstance = LoadLibrary("jvm.dll");
    if( m_hDllInstance == 0)
    {
        cout << "The jvm.dll could not be found" << endl;
        getchar();
    }
    else
        cout << "jvm.dll found" << endl;


    JavaVM *jvm;
    JNIEnv *env;

    typedef jint (JNICALL * GetCreatedJavaVMs)(JavaVM**, jsize, jsize*);
    GetCreatedJavaVMs jni_GetCreatedJavaVMs = (GetCreatedJavaVMs)GetProcAddress(m_hDllInstance, "JNI_GetCreatedJavaVMs");

    jint size = 1;
    jint vmCount;

    jint ret= jni_GetCreatedJavaVMs(&jvm, size, &vmCount);

    cout << endl << "GetCreated: " << vmCount << endl;
    getchar();

    jint rc = jvm->AttachCurrentThread((void **) & env, NULL);

    jclass cls = env->FindClass("com/InjectMe");
    jfieldID field = env->GetStaticFieldID(cls, "prefix", "I");
    jint integer = 1;
    env->SetIntField(cls, field, integer);

    return TRUE;
}

java类:

package com;

public class InjectMe 
{
    static int prefix = 0;

    public static void main(String[] args) 
    {
        java.util.Scanner sc = new java.util.Scanner(System.in);

        while(true)
        {
            String s = sc.nextLine();
            System.out.println(prefix + ": " + s);

            if(prefix == 1)
                break;
        }

        sc.close();
    }
}

当我在Dll注入器中调用GetLastError()时,我得到0,所以我没有将代码发布到它。

当我运行以下代码时,没有任何反应。我做错了什么?

谢谢

1 个答案:

答案 0 :(得分:0)

由于prefix是静态变量,因此您需要使用正确的函数:

env->SetStaticIntField(cls, field, integer);

DllMain()开始时,您可能还想添加类似的内容,因此所有内容都不会多次执行:

if( Reason!=DLL_PROCESS_ATTACH ) return TRUE;

最后,为了正确清理:

jvm->DetachCurrentThread();