通过读源码win10驱动下实现3环的GetEnvironmentVariable

2021-06-23 20:05

阅读:404

标签:starting   效果   uml   imu   pre   text   erro   getenv   sch   

效果图:
技术分享图片
NTSTATUS NTAPI
RtlQueryEnvironmentVariable_U(PWSTR Environment,
    PCUNICODE_STRING Name,
    PUNICODE_STRING Value)
{
    NTSTATUS Status;
    PWSTR wcs;
    UNICODE_STRING var;
    PWSTR val;
    BOOLEAN SysEnvUsed = FALSE;

    DbgPrint("RtlQueryEnvironmentVariable_U Environment %p Variable %wZ Value %p\n",
        Environment, Name, Value);

    if (Environment == NULL)
    {
        MPPEB Peb = RtlGetCurrentPeb();
        if (Peb) {
            //RtlAcquirePebLock();

            Environment = Peb->ProcessParameters->Environment;
            SysEnvUsed = TRUE;
        }
    }

    if (Environment == NULL)
    {
        //if (SysEnvUsed)
            //RtlReleasePebLock();
        return(STATUS_VARIABLE_NOT_FOUND);
    }

    Value->Length = 0;

    wcs = Environment;
    DbgPrint("Starting search at :%p\n", wcs);
    while (*wcs)
    {
        var.Buffer = wcs++;
        wcs = wcschr(wcs, L‘=‘);
        if (wcs == NULL)
        {
            wcs = var.Buffer + wcslen(var.Buffer);
            DbgPrint("Search at :%S\n", wcs);
        }
        if (*wcs)
        {
            var.Length = var.MaximumLength = (USHORT)(wcs - var.Buffer) * sizeof(WCHAR);
            val = ++wcs;
            wcs += wcslen(wcs);
            DbgPrint("Search at :%S\n", wcs);

            if (RtlEqualUnicodeString(&var, Name, TRUE))
            {
                Value->Length = (USHORT)(wcs - val) * sizeof(WCHAR);
                if (Value->Length MaximumLength)
                {
                    memcpy(Value->Buffer, val,
                        min(Value->Length + sizeof(WCHAR), Value->MaximumLength));
                    DbgPrint("Value %S\n", val);
                    DbgPrint("Return STATUS_SUCCESS\n");
                    Status = STATUS_SUCCESS;
                }
                else
                {
                    DbgPrint("Return STATUS_BUFFER_TOO_SMALL\n");
                    Status = STATUS_BUFFER_TOO_SMALL;
                }

                //if (SysEnvUsed)
                    //RtlReleasePebLock();

                return(Status);
            }
        }
        wcs++;
    }

    /*if (SysEnvUsed)
        RtlReleasePebLock();
*/
    DbgPrint("Return STATUS_VARIABLE_NOT_FOUND: %wZ\n", Name);
    return(STATUS_VARIABLE_NOT_FOUND);
}
//获取环境变量 
DWORD My_Get_Environment_Variable(IN LPCWSTR lpName,
    IN LPWSTR lpBuffer,
    IN DWORD nSize) {
    UNICODE_STRING VarName, VarValue;
    NTSTATUS Status;
    USHORT UniSize;

    if (nSize 

用法:

wchar_t buffer[256];
    wchar_t pwcDevNameBuf = NULL;
    DWORD code = My_Get_Environment_Variable(L"TEMP", buffer, 256);
    DbgPrint("buffer----------- %S\n", buffer);

通过读源码win10驱动下实现3环的GetEnvironmentVariable

标签:starting   效果   uml   imu   pre   text   erro   getenv   sch   

原文地址:http://blog.51cto.com/haidragon/2336002


评论


亲,登录后才可以留言!