Skip to content

Changes for different openssl versions #54 - #66

Open
joachimmetz wants to merge 3 commits into
sshock:masterfrom
joachimmetz:fix54
Open

joachimmetz wants to merge 3 commits into
sshock:masterfrom
joachimmetz:fix54

Conversation

@joachimmetz

Copy link
Copy Markdown

No description provided.

@joachimmetz

Copy link
Copy Markdown
Author

@sshock PTAL, note that I'm not too familiar with the code base

@sshock

sshock commented Oct 27, 2026

Copy link
Copy Markdown
Owner

Thanks @joachimmetz. This is much appreciated. I'll take a look when I can 😉.

@sshock

sshock commented Nov 2, 2026

Copy link
Copy Markdown
Owner

workflows use --enable-s3 which builds s3_glue.cpp, which is failing with this:

s3_glue.cpp: In function 'int s3::object_put(std::string, std::string, const char*, size_t, const s3headers*)':
s3_glue.cpp:644:5: error: 'af_MD5' was not declared in this scope

please add #include "afflib.h" to s3_glue.cpp, and then we'll run the workflows again...

@joachimmetz

joachimmetz commented Nov 2, 2026 •

Copy link
Copy Markdown
Author

Done, also note that Distributed under the Berkeley 4-part license in afflib.h might not be sufficient and a still requires a Copyright statement. Suggested

// SPDX-License-Identifier: BSD-4-Clause
// Copyright (c) [Year], [Your Name/Organization]. All rights reserved.

But it might be better that you as the maintainer make copyright related changes (given optics). Can create an issue as reminder if you want.

@sshock

sshock commented Nov 2, 2026

Copy link
Copy Markdown
Owner

Thanks. Hoping I can take a closer look at this PR soon.

Let's discuss copyright statements separately. I was not aware that anything needed to be clarified. Can you create a discussion?

@joachimmetz

joachimmetz commented Nov 2, 2026 •

Copy link
Copy Markdown
Author

Let's discuss copyright statements separately. I was not aware that anything needed to be clarified. Can you create a discussion?

sure, done #68

@sshock

sshock commented Nov 28, 2026

Copy link
Copy Markdown
Owner

Hmm, seeing a lot of feedback from AI. I'll share feedback from Gemini, Claude and OpenAI below.

@sshock

sshock commented Nov 28, 2026

Copy link
Copy Markdown
Owner

From Gemini:

Overview

Commit f368de74209a76843eea598878854e59b9632e87 ("Changes for different openssl versions #54") migrates AFFLIBv3 from deprecated low-level OpenSSL calls (MD5*, SHA1*, AES_*, <openssl/aes.h>, <openssl/md5.h>, <openssl/sha.h>) to the EVP API (EVP_MD_CTX, EVP_CIPHER_CTX, <openssl/evp.h>) and adds an AX_OPENSSL_VERSION Autoconf macro.

Overall, the direction is sound for OpenSSL 3.x/4.x (including no-deprecated builds) while preserving compatibility with older OpenSSL versions, and it even fixes an existing 32-byte stack-copy bug in affinfo.cpp. However, there are several concrete safety, correctness, and portability bugs in the patch that should be addressed before merging.


High & Medium Severity Issues

1. Buffer Overflow / Heap Corruption in af_update_segf (lib/afflib.cpp)

In af_update_segf (lib/afflib.cpp):

uint32_t extra = (datalen) % AFF_AES_BLOCK_SIZE;
uint32_t pad = (AFF_AES_BLOCK_SIZE - extra) % AFF_AES_BLOCK_SIZE;
newdata = (unsigned char *)malloc(datalen+pad+extra);
memcpy(newdata,(const unsigned char *)data,datalen);
memset(newdata+datalen,pad+extra,pad); // PKCS7 uses 01 for one pad byte, 02 02 for two, etc.
memset(newdata+datalen+pad,0,extra);	// zero the trailing alignment region
  • Null pointer dereference: malloc is not checked for NULL before memcpy and memset.

  • 32-bit truncation in EVP_EncryptUpdate: datalen is a size_t, while EVP_EncryptUpdate takes an int length ((int)(datalen+pad)). If datalen + pad > INT_MAX, it truncates/wraps to a negative or wrong int.

  • Check EVP_EncryptUpdate return value and buffer bounds: EVP_EncryptUpdate can write up to input_len + block_size - 1 bytes. Even with padding disabled (set_padding(..., 0)), checking return codes (== 1) and ensuring datalen + pad + extra is safe against overflow avoids silent partial/corrupted encryption.

2. EVP_DigestFinal_ex Output Length Type Mismatch (lib/crypto.cpp)

In af_MD5, af_sha1, and af_SHA256 (lib/crypto.cpp):

uint32_t md5_buflen = 16;
...
EVP_DigestFinal_ex(ctx,md,&md5_buflen);
  • EVP_DigestFinal_ex takes unsigned int *outl, not uint32_t *. On LP64 platforms uint32_t and unsigned int are both 32-bit, but on LLP64/Windows or strict type-checking setups passing &md5_buflen where unsigned int * is expected can fail to compile or trigger warnings. Using unsigned int md5_buflen = 16; (and matching types for SHA1/SHA256) is cleaner and safer.

  • Also in af_MD5 and af_sha1, EVP_DigestUpdate return values are not checked (though EVP_DigestUpdate returns 1 on success and 0 on failure).

3. Potential NULL Dereference or Uninitialized Context Usage in affinfo.cpp (validate)

In tools/affinfo.cpp:

