haskell / entropy

Easy entropy source for Haskell users.
Other
24 stars 49 forks source link

Fix winapi foreign imports on 64-bit windows #43

Closed mwu-tow closed 6 years ago

mwu-tow commented 6 years ago

Hello, when using entropy in our project we observed rare, non-deterministic failures on 64-bit Windows. Calling getEntropy sometimes fails with message c_cryptReleaseCtx.

My investigation showed that the reason is that where WinAPI cryptography functions use HCRYPTPROV, this pacakge use Word32 in FFI foreign imports. This introduces the bug on 64-bit Windows, as HCRYPTPROV, being a pointer, should be 64-bit as well. Bug happens only sometimes, because on x64 calling convention registers used are 64-bit anyway and the only effect of size mismatch is 4 upper bytes of cryptography provider getting zeroed. So it failed only when provider handle was a value higher than 0xffffffff.

This PR introduces two fixes: 1) replace Word32 with HCRYPTPROV type being a ULONG_PTR — as described in WinAPI documentation 2) replace fail "magic string" calls with Win32's errorWin. This checks last error set by WinAPI and obtains appropriate error message, giving much better diagnostics in case something goes wrong.

TomMD commented 6 years ago

Hideous bug - so sorry and thanks for the patch!