Data.ByteString.Unsafe.unsafeWipe

Erik de Castro Lopo mle+hs at mega-nerd.com
Mon Jan 12 03:42:45 UTC 2015


Discussion period: one month

When handling sensitive information (like a user's password) it is
desirable to only keep the data around for as short a time as possible.
Specifically, relying on the garbage collector to clean it up is simply
not good enough.

I therefore propose that the following function to be added to the
Data.ByteString.Unsafe module:

    -- | Overwrites the contents of a ByteString with \0 bytes.
    unsafeWipe :: ByteString -> IO ()
    unsafeWipe bs =
        BS.unsafeUseAsCStringLen bs $ \(ptr, len) ->
            let go i
                    | i < 0 = return ()
                    | otherwise = pokeElemOff ptr i 0 >> go (i - 1)
            in go (len - 1)

It is added to the Unsafe module because it break referential transparency
but since ByteStrings are always kept in pinned memory, it should not
otherwise be considered unsafe.

It could be used as follows:

    main = do
        passwd <- getPassword
        doSomethingWith passwd
        unsafeWipe passwd
        restOfProgram


Cheers,
Erik
-- 
----------------------------------------------------------------------
Erik de Castro Lopo
http://www.mega-nerd.com/


More information about the Libraries mailing list