EVP_MD_CTX *md5ctx = EVP_MD_CTX_new();
EVP_MD_CTX *sha1ctx = EVP_MD_CTX_new();
if(opt_validate & VALIDATE_MD5){
    const EVP_MD *md5_md = EVP_get_digestbyname("MD5");
    if(!md5_md || EVP_DigestInit_ex(md5ctx,md5_md,NULL)!=1){
        af_close(af);
        return;
    }
}
  • md5ctx and sha1ctx are **not checked for NULL** before EVP_DigestInit_ex. If EVP_MD_CTX_new() returns NULL, EVP_DigestInit_ex(NULL, ...) fails, returning early and **leaking sha1ctx**.

  • Furthermore, if opt_validate has VALIDATE_MD5 set (and not VALIDATE_SHA1), sha1ctx is allocated and later freed via EVP_MD_CTX_free(sha1ctx), which is fine for NULL, except if EVP_MD_CTX_new() failed on md5ctx while sha1ctx succeeded—it leaks sha1ctx on the early return.

4. Missing Return Value Checks on EVP_*Init_ex / EVP_*Update in encrypt_sectors (block-qcow.c and block-qcow2.c)

In both lib/qemu/block-qcow.c and lib/qemu/block-qcow2.c, encrypt_sectors is void and ignores return codes from EVP_EncryptInit_ex, EVP_EncryptUpdate, EVP_DecryptInit_ex, and EVP_DecryptUpdate. If an EVP operation fails (for example, in a restricted/FIPS provider state or bad context), out_buf is left untouched/unencrypted/undecrypted without any error indication to the caller.

5. af_aes_decrypt In-Place Length & Block Alignment Edge Cases (lib/afflib.cpp)

Look closely at af_aes_decrypt (lib/afflib.cpp):

uint32_t extra = (*datalen) % AFF_AES_BLOCK_SIZE;
uint32_t pad = (AFF_AES_BLOCK_SIZE - extra) % AFF_AES_BLOCK_SIZE;

if(data==0){			// just wants to find out new length
	if(extra>0){
	    *datalen -= AFF_AES_BLOCK_SIZE;
	}
	return;
}
  • There is a duplicate if(data==0) block right below if(extra!=0 && *datalen < AFF_AES_BLOCK_SIZE) that is unreachable dead code.

  • *datalen is a size_t, while EVP_DecryptUpdate expects an int length ((int)*datalen). If *datalen > INT_MAX, casting to int truncates it.

  • Also in af_get_seg (lib/afflib.cpp), datalen_orig + AFF_AES_BLOCK_SIZE does not check for size_t overflow before malloc.


Build, Portability & OpenSSL Compatibility Notes

  • m4/ax_openssl_version.m4 cross-compilation behavior: When cross-compiling, AC_RUN_IFELSE cannot execute the probe binary, so OPENSSL_VERSION becomes "unknown" and HAVE_OPENSSL3 / HAVE_OPENSSL4 are not defined via the runtime probe. If cross-compiling against OpenSSL 3.x/4.x, compile-time checks (#if OPENSSL_VERSION_NUMBER >= 0x30000000L) are generally more reliable than AC_RUN_IFELSE.

  • Legacy provider in OpenSSL 3.x for MD5 / SHA1 / AES-ECB: Switching from low-level calls (MD5(), SHA1(), AES_encrypt()) to EVP_get_digestbyname("MD5"), EVP_sha1(), and EVP_aes_256_ecb() moves to the EVP API, but MD5, SHA-1, and ECB mode are legacy/weak algorithms. On systems with strict OpenSSL security policies or disabled legacy providers, EVP_get_digestbyname("MD5") or EVP_aes_256_ecb() may return NULL (causing af_MD5 / af_save_aes_key_with_passphrase / af_get_aes_key_from_passphrase to fail), though forensic tools (affinfo, affconvert, affcopy) intentionally need MD5/SHA1/legacy AFF key handling for compatibility with existing AFF/QCOW images.

  • Pre-1.1.0 OpenSSL macro guard (include/afflib/afflib_i.h): EVP_MD_CTX_new / EVP_CIPHER_CTX_new shims are defined for OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER). Modern LibreSSL versions already provide EVP_MD_CTX_new and EVP_CIPHER_CTX_new (LibreSSL removed/deprecated EVP_MD_CTX_create in newer releases), so blindly aliasing EVP_MD_CTX_new to EVP_MD_CTX_create whenever LIBRESSL_VERSION_NUMBER is defined can break builds against newer LibreSSL versions. Guarding with #if OPENSSL_VERSION_NUMBER < 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER) (or checking LIBRESSL_VERSION_NUMBER < 0x2070000fL) is safer.

  • Unused/dead #ifdef symbols in ax_openssl_version.m4: HAVE_OPENSSL_DEPRECATED_MD5_SHA1 and HAVE_OPENSSL_DEPRECATED_AES are defined in ax_openssl_version.m4, but nothing in the patch appears to read them.


Summary Verdict

  • Good improvements: Clean migration off deprecated AES_* / MD5* / SHA1* symbols to EVP_*, proper EVP_CIPHER_CTX_free cleanup in af_crypto_deallocate and qcow_close/qcow2 close, and fixing the 32-byte memcpy over-read in affinfo.cpp's opt_preview_md5 path.

  • Must-fix before merging:

  1. Check malloc return values in af_update_segf (and af_get_seg overflow check).
  2. Fix uint32_t * vs unsigned int * in EVP_DigestFinal_ex calls (af_MD5, af_sha1, af_SHA256), and handle size_t -> int length bounds on EVP_*Update.
  3. Null-check EVP_MD_CTX_new() and avoid leaking allocated contexts on early error returns in affinfo.cpp (validate).
  4. Revisit the LIBRESSL_VERSION_NUMBER macro alias in include/afflib/afflib_i.h for newer LibreSSL versions.

