bashunix

Hiding secret from command line parameter on Unix


I've a script that launches inside of itself a command with a parameter that is a secret. For example:

#!/bin/bash
command-name secret

While running the command I can read through ps -ef | grep command-name which is the secret.

Is there any way of hiding the secret in a way that through ps -ef, the command line parameter is obfuscated?


Solution

  • First, you can NOT hide command line arguments. They will still be visible to other users via ps aux and cat /proc/$YOUR_PROCESS_PID/cmdline at the time of launching the program (before the program has a chance to do run-time changes to arguments). Good news is that you can still have a secret by using alternatives:

    1. Use standard input:

       mySecret='hello-neo' printenv mySecret | myCommand
      
    2. Use a dedicated file if you want to keep the secret detached from the main script (note that you'd be recommended to use full disc encryption and make sure the file has correct chmod permissions):

       cat /my/secret | myCommand
      
    3. Use environment variables (with caveats). If your program can read them, do this:

       mySecret='hello-neo' myCommand
      
    4. Use temporary file descriptor:

       myCommand <( mySecret='hello-neo' printenv mySecret )
      

    In the last case your program will be launched like myCommand /dev/fd/67, where the contents of /dev/fd/67 is your secret (hello-neo in this example).


    In all of the above approaches, be wary of leaving the command in bash command history (~/.bash_history). You can avoid this by either running the command from a script (file), or by interactively prompting yourself for password each time:

    read -s secret
    s=$secret printenv s | myCommand  # approach 2
    myCommand <( s=$secret printenv s )  # approach 3
    secret=$secret myCommand  # approach 4
    export secret && myCommand  # another variation of approach 4