modern-go / reflect2

reflect api without runtime reflect.Value cost
Apache License 2.0
758 stars 73 forks source link

fix possible memory confusion in unsafe slice cast #13

Closed jlauinger closed 4 years ago

jlauinger commented 4 years ago

I found an incorrect cast from string to []byte in reflect2.go. The problem is that when reflect.SliceHeader is created as a composite literal (instead of deriving it from an actual slice by cast), then the Go garbage collector will not treat its Data field as a reference. If the GC runs just between creating the SliceHeader and casting it into the final, real []byte slice, then the underlying data might have been collected already, effectively making the returned []byte slice a dangling pointer.

This has a low probability to occur, but projects that import this library might still use it in a code path that gets executed a lot, thus increasing the probability to happen. Depending on the memory layout at the time of the GC run, this could potentially create an information leak vulnerability.

This PR changes the function to create the reflect.SliceHeader from an actual slice by first instantiating the return value.

taowen commented 4 years ago

you are right

taowen commented 4 years ago

@AllenX2018

aosting commented 4 years ago

reflect2.go forget import "runtime"

jlauinger commented 4 years ago

Yes, I am sorry. there needs to be an import runtime, my bad!

AllenX2018 commented 4 years ago

Awesome!