@sshock

sshock commented Nov 28, 2026

Copy link
Copy Markdown
Owner

From Claude:

Verdict: request changes. The migration is mostly mechanical, and the AES-ECB key-wrap paths and the af_SHA256 cleanup look correct. But several error paths fail open in a forensic tool, and the build changes regress LibreSSL and OpenSSL 1.0.2. Nothing looks malicious: the new m4 macro only compiles and runs a version probe and writes one temp file. I couldn't build or run anything here.

Must fix

  1. Encryption and decryption fail open. In afflib.cpp (af_update_segf, af_aes_decrypt) and both qcow encrypt_sectors, every EVP return value is ignored. If Init fails, the segment is written as padded plaintext (qcow writes the sector unencrypted), and decrypt hands back ciphertext as data. All of it reports success. The old AES_cbc_encrypt couldn't fail. Check each return, free newdata, and return an error.

  2. Integrity checks fail open. af_MD5 and af_sha1 return -1 on failure, for example under FIPS-mode OpenSSL 3 where MD5 is unavailable. No caller checks that:

    • afflib_pages.cpp stores uninitialized stack bytes as the page hash.
    • affcopy leaves both the stored hash and the verification hash uninitialized, so its "doesn't validate" check is meaningless. It either aborts spuriously and unlinks the outputs, or passes vacuously.
    • affinfo's MD5 preview copies the uninitialized buffer.
    • EVP_DigestFinal_ex is also unchecked in affconvert and affinfo.
  3. Padding is set in inconsistent order, and the code depends on it. af_set_aes_key calls EVP_CIPHER_CTX_set_padding(…,0) after Init. The passphrase save/load code and both qcow_set_key copies call it before Init, on a context with no cipher yet. I'm not sure OpenSSL 3.x honors that. If it doesn't, decrypt holds back the last block, so passphrase key unwrapping and qcow reads would silently produce wrong output. Call it after Init everywhere, and add a known-answer test against an existing passphrase-protected file.

  4. Shared mutable cipher contexts. ekey and dkey (and the qcow equivalents) are now stateful and re-initialized on every call. The old AES_KEY was read-only, so concurrent decrypts under AF_READLOCK were safe. If AF_READLOCK admits concurrent readers, this is a data race. Use a per-call context, or EVP_CIPHER_CTX_copy from a template.

  5. Build and config regressions:

    • The <1.1.0 || LIBRESSL shim maps EVP_CIPHER_CTX_new/free to _create/_destroy, which I don't believe exist in any release. That now breaks OpenSSL 1.0.2 and LibreSSL, which macOS ships. Delete those two lines; the cipher functions already exist under their _new/_free names.
    • On 1.0.2, HAVE_MD5 and HAVE_SHA1 require EVP_MD_CTX_new, so they're never defined, and s3_glue.cpp hits its #error. This contradicts the "works on 1.0.2" comments.
    • The patch drops des_read_pw_string, EVP_read_pw_string and EVP_MD_size from AC_CHECK_FUNCS with no replacement. Their HAVE_* macros vanish, so any code behind them silently turns off.
    • AC_RUN_IFELSE has no cross-compile branch, so configure aborts when cross-compiling. The comment claims it reports "unknown" instead.
    • config.h now defines OPENSSL_VERSION_MAJOR, MINOR and PATCH, which collide with OpenSSL 3's own macros. Use an AFF_ prefix. The deprecated-API probes and HAVE_OPENSSL3/4 macros aren't used anywhere in the patch, so I'd drop them.
    • afflib_i.h and configure no longer provide md5.h, sha.h or aes.h. Any other file still using MD5_CTX, SHA_CTX, AES_* or HAVE_OPENSSL_{MD5,SHA,AES}_H breaks or silently loses features. s3.cpp's #ifdef HAVE_OPENSSL_MD5_H is now dead, while s3_glue.cpp moved to HAVE_MD5. This needs a repo-wide grep.

Should fix

  • affinfo and affconvert don't NULL-check EVP_MD_CTX_new. They leak contexts on early returns (affinfo's init-failure paths free nothing).
  • The (int) casts on lengths truncate above INT_MAX.
  • Confirm af_crypto_allocate zeroes the struct, since ekey and dkey are now pointers. Also confirm sealing_key_set and auto_encrypt can't be set without af_set_aes_key, or ekey is a NULL dereference.
  • Prefer EVP_md5() and EVP_sha1() over EVP_get_digestbyname, which needs OpenSSL_add_all_digests on 1.0.2.
  • The .gitignore change is unrelated.

What's good

  • Encrypting from newdata fixes the old over-read past the caller's buffer.
  • Zeroing the trailing extra bytes stops uninitialized heap from being written to disk.
  • The affinfo MD5-preview fix stops 16 bytes of stack garbage being copied.
  • EVP_CIPHER_CTX_free cleanses key material, which the old memset didn't reliably do.
  • af_set_aes_key now validates key length, and af_SHA256 now checks its return values.
  • Read compatibility should hold: only discarded padding bytes in ciphertext change.

Corrections to my earlier notes

With the full patch, qemu/aes.h turns out to be deleted, so the Makefile.am change is fine. crypto.cpp does disable padding, so that concern narrows to the ordering in finding 3. The m4 macro is benign apart from the cross-compile bug.

