“'getenv': This function or variable may be unsafe.” - really?

被刻印的时光 ゝ 提交于 2020-04-12 19:46:13

问题


I'm using MSVC to compile some C code which uses standard-library functions, such as getenv(), sprintf and others, with /W3 set for warnings. I'm told by MSVC that:

'getenv': This function or variable may be unsafe. Consider using _dupenv_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS

Questions:

  • Why would this be unsafe, theoretically - as opposed to its use on other platforms?
  • Is it unsafe on Windows in practice?
  • Assuming I'm not writing security-oriented code - should I disable this warning or actually start aliasing a bunch of standard library functions?

回答1:


getenv() is potentially unsafe in that subsequent calls to that same function may invalidate earlier returned pointers. As a result, usage such as

char *a = getenv("A");
char *b = getenv("B");
/* do stuff with both a and b */

may break, because there's no guarantee a is still usable at that point.

getenv_s() - available in the C standard library since C11 - avoids this by immediately copying the value into a caller-supplied buffer, where the caller has full control over the buffer's lifetime. dupenv_s() avoids this by making the caller responsible for managing the lifetime of the allocated buffer.

However, the signature for getenv_s is somewhat controvertial, and the function may even be removed from the C standard at some point... see this report.




回答2:


getenv suffers like much of the classic C Standard Library by not bounding the string buffer length. This is where security bugs like buffer overrun often originate from.

If you look at getenv_s you'll see it provides an explicit bound on the length of the returned string. It's recommended for all coding by the Security Development Lifecycle best practice, which is why Visual C++ emits deprecation warnings for the less secure versions.

See MSDN and this blog post

There was an effort by Microsoft to get the C/C++ ISO Standard Library to include the Secure CRT here, some of which was approved for C11 Annex K as noted here. That also means that getenv_s should be part of the C++17 Standard Library by reference. That said, Annex K is officially considered optional for conformance. The _s bounds-checking versions of these functions are also still a subject of some debate in the C/C++ community.



来源:https://stackoverflow.com/questions/48568707/getenv-this-function-or-variable-may-be-unsafe-really

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!