0

I am new to C++ programming. I am carrying out an SAST violations check for my code, and the scan throws a warning:

_tcscpy(destination_array,Source);

The dangerous function, _tcscpy, was found in use at line 58 in Source.cpp file. Such functions may expose information and allow an attacker to get full control over the host machine

So instead, now I had to use this which makes the warning go away:

_tcscpy_s(destination_array,_countof(destination_array),Source);

What is the actual difference between _tcscpy and _tcscpy_s, and how does it make the code safe?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Mr.Curious
  • 282
  • 1
  • 3
  • 11
  • 2
    It's all documented here: https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strcpy-s-wcscpy-s-mbscpy-s and here: https://learn.microsoft.com/en-us/cpp/c-runtime-library/security-features-in-the-crt?view=msvc-160 – Jabberwocky Oct 27 '21 at 07:48
  • 1
    Don't forget to look at std::copy. https://en.cppreference.com/w/cpp/algorithm/copy it is safe, and it can even outperform other copy functions: https://stackoverflow.com/questions/4707012/is-it-better-to-use-stdmemcpy-or-stdcopy-in-terms-to-performance) – Pepijn Kramer Oct 27 '21 at 08:34
  • 1
    Why are you considering using either? Even if there is a good reason to be working with C strings rather than using the classes from the C++ std lib, why would you be using generic text functions? Surely you aren't trying to support Windows 9x and Windows NT with the same codebase. Surely your code can settle on using the native UTF-16 encoding. – David Heffernan Oct 27 '21 at 09:48

1 Answers1

6

The actual difference is that _s functions check the destination buffer before writing to it. If the buffer is too small then either the program is aborted, or an error value is reported, depending on the current error handler.

This prevents buffer overrun attacks, when malicious data is formed in some specific way to overwrite other data and gain the control over the program.

Sure the prevention only works if the size of destination buffer is passed correctly. If not, buffer overruns and attacks are still possible.

Even if the application does not have security implication, it may be useful to use _s functions anyway to avoid hard to pinpoint memory corruption bugs.

Visual C++ provides a templated version of _tcscpy_s, so for arrays instead of

_tcscpy_s(destination_array,_countof(destination_array),Source);

you can use

_tcscpy_s(destination_array,Source);

this is even more safe, as the size is deduced, so an incorrect size is not possible.

Alex Guteniev
  • 12,039
  • 2
  • 34
  • 79