by malft · 5y ago · 0 comments
// The documentation says that if the string for some reason was not stored with zero-termination, we need to manually terminate it. Sigh!
if (value[length]) { value[length+1] = 0; }
DWORD required_length;
auto rc = RegQueryValueExW(key, version, NULL, NULL, NULL, &required_length);
if (rc != 0) return NULL;
DWORD length = required_length + 2; // The +2 is for the maybe optional zero later on. Probably we are over-allocating.
wchar_t *value = (wchar_t *)malloc(length);
if (!value) return NULL;
rc = RegQueryValueExW(key, version, NULL, NULL, (LPBYTE)value, &length); // We know that version is zero-terminated...
if (rc != 0) return NULL;
// The documentation says that if the string for some reason was not stored
// with zero-termination, we need to manually terminate it. Sigh!!
if (value[length]) {
value[length+1] = 0;
}
`length` starts at 2 greater than naively needed, then is updated to the real value (again, always 2 less I guess).Don't poke beyond your end. Don't poke using a value that was returned by a function you don't control. The code shown does both. Such quality, it Jonathan Blow.
> NOTE(Kalinovcic): I have translated the original implementation to C
Another point, this is a build-time tool: some assumptions of good-faith input are reasonable and necessary. If an attacker can modify paths to visual studio components in your registry, you have bigger problems (just running the attacker's code directly regardless of safe string handling).
EDIT: I develop on unix systems, not windows, so I'm rusty here ... looking up RegQueryValueExW() the `length` ("lpcbData") is in bytes so everything goes fine until `value[length]` which is indexing by wchar_t (16-bit on windows I guess, 32-bit on linux systems) so it's double the byte offset intended, that's way out.
wchar_t is also more than one byte, so the buffer is at most half as big as the code appears to expect.
Source seems to take into account the buffer overflow:
DWORD length = required_length + 2; // The +2 is for the maybe optional zero later on. Probably we are over-allocating.