]> granicus.if.org Git - file/commitdiff
Eliminate toctou by using fstat and always opening with non-blocking i/o.
authorChristos Zoulas <christos@zoulas.com>
Wed, 1 Aug 2018 10:07:00 +0000 (10:07 +0000)
committerChristos Zoulas <christos@zoulas.com>
Wed, 1 Aug 2018 10:07:00 +0000 (10:07 +0000)
Found by coverity.

src/file.h
src/magic.c

index 57a84a80c0d5ec0cd4118f9599fa80a36e946ec6..1cdfe8250ea0aef46bb9e98c4d4ad51430e7d5eb 100644 (file)
@@ -27,7 +27,7 @@
  */
 /*
  * file.h - definitions for file(1) program
- * @(#)$File: file.h,v 1.193 2018/05/24 18:09:17 christos Exp $
+ * @(#)$File: file.h,v 1.194 2018/08/01 10:07:00 christos Exp $
  */
 
 #ifndef __file_h__
@@ -634,6 +634,9 @@ protected void file_warnx(const char *, ...)
 #ifndef O_BINARY
 #define O_BINARY       0
 #endif
+#ifndef O_NONBLOCK
+#define O_NONBLOCK     0
+#endif
 
 #ifndef __cplusplus
 #if defined(__GNUC__) && (__GNUC__ >= 3)
index e3c31ee0cfee9839138b90618993fc175b788ddc..1bb46659738fed37c072e7016ef21a92eb5aa757 100644 (file)
@@ -33,7 +33,7 @@
 #include "file.h"
 
 #ifndef        lint
-FILE_RCSID("@(#)$File: magic.c,v 1.103 2018/07/25 06:27:09 christos Exp $")
+FILE_RCSID("@(#)$File: magic.c,v 1.104 2018/08/01 10:07:00 christos Exp $")
 #endif /* lint */
 
 #include "magic.h"
@@ -442,18 +442,12 @@ file_or_fd(struct magic_set *ms, const char *inname, int fd)
                else
                        pos = lseek(fd, (off_t)0, SEEK_CUR);
        } else {
-               int flags = O_RDONLY|O_BINARY;
-               int okstat = stat(inname, &sb) == 0;
-
-               if (okstat && S_ISFIFO(sb.st_mode)) {
-#ifdef O_NONBLOCK
-                       flags |= O_NONBLOCK;
-#endif
-                       ispipe = 1;
-               }
-
+               int flags = O_RDONLY|O_BINARY|O_NONBLOCK;
                errno = 0;
                if ((fd = open(inname, flags)) < 0) {
+                       int okstat = fstat(fd, &sb) == 0;
+                       if (okstat && S_ISFIFO(sb.st_mode))
+                               ispipe = 1;
 #ifdef WIN32
                        /*
                         * Can't stat, can't open.  It may have been opened in