F-8205: bound direct buffer write position in Md5 final

pull/257/head
Chris Conlon 2026-08-13 16:10:51 -06:00
parent 4ed855d629
commit 40a1039110
2 changed files with 35 additions and 1 deletions

View File

@ -221,6 +221,7 @@ Java_com_wolfssl_wolfcrypt_Md5_native_1final_1internal__Ljava_nio_ByteBuffer_2I(
int ret = 0;
Md5* md5 = NULL;
byte* hash = NULL;
jlong hashSz = 0;
md5 = (Md5*) getNativeStruct(env, this);
if ((*env)->ExceptionOccurred(env)) {
@ -229,8 +230,10 @@ Java_com_wolfssl_wolfcrypt_Md5_native_1final_1internal__Ljava_nio_ByteBuffer_2I(
}
hash = getDirectBufferAddress(env, hash_buffer);
hashSz = (*env)->GetDirectBufferCapacity(env, hash_buffer);
if (!md5 || !hash) {
if (!md5 || !hash || (position < 0) ||
((jlong)position + MD5_DIGEST_SIZE) > hashSz) {
throwWolfCryptExceptionFromError(env, BAD_FUNC_ARG);
} else {
ret = wc_Md5Final(md5, hash + position);

View File

@ -75,6 +75,37 @@ public class Md5Test {
assertEquals(NativeStruct.NULL, new Md5().getNativeStruct());
}
/* Exposes protected native_final() to test its position validation */
private static class ExposedMd5 extends Md5 {
public void finalAt(ByteBuffer hash, int position) {
native_final(hash, position);
}
}
@Test
public void finalWithInvalidPositionShouldThrow() {
ExposedMd5 md5 = new ExposedMd5();
ByteBuffer hash = ByteBuffer.allocateDirect(Md5.DIGEST_SIZE);
/* initialize digest state */
md5.update(new byte[4]);
try {
md5.finalAt(hash, -1);
fail("native_final() should have thrown for negative position");
} catch (WolfCryptException e) {
/* expected */
}
try {
md5.finalAt(hash, 1);
fail("native_final() should have thrown for position leaving " +
"less than DIGEST_SIZE bytes");
} catch (WolfCryptException e) {
/* expected */
}
}
@Test
public void updateWithWrappedOffsetAndLenShouldThrow() {
Md5 md5 = new Md5();