将自定义环境添加到 CreateEnvironmentBlock()



我正在使用CreateProcessAsUser + CreateEnvironmentBlock从另一个进程复制环境变量。

是否可以将自定义环境变量添加到调用CreateEnvironmentBlock结果中?

环境块只是一系列以空结尾的字符串(以双空终止的字符串结尾(。 只需解析它,插入新的键/值对,然后保存回缓冲区。 我写了一些代码来帮助你入门:

wstring lowercase(const wstring& s)
{
std::wstring str(s);
std::transform(str.begin(), str.end(), str.begin(),
[](wchar_t c) { return std::tolower(c); });
return str;
}
wstring appendToEnvironmentBlock(const void* pEnvBlock, const wstring& varname, const wstring& varvalue)
{
map<wstring, wstring> env;
const wchar_t* currentEnv = (const wchar_t*)pEnvBlock;
wstring result;
// parse the current block into a map of key/value pairs
while (*currentEnv)
{
wstring keyvalue = currentEnv;
wstring key;
wstring value;
size_t pos = keyvalue.find_last_of(L'=');
if (pos != wstring::npos)
{
key = keyvalue.substr(0, pos);
value = keyvalue; // entire string
}
else
{
// ??? no '=' sign, just save it off
key = keyvalue;
value = keyvalue;
}
value += L''; // reappend the null char
env[lowercase(key)] = value;
currentEnv += keyvalue.size() + 1;
}
// add the new key and value to the map
if (varvalue.empty())
{
env.erase(lowercase(varname)); // if varvalue is empty, just assume this means, "delete this environment variable"
}
else
{
env[lowercase(varname)] = varname + L'=' + varvalue + L'';
}
// serialize the map into the buffer we just allocated
for (auto& item : env)
{
result += item.second;
}
result += L'';
auto ptr = result.c_str();
return result;
}

然后假设您想在环境块中插入"NewEnvironmentVariable=GoSeahawks!!"。 按如下方式调用:

::CreateEnvironmentBlock(&envblock, hToken, TRUE);
wstring updatedBlock = appendToEnvironmentBlock(envblock, L"NewEnvironmentVariable", L"GoSeahawks!!!");
CreateProcessAsUser(token, ..., updatedBlock.c_str(), ...);

相关内容

  • 没有找到相关文章

最新更新