In server-side Go code I acquire private keys and use them to sign assertions, but I don't want to leave them lying around in memory. Is the following sane?
var private ed25519.PrivateKey
// acquire and use the private key
// now I want to overwrite it so it's not lurking in memory
privKeyBytes := []byte(private)
_, _ = rand.Read(privKeyBytes)
CodePudding user response:
Yes, overwriting the key bytes should do it in most cases.
Note that currently the Go CMS garbage collector is a non-moving generational GC, meaning that if you don't make a copy of an object, then GC won't make copies either. This is implementation detail and may change in the future though.
Also, the // acquire and use the private key
part, depending on what it does, may also leak the key onto the heap. For example, reading a file in PEM format would probably leak the PEM-encoded string.
To really know for sure, break in gdb
immediately after overwriting the key and dump the entire heap to a file. Then search in it for the key bytes.
$ go build -gcflags "-N -l"
$ gdb ./test
(gdb) source /usr/go/src/runtime/runtime-gdb.py
Loading Go Runtime support.
(gdb) b test.go:16
(gdb) r
Thread 1 "test" hit Breakpoint 1, main.main () at test/test.go:16
(gdb) info i
Num Description Executable
* 1 process 14176 test/test
(gdb) (Ctrl-Z)
[1] Stopped gdb ./test
$ cat /proc/14176/maps|grep '\[heap\]'|(read a; x=(${a//-/ }); dd if=/proc/14176/mem bs=4096 iflag=skip_bytes,count_bytes skip=$((0x${x[0]})) count=$((0x${x[1]}-0x${x[0]})) of=heap.bin)
$ grep -obUaP "\x01\x02\x03..." heap.bin
$ fg
(gdb) q