awnumar/memguard

Securely copying from Memguard?

malexdev opened this issue · 3 comments

Thanks so much for making this project.

I have a use case where essentially I need to be able to stream data from a socket, encrypt it, and then write it to disk. I need to ensure that this data is not inadvertently swapped to disk while this happens.

It seems to me that memguard would be a great way to ensure that the data doesn't swap. But, how do I actually safely access the data in the memguard buffer? I imagine I could just write byte-by-byte from a LockedBuffer, but if I do this won't the GC then suddenly become aware of the byte and potentially copy it around?

I imagine I'm misunderstanding something, any guidance is appreciated. Thanks!

From the socket, you could stream data directly into a LockedBuffer with something like:

data, err := memguard.NewMutable(1024)
if err != nil {
    return err
}
defer data.Destroy()

if _, err := conn.Read(data.Buffer()); err != nil {
    return err
}

And then use this buffer as the input to whatever encryption function you use, destroying the buffer afterwards. You don't really need to store the encrypted version in a LockedBuffer since you're writing it to disk anyways.

Fair point. Not sure how I didn’t think of that. Thanks very much!

No worries, I'm happy to help!