tmpnam warning saying it is dangerous

后端 未结 5 1023
醉话见心
醉话见心 2021-01-03 19:15

I get this warning saying that tmpnam is dangerous, but I would prefer to use it, since it can be used as is in Windows as well as Linux. I was wondering why it would be con

相关标签:
5条回答
  • 2021-01-03 19:42

    From tmpnam manpage :

    The tmpnam() function generates a different string each time it is called, up to TMP_MAX times. If it is called more than TMP_MAX times, the behavior is implementation defined.

    Although tmpnam() generates names that are difficult to guess, it is nevertheless possible that between the time that tmpnam() returns a pathname, and the time that the program opens it, another program might create that pathname using open(2), or create it as a symbolic link. This can lead to security holes. To avoid such possibilities, use the open(2) O_EXCL flag to open the pathname. Or better yet, use mkstemp(3) or tmpfile(3).

    Mktemp really create the file, so you are assured it works, whereas tmpnam returns a name, possibly already existing.

    0 讨论(0)
  • 2021-01-03 19:44

    If you want to use the same symbol on multiple platforms, use a macro to define TMPNAM. As long as you pick more secure functions with the same interface, you'll be able to use it on both. You have conditional compilation somewhere in your code anyway, right?

    0 讨论(0)
  • 2021-01-03 19:52

    From the tmpnam(3) manpage:

    Although tmpnam() generates names that are difficult to guess, it is nevertheless possible that between the time that tmpnam() returns a pathname, and the time that the program opens it, another program might create that path‐ name using open(2), or create it as a symbolic link. This can lead to security holes. To avoid such possibili‐ ties, use the open(2) O_EXCL flag to open the pathname. Or better yet, use mkstemp(3) or tmpfile(3).

    0 讨论(0)
  • 2021-01-03 19:54

    if you speak about the compiler warning of MSVC:

     These functions are deprecated because more secure versions are available;
     see tmpnam_s, _wtmpnam_s.
    

    (http://msdn.microsoft.com/de-de/library/hs3e7355(VS.80).aspx)

    otherwise just read what the manpages say about the drawbacks of this function. it is mostly about a 2nd process creating exactly the same file name as your process just did.

    0 讨论(0)
  • 2021-01-03 19:54

    The function is dangerous, because you are responsible for allocating a buffer that will be big enough to handle the string that tmpnam() is going to write into that buffer. If you allocate a buffer that is too small, tmpnam() has no way of knowing that, and will overrun the buffer (Causing havoc). tmpnam_s() (MS's secure version) requires you to pass the length of the buffer, so tmpnam_s know when to stop.

    0 讨论(0)
提交回复
热议问题