Before merging

Run round-trip tests, old-writes/new-reads and the reverse, on OpenSSL 1.1.1 and 3.x. Cover AFF segment encryption, passphrase keys and qcow. Add a build matrix that includes LibreSSL and a no-deprecated build. If you give me the repo, I can do the grep for the removed headers and macros, AF_READLOCK semantics and sealing_key_set.

@sshock

sshock commented Nov 28, 2026

Copy link
Copy Markdown
Owner

From ChatGPT:

I'll review PR #66 as a code-review exercise, focusing on:

  1. Correctness: Whether the changes work across the OpenSSL versions they intend to support.

  2. Compatibility: Whether they preserve compatibility with older OpenSSL versions and existing AFFLIB builds.

  3. Safety: Whether the changes introduce memory-management problems, cryptographic errors, undefined behavior, or other security vulnerabilities.

  4. Build and testing: Whether the changes compile correctly across the supported configurations, including optional S3 support.

The PR is titled Changes for different OpenSSL versions, targets master, and contains one commit (9f171f9).

GitHub

1. Preliminary findings

Changes requested

I found several issues worth addressing before merging. Some are correctness bugs rather than merely portability concerns.

The most important problems are in the new EVP-based encryption implementation, particularly error handling and the QEMU encryption changes.

A. EVP encryption/decryption errors are ignored

Files: lib/afflib.cpp, lib/qemu/block-qcow.c, lib/qemu/block-qcow2.c

For example, the new code in af_aes_decrypt() does this:

if(EVP_DecryptInit_ex(af->crypto->dkey,NULL,NULL,NULL,iv)==1){
    outlen = 0;
    EVP_DecryptUpdate(af->crypto->dkey,data,&outlen,data,(int)*datalen);
    {
        int flen = 0;
        EVP_DecryptFinal_ex(af->crypto->dkey,data+outlen,&flen);
    }
}

There are three problems:

  • The return value from EVP_DecryptUpdate() is ignored.

  • The return value from EVP_DecryptFinal_ex() is ignored.

  • If EVP_DecryptInit_ex() fails, the function continues as though decryption succeeded.

This can result in corrupted or partially decrypted data being returned to the caller without an error indication.

The same general problem occurs in the QEMU encrypt_sectors() implementations, where neither initialization nor update failures are checked.

Recommendation: Check every EVP operation that can fail and propagate an error to the caller. In particular, don't report a successful read or write when the encryption operation failed.

B. Potential integer overflow when converting size_t to int

File: lib/afflib.cpp

The new code contains:

EVP_DecryptUpdate(
    af->crypto->dkey,
    data,
    &outlen,
    data,
    (int)*datalen
);

The EVP API takes an int input length, whereas AFFLIB uses size_t.

If *datalen exceeds INT_MAX, the conversion can produce an invalid length. This is particularly relevant when processing large forensic images.

The same issue exists in the encryption path:

EVP_EncryptUpdate(
    af->crypto->ekey,
    newdata,
    &ctlen,
    newdata,
    (int)(datalen+pad)
);

Recommendation: Either process the input in appropriately sized chunks or explicitly reject lengths that cannot safely be represented by int. Also check the addition used to calculate the allocation size.

C. QEMU encryption contexts introduce mutable shared state

Files: lib/qemu/block-qcow.c, lib/qemu/block-qcow2.c

Previously, the QEMU code used:

AES_KEY aes_encrypt_key;
AES_KEY aes_decrypt_key;

These structures contain expanded key material and can be used without maintaining an ongoing cipher-operation state.

The PR changes them to:

EVP_CIPHER_CTX *aes_encrypt_key;
EVP_CIPHER_CTX *aes_decrypt_key;

These are mutable contexts.

The new encrypt_sectors() function repeatedly reinitializes the context with a different IV:

EVP_EncryptInit_ex(key, NULL, NULL, NULL, ivec.b);
EVP_EncryptUpdate(key, out_buf, &len, in_buf, 512);

This is important because QEMU has asynchronous I/O paths. If multiple operations can access the same context concurrently, they can interfere with one another.

The previous AES_KEY implementation did not have this particular state-sharing problem.

Recommendation: Verify the QEMU execution and locking model. If concurrent access is possible, use independent EVP contexts per operation, or otherwise serialize access.

I would consider this a significant issue until concurrency has been ruled out.

D. QEMU disables padding in the wrong order

Files: lib/qemu/block-qcow.c, lib/qemu/block-qcow2.c

This is a more serious issue than it might initially appear.

The PR does:

EVP_CIPHER_CTX_set_padding(s->aes_encrypt_key, 0);
EVP_CIPHER_CTX_set_padding(s->aes_decrypt_key, 0);

if (EVP_EncryptInit_ex(s->aes_encrypt_key, EVP_aes_128_cbc(),
NULL, keybuf, NULL) != 1 ||
EVP_DecryptInit_ex(s->aes_decrypt_key, EVP_aes_128_cbc(),
NULL, keybuf, NULL) != 1)
return -1;

OpenSSL documents that EVP_CIPHER_CTX_set_padding() should be called after initializing the cipher context.

OpenSSL Documentation+1

The correct order is:

if (EVP_EncryptInit_ex(...) != 1)
return -1;

if (EVP_CIPHER_CTX_set_padding(s->aes_encrypt_key, 0) != 1)
return -1;

And equivalently for decryption.

This matters because the QEMU code also omits EVP_EncryptFinal_ex() and EVP_DecryptFinal_ex(), relying on padding being disabled and all sector lengths being multiples of the AES block size.

