oss-sec mailing list archives

AW: O_CREAT|O_DIRECTORY on nonexisting file expected behaviour?


From: Fiedler Roman <Roman.Fiedler () ait ac at>
Date: Wed, 26 Nov 2014 15:28:02 +0000

Von: Eric Blake [mailto:eblake () redhat com]

On 11/26/2014 06:45 AM, Fiedler Roman wrote:
Hello,

While trying to write a small python helper library for secure opening of
files, I found behaviour of following call unexpected because it created a
file instead of creating/failing in opening a directory:

open("xxx", O_RDONLY|O_CREAT|O_DIRECTORY, 0600) = 3

What does fstat say about the file type of the just-created fd 3?

Fstat is also saying "file", same as "ls xxx" afterwards.

Here's what POSIX has to say about the matter:
http://austingroupbugs.net/view.php?id=847

If the combination is supported, it MUST create a directory.  This is
actually a nice extension if it is provided, as there is no other
standard interface that can atomically create AND open a directory;
remember, there is a minor TOCTTOU race between mkdir()/open(), although
the effects of that race are not too horrible (it is sufficient to use
O_DIRECTORY during the open as well as a quick readdir to confirm that
the just-opened directory is still empty, to be reasonably sure that the
race was not won by someone replacing the directory with something
unintended).  On the other hand, the behavior is an extension, and
historical implementations would fail (probably with EINVAL for invalid
flag combination), so portable applications cannot rely on it working.

But if it succeeds, and did NOT create a directory, then it is in
violation of POSIX.

Thanks for the pointer to the POSIX documentation. So it seems to be a 
POSIX-violation, at least on "Linux version 3.2.0-69-generic".

My test program was:

#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>

int main(int argc, char **argv) {
  int fd;
  struct stat statBuf;
  int result;

  fd=open("xxx", O_RDWR|O_CREAT|O_DIRECTORY, 0600);
  result=fstat(fd, &statBuf);
  if(result) {
    fprintf(stderr, "Stat failed\n");
    return(1);
  }
  fprintf(stderr, "New element type is %d\n", S_ISDIR(fd));
  return(0);
}

Attachment: smime.p7s
Description:


Current thread: