WCHAR overflow when performing wcscpy_s

2.7k views Asked by At

When trying to retrieve a massive folder path from an outlook mailbox (no 255 char max length in path) I seem not be be handling it correctly, yet i have tried everything on the code and nothing seems to shine some light on the issue.

Path:        \\Mailbox - long\Inbox\fgsegesgrgesrgegthtrhrthyerytyertytthgfhgdfhdfh\sfhsjkdfhsjkhfweuifhskjefhjksdhjsdhfusehfklahdfajkehwfuasdf\sadfhjaehjfhaeufhuaseh9oa3heufhshudhjksahdfjkshadmldhasnf\awefuyawefioaw3yfiuapgpapwqq0uwqfeiusdfsgpsadncabpaw\iawehfiowaeghuiaegfwuioaghpaweufrhasdfhlkasvjdhlaehfuawieghgawgwaef\fasbclajsbvbwaubhvwabveuabvdjklzbdvjkhzusefhzlhsdf\vshiuwhpqphdfhvjsamhashmasdfvhnakjdsfiawjeijfvsadkjfsa\aefrghjksadfhjklshareuhsadhsahvsandvnlsdffalsdfh384fhsduafhl\fasfdlashjklefrhuaehfskhaahsdfhuhaiyeifoa38fodasfhsahdfklkkasdf\jkfhsakdfjhsjkladfhdsjkahfjkajkflashdfjkshafjksahfsdjafhsdjahfjsahldfkasf\fauiwehfeawhfjkhsakjfhsjkaefheuifhjksdhjkafhjksadhfjhaseuhfasjhdjkfhasfjhaskjdfhslaf\jklshadjkfhasjkhfjkaheuyhruiyq3y83yuryvnzxcvxzcviouxzcvzxvklzxvkl
Path Length: 766 to 812 char

Hopefully explaining it a bit better, the code;

if(....)
{
    size_t n = wcslen(outlookFolderPath->Value.lpszW);
    if(n < 100)
        wcscpy_s(m_szInheritedFolderPath, outlookFolderPath->Value.lpszW);
    else
    {
        WCHAR szTemp[2048] = {}, szText[2048]= {};
        LoadStringW(ghInstDLL, IDS_PATH_TRUNCATED, szText, 2048);
        swprintf_s(szTemp, szText, outlookFolderPath->Value.lpszW + ((n-80) * sizeof(WCHAR)));
        wcscpy_s(m_szInheritedFolderPath, szTemp);     // *** Dies Here ***
    }
} 
...

The fatal error occurrs at string.h line;

__DEFINE_CPP_OVERLOAD_SECURE_FUNC_0_1(errno_t, wcscpy_s, wchar_t, _Dest, _In_z_ const wchar_t *, _Source)
2

There are 2 answers

0
Hans Passant On BEST ANSWER
(n-80) * sizeof(WCHAR). 

That copies 160 characters in an array that's 100 characters long. Kaboom.

You want to count characters, not bytes. Delete * sizeof(WCHAR). And you ought to check for a surrogate.

0
Jan S On
swprintf_s(szTemp, szText, outlookFolderPath->Value.lpszW + ((n-80) * sizeof(WCHAR)));

Here the second argument is supposed to be the size of the buffer.