If padding remains enabled, EVP_EncryptUpdate() and EVP_DecryptUpdate() can retain the final block rather than producing all 512 bytes immediately. That breaks the assumption that the operation has processed the entire sector.

I would treat this as a potentially critical data-corruption bug.

E. affinfo does not check EVP context allocation

File: tools/affinfo.cpp

The new code allocates two contexts:

EVP_MD_CTX *md5ctx = EVP_MD_CTX_new();
EVP_MD_CTX *sha1ctx = EVP_MD_CTX_new();

But it never checks whether either allocation succeeded before passing the pointers to EVP_DigestInit_ex().

For example:

if(opt_validate & VALIDATE_MD5){
const EVP_MD *md5_md = EVP_get_digestbyname("MD5");
if(!md5_md || EVP_DigestInit_ex(md5ctx,md5_md,NULL)!=1){
af_close(af);
return;
}
}

If EVP_MD_CTX_new() returns NULL, this can dereference a null context.

There is also a memory leak in the MD5 initialization failure path: neither allocated context is freed.

Recommendation: Check both allocations immediately, and free both contexts on every error path.

F. Hashing errors are not consistently propagated

Files: lib/crypto.cpp, lib/afflib_pages.cpp, tools/affcopy.cpp, tools/affinfo.cpp, tools/affconvert.cpp

The new af_MD5() and af_sha1() functions return an error code, which is good.

However, several callers ignore it.

For example:

af_MD5((const unsigned char *)data,datalen,md5_buf);

This occurs in af_update_page().

If the digest operation fails, the caller can continue and store an invalid digest.

The same general concern applies to EVP_DigestUpdate() and EVP_DigestFinal_ex() calls in the utilities.

This is especially important for forensic software: a failed integrity calculation must not silently be treated as a successful integrity calculation.

Recommendation: Propagate digest failures, and do not write or report a digest as valid unless its calculation succeeded.

G. Cross-compilation support in the OpenSSL version detection

File: m4/ax_openssl_version.m4

The new macro uses:

AC_RUN_IFELSE([AC_LANG_PROGRAM(... )],
[...],
[...])

But it does not supply the fourth argument, which is the cross-compilation action.

The comment explicitly claims:

when execution is not possible (e.g. cross-compiling), the version is reported as unknown.

However, Autoconf's AC_RUN_IFELSE requires a cross-compilation alternative if the test must work when the target executable cannot be run.

Without it, configure can fail outright during cross-compilation rather than reporting an unknown version.

Recommendation: Supply the fourth argument and explicitly set ax_openssl_version to an empty value in that case.

This is a portability issue rather than a direct security vulnerability, but it contradicts the stated behavior of the new macro.

2. Additional findings

H. The passphrase-based AES implementation has the same padding-order bug

File: lib/crypto.cpp

This is particularly important because the PR changes the implementation of AFF key storage and retrieval.

In af_save_aes_key_with_passphrase():

EVP_CIPHER_CTX *ectx = EVP_CIPHER_CTX_new();

EVP_CIPHER_CTX_set_padding(ectx,0);

