0

I have a test, which is run during the standard cmake/ctest process.

The problem is that my test needs to create a temporary file (no need to preserve it across different tests), and it fails with the EACCES error code.

The following (presumably) fails:

m_hFile = open("/tmp/mytest.bin", O_RDWR | O_CREAT);

Do I have to tweak something related to the permissions, or perhaps write to another location?

jww
  • 97,681
  • 90
  • 411
  • 885
valdo
  • 12,632
  • 2
  • 37
  • 67
  • The documentation is here: http://man7.org/linux/man-pages/man2/open.2.html – alk Apr 16 '18 at 05:40
  • You should probably use `TMPDIR` if it is set. If it is not set, then you need to find a writable directory that an attacker does not control or influence. Maybe `~/.tmp/`. Note that the [GCC Compile Farm](https://gcc.gnu.org/wiki/CompileFarm) mounts `/` read-only and denies users write access, so even `/tmp` is off-limits. Also see [`cryptest.sh`](https://github.com/weidai11/cryptopp/blob/master/cryptest.sh), which we can use (almost?) everywhere, including AIX, BSDs, OS X, Linux, Solaris. One of the first things it tries to do is find a suitable `TMPDIR`. – jww Apr 17 '18 at 01:39

2 Answers2

3

You can use the ISO C function tmpfile to create a temporary file with an auto-generated filename. The file is opened in "wb+" mode.

The implementation should select a directory by itself where temp files can be created; in the POSIX documentation it specifies that this can only fail if there are too many open file handles already, or the disk is out of space. (i.e. permission error isn't possible).

Also you can use the tmpnam function to generate a unique filename (this is not thread-safe), which you can then try to create a file for.

M.M
  • 138,810
  • 21
  • 208
  • 365
  • didn't know this function, very useful but `tmpnam()` don't look useful or even safe to use. – Stargateur Apr 17 '18 at 03:28
  • @Stargateur Yeah it probably is not something you'd want to use in production code; opening a file using that name might fail for various reasons (e.g. some other process used the same name in the meantime) – M.M Apr 17 '18 at 03:29
  • Thanks, but I don't need it to be a temp file. It should support any file, and the test should give it a path in a temp directory. – valdo Apr 17 '18 at 06:53
  • @valdo your question says "my test needs to create a temporary file (no need to preserve it across different tests)" – M.M Apr 17 '18 at 09:37
  • @valdo ???????????????????? What you say don't make sense read [ask] – Stargateur Apr 17 '18 at 10:18
1

Thanks everybody, I found the problem.

Turns-out that in case the file doesn't exist and should be created - it seems that I must specify the mode, and use the 3-parameter version of open.

m_hFile = open("/tmp/mytest.bin", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);
valdo
  • 12,632
  • 2
  • 37
  • 67