anekix
anekix

Reputation: 2563

Debugging the stack corruptuion around a variable in windbg

i am trying to use a .dll in windows to test custom login in windows. This is the source of dll.

Note: This is more of a general debugging question(& the working of .dll plugin i am using might not be required)

The Dll loads fine ( i can visually verify this on windows logon screen) But when i enter the password & Otp and submit it gives an error saying stack around the variable onelinew is corrupted. as far as i can tell this means its either because of writing too much data than the buffer can hold or trying to reference something that isn't in memory?.

I tried to attach the windbg debugger to find the source of stack corruption & tried to look at various things like stack frames/call stacks/register values...etc .but i am stuck on how to make sense of this as i a bit new to this style of debugging(2 days now).

i will attach a screen shot of error and stack calls , hopefully someone can tell where to go on from here.

The last log in the log file created by this plugin is MultiotpCredential::Dll compiled with SKIP_OTP_CHECK !!!!!!!!" which is defined here

the variable onelinew which is appering in error box is defined here as:

void PrintLn(const wchar_t *message, int line)
{
    INIT_ZERO_CHAR(date_time, MAX_TIME_SIZE);
    GetCurrentTimeAndDate(date_time);
    WriteLogFile(date_time);

    // MessageBox(NULL, (LPCWSTR)message, NULL, MB_ICONWARNING);

    wchar_t onelinew[1024];
    swprintf_s(onelinew, sizeof(onelinew), message, line);

    //  OutputDebugStringW(message);
    WriteLogFile(onelinew);
    WriteLogFile("\n");
}

error image

enter image description here

Upvotes: 0

Views: 303

Answers (1)

Neitsa
Neitsa

Reputation: 8166

You have done the more difficult part which is to find the culprit. The error message tells you that you have a stack based buffer overflow.

    wchar_t onelinew[1024];
    swprintf_s(onelinew, sizeof(onelinew), message, line);

Note that in your case, as the code is using wchar_t, there are 2 bytes per character. Simply put, your buffer can contain at most 1024 wchar_t. If message is more than 1024 wchar_t (2048 bytes, including the null characters) then your buffer is overflowed.

The documentation for swprintf_s is not very clear, but if I'm not mistaken (I think it's clearer in the documentation for swprintf) the second parameter is the number of characters, not bytes.

The problem is that the sizeof operator will return the number of bytes (2048 in this case) which tells the API that the buffer is 2048 characters but your buffer is only 1024 characters.

Thus you should specify it like this (or use the _countof macro):

    wchar_t onelinew[1024];
    swprintf_s(onelinew, sizeof(onelinew) / sizeof(wchar_t), message, line);

Upvotes: 1

Related Questions