Clipboard hygiene

After using the excellent keepassx password manager for a while, I’ve noticed it has a nice little security feature: once you copy a password to the clipboard, keepassx waits for a short period of time and then clears your clipboard. It also clears the clipboard when you close keepassx.

This is a good idea as it somewhat reduces the chance of some other process being able to steal a password from the clipboard (which any user-level process could do). More usefully, it also reduces the chance of you accidentally pasting the password somewhere you didn’t want to.

It’s the second point that’s important, and got me thinking about this general hazard with the clipboard. There are other risks besides passwords being copied where they shouldn’t be:

Because of these potential hazards, I thought it would be nice to apply the clipboard cleaning idea from keepassx more generally. It won’t totally eliminate the risk of the above happening, but it can at least mitigate it to some extent.

It looks like it is possible to do this by listening to clipboard events in X with something like clipnotify, but it seems simpler to just clean the clipboard on a regular basis.

This command overwrites the clipboard in X using xsel:

xsel -bc

It would be possible to run this using cron, but it’s easier for me to have it run from my .profile.

This one-liner has it run every 30 seconds, which seems a good balance between cleaning the clipboard to reduce risk and not having it kick in at a bad moment when I do actually want to paste something:

watch -n 30 'xsel -bc' &

I’ve got it in ~/.profile like this:

if ! pgrep -f 'xsel -bc' > /dev/null                
        watch -n 30 'xsel -bc' &                    

There’s a simple check for an existing process that looks like its doing the same thing, to avoid creating several processes all doing this at different times.

This may not be the most elegant solution, but it serves my needs in keeping the clipboard a bit cleaner and reducing the risk of bad mistakes.

Tech mentioned