Search code examples
windowsbashgit-bashmingw-w64

"history -c" doesn't work when called inside a script?


I wrote a bash script to call a Python script that encrypts private data using AES, taking a filepath and a 256-bit password as the only arguments. After encryption is done, it clears the history so the password isn't sitting there in case I leave the terminal open. It looks something like this:

#!/bin/bash

python aesencrypt.py "$1" "$2"
history -c
echo "" > ~/.bash_history

The ~/.bash_history file is cleared just fine, but if I run history after running this script then all of my history is still there (until I exit the terminal). Is there anything I'm missing here?


Solution

  • Don't try to clear history -- even though that's the most obvious way that passing a password on the command line exposes it, that action is giving a false sense of security: Passwords given on the command line are trivial to capture via other processes running on the same machine (even under untrusted accounts!) even without history involved at all.

    Moreover, as you note, a shell can only modify its own in-memory state, not the in-memory state of the separate process that started it (which may not even be the same shell, or a shell at all!).


    Instead, modify your Python program's calling convention to read the password direct from the TTY (as SSH does), or from the environment. For the latter, usage might look like:

    # assumes you renamed aesencrypt.py to aesencrypt, ran chmod +x, and gave a valid shebang
    password="somePassword" aesencrypt outFile
    

    ...and you would want to modify your Python script to do something like:

    #!/usr/bin/env python
    import os, sys
    
    filename = sys.argv[1]
    password = os.environ['password']
    
    # ...put the rest of your logic here.