Skip to content

Commit ed56452

Browse files
committed
Fix memory safety in schnorrSign function
Ensure pointer from useAsCStringLen is used within its scope to prevent potential use-after-free errors.
1 parent 73758ee commit ed56452

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

src/Crypto/Secp256k1.hs

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -755,18 +755,25 @@ schnorrSign mGen KeyPair{..} bs
755755
keyPairPtr <- ContT (withForeignPtr keyPairFPtr)
756756
lift $ do
757757
sigBuf <- mallocBytes 64
758-
let randomPtr = case mGen of
759-
Just gen -> castPtr . unsafePerformIO . BS.useAsCString (BS.pack $ Prelude.take 32 $ randoms gen) $ return
760-
Nothing -> nullPtr
761-
ret <- Prim.schnorrsigSign ctx sigBuf msgHashPtr keyPairPtr randomPtr
758+
ret <- case mGen of
759+
Just gen -> do
760+
let randomBytes = BS.pack $ Prelude.take 32 $ randoms gen
761+
BS.useAsCStringLen randomBytes $ \(ptr, _) ->
762+
Prim.schnorrsigSign ctx sigBuf msgHashPtr keyPairPtr (castPtr ptr)
763+
Nothing ->
764+
Prim.schnorrsigSign ctx sigBuf msgHashPtr keyPairPtr nullPtr
762765
if isSuccess ret
763766
then Just . SchnorrSignature <$> newForeignPtr finalizerFree sigBuf
764-
else free sigBuf $> Nothing
767+
else do
768+
free sigBuf
769+
return Nothing
770+
765771

766772
-- | Compute a deterministic schnorr signature using a 'KeyPair'.
767773
schnorrSignDeterministic :: KeyPair -> ByteString -> Maybe SchnorrSignature
768774
schnorrSignDeterministic = schnorrSign Nothing
769775

776+
770777
-- | Compute a non-deterministic schnorr signature using a 'KeyPair'.
771778
schnorrSignNondeterministic :: KeyPair -> ByteString -> IO (Maybe SchnorrSignature)
772779
schnorrSignNondeterministic kp bs = newStdGen >>= \gen -> pure $ schnorrSign (Just gen) kp bs

0 commit comments

Comments
 (0)