gorgonia / tensor

package tensor provides efficient and generic n-dimensional arrays in Go that are useful for machine learning and deep learning purposes
Apache License 2.0
359 stars 49 forks source link

Fix possible memory confusion in unsafe slice cast #68

Closed jlauinger closed 4 years ago

jlauinger commented 4 years ago

I found an incorrect cast []byte in internal/storage/header.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.

coveralls commented 4 years ago

Coverage Status

Coverage decreased (-0.01%) to 73.082% when pulling 79fdf884b8210aed49c819494b412fa60f7fa8d7 on jlauinger:fix-unsafe-slice-cast into d08c5f3a734b96df0b642ea26270cbb18be0bffd on gorgonia:master.

chewxy commented 4 years ago

Merged. @jlauinger I was wondering if you could send me an email with the title "Gorgonia Contributor 2020" ? chewxy [at] gmail