java equivalent for mkstemp
<p>Is there any way in Java to write out to a temporary file securely?</p>

<p>As far as I can tell, the only way to create a temporary file (createTempFile) does't actually open it at the same time, so there's a race condition between file open &amp; file write.  Am I missing something?  I couldn't find the C source code behind createFileExclusively(String) in UnixFileSystem.java, but I doubt it can really do anything since the file open occurs in the Java code after the temp file is created (unless it tries to do something with file locks?).</p>

<p><strong>The problem</strong></p>

<p>Between when the temporary file is created &amp; you open it, a malicious attacker could unlink that temporary file &amp; put malicious stuff there.  For example, an attacker could create a named pipe to read sensitive data.  Or similarly if you eventually copy the file by reading it, then the named pipe could just ignore everything written &amp; supply malicious content to be read.</p>

<p>I remember reading of numerous examples of temporary file attacks in the past 10+ years that exploit the race condition between when the name appears in the namespace and when the file is actually opened.</p>

<p>Hopefully a mitigating factor is that Java set's the umask correctly so a less-privileged user can't read/write to the file and typically the /tmp directory restricts permissions properly so that you can't perform an unlink attack.</p>

<p>Of course if you pass a custom directory for the temporary file that's owned by a less-privileged user who's compromised, the user could do an unlink attack against you.  Hell, with inotify, it's probably even easier to exploit the race condition than just a brute force loop that does a directory listing.</p>
