cherry-pick.FILE5_34-17-g54bec4a0.eliminate-toctou-by-using-fstat-and-always-opening-with-non-blocking-i-o.patch 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. Subject: Eliminate toctou by using fstat and always opening with non-blocking i/o
  2. Origin: FILE5_34-17-g54bec4a0 <https://github.com/file/file/commit/FILE5_34-17-g54bec4a0>
  3. Upstream-Author: Christos Zoulas <christos@zoulas.com>
  4. Date: Wed Aug 1 10:07:00 2018 +0000
  5. Found by coverity.
  6. --- a/src/file.h
  7. +++ b/src/file.h
  8. @@ -597,6 +597,9 @@
  9. #ifndef O_BINARY
  10. #define O_BINARY 0
  11. #endif
  12. +#ifndef O_NONBLOCK
  13. +#define O_NONBLOCK 0
  14. +#endif
  15. #ifndef __cplusplus
  16. #if defined(__GNUC__) && (__GNUC__ >= 3)
  17. --- a/src/magic.c
  18. +++ b/src/magic.c
  19. @@ -442,18 +442,12 @@
  20. else
  21. pos = lseek(fd, (off_t)0, SEEK_CUR);
  22. } else {
  23. - int flags = O_RDONLY|O_BINARY;
  24. - int okstat = stat(inname, &sb) == 0;
  25. -
  26. - if (okstat && S_ISFIFO(sb.st_mode)) {
  27. -#ifdef O_NONBLOCK
  28. - flags |= O_NONBLOCK;
  29. -#endif
  30. - ispipe = 1;
  31. - }
  32. -
  33. + int flags = O_RDONLY|O_BINARY|O_NONBLOCK;
  34. errno = 0;
  35. if ((fd = open(inname, flags)) < 0) {
  36. + int okstat = fstat(fd, &sb) == 0;
  37. + if (okstat && S_ISFIFO(sb.st_mode))
  38. + ispipe = 1;
  39. #ifdef WIN32
  40. /*
  41. * Can't stat, can't open. It may have been opened in