awnumar / memguard

Secure software enclave for storage of sensitive information in memory.
Apache License 2.0
2.49k stars 124 forks source link

Securely copying from Memguard? #55

Closed malexdev closed 6 years ago

malexdev commented 6 years ago

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!

awnumar commented 6 years ago

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.

malexdev commented 6 years ago

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

awnumar commented 6 years ago

No worries, I'm happy to help!