Freigeben über


Rant: Why do unsafe string functions still exist?

One thing that I fail to understand is why, in 2004, we still have code that uses strcat, strcpy, sprintf or any of the other string functions that don’t take a buffer size input. Microsoft, Open source, etc all still use these functions. Why? Can you write safe code that uses these functions? Sure. Can you write unsafe code that uses the ‘n’ versions? Sure, but at least it won't buffer overrun. Why bother trying to figure out if a call site to strcpy is safe? Just replace it with StringCchCopy. It’s easy to do. Much easier then proving that the call sight is okay.

What I would like to see is:

  1. The functions removed from the static versions of the CRT
  2. Add a regkey to disable the functions in the dynamic CRTs
  3. As a requirement before we ship a service pack, or new product, every call site removed

Oh, and if you think it is too hard to replace all the calls to strcpy. You can do this:

template <int CCH>

inline HRESULT SafeStrCopy(char (&szBuffer)[CCH], const char *szStr)

{

      C_ASSERT(CCH > 0);

      return StringCchCopy(szBuffer, CCH, szStr);

}

#define strcpy SafeStrCopy

This will automatically convert these kinds of calls to be safe:

char buff[255];

strcpy(buff, UserString);

And cause a compiler error on these calls:

char* buff = new char[255];

strcpy(buff, UserString);

In my experience, most call sites to strcpy look like the first example.

Comments

  • Anonymous
    April 20, 2004
    Just FYI. This was posted to the MSDN site a couple of weeks ago.
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncode/html/secure03102004.asp
  • Anonymous
    April 20, 2004
    The industry is definately making progress on this front. But I think we are progressing too slowly. For instance, Microsoft spent a lot of time security reviewing Windows Server 2003. But we didn't fix this. Why? It would be nearly free.
  • Anonymous
    April 20, 2004
    You're way too confident that using 'n' string function won't cause a buffer overrun. If you get the buffer size wrong it will overrun no matter how much you believe that it won't. And getting the buffer size wrong is trivial, at least to people who would buffer overrun in the first place - using sizeof() for Unicode strings, bad pointer arithmetics when adding strings, and so on...
  • Anonymous
    April 20, 2004
    First, use templates like above (SafeStrCopy), and you will never get the size wrong. You can use them anytime that your buffer is fixed size. If you have a dynamic buffer, use CString.

    Second, you are not going to get the size wrong 100% of the time, so you have still made an improvement.
  • Anonymous
    April 20, 2004
    Corrected link
  • Anonymous
    July 28, 2004
    your web page looks screwy on mozilla, dude.