if(EVP_EncryptInit_ex(ectx,EVP_aes_256_ecb(),NULL,
passphrase_hash,NULL)==1){

And in af_get_aes_key_from_passphrase():

EVP_CIPHER_CTX *dctx = EVP_CIPHER_CTX_new();

EVP_CIPHER_CTX_set_padding(dctx,0);

if(EVP_DecryptInit_ex(dctx,EVP_aes_256_ecb(),NULL,
passphrase_hash,NULL)==1){

Both functions set padding before initializing the cipher.

This is especially problematic because both functions process three separate 16-byte blocks using EVP_EncryptUpdate() or EVP_DecryptUpdate(), but never call the corresponding Final function.

With standard EVP block padding enabled, the final block is retained by Update for processing during Final. Consequently, the three-block operations cannot be assumed to produce the expected three encrypted/decrypted blocks.

Recommendation: Initialize the cipher first, disable padding second, and verify every operation. Add tests that save and retrieve an AFF encryption key using a passphrase.

I would classify this as a high-priority correctness issue.

I. af_MD5() and af_sha1() don't check all EVP operations

File: lib/crypto.cpp

The new implementations check initialization and finalization, but don't check:

EVP_DigestUpdate(ctx,data,datalen);

They should check its return value as well.

Otherwise, a failed update could result in an invalid digest being returned as successful.

This is particularly important because the functions are intended to become the common replacement for the old OpenSSL hashing functions.

J. affconvert also needs better error handling

File: tools/affconvert.cpp

The new code allocates two contexts:

EVP_MD_CTX *md5ctx = EVP_MD_CTX_new();
EVP_MD_CTX *sha1ctx = EVP_MD_CTX_new();

It checks for allocation failure, which is good.

However:

  • If one allocation succeeds and the other fails, the successful allocation is leaked.

  • The return values of EVP_DigestUpdate() are ignored.

  • The return values of EVP_DigestFinal_ex() are ignored.

The last two issues can result in incorrect MD5/SHA1 metadata being written to the output AFF file.

K. affinfo preview change is actually an improvement

File: tools/affinfo.cpp

There is one positive change worth mentioning.

The old code used:

u_char md5[32];
MD5(data,data_len,md5);
memcpy(data,md5,32);
data_len = 32;

MD5 produces only 16 bytes. Consequently, the second 16 bytes copied into data were uninitialized stack contents.

The PR corrects this:

u_char md5[16];
af_MD5((const unsigned char *)data,data_len,md5);
memcpy(data,md5,16);
data_len = 16;

This eliminates an unintended disclosure of stack contents through the preview functionality.

That's a good fix.

3. Compatibility and design considerations

There are several other aspects I would investigate, although I don't consider them established defects from the diff alone.

Area Assessment
OpenSSL 1.0.2 compatibility EVP context aliases appear reasonable.
OpenSSL 1.1.1 compatibility Generally reasonable.
OpenSSL 3.x compatibility Moving away from deprecated low-level APIs is appropriate.
OpenSSL 4.x compatibility Worth testing against an actual release and its provider behavior.
LibreSSL Needs a dedicated build test.
AES file-format compatibility Requires regression testing against existing AFF files.
QEMU asynchronous I/O Needs verification of context sharing and synchronization.
S3 support Needs a dedicated build and runtime test.

My overall opinion: The direction of the PR is good. Moving from the deprecated low-level OpenSSL interfaces to EVP is the right general approach, and some of the changes fix existing problems.

However, the migration has introduced several problems because EVP has a different operational model from the low-level AES interfaces.

The most important distinction is that AES_KEY is essentially an expanded key, whereas EVP_CIPHER_CTX is a stateful encryption/decryption context. The code needs to account for initialization, padding, update/final processing, errors, and potentially concurrent access.

I would fix the padding-order issues first, then address error propagation and context management before considering the PR ready.

Primary references:

One particularly useful next step would be to work through lib/crypto.cpp and lib/afflib.cpp line by line and establish exactly which changes are necessary to preserve the existing AFF encryption format. That would address the most consequential part of this PR before tackling the build-system changes.

I'll review PR #66 as a code-review exercise, focusing on:
  1. Correctness: Whether the changes work across the OpenSSL versions they intend to support.
  2. Compatibility: Whether they preserve compatibility with older OpenSSL versions and existing AFFLIB builds.
  3. Safety: Whether the changes introduce memory-management problems, cryptographic errors, undefined behavior, or other security vulnerabilities.
  4. Build and testing: Whether the changes compile correctly across the supported configurations, including optional S3 support.

The PR is titled Changes for different OpenSSL versions, targets master, and contains one commit (9f171f9).

image

GitHub

1. Preliminary findings

Changes requested

I found several issues worth addressing before merging. Some are correctness bugs rather than merely portability concerns.

The most important problems are in the new EVP-based encryption implementation, particularly error handling and the QEMU encryption changes.

A. EVP encryption/decryption errors are ignored

Files: lib/afflib.cpp, lib/qemu/block-qcow.c, lib/qemu/block-qcow2.c

For example, the new code in af_aes_decrypt() does this:

if(EVP_DecryptInit_ex(af->crypto->dkey,NULL,NULL,NULL,iv)==1){
    outlen = 0;
    EVP_DecryptUpdate(af->crypto->dkey,data,&outlen,data,(int)*datalen);
    {
        int flen = 0;
        EVP_DecryptFinal_ex(af->crypto->dkey,data+outlen,&flen);
    }
}

There are three problems:

  • The return value from EVP_DecryptUpdate() is ignored.
  • The return value from EVP_DecryptFinal_ex() is ignored.
  • If EVP_DecryptInit_ex() fails, the function continues as though decryption succeeded.

This can result in corrupted or partially decrypted data being returned to the caller without an error indication.

The same general problem occurs in the QEMU encrypt_sectors() implementations, where neither initialization nor update failures are checked.

Recommendation: Check every EVP operation that can fail and propagate an error to the caller. In particular, don't report a successful read or write when the encryption operation failed.

B. Potential integer overflow when converting size_t to int

File: lib/afflib.cpp

The new code contains:

EVP_DecryptUpdate(
    af->crypto->dkey,
    data,
    &outlen,
    data,
    (int)*datalen
);

The EVP API takes an int input length, whereas AFFLIB uses size_t.

If *datalen exceeds INT_MAX, the conversion can produce an invalid length. This is particularly relevant when processing large forensic images.

The same issue exists in the encryption path:

EVP_EncryptUpdate(
    af->crypto->ekey,
    newdata,
    &ctlen,
    newdata,
    (int)(datalen+pad)
);

Recommendation: Either process the input in appropriately sized chunks or explicitly reject lengths that cannot safely be represented by int. Also check the addition used to calculate the allocation size.

C. QEMU encryption contexts introduce mutable shared state

Files: lib/qemu/block-qcow.c, lib/qemu/block-qcow2.c

Previously, the QEMU code used:

AES_KEY aes_encrypt_key;
AES_KEY aes_decrypt_key;

These structures contain expanded key material and can be used without maintaining an ongoing cipher-operation state.

The PR changes them to:

EVP_CIPHER_CTX *aes_encrypt_key;
EVP_CIPHER_CTX *aes_decrypt_key;

These are mutable contexts.

The new encrypt_sectors() function repeatedly reinitializes the context with a different IV:

EVP_EncryptInit_ex(key, NULL, NULL, NULL, ivec.b);
EVP_EncryptUpdate(key, out_buf, &len, in_buf, 512);

This is important because QEMU has asynchronous I/O paths. If multiple operations can access the same context concurrently, they can interfere with one another.

The previous AES_KEY implementation did not have this particular state-sharing problem.

Recommendation: Verify the QEMU execution and locking model. If concurrent access is possible, use independent EVP contexts per operation, or otherwise serialize access.

I would consider this a significant issue until concurrency has been ruled out.

D. QEMU disables padding in the wrong order

Files: lib/qemu/block-qcow.c, lib/qemu/block-qcow2.c

This is a more serious issue than it might initially appear.

The PR does:

EVP_CIPHER_CTX_set_padding(s->aes_encrypt_key, 0);
EVP_CIPHER_CTX_set_padding(s->aes_decrypt_key, 0);

if (EVP_EncryptInit_ex(s->aes_encrypt_key, EVP_aes_128_cbc(),
                       NULL, keybuf, NULL) != 1 ||
    EVP_DecryptInit_ex(s->aes_decrypt_key, EVP_aes_128_cbc(),
                       NULL, keybuf, NULL) != 1)
    return -1;

OpenSSL documents that EVP_CIPHER_CTX_set_padding() should be called after initializing the cipher context.

image

OpenSSL Documentation+1

The correct order is:

if (EVP_EncryptInit_ex(...) != 1)
    return -1;

if (EVP_CIPHER_CTX_set_padding(s->aes_encrypt_key, 0) != 1)
    return -1;

And equivalently for decryption.

This matters because the QEMU code also omits EVP_EncryptFinal_ex() and EVP_DecryptFinal_ex(), relying on padding being disabled and all sector lengths being multiples of the AES block size.

If padding remains enabled, EVP_EncryptUpdate() and EVP_DecryptUpdate() can retain the final block rather than producing all 512 bytes immediately. That breaks the assumption that the operation has processed the entire sector.

I would treat this as a potentially critical data-corruption bug.

E. affinfo does not check EVP context allocation

File: tools/affinfo.cpp

The new code allocates two contexts:

EVP_MD_CTX *md5ctx = EVP_MD_CTX_new();
EVP_MD_CTX *sha1ctx = EVP_MD_CTX_new();

But it never checks whether either allocation succeeded before passing the pointers to EVP_DigestInit_ex().

For example:

if(opt_validate & VALIDATE_MD5){
    const EVP_MD *md5_md = EVP_get_digestbyname("MD5");
    if(!md5_md || EVP_DigestInit_ex(md5ctx,md5_md,NULL)!=1){
        af_close(af);
        return;
    }
}

If EVP_MD_CTX_new() returns NULL, this can dereference a null context.

There is also a memory leak in the MD5 initialization failure path: neither allocated context is freed.

Recommendation: Check both allocations immediately, and free both contexts on every error path.

F. Hashing errors are not consistently propagated

Files: lib/crypto.cpp, lib/afflib_pages.cpp, tools/affcopy.cpp, tools/affinfo.cpp, tools/affconvert.cpp

The new af_MD5() and af_sha1() functions return an error code, which is good.

However, several callers ignore it.

For example:

af_MD5((const unsigned char *)data,datalen,md5_buf);

This occurs in af_update_page().

If the digest operation fails, the caller can continue and store an invalid digest.

The same general concern applies to EVP_DigestUpdate() and EVP_DigestFinal_ex() calls in the utilities.

This is especially important for forensic software: a failed integrity calculation must not silently be treated as a successful integrity calculation.

Recommendation: Propagate digest failures, and do not write or report a digest as valid unless its calculation succeeded.

G. Cross-compilation support in the OpenSSL version detection

File: m4/ax_openssl_version.m4

The new macro uses:

AC_RUN_IFELSE([AC_LANG_PROGRAM(... )],
[...],
[...])

But it does not supply the fourth argument, which is the cross-compilation action.

The comment explicitly claims:

when execution is not possible (e.g. cross-compiling), the version is reported as unknown.

However, Autoconf's AC_RUN_IFELSE requires a cross-compilation alternative if the test must work when the target executable cannot be run.

Without it, configure can fail outright during cross-compilation rather than reporting an unknown version.

Recommendation: Supply the fourth argument and explicitly set ax_openssl_version to an empty value in that case.

This is a portability issue rather than a direct security vulnerability, but it contradicts the stated behavior of the new macro.

2. Additional findings

H. The passphrase-based AES implementation has the same padding-order bug

File: lib/crypto.cpp

This is particularly important because the PR changes the implementation of AFF key storage and retrieval.

In af_save_aes_key_with_passphrase():

EVP_CIPHER_CTX *ectx = EVP_CIPHER_CTX_new();

EVP_CIPHER_CTX_set_padding(ectx,0);

if(EVP_EncryptInit_ex(ectx,EVP_aes_256_ecb(),NULL,
                      passphrase_hash,NULL)==1){

And in af_get_aes_key_from_passphrase():

EVP_CIPHER_CTX *dctx = EVP_CIPHER_CTX_new();

EVP_CIPHER_CTX_set_padding(dctx,0);

if(EVP_DecryptInit_ex(dctx,EVP_aes_256_ecb(),NULL,
                      passphrase_hash,NULL)==1){

Both functions set padding before initializing the cipher.

This is especially problematic because both functions process three separate 16-byte blocks using EVP_EncryptUpdate() or EVP_DecryptUpdate(), but never call the corresponding Final function.

With standard EVP block padding enabled, the final block is retained by Update for processing during Final. Consequently, the three-block operations cannot be assumed to produce the expected three encrypted/decrypted blocks.

Recommendation: Initialize the cipher first, disable padding second, and verify every operation. Add tests that save and retrieve an AFF encryption key using a passphrase.

I would classify this as a high-priority correctness issue.

I. af_MD5() and af_sha1() don't check all EVP operations

File: lib/crypto.cpp

The new implementations check initialization and finalization, but don't check:

EVP_DigestUpdate(ctx,data,datalen);

They should check its return value as well.

Otherwise, a failed update could result in an invalid digest being returned as successful.

This is particularly important because the functions are intended to become the common replacement for the old OpenSSL hashing functions.

J. affconvert also needs better error handling

File: tools/affconvert.cpp

The new code allocates two contexts:

EVP_MD_CTX *md5ctx = EVP_MD_CTX_new();
EVP_MD_CTX *sha1ctx = EVP_MD_CTX_new();

It checks for allocation failure, which is good.

However:

  • If one allocation succeeds and the other fails, the successful allocation is leaked.
  • The return values of EVP_DigestUpdate() are ignored.
  • The return values of EVP_DigestFinal_ex() are ignored.

The last two issues can result in incorrect MD5/SHA1 metadata being written to the output AFF file.

K. affinfo preview change is actually an improvement

File: tools/affinfo.cpp

There is one positive change worth mentioning.

The old code used:

u_char md5[32];
MD5(data,data_len,md5);
memcpy(data,md5,32);
data_len = 32;

MD5 produces only 16 bytes. Consequently, the second 16 bytes copied into data were uninitialized stack contents.

The PR corrects this:

u_char md5[16];
af_MD5((const unsigned char *)data,data_len,md5);
memcpy(data,md5,16);
data_len = 16;

This eliminates an unintended disclosure of stack contents through the preview functionality.

That's a good fix.

3. Compatibility and design considerations

There are several other aspects I would investigate, although I don't consider them established defects from the diff alone.

Area Assessment
OpenSSL 1.0.2 compatibility EVP context aliases appear reasonable.
OpenSSL 1.1.1 compatibility Generally reasonable.
OpenSSL 3.x compatibility Moving away from deprecated low-level APIs is appropriate.
OpenSSL 4.x compatibility Worth testing against an actual release and its provider behavior.
LibreSSL Needs a dedicated build test.
AES file-format compatibility Requires regression testing against existing AFF files.
QEMU asynchronous I/O Needs verification of context sharing and synchronization.
S3 support Needs a dedicated build and runtime test.

One additional consideration is that OpenSSL 3 uses providers for cryptographic algorithms. In particular, MD5 may not be available under every provider configuration.

The new af_MD5() implementation uses:

EVP_get_digestbyname("MD5");

If MD5 is unavailable, it returns an error. That's reasonable behavior, but callers must actually handle that error.

AES compatibility testing

I would be particularly careful about the claim that the EVP implementation produces byte-identical results to the old AES implementation.

The conversion is conceptually reasonable:

  • AES-CBC remains AES-CBC.
  • The key sizes are preserved.
  • The IV construction is preserved.
  • Padding is intended to be disabled in EVP.
  • The existing AFF segment padding scheme is retained.

However, the new code also changes how the input buffer is prepared before encryption.

I would test actual ciphertext compatibility rather than relying on the comments.

4. Recommended test plan

Before merging, I would want the following tests.

Test Expected result
Build with OpenSSL 1.0.2 Successful
Build with OpenSSL 1.1.1 Successful
Build with OpenSSL 3.x Successful
Build with OpenSSL 3.x, no deprecated APIs Successful
Cross-compile with OpenSSL Configure succeeds
AES-128 AFF encryption/decryption Correct round trip
AES-192 AFF encryption/decryption Correct round trip
AES-256 AFF encryption/decryption Correct round trip
Passphrase-based key storage/retrieval Correct round trip
Read previously encrypted AFF files Successful
Write and read encrypted QEMU QCOW images Correct data
QEMU concurrent I/O No data corruption
MD5/SHA1 page verification Correct results
S3-enabled build Successful

For AES, I would test input lengths of:

  • 0 bytes
  • 1 byte
  • 15 bytes
  • 16 bytes
  • 17 bytes
  • 511 bytes
  • 512 bytes
  • 513 bytes

These exercise the different padding and alignment cases.

I would also compare ciphertext generated by the old implementation and the new implementation for identical keys, IVs, and input data, wherever the old implementation's behavior is well-defined.

5. Overall assessment

I would not merge this PR yet

Here is my prioritization:

Priority Finding File
Critical QEMU padding initialization order block-qcow.c, block-qcow2.c
Critical Passphrase AES padding initialization order crypto.cpp
High Ignored encryption/decryption failures afflib.cpp, QEMU files
High Shared mutable QEMU cipher contexts QEMU files
High Unchecked size_t to int conversion afflib.cpp
High Missing context allocation check affinfo.cpp
Medium Ignored digest failures Multiple files
Medium Cross-compilation configure failure ax_openssl_version.m4
Low Context cleanup on allocation failures affconvert.cpp

My overall opinion: The direction of the PR is good. Moving from the deprecated low-level OpenSSL interfaces to EVP is the right general approach, and some of the changes fix existing problems.

However, the migration has introduced several problems because EVP has a different operational model from the low-level AES interfaces.

The most important distinction is that AES_KEY is essentially an expanded key, whereas EVP_CIPHER_CTX is a stateful encryption/decryption context. The code needs to account for initialization, padding, update/final processing, errors, and potentially concurrent access.

I would fix the padding-order issues first, then address error propagation and context management before considering the PR ready.

Primary references:

One particularly useful next step would be to work through lib/crypto.cpp and lib/afflib.cpp line by line and establish exactly which changes are necessary to preserve the existing AFF encryption format. That would address the most consequential part of this PR before tackling the build-system changes.

@joachimmetz

Copy link
Copy Markdown
Author

Changes based on review feedback PTAL

also CI tests are failing due to what looks like connectivity issues between GitHub and the apt repositories

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants