How do I create temporary files and directories in a secure way on linux?



  • Also see: Man page for mktemp

    Many know of putting the process ID at the end of the file /tmp/mylog.$$, which can be done as long as there is nothing sensitive in the file. The $$ just puts your shell process id at the end of the file.
    The file name is created with these permissions; anyone can read it.

    ls -l /tmp/mylog.5929
    -rw-rw-r-- 1 trainer trainer 0 Nov 13 11:18 mylog.5929
    

    A better way is to always use mktemp in scripts to make the file name difficult for anyone to guess.

    Create a temporary file with 10 random characters.

    $ mktemp /tmp/mylog.XXXXXXXXXX
    /tmp/mylog.LlIu9B0PPw
    

    Notice the file permissions are a lot more secure.

    $ ls -l /tmp/mylog.LlIu9B0PPw
    -rw------- 1 trainer trainer 0 Nov 13 11:15 /tmp/mylog.LlIu9B0PPw
    

    The same can be done for directories. Assuming TMPDIR is set to /tmp.

    $ mktemp -d -t my_logfiles.XXXXXXXXXX
    /tmp/my_logfiles.l2DPRJuGne
    
    $ ls -ld /tmp/my_logfiles.l2DPRJuGne
    drwx------ 2 trainer trainer 2 Nov 13 11:24 /tmp/my_logfiles.l2DPRJuGne
    

Log in to reply
 

© Lightnetics 2024