Merge pull request #16719 from MarrasFederico/feat/libressl-evp-digestverifyfinal

feat(libSceLibreSsl): verify RSA signatures through EVP_DigestVerify
This commit is contained in:
Dean authored and GitHub committed 2026-11-10 23:57:22 +13:00
commit 1e67c2782d
12 files changed
+1322 -35

No files matched your search

@@ -651,6 +651,22 @@ endif()
target_sources(libSceLibreSsl PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/X509NameOneline.cpp)
target_sources(libSceLibreSsl PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/DigestVerify.cpp)
if(BUILD_TESTING)
add_test_executable(guest_libressl_digest_verify_tests ${CMAKE_CURRENT_SOURCE_DIR}/tests/DigestVerify.cpp)
target_include_directories(guest_libressl_digest_verify_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(guest_libressl_digest_verify_tests PRIVATE libSceLibreSsl libc)
configure_windows_unwind(guest_libressl_digest_verify_tests)
add_test(NAME guest_libressl_digest_verify COMMAND guest_libressl_digest_verify_tests)
add_test(NAME guest_libressl_digest_verify_allocator COMMAND guest_libressl_digest_verify_tests allocator)
set_tests_properties(guest_libressl_digest_verify guest_libressl_digest_verify_allocator PROPERTIES TIMEOUT 30)
if(WIN32)
set_tests_properties(guest_libressl_digest_verify guest_libressl_digest_verify_allocator PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceLibreSsl>")
endif()
endif()
if(BUILD_TESTING)
add_test_executable(guest_libressl_x509_name_oneline_tests ${CMAKE_CURRENT_SOURCE_DIR}/tests/X509NameOneline.cpp)
target_include_directories(guest_libressl_x509_name_oneline_tests PRIVATE ${LIBS_INCLUDE_DIR})
-11
View File
@@ -142,17 +142,6 @@ int APS5_VABI ENGINE_set_default_nid_postfix(void) {
return 0;
}
int APS5_VABI EVP_DigestVerifyFinal_nid_postfix(void) {
NotImplemented_nid_no_patch(__func__);
return 0;
}
int APS5_VABI EVP_DigestVerifyInit_nid_postfix(EvpMdContext* context, void**, const EvpMd*, void*, void* pkey) {
if (!context) throw std::invalid_argument("null EVP digest context");
if (context->pkeyContext || pkey) NotImplemented_nid_no_patch(__func__);
return 0;
}
int APS5_VABI EVP_PKEY_get1_EC_KEY_nid_postfix(void) {
NotImplemented_nid_no_patch(__func__);
return 0;
+1 -1
View File
@@ -681,7 +681,7 @@ int APS5_VABI EVP_Digest_nid_postfix(const void* data, std::size_t length, unsig
int APS5_VABI EVP_DigestFinal_ex_nid_postfix(EvpMdContext* context, unsigned char* digest, std::uint32_t* size);
int APS5_VABI EVP_DigestInit_ex_nid_postfix(EvpMdContext* context, const EvpMd* type, void* engine);
int APS5_VABI EVP_DigestUpdate_nid_postfix(EvpMdContext* context, const void* data, std::size_t length);
int APS5_VABI EVP_DigestVerifyFinal_nid_postfix(void);
int APS5_VABI EVP_DigestVerifyFinal_nid_postfix(EvpMdContext* context, unsigned char* signature, std::size_t signatureLength);
int APS5_VABI EVP_DigestVerifyInit_nid_postfix(EvpMdContext* context, void** pctx, const EvpMd* type, void* engine, void* pkey);
int APS5_VABI EVP_EncryptFinal_ex_nid_postfix(LibreSslEvpCipherCtx* ctx, unsigned char* out, int* outl);
int APS5_VABI EVP_EncryptInit_ex_nid_postfix(LibreSslEvpCipherCtx* ctx, const LibreSslEvpCipher* cipher, void* engine, const unsigned char* key, const unsigned char* iv);
@@ -30,4 +30,10 @@ static_assert(offsetof(LibreSslEvpCipherCtx, num) == 88);
static_assert(offsetof(LibreSslEvpCipherCtx, flags) == 112);
static_assert(offsetof(LibreSslEvpCipherCtx, final) == 136);
extern "C" {
int CopyContext_nid_no_patch(EvpMdContext& target, const EvpMdContext& source, const char* function);
}
#endif
@@ -0,0 +1,110 @@
#ifndef CORE_LIBS_PRX_LIBSCELIBRESSL_INCLUDE_PKEYCONTEXT_HPP
#define CORE_LIBS_PRX_LIBSCELIBRESSL_INCLUDE_PKEYCONTEXT_HPP
#include <cstddef>
#include <cstdint>
#include "prx/libSceLibreSsl/include/Api.hpp"
struct PkeyContext;
struct PkeyMethod {
std::int32_t pkeyId;
std::int32_t flags;
int (APS5_VABI* init)(PkeyContext* context);
int (APS5_VABI* copy)(PkeyContext* target, PkeyContext* source);
void (APS5_VABI* cleanup)(PkeyContext* context);
int (APS5_VABI* parameterGenerationInit)(PkeyContext* context);
int (APS5_VABI* parameterGeneration)(PkeyContext* context, void* key);
int (APS5_VABI* keyGenerationInit)(PkeyContext* context);
int (APS5_VABI* keyGeneration)(PkeyContext* context, void* key);
int (APS5_VABI* signInit)(PkeyContext* context);
int (APS5_VABI* sign)(PkeyContext* context, unsigned char* signature, std::size_t* signatureLength, const unsigned char* data,
std::size_t dataLength);
int (APS5_VABI* verifyInit)(PkeyContext* context);
int (APS5_VABI* verify)(PkeyContext* context, const unsigned char* signature, std::size_t signatureLength, const unsigned char* data,
std::size_t dataLength);
int (APS5_VABI* verifyRecoverInit)(PkeyContext* context);
int (APS5_VABI* verifyRecover)(PkeyContext* context, unsigned char* output, std::size_t* outputLength, const unsigned char* signature,
std::size_t signatureLength);
int (APS5_VABI* signContextInit)(PkeyContext* context, EvpMdContext* digestContext);
int (APS5_VABI* signContext)(PkeyContext* context, unsigned char* signature, std::size_t* signatureLength, EvpMdContext* digestContext);
int (APS5_VABI* verifyContextInit)(PkeyContext* context, EvpMdContext* digestContext);
int (APS5_VABI* verifyContext)(PkeyContext* context, const unsigned char* signature, int signatureLength, EvpMdContext* digestContext);
int (APS5_VABI* encryptInit)(PkeyContext* context);
int (APS5_VABI* encrypt)(PkeyContext* context, unsigned char* output, std::size_t* outputLength, const unsigned char* input,
std::size_t inputLength);
int (APS5_VABI* decryptInit)(PkeyContext* context);
int (APS5_VABI* decrypt)(PkeyContext* context, unsigned char* output, std::size_t* outputLength, const unsigned char* input,
std::size_t inputLength);
int (APS5_VABI* deriveInit)(PkeyContext* context);
int (APS5_VABI* derive)(PkeyContext* context, unsigned char* key, std::size_t* keyLength);
int (APS5_VABI* control)(PkeyContext* context, int command, int argument, void* pointer);
int (APS5_VABI* controlString)(PkeyContext* context, const char* name, const char* value);
};
struct PkeyContext {
const PkeyMethod* method;
void* engine;
void* key;
void* peerKey;
int operation;
void* data;
void* applicationData;
void* generationCallback;
int* generationInformation;
int generationInformationCount;
};
struct RsaPkeyContext {
int bits;
void* publicExponent;
int generationInformation[2];
int padding;
const EvpMd* digest;
const EvpMd* maskDigest;
int saltLength;
unsigned char* buffer;
};
static_assert(sizeof(PkeyMethod) == 208);
static_assert(offsetof(PkeyMethod, pkeyId) == 0);
static_assert(offsetof(PkeyMethod, flags) == 4);
static_assert(offsetof(PkeyMethod, init) == 8);
static_assert(offsetof(PkeyMethod, sign) == 72);
static_assert(offsetof(PkeyMethod, verify) == 88);
static_assert(offsetof(PkeyMethod, signContext) == 120);
static_assert(offsetof(PkeyMethod, verifyContextInit) == 128);
static_assert(offsetof(PkeyMethod, verifyContext) == 136);
static_assert(offsetof(PkeyMethod, control) == 192);
static_assert(offsetof(PkeyMethod, controlString) == 200);
static_assert(sizeof(PkeyContext) == 80);
static_assert(offsetof(PkeyContext, method) == 0);
static_assert(offsetof(PkeyContext, engine) == 8);
static_assert(offsetof(PkeyContext, key) == 16);
static_assert(offsetof(PkeyContext, peerKey) == 24);
static_assert(offsetof(PkeyContext, operation) == 32);
static_assert(offsetof(PkeyContext, data) == 40);
static_assert(offsetof(PkeyContext, applicationData) == 48);
static_assert(offsetof(PkeyContext, generationCallback) == 56);
static_assert(offsetof(PkeyContext, generationInformation) == 64);
static_assert(offsetof(PkeyContext, generationInformationCount) == 72);
static_assert(sizeof(RsaPkeyContext) == 64);
static_assert(offsetof(RsaPkeyContext, bits) == 0);
static_assert(offsetof(RsaPkeyContext, publicExponent) == 8);
static_assert(offsetof(RsaPkeyContext, generationInformation) == 16);
static_assert(offsetof(RsaPkeyContext, padding) == 24);
static_assert(offsetof(RsaPkeyContext, digest) == 32);
static_assert(offsetof(RsaPkeyContext, maskDigest) == 40);
static_assert(offsetof(RsaPkeyContext, saltLength) == 48);
static_assert(offsetof(RsaPkeyContext, buffer) == 56);
extern "C" {
PkeyContext* PkeyContextNew_nid_no_patch(void* key, void* engine);
PkeyContext* PkeyContextDuplicate_nid_no_patch(PkeyContext* context);
void PkeyContextFree_nid_no_patch(PkeyContext* context);
int PkeyContextControl_nid_no_patch(PkeyContext* context, int keyType, int operationType, int command, int argument, void* pointer);
}
#endif
@@ -0,0 +1,413 @@
#include "prx/libSceLibreSsl/include/Api.hpp"
#include "prx/libSceLibreSsl/include/Error.hpp"
#include "prx/libSceLibreSsl/include/Evp.hpp"
#include "prx/libSceLibreSsl/include/PkeyContext.hpp"
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <stdexcept>
#include <string>
#include "prx/libc/include/Api.hpp"
#include "prx/libc/include/General.hpp"
namespace {
struct PkeyHeader {
std::int32_t type;
std::int32_t saveType;
std::int32_t references;
const void* method;
};
static_assert(offsetof(PkeyHeader, references) == 8);
static_assert(offsetof(PkeyHeader, method) == 16);
constexpr int EvpLibrary = 6;
constexpr int AnyFunction = 0xfff;
constexpr int MallocFailure = 65;
constexpr int CommandNotSupported = 147;
constexpr int InvalidOperation = 148;
constexpr int NoOperationSet = 149;
constexpr int OperationNotSupported = 150;
constexpr int OperationNotInitialized = 151;
constexpr int NoDefaultDigest = 158;
constexpr int InputNotInitialized = 111;
constexpr std::int32_t PkeyRsa = 6;
constexpr std::int32_t PkeyRsa2 = 19;
constexpr std::int32_t NidSha1 = 64;
constexpr std::int32_t NidSha1WithRsaEncryption = 65;
constexpr std::uint64_t FlagMethodSignature = 0x4;
constexpr std::uint64_t FlagDigestAlgorithmIdAbsent = 0x8;
constexpr int AutoArgLength = 2;
constexpr std::size_t MaxDigestSize = 64;
constexpr std::ptrdiff_t PointerSize = 8;
constexpr int DefaultKeyBits = 2048;
constexpr int LongestSalt = -2;
constexpr int PaddingPkcs1 = 1;
constexpr int PaddingSslV23 = 2;
constexpr int PaddingNone = 3;
constexpr int PaddingOaep = 4;
constexpr int PaddingX931 = 5;
constexpr int PaddingPss = 6;
constexpr int OperationUndefined = 0;
constexpr int OperationSign = 1 << 3;
constexpr int OperationVerify = 1 << 4;
constexpr int OperationVerifyRecover = 1 << 5;
constexpr int OperationSignContext = 1 << 6;
constexpr int OperationVerifyContext = 1 << 7;
constexpr int OperationTypeSign = OperationSign | OperationVerify | OperationVerifyRecover | OperationSignContext | OperationVerifyContext;
constexpr int ControlMd = 1;
constexpr int ControlDigestInit = 7;
int APS5_VABI EvpSha1Init(EvpMdContext* context) {
return SHA1_Init_nid_postfix(static_cast<Sha1Context*>(context->mdData));
}
int APS5_VABI EvpSha1Update(EvpMdContext* context, const void* data, std::size_t length) {
return SHA1_Update_nid_postfix(static_cast<Sha1Context*>(context->mdData), data, length);
}
int APS5_VABI EvpSha1Final(EvpMdContext* context, unsigned char* digest) {
return SHA1_Final_nid_postfix(digest, static_cast<Sha1Context*>(context->mdData));
}
constexpr EvpMd Sha1 {
NidSha1, NidSha1WithRsaEncryption, 20, FlagMethodSignature | FlagDigestAlgorithmIdAbsent, EvpSha1Init, EvpSha1Update, EvpSha1Final,
nullptr, nullptr, nullptr, nullptr, {PkeyRsa, PkeyRsa2, 0, 0, 0}, 64, static_cast<std::int32_t>(PointerSize + sizeof(Sha1Context)), nullptr,
};
static_assert(sizeof(Sha1Context) == 96);
static_assert(offsetof(EvpMd, contextSize) == 104);
void QueueEvp(int reason) {
LibreSslPutError_nid_no_patch(EvpLibrary, AnyFunction, reason, __FILE__, __LINE__);
}
int APS5_VABI RsaContextInit(PkeyContext* context);
void APS5_VABI RsaContextCleanup(PkeyContext* context);
int APS5_VABI UnavailableSign(PkeyContext*, unsigned char* signature, std::size_t* signatureLength, const unsigned char*, std::size_t) {
NotImplemented_nid_no_patch("EVP_PKEY_sign with a key context this library created");
return -2;
}
int APS5_VABI UnavailableVerifyRecover(PkeyContext*, unsigned char* output, std::size_t* outputLength, const unsigned char*, std::size_t) {
NotImplemented_nid_no_patch("EVP_PKEY_verify_recover with a key context this library created");
return -2;
}
int APS5_VABI UnavailableEncrypt(PkeyContext*, unsigned char* output, std::size_t* outputLength, const unsigned char*, std::size_t) {
NotImplemented_nid_no_patch("EVP_PKEY_encrypt with a key context this library created");
return -2;
}
int APS5_VABI UnavailableDecrypt(PkeyContext*, unsigned char* output, std::size_t* outputLength, const unsigned char*, std::size_t) {
NotImplemented_nid_no_patch("EVP_PKEY_decrypt with a key context this library created");
return -2;
}
int APS5_VABI UnavailableKeyGeneration(PkeyContext*, void*) {
NotImplemented_nid_no_patch("EVP_PKEY_keygen with a key context this library created");
return -2;
}
int APS5_VABI UnavailableControlString(PkeyContext*, const char*, const char*) {
NotImplemented_nid_no_patch("EVP_PKEY_CTX_ctrl_str with a key context this library created");
return -2;
}
const RsaPkeyContext& RequireRsaContextData(const PkeyContext& context, const char* function) {
if (!context.data) throw std::invalid_argument(std::string(function) + ": an RSA key context without its method data");
return *static_cast<const RsaPkeyContext*>(context.data);
}
RsaPkeyContext& RequireRsaContextData(PkeyContext& context, const char* function) {
if (!context.data) throw std::invalid_argument(std::string(function) + ": an RSA key context without its method data");
return *static_cast<RsaPkeyContext*>(context.data);
}
int APS5_VABI RsaContextCopy(PkeyContext* target, PkeyContext* source) {
if (!RsaContextInit(target)) return 0;
const auto& from = RequireRsaContextData(*source, "pkey_rsa_copy");
auto& to = RequireRsaContextData(*target, "pkey_rsa_copy");
if (from.publicExponent) NotImplemented_nid_no_patch("pkey_rsa_copy of a key context with a keygen public exponent");
to.bits = from.bits;
to.padding = from.padding;
to.digest = from.digest;
return 1;
}
LibreSslRsa* KeyOf(const PkeyContext& context, const char* function) {
if (!context.key) throw std::invalid_argument(std::string(function) + ": a key context without a key");
return EVP_PKEY_get1_RSA_nid_postfix(context.key);
}
int SetupTemporaryBuffer(RsaPkeyContext& data, const LibreSslRsa& rsa, const char* function) {
if (data.buffer) return 1;
const int size = RSA_size_nid_postfix(const_cast<LibreSslRsa*>(&rsa));
if (size <= 0) throw std::invalid_argument(std::string(function) + ": an RSA key with a non-positive size");
data.buffer = static_cast<unsigned char*>(malloc_nid_postfix(static_cast<std::size_t>(size)));
return data.buffer ? 1 : 0;
}
int APS5_VABI RsaVerify(PkeyContext* context, const unsigned char* signature, std::size_t signatureLength, const unsigned char* data, std::size_t dataLength) {
auto& method = RequireRsaContextData(*context, "pkey_rsa_verify");
auto* rsa = KeyOf(*context, "pkey_rsa_verify");
if (method.digest) {
if (method.padding == PaddingPkcs1) {
const int result = RSA_verify_nid_postfix(method.digest->type, data, static_cast<unsigned int>(dataLength), signature,
static_cast<unsigned int>(signatureLength), rsa);
RSA_free_nid_postfix(rsa);
return result;
}
RSA_free_nid_postfix(rsa);
if (method.padding == PaddingPss) NotImplemented_nid_no_patch("EVP_DigestVerifyFinal with RSA-PSS padding");
if (method.padding != PaddingX931) return -1;
NotImplemented_nid_no_patch("EVP_DigestVerifyFinal with RSA X9.31 padding");
}
if (!SetupTemporaryBuffer(method, *rsa, "pkey_rsa_verify")) {
RSA_free_nid_postfix(rsa);
return -1;
}
const int length = RSA_public_decrypt_nid_postfix(static_cast<int>(signatureLength), signature, method.buffer, rsa, method.padding);
if (length == 0) {
RSA_free_nid_postfix(rsa);
return 0;
}
const bool same = static_cast<std::size_t>(length) == dataLength && std::memcmp(method.buffer, data, static_cast<std::size_t>(length)) == 0;
RSA_free_nid_postfix(rsa);
return same ? 1 : 0;
}
bool CheckPaddingDigest(const EvpMd* digest, int padding) {
if (!digest) return true;
if (padding != PaddingPkcs1) NotImplemented_nid_no_patch("pkey_rsa_ctrl with a padding mode other than PKCS#1 v1.5");
return true;
}
int APS5_VABI RsaControl(PkeyContext* context, int command, int argument, void* pointer) {
auto& data = RequireRsaContextData(*context, "pkey_rsa_ctrl");
switch (command) {
case ControlMd:
if (!CheckPaddingDigest(static_cast<const EvpMd*>(pointer), data.padding)) return 0;
data.digest = static_cast<const EvpMd*>(pointer);
return 1;
case ControlDigestInit:
return 1;
default:
return -2;
}
}
int APS5_VABI RsaContextInit(PkeyContext* context) {
auto* data = static_cast<RsaPkeyContext*>(malloc_nid_postfix(sizeof(RsaPkeyContext)));
if (!data) return 0;
std::memset(data, 0, sizeof(*data));
data->bits = DefaultKeyBits;
data->padding = PaddingPkcs1;
data->saltLength = LongestSalt;
context->data = data;
context->generationInformation = data->generationInformation;
context->generationInformationCount = 2;
return 1;
}
void APS5_VABI RsaContextCleanup(PkeyContext* context) {
auto* data = static_cast<RsaPkeyContext*>(context->data);
if (!data) return;
if (data->publicExponent) NotImplemented_nid_no_patch("pkey_rsa_cleanup of a key context with a keygen public exponent");
free_nid_postfix(data->buffer);
free_nid_postfix(data);
context->data = nullptr;
}
constexpr PkeyMethod RsaMethod {
.pkeyId = PkeyRsa,
.flags = AutoArgLength,
.init = RsaContextInit,
.copy = RsaContextCopy,
.cleanup = RsaContextCleanup,
.keyGeneration = UnavailableKeyGeneration,
.sign = UnavailableSign,
.verify = RsaVerify,
.verifyRecover = UnavailableVerifyRecover,
.encrypt = UnavailableEncrypt,
.decrypt = UnavailableDecrypt,
.control = RsaControl,
.controlString = UnavailableControlString,
};
static_assert(RsaMethod.verifyContext == nullptr);
static_assert(RsaMethod.verifyContextInit == nullptr);
static_assert(RsaMethod.flags == 2);
void RequireOurMethod(const PkeyContext& context, const char* function) {
if (context.method != &RsaMethod) NotImplemented_nid_no_patch((std::string(function) + ": a key context this library did not create").c_str());
}
PkeyContext* NewContext(void* key, void* engine) {
if (!key) return nullptr;
if (engine) NotImplemented_nid_no_patch("EVP_PKEY_CTX_new with an ENGINE");
auto& header = *static_cast<PkeyHeader*>(key);
if (!header.method) return nullptr;
if (header.type != PkeyRsa) NotImplemented_nid_no_patch("EVP_PKEY_CTX_new for a key that is not RSA");
auto* context = static_cast<PkeyContext*>(malloc_nid_postfix(sizeof(PkeyContext)));
if (!context) {
QueueEvp(MallocFailure);
return nullptr;
}
std::memset(context, 0, sizeof(*context));
context->method = &RsaMethod;
context->key = key;
std::atomic_ref<std::int32_t>(header.references).fetch_add(1, std::memory_order_relaxed);
if (RsaMethod.init && RsaMethod.init(context) <= 0) {
PkeyContextFree_nid_no_patch(context);
return nullptr;
}
return context;
}
void FreeContext(PkeyContext* context) {
if (!context) return;
RequireOurMethod(*context, "EVP_PKEY_CTX_free");
if (RsaMethod.cleanup) RsaMethod.cleanup(context);
EVP_PKEY_free_nid_postfix(context->key);
EVP_PKEY_free_nid_postfix(context->peerKey);
free_nid_postfix(context);
}
PkeyContext* DuplicateContext(PkeyContext* context) {
RequireOurMethod(*context, "EVP_PKEY_CTX_dup");
auto* copy = static_cast<PkeyContext*>(malloc_nid_postfix(sizeof(PkeyContext)));
if (!copy) return nullptr;
std::memset(copy, 0, sizeof(*copy));
copy->method = context->method;
copy->engine = context->engine;
if (context->key) std::atomic_ref<std::int32_t>(static_cast<PkeyHeader*>(context->key)->references).fetch_add(1, std::memory_order_relaxed);
copy->key = context->key;
copy->peerKey = context->peerKey;
copy->operation = context->operation;
if (context->method->copy(copy, context) > 0) return copy;
FreeContext(copy);
return nullptr;
}
int ControlContext(PkeyContext* context, int keyType, int operationType, int command, int argument, void* pointer) {
if (!context || !context->method || !context->method->control) {
QueueEvp(CommandNotSupported);
return -2;
}
if (keyType != -1 && context->method->pkeyId != keyType) return -1;
if (context->operation == OperationUndefined) {
QueueEvp(NoOperationSet);
return -1;
}
if (operationType != -1 && !(context->operation & operationType)) {
QueueEvp(InvalidOperation);
return -1;
}
const int result = context->method->control(context, command, argument, pointer);
if (result == -2) QueueEvp(CommandNotSupported);
return result;
}
int VerifyWithKey(PkeyContext* context, const unsigned char* signature, std::size_t signatureLength, const unsigned char* data, std::size_t dataLength) {
if (!context || !context->method || !context->method->verify) {
QueueEvp(OperationNotSupported);
return -2;
}
if (context->operation != OperationVerify) {
QueueEvp(OperationNotInitialized);
return -1;
}
return context->method->verify(context, signature, signatureLength, data, dataLength);
}
const EvpMd* DefaultDigest(const PkeyContext& context) {
if (!context.key) return nullptr;
if (static_cast<const PkeyHeader*>(context.key)->type != PkeyRsa) return nullptr;
return &Sha1;
}
} // namespace
extern "C" {
PkeyContext* PkeyContextNew_nid_no_patch(void* key, void* engine) {
return NewContext(key, engine);
}
PkeyContext* PkeyContextDuplicate_nid_no_patch(PkeyContext* context) {
return DuplicateContext(context);
}
void PkeyContextFree_nid_no_patch(PkeyContext* context) {
FreeContext(context);
}
int PkeyContextControl_nid_no_patch(PkeyContext* context, int keyType, int operationType, int command, int argument, void* pointer) {
return ControlContext(context, keyType, operationType, command, argument, pointer);
}
int APS5_VABI EVP_DigestVerifyInit_nid_postfix(EvpMdContext* context, void** pctx, const EvpMd* type, void* engine, void* pkey) {
if (!context) throw std::invalid_argument(std::string(__func__) + ": null digest context");
if (!context->pkeyContext && !pkey) return 0;
if (engine) NotImplemented_nid_no_patch((std::string(__func__) + ": ENGINE").c_str());
if (!context->pkeyContext) {
context->pkeyContext = NewContext(pkey, nullptr);
if (!context->pkeyContext) return 0;
}
auto* pkeyContext = static_cast<PkeyContext*>(context->pkeyContext);
RequireOurMethod(*pkeyContext, __func__);
const auto* method = pkeyContext->method;
const EvpMd* digest = type;
if (!digest) {
digest = DefaultDigest(*pkeyContext);
if (!digest) {
QueueEvp(NoDefaultDigest);
return 0;
}
}
if (method->verifyContextInit) {
if (method->verifyContextInit(pkeyContext, context) <= 0) return 0;
pkeyContext->operation = OperationVerifyContext;
} else {
if (!method->verify) {
QueueEvp(OperationNotSupported);
return 0;
}
pkeyContext->operation = OperationVerify;
if (method->verifyInit && method->verifyInit(pkeyContext) <= 0) {
pkeyContext->operation = OperationUndefined;
return 0;
}
}
if (ControlContext(pkeyContext, -1, OperationTypeSign, ControlMd, 0, const_cast<EvpMd*>(digest)) <= 0) return 0;
if (pctx) *pctx = pkeyContext;
if (!EVP_DigestInit_ex_nid_postfix(context, digest, nullptr)) return 0;
const int digestInit = ControlContext(pkeyContext, -1, OperationTypeSign, ControlDigestInit, 0, context);
if (digestInit <= 0 && digestInit != -2) return 0;
return 1;
}
int APS5_VABI EVP_DigestVerifyFinal_nid_postfix(EvpMdContext* context, unsigned char* signature, std::size_t signatureLength) {
if (!context || !context->pkeyContext) NotImplemented_nid_no_patch(__func__);
auto* pkeyContext = static_cast<PkeyContext*>(context->pkeyContext);
RequireOurMethod(*pkeyContext, __func__);
EvpMdContext copy {};
if (!CopyContext_nid_no_patch(copy, *context, __func__)) {
if (!context->digest) QueueEvp(InputNotInitialized);
return -1;
}
unsigned char digest[MaxDigestSize];
std::uint32_t digestLength = 0;
const int finalized = EVP_DigestFinal_ex_nid_postfix(&copy, digest, &digestLength);
EVP_MD_CTX_cleanup_nid_postfix(&copy);
if (!finalized) return finalized;
return VerifyWithKey(pkeyContext, signature, signatureLength, digest, digestLength);
}
}
+16 -1
View File
@@ -168,6 +168,8 @@
#include "prx/libc/include/Api.hpp"
#include "prx/libSceLibreSsl/include/Api.hpp"
#include "prx/libSceLibreSsl/include/Evp.hpp"
#include "prx/libSceLibreSsl/include/PkeyContext.hpp"
#include <cstddef>
#include <cstdint>
#include <cstring>
@@ -266,7 +268,6 @@ template<class TContext> TContext& RequireContext(TContext* context, const char*
void RequireNoEngineOrKey(const EvpMdContext& context, const char* function) {
if (context.engine) NotImplemented_nid_no_patch((std::string(function) + ": ENGINE").c_str());
if (context.pkeyContext) NotImplemented_nid_no_patch((std::string(function) + ": EVP_PKEY_CTX").c_str());
}
void ReleaseData(EvpMdContext& context) {
@@ -280,6 +281,7 @@ int CleanupContext(EvpMdContext& context, const char* function) {
RequireNoEngineOrKey(context, function);
if (context.digest && context.digest->cleanup && !(context.flags & FlagCleaned)) context.digest->cleanup(&context);
ReleaseData(context);
PkeyContextFree_nid_no_patch(static_cast<PkeyContext*>(context.pkeyContext));
std::memset(&context, 0, sizeof(context));
return 1;
}
@@ -298,6 +300,8 @@ int DigestInit(EvpMdContext& context, const EvpMd* type, void* engine, const cha
if (type->contextSize < 0) throw std::invalid_argument(std::string(function) + ": negative digest context size");
context.mdData = malloc_nid_postfix(static_cast<std::size_t>(type->contextSize));
if (!context.mdData) {
PkeyContextFree_nid_no_patch(static_cast<PkeyContext*>(context.pkeyContext));
context.pkeyContext = nullptr;
context.digest = nullptr;
context.update = nullptr;
return 0;
@@ -356,6 +360,13 @@ int CopyContext(EvpMdContext& to, const EvpMdContext& from, const char* function
std::memmove(to.mdData, from.mdData, size);
}
to.update = from.update;
if (from.pkeyContext) {
to.pkeyContext = PkeyContextDuplicate_nid_no_patch(static_cast<PkeyContext*>(from.pkeyContext));
if (!to.pkeyContext) {
CleanupContext(to, function);
return 0;
}
}
if (to.digest->copy) return to.digest->copy(&to, &from);
return 1;
}
@@ -430,6 +441,10 @@ int HmacFinal(HmacContext& context, unsigned char* digest, std::uint32_t* length
}
}
extern "C" int CopyContext_nid_no_patch(EvpMdContext& to, const EvpMdContext& from, const char* function) {
return CopyContext(to, from, function);
}
extern "C" {
const EvpMd* APS5_VABI EVP_md5_nid_postfix(void) {
+70 -17
View File
@@ -434,19 +434,35 @@ int AddNone(unsigned char* to, int size, const unsigned char* from, int length,
}
int CheckPkcs1Type1(unsigned char* to, int size, const unsigned char* from, int length, int modulusLength, const char* function) {
if (modulusLength != length + 1 || !length || from[0] != 0x01) return -1;
if (modulusLength != length + 1 || !length || from[0] != 0x01) {
LibreSslPutError_nid_no_patch(4, 0xfff, 106, __FILE__, __LINE__);
return -1;
}
const unsigned char* data = from + 1;
int remaining = length - 1;
int index = 0;
for (; index < remaining; ++index, ++data) {
if (*data == 0xFF) continue;
if (*data) return -1;
if (*data) {
LibreSslPutError_nid_no_patch(4, 0xfff, 102, __FILE__, __LINE__);
return -1;
}
++data;
break;
}
if (index == remaining || index < 8) return -1;
if (index == remaining) {
LibreSslPutError_nid_no_patch(4, 0xfff, 113, __FILE__, __LINE__);
return -1;
}
if (index < 8) {
LibreSslPutError_nid_no_patch(4, 0xfff, 103, __FILE__, __LINE__);
return -1;
}
remaining -= index + 1;
if (remaining > size) return -1;
if (remaining > size) {
LibreSslPutError_nid_no_patch(4, 0xfff, 109, __FILE__, __LINE__);
return -1;
}
RequireBuffer(to, remaining, function, "output");
if (remaining) std::memcpy(to, data, static_cast<std::size_t>(remaining));
return remaining;
@@ -520,24 +536,39 @@ int APS5_VABI DefaultPublicDecrypt(int length, const unsigned char* from, unsign
constexpr const char* function = "RSA_eay_public_decrypt";
const LibreSslBignum* modulus;
const LibreSslBignum* exponent;
if (!UsablePublicKey(rsa, function, modulus, exponent)) return -1;
if (!UsablePublicKey(rsa, function, modulus, exponent)) {
LibreSslPutError_nid_no_patch(4, 0xfff, Bits(*modulus) > MaxModulusBits ? 105 : 101, __FILE__, __LINE__);
return -1;
}
const int size = (Bits(*modulus) + 7) / 8;
if (length > size || length < 0) return -1;
if (length > size) {
LibreSslPutError_nid_no_patch(4, 0xfff, 108, __FILE__, __LINE__);
return -1;
}
if (length < 0) return -1;
RequireBuffer(from, length, function, "input");
const auto value = FromBytes(from, static_cast<std::size_t>(length));
if (Compare(value.data(), static_cast<int>(value.size()), modulus->d, modulus->top) >= 0) return -1;
if (Compare(value.data(), static_cast<int>(value.size()), modulus->d, modulus->top) >= 0) {
LibreSslPutError_nid_no_patch(4, 0xfff, 132, __FILE__, __LINE__);
return -1;
}
Words result;
if (!PublicOperation(*rsa, value, *exponent, *modulus, result, function)) return -1;
if (padding == PaddingX931) NotImplemented_nid_no_patch("RSA_padding_check_X931");
const auto bytes = ToBytes(result);
switch (padding) {
case PaddingPkcs1:
return CheckPkcs1Type1(to, size, bytes.data(), static_cast<int>(bytes.size()), size, function);
if (const int pkcs1 = CheckPkcs1Type1(to, size, bytes.data(), static_cast<int>(bytes.size()), size, function); pkcs1 >= 0) return pkcs1;
break;
case PaddingNone:
return CheckNone(to, size, bytes.data(), static_cast<int>(bytes.size()), function);
if (const int none = CheckNone(to, size, bytes.data(), static_cast<int>(bytes.size()), function); none >= 0) return none;
break;
default:
LibreSslPutError_nid_no_patch(4, 0xfff, 118, __FILE__, __LINE__);
return -1;
}
LibreSslPutError_nid_no_patch(4, 0xfff, 114, __FILE__, __LINE__);
return -1;
}
struct DigestObject {
@@ -608,11 +639,22 @@ int VerifyDigestInfo(int type, const unsigned char* digest, unsigned int digestL
Element hash;
if (!ReadAlgorithm(fields, algorithm, function) || !ReadPrimitive(fields, 4, hash, function) || fields.length) return 0;
if (sequence.end != data + length) return 0;
if (algorithm.parameter && !algorithm.nullParameter) return 0;
if (!SameDigestType(algorithm, type, function)) return 0;
if (static_cast<unsigned long>(hash.length) != digestLength) return 0;
if (algorithm.parameter && !algorithm.nullParameter) {
LibreSslPutError_nid_no_patch(4, 0xfff, 104, __FILE__, __LINE__);
return 0;
}
if (!SameDigestType(algorithm, type, function)) {
LibreSslPutError_nid_no_patch(4, 0xfff, 100, __FILE__, __LINE__);
return 0;
}
if (static_cast<unsigned long>(hash.length) != digestLength) {
LibreSslPutError_nid_no_patch(4, 0xfff, 104, __FILE__, __LINE__);
return 0;
}
RequireBuffer(digest, digestLength, function, "digest");
return !digestLength || !std::memcmp(digest, hash.content, digestLength);
if (!digestLength || !std::memcmp(digest, hash.content, digestLength)) return 1;
LibreSslPutError_nid_no_patch(4, 0xfff, 104, __FILE__, __LINE__);
return 0;
}
const LibreSslBignum& RequireNormal(const void* number, const char* function, const char* name) {
@@ -1163,15 +1205,26 @@ int APS5_VABI RSA_verify_nid_postfix(int type, const unsigned char* digest, unsi
if (!rsa->meth) throw std::invalid_argument(std::string(__func__) + ": null method");
if (rsa->meth->verify) return reinterpret_cast<RsaVerify>(rsa->meth->verify)(type, digest, digestLength, signature, signatureLength, rsa);
}
if (signatureLength != static_cast<unsigned int>(RSA_size_nid_postfix(rsa))) return 0;
if (type == DigestMd5Sha1 && digestLength != Md5Sha1Bytes) return 0;
if (signatureLength != static_cast<unsigned int>(RSA_size_nid_postfix(rsa))) {
LibreSslPutError_nid_no_patch(4, 0xfff, 119, __FILE__, __LINE__);
return 0;
}
if (type == DigestMd5Sha1 && digestLength != Md5Sha1Bytes) {
LibreSslPutError_nid_no_patch(4, 0xfff, 131, __FILE__, __LINE__);
return 0;
}
std::vector<unsigned char> block(signatureLength);
const int length = RSA_public_decrypt_nid_postfix(static_cast<int>(signatureLength), signature, block.data(), rsa, PaddingPkcs1);
if (length <= 0) return 0;
if (type != DigestMd5Sha1) return VerifyDigestInfo(type, digest, digestLength, block.data(), length, __func__);
if (length != static_cast<int>(Md5Sha1Bytes)) return 0;
if (length != static_cast<int>(Md5Sha1Bytes)) {
LibreSslPutError_nid_no_patch(4, 0xfff, 104, __FILE__, __LINE__);
return 0;
}
RequireBuffer(digest, Md5Sha1Bytes, __func__, "digest");
return !std::memcmp(block.data(), digest, Md5Sha1Bytes);
if (!std::memcmp(block.data(), digest, Md5Sha1Bytes)) return 1;
LibreSslPutError_nid_no_patch(4, 0xfff, 104, __FILE__, __LINE__);
return 0;
}
LibreSslRsa* APS5_VABI d2i_RSA_PUBKEY_nid_postfix(LibreSslRsa** out, const unsigned char** input, long length) {
@@ -0,0 +1,422 @@
#include "prx/libSceLibreSsl/libSceLibreSsl.hpp"
#include "prx/libSceLibreSsl/include/Api.hpp"
#include "prx/libc/include/Api.hpp"
#include "prx/libc/include/ApplicationHeap.hpp"
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <initializer_list>
#include <stdexcept>
#include <vector>
namespace {
struct PkeyHeader {
std::int32_t type;
std::int32_t saveType;
std::int32_t references;
const void* ameth;
void* engine;
void* key;
std::int32_t saveParameters;
void* attributes;
};
struct ForeignKeyContext {
const void* method;
};
static_assert(sizeof(PkeyHeader) == 56);
static_assert(offsetof(PkeyHeader, references) == 8);
static_assert(offsetof(PkeyHeader, key) == 32);
static_assert(sizeof(EvpMdContext) == 48);
static_assert(offsetof(EvpMdContext, pkeyContext) == 32);
constexpr int NidSha1 = 64;
constexpr std::size_t KeyBytes = 128;
constexpr const char Message[] = "AnyPS5 digest verify message";
constexpr const char OtherMessage[] = "AnyPS5 digest verify other message";
constexpr std::uint64_t EvpQueue = (6ull << 24) | (0xfffull << 12);
constexpr std::uint64_t RsaQueue = (4ull << 24) | (0xfffull << 12);
constexpr std::uint64_t MallocFailure = EvpQueue | 65;
constexpr std::uint64_t InputNotInitialized = EvpQueue | 111;
constexpr std::uint64_t AlgorithmMismatch = RsaQueue | 100;
constexpr std::uint64_t BadSignature = RsaQueue | 104;
constexpr std::uint64_t BlockTypeIsNot01 = RsaQueue | 106;
constexpr std::uint64_t PaddingCheckFailed = RsaQueue | 114;
constexpr std::uint64_t WrongSignatureLength = RsaQueue | 119;
constexpr std::uint64_t DataTooLargeForModulus = RsaQueue | 132;
constexpr const char* PublicKeyDer =
"30819f300d06092a864886f70d010101050003818d0030818902818100cfb9ade97bdfe0f53bbc2e7fc3548450fcf1f8"
"74c35aeef29b6fa3e2c59aeb4f3731cf6f5335d806665722251264c3744cc2baef0c5b8975ba580d2674df0f1eb96516"
"d6450c949ed6a3e4fdd66b173a2fa880b6a7dbf60cea94d33c182d2a9175b1db439d10adcb5e2e9756d27ba6e87291ae"
"4b96b13592bd9fa570d06b4ebb0203010001";
constexpr const char* Md5Signature =
"6da10f919c2a6859c396e9fc40a99ba491ac6e8b39ea3cc07dc904c65557ca9f704a6e2b749450dad1320233e481979b"
"ceac3688f431984efbaab3199fcb10236d5075519eb0e0d45464269aa59a5427c39a2789d575b1b23b68a5ceee83d433"
"00900d026bf6ed3adafcd9800562d96ff66dc5725c2a0334225110a979f0b7b2";
constexpr const char* Sha1Signature =
"6118883be4f3da14c8de5243ac47acc8fe64ba35c36e6d05e59e46a56574b64526599c39d54306f3efe66e864973d1b9"
"7d0b441a06b040996972525dc0c149443d8868070324a58e50a12e9ba0cf2df68c5dd05446ce31dabec473348322b8a1"
"3ef08764c3603040f05c3a3a11f9f36b4478ba601d6ad72bffcdd27f4db7b9f8";
constexpr const char* Sha224Signature =
"109bb60c7b72d7079fd5cd8772d3464ac8ffa1677273ac5f8b373e6d67d0f03e427420e017d1962784786e376d1f9899"
"97873fb6bc7305c754169a42e0f5e995dc1fe0d28d0f9e5574ef3a5dd2cd869f390b8dba6ecd6a9eb71e6fb301727cd3"
"a51f0a3e86083b78db0411fc4b4fbd1cff36725402b6c7173bb7474b92f6139c";
constexpr const char* Sha256Signature =
"795db6306fb0c69d3d79ff43253bd65cf18a49dfc9be6fd435fa53f78f1cc02a7b7a840b526ebafa1366e1d851efc38e"
"ef9634de408bfbc22deb5a6aab43d8c23a21a83feae77d295dbd282480ad69aa663dc2242c41b69503eb0d7f72be25be"
"65256c263015da9b82cfb575cdd54fe5bf71a50584530f03ccf965479c79e281";
constexpr const char* Sha384Signature =
"b949f553a6cd9dd73cd285e072f4f15c1f5dc98fb2b6f476151f191978f63e30ed32783b222a44a983869762d583d06a"
"8c21257b76f67c5f6c42d9089a6fdc98e993a602c53f181ba7cf48a2ea60e0c0a4a16e1b8d52444ee84e7c724af31da4"
"39c268d9937f857d3b6d6422b547e34fe2a17e669c5361d8612a3fac16ed672f";
constexpr const char* Sha512Signature =
"8a534bb327ff05724690afb218b91c1ee476cfa6cee65eb98936d991007e2a7127687bdb1e99b5de3ece6c77ecd0a827"
"c964f2ca4dad9710107595c794ffee62421a3e57350a7cec42baa1e4dc103b7110e33111cd7e003f346d39c7f84b9312"
"a106a3e140e36305880775bfd5fe93cfdaf8712c28d1b471a7509fc71d1a6bb2";
constexpr const char* OtherSha256Signature =
"613e57c1b9021d8b04cb8e90d5d56b58c61932c36b5c2d583caee13a43f2d9f9c5a1a672a78d7dd81f2b228231951ba2"
"0e0ed8c59d04e0b0a926f6c5fd8e76d7f3d8e25eb299edf1e70239f5419f948020dd72f0985bc33c5df826551b37d031"
"36760feece2bee3255c733c7c98c0dd23f3be2c17b8c37e7829efcffc1fc7d05";
void Require(bool condition, const char* message) {
if (condition) return;
std::fprintf(stderr, "failed: %s\n", message);
std::abort();
}
template<typename TAction>
void RequireThrows(TAction action, const char* message) {
try {
action();
} catch (const std::exception&) {
return;
}
Require(false, message);
}
std::vector<unsigned char> Bytes(const char* hex) {
const auto digit = [](char c) { return c >= 'a' ? c - 'a' + 10 : c - '0'; };
std::vector<unsigned char> bytes;
for (; hex[0] && hex[1]; hex += 2) bytes.push_back(static_cast<unsigned char>(digit(hex[0]) * 16 + digit(hex[1])));
return bytes;
}
void RequireErrors(std::initializer_list<std::uint64_t> codes, const char* message) {
for (const auto code : codes) Require(ERR_get_error_nid_postfix() == code, message);
Require(ERR_get_error_nid_postfix() == 0, message);
}
struct Key {
void* pkey;
std::vector<unsigned char> der;
};
Key LoadKey() {
Key key {{}, Bytes(PublicKeyDer)};
const unsigned char* cursor = key.der.data();
auto* rsa = d2i_RSA_PUBKEY_nid_postfix(nullptr, &cursor, static_cast<long>(key.der.size()));
Require(rsa, "the RSA public key is read from its encoding");
Require(cursor == key.der.data() + key.der.size(), "the whole public key encoding is read");
key.pkey = EVP_PKEY_new_nid_postfix();
Require(key.pkey, "a key object is allocated");
Require(EVP_PKEY_set1_RSA_nid_postfix(key.pkey, rsa) == 1, "the key object takes the RSA key");
Require(static_cast<const PkeyHeader*>(key.pkey)->type == 6, "the key object is an RSA key");
RSA_free_nid_postfix(rsa);
return key;
}
int References(const Key& key) {
return static_cast<const PkeyHeader*>(key.pkey)->references;
}
struct Attempt {
int initialized = 0;
int updated = 0;
int verified = 0;
int cleaned = 0;
void* pctx = nullptr;
};
Attempt Run(const Key& key, const EvpMd* digest, const std::vector<unsigned char>& signature, const char* message = Message,
std::size_t signatureLength = KeyBytes) {
Attempt attempt;
EvpMdContext context {};
EVP_MD_CTX_init_nid_postfix(&context);
attempt.initialized = EVP_DigestVerifyInit_nid_postfix(&context, &attempt.pctx, digest, nullptr, key.pkey);
if (attempt.initialized == 1) {
attempt.updated = EVP_DigestUpdate_nid_postfix(&context, message, std::strlen(message)) &&
EVP_DigestUpdate_nid_postfix(&context, message, 0);
if (attempt.updated == 1)
attempt.verified = EVP_DigestVerifyFinal_nid_postfix(&context, const_cast<unsigned char*>(signature.data()), signatureLength);
}
attempt.cleaned = EVP_MD_CTX_cleanup_nid_postfix(&context);
return attempt;
}
void ValidSignatures(const Key& key) {
struct Case {
const EvpMd* digest;
const char* signature;
};
const Case cases[] {
{EVP_md5_nid_postfix(), Md5Signature},
{EVP_sha256_nid_postfix(), Sha256Signature},
{EVP_sha384_nid_postfix(), Sha384Signature},
{EVP_sha512_nid_postfix(), Sha512Signature},
{nullptr, Sha1Signature},
};
for (const auto& testCase : cases) {
ERR_clear_error_nid_postfix();
const auto signature = Bytes(testCase.signature);
Require(signature.size() == KeyBytes, "the fixed signature is as long as the key");
const auto attempt = Run(key, testCase.digest, signature);
Require(attempt.initialized == 1 && attempt.updated == 1 && attempt.verified == 1 && attempt.cleaned == 1,
"a signature made for the digest is accepted");
Require(attempt.pctx != nullptr, "the caller is given the key context of the digest");
RequireErrors({}, "an accepted signature queues no error");
Require(References(key) == 1, "the key returns to one reference");
}
}
void DefaultDigest(const Key& key) {
ERR_clear_error_nid_postfix();
EvpMdContext context {};
EVP_MD_CTX_init_nid_postfix(&context);
void* pctx = nullptr;
Require(EVP_DigestVerifyInit_nid_postfix(&context, &pctx, nullptr, nullptr, key.pkey) == 1, "an initialization without a digest succeeds");
Require(context.digest && context.digest->type == NidSha1 && context.digest->mdSize == 20, "the RSA key asks for the SHA1 digest");
Require(pctx && pctx == context.pkeyContext, "the digest context and the caller get the same key context");
Require(References(key) == 2, "the key context holds one reference to the key");
RequireErrors({}, "a successful initialization queues no error");
Require(EVP_DigestUpdate_nid_postfix(&context, Message, 10) == 1 && EVP_DigestUpdate_nid_postfix(&context, Message + 10,
std::strlen(Message) - 10) == 1, "the message is added in two parts");
auto signature = Bytes(Sha1Signature);
Require(EVP_DigestVerifyFinal_nid_postfix(&context, signature.data(), signature.size()) == 1,
"the SHA1 signature verifies through the default digest");
RequireErrors({}, "the default digest verification queues no error");
Require(EVP_MD_CTX_cleanup_nid_postfix(&context) == 1, "the digest context is cleaned");
Require(context.pkeyContext == nullptr && context.digest == nullptr && context.mdData == nullptr, "the cleanup clears the digest context");
Require(References(key) == 1, "the cleanup releases the key context reference");
}
void CorruptSignatures(const Key& key) {
const auto valid = Bytes(Sha256Signature);
ERR_clear_error_nid_postfix();
Require(Run(key, EVP_sha256_nid_postfix(), valid, OtherMessage).verified == 0, "a signature of another message is refused");
RequireErrors({BadSignature}, "a signature of another message queues the bad signature error");
auto changed = valid;
changed[63] ^= 0x02;
const auto before = changed;
Require(Run(key, EVP_sha256_nid_postfix(), changed).verified == 0, "a changed signature bit is refused");
RequireErrors({BlockTypeIsNot01, PaddingCheckFailed}, "a changed signature bit queues the padding errors");
Require(changed == before, "the signature bytes are left alone");
Require(Run(key, EVP_sha384_nid_postfix(), valid).verified == 0, "a signature of another digest is refused");
RequireErrors({AlgorithmMismatch}, "a signature of another digest queues the algorithm mismatch error");
Require(Run(key, EVP_sha256_nid_postfix(), valid, Message, KeyBytes - 1).verified == 0, "a short signature length is refused");
RequireErrors({WrongSignatureLength}, "a short signature length queues its error");
RequireErrors({}, "no second error follows the signature length");
Require(Run(key, EVP_sha256_nid_postfix(), valid, Message, KeyBytes + 8).verified == 0, "a long signature length is refused");
RequireErrors({WrongSignatureLength}, "a long signature length queues its error");
std::vector<unsigned char> empty(KeyBytes, 0);
Require(Run(key, EVP_sha256_nid_postfix(), empty).verified == 0, "an empty signature is refused");
RequireErrors({BlockTypeIsNot01, PaddingCheckFailed}, "an empty signature queues the padding errors");
std::vector<unsigned char> above(KeyBytes, 0xff);
Require(Run(key, EVP_sha256_nid_postfix(), above).verified == 0, "a signature above the modulus is refused");
RequireErrors({DataTooLargeForModulus}, "a signature above the modulus queues its error");
Require(Run(key, EVP_sha256_nid_postfix(), valid, Message, 0).verified == 0, "a zero signature length is refused");
RequireErrors({WrongSignatureLength}, "a zero signature length queues its error");
auto truncated = valid;
Require(Run(key, EVP_sha256_nid_postfix(), truncated, Message, 90).verified == 0, "a truncated signature length is refused");
RequireErrors({WrongSignatureLength}, "a truncated signature length queues its error");
Require(Run(key, EVP_sha256_nid_postfix(), Bytes(Sha224Signature)).verified == 0, "a SHA224 signature verified as SHA256 is refused");
RequireErrors({AlgorithmMismatch}, "a SHA224 signature verified as SHA256 queues the algorithm mismatch error");
Require(References(key) == 1, "the refused signatures leave one key reference");
}
void UninitializedDigest(const Key& key) {
ERR_clear_error_nid_postfix();
EvpMdContext context {};
EVP_MD_CTX_init_nid_postfix(&context);
void* pctx = nullptr;
Require(EVP_DigestVerifyInit_nid_postfix(&context, &pctx, EVP_sha256_nid_postfix(), nullptr, key.pkey) == 1, "the context is initialized");
context.digest = nullptr;
auto signature = Bytes(Sha256Signature);
const auto before = signature;
Require(EVP_DigestVerifyFinal_nid_postfix(&context, signature.data(), signature.size()) == -1,
"a context without a digest returns the copy failure");
RequireErrors({InputNotInitialized}, "a context without a digest queues the input not initialized error");
Require(signature == before, "the copy failure does not read the signature");
Require(EVP_MD_CTX_cleanup_nid_postfix(&context) == 1, "the context that keeps a key context is cleaned");
Require(References(key) == 1, "the cleanup of the uninitialized context releases the key reference");
}
void MissingOrForeignState(const Key& key) {
ERR_clear_error_nid_postfix();
RequireThrows([] { EVP_DigestVerifyFinal_nid_postfix(nullptr, nullptr, 0); }, "a null digest context follows the source's unchecked read");
EvpMdContext empty {};
RequireThrows([&] { EVP_DigestVerifyFinal_nid_postfix(&empty, nullptr, 0); },
"a digest context without a key context follows the source's unchecked read");
Require(References(key) == 1, "the missing state touches no key reference");
int marker = 0;
const ForeignKeyContext foreign {&marker};
EvpMdContext context {};
EVP_MD_CTX_init_nid_postfix(&context);
context.pkeyContext = const_cast<void*>(static_cast<const void*>(&foreign));
RequireThrows([&] { EVP_DigestVerifyFinal_nid_postfix(&context, nullptr, 0); }, "a key context this library did not create throws");
RequireThrows([&] { EVP_DigestVerifyInit_nid_postfix(&context, nullptr, EVP_sha256_nid_postfix(), nullptr, key.pkey); },
"an existing foreign key context throws during the initialization");
RequireThrows([&] { EVP_MD_CTX_cleanup_nid_postfix(&context); }, "freeing a foreign key context throws");
Require(References(key) == 1, "a foreign key context takes no key reference");
context.pkeyContext = nullptr;
Require(EVP_DigestVerifyInit_nid_postfix(&context, nullptr, nullptr, nullptr, nullptr) == 0, "an initialization without a key fails");
Require(context.pkeyContext == nullptr, "an initialization without a key leaves no key context");
RequireErrors({}, "an initialization without a key queues no error");
void* untouched = reinterpret_cast<void*>(std::uintptr_t{0x9abc});
Require(EVP_DigestVerifyInit_nid_postfix(&context, &untouched, EVP_sha256_nid_postfix(),
reinterpret_cast<void*>(std::uintptr_t{7}), nullptr) == 0, "an initialization with an ENGINE and no key fails without reading them");
Require(untouched == reinterpret_cast<void*>(std::uintptr_t{0x9abc}), "the missing key leaves the output context alone");
RequireErrors({}, "an initialization with an ENGINE and no key queues no error");
Require(EVP_DigestVerifyInit_nid_postfix(&context, nullptr, EVP_sha256_nid_postfix(), nullptr, key.pkey) == 1,
"the same context is initialized again after the failures");
Require(EVP_MD_CTX_cleanup_nid_postfix(&context) == 1, "the context is cleaned after the failures");
Require(References(key) == 1, "the failures leave one key reference");
}
void CopyAndCleanup(const Key& key) {
ERR_clear_error_nid_postfix();
auto signature = Bytes(Sha384Signature);
for (int part = 0; part < 3; ++part) {
EvpMdContext context {};
EVP_MD_CTX_init_nid_postfix(&context);
void* pctx = nullptr;
Require(EVP_DigestVerifyInit_nid_postfix(&context, &pctx, EVP_sha384_nid_postfix(), nullptr, key.pkey) == 1,
"the context is initialized for the copy check");
std::size_t done = 0;
for (const std::size_t chunk : {std::size_t{7}, std::size_t{11}, std::size_t{10}}) {
const std::size_t length = std::min(chunk, std::strlen(Message) - done);
Require(EVP_DigestUpdate_nid_postfix(&context, Message + done, length) == 1, "each part of the message is added");
done += length;
if (done == std::strlen(Message)) break;
}
Require(done == std::strlen(Message), "every message byte reaches the digest");
Require(EVP_DigestVerifyFinal_nid_postfix(&context, signature.data(), signature.size()) == 1, "the copied digest context verifies");
Require(EVP_MD_CTX_cleanup_nid_postfix(&context) == 1, "the copied digest context is cleaned");
}
RequireErrors({}, "the copies of the digest context queue no error");
Require(References(key) == 1, "the copies and cleanups leave one key reference");
}
void ReleaseKey(const Key& key) {
EVP_PKEY_free_nid_postfix(key.pkey);
}
int allocations = 0;
int callocs = 0;
int frees = 0;
int failAllocationAt = 0;
void* APS5_VABI Allocate_nid_no_patch(std::size_t size) {
if (++allocations == failAllocationAt) return nullptr;
return std::malloc(size);
}
void APS5_VABI Free_nid_no_patch(void* pointer) {
if (pointer) ++frees;
std::free(pointer);
}
void* APS5_VABI Calloc_nid_no_patch(std::size_t count, std::size_t size) {
++callocs;
return std::calloc(count, size);
}
void* APS5_VABI Reallocate_nid_no_patch(void*, std::size_t) { throw std::runtime_error("unexpected realloc"); }
void* APS5_VABI Align_nid_no_patch(std::size_t, std::size_t) { throw std::runtime_error("unexpected aligned allocation"); }
void* APS5_VABI Realign_nid_no_patch(void*, std::size_t, std::size_t) { throw std::runtime_error("unexpected aligned reallocation"); }
int APS5_VABI PosixAlign_nid_no_patch(void**, std::size_t, std::size_t) { throw std::runtime_error("unexpected posix_memalign"); }
void RegisterHeap() {
const std::array<void*, 10> api {
reinterpret_cast<void*>(Allocate_nid_no_patch), reinterpret_cast<void*>(Free_nid_no_patch), reinterpret_cast<void*>(Calloc_nid_no_patch),
reinterpret_cast<void*>(Reallocate_nid_no_patch), reinterpret_cast<void*>(Align_nid_no_patch), reinterpret_cast<void*>(Realign_nid_no_patch),
reinterpret_cast<void*>(PosixAlign_nid_no_patch)};
ApplicationHeapRegister_nid_no_patch(api.data());
}
void Allocator() {
RegisterHeap();
allocations = callocs = frees = 0;
const Key key = LoadKey();
const int keyBlocks = allocations - frees;
const auto signature = Bytes(Sha256Signature);
allocations = callocs = frees = 0;
const auto full = Run(key, EVP_sha256_nid_postfix(), signature);
Require(full.initialized == 1 && full.updated == 1 && full.verified == 1 && full.cleaned == 1, "the allocation check verifies its signature");
Require(allocations == 6 && callocs == 0 && frees == 6,
"the key context, its method data, the digest data and their copy are all released");
for (int failing = 1; failing <= 6; ++failing) {
ERR_clear_error_nid_postfix();
allocations = callocs = frees = 0;
failAllocationAt = failing;
const auto attempt = Run(key, EVP_sha256_nid_postfix(), signature);
failAllocationAt = 0;
switch (failing) {
case 1:
Require(attempt.initialized == 0 && attempt.verified == 0 && attempt.pctx == nullptr,
"a failed key context allocation fails the initialization");
RequireErrors({MallocFailure}, "a failed key context allocation queues the malloc failure");
break;
case 2:
Require(attempt.initialized == 0 && attempt.verified == 0 && attempt.pctx == nullptr,
"a failed method data allocation fails the initialization");
RequireErrors({}, "a failed method data allocation queues no error");
break;
case 3:
Require(attempt.initialized == 0 && attempt.verified == 0, "a failed digest data allocation fails the initialization");
break;
case 4:
Require(attempt.initialized == 1 && attempt.updated == 1 && attempt.verified == -1,
"a failed copy of the digest data fails the verification");
break;
case 5:
case 6:
Require(attempt.initialized == 1 && attempt.updated == 1 && attempt.verified == -1,
"a failed copy of the key context fails the verification");
break;
default:
Require(false, "the failing allocation index is one to six");
break;
}
Require(attempt.cleaned == 1 && frees + 1 == allocations, "a failed allocation releases everything the attempt allocated");
}
allocations = callocs = frees = 0;
ReleaseKey(key);
Require(frees == keyBlocks, "the key release frees every block that is still allocated");
}
} // namespace
int main(int argc, char** argv) {
if (argc > 1 && std::strcmp(argv[1], "allocator") == 0) {
Allocator();
return 0;
}
const std::array<void*, 10> api {};
ApplicationHeapRegister_nid_no_patch(api.data());
const Key key = LoadKey();
ValidSignatures(key);
DefaultDigest(key);
CorruptSignatures(key);
UninitializedDigest(key);
MissingOrForeignState(key);
CopyAndCleanup(key);
ReleaseKey(key);
return 0;
}
@@ -1,5 +1,6 @@
#include "prx/libSceLibreSsl/include/Api.hpp"
#include "prx/libSceLibreSsl3/include/Api.hpp"
#include "prx/libc/include/ApplicationHeap.hpp"
#include <algorithm>
#include <cstddef>
#include <cstdint>
@@ -42,6 +43,21 @@ void ConfModulesFree();
int I2tAsn1Object(char* buffer, int length, const void* object);
unsigned long ErrGetError();
void ErrClearError();
std::size_t MdContextSize();
void MdContextInit(void* context);
int MdContextCleanup(void* context);
void* DigestMethod(int kind);
void* GenerateRsa(int bits);
void RsaFree(void* rsa);
int RsaSign(int type, const unsigned char* message, unsigned int messageLength, unsigned char* signature, unsigned int* signatureLength, void* rsa);
int I2dRsaPubKey(void* rsa, unsigned char** output);
void ReferenceFree(void* pointer);
void* PkeyNew();
int PkeySet1Rsa(void* pkey, void* rsa);
void PkeyFree(void* pkey);
int DigestUpdateContext(void* context, const void* data, std::size_t length);
int DigestVerifyInit(void* context, void** pctx, const void* digest, void* pkey);
int DigestVerifyFinal(void* context, unsigned char* signature, std::size_t signatureLength);
}
namespace {
@@ -407,12 +423,222 @@ void CompareCreatedObjects() {
LibreSslReference::ObjCleanup();
}
struct VerifyKey {
std::vector<unsigned char> der;
void* referenceKey;
void* referencePkey;
void* minePkey;
};
int DigestNid(int kind) {
switch (kind) {
case 1: return 4;
case 2: return 64;
case 3: return 675;
case 4: return 672;
case 5: return 673;
default: return 674;
}
}
std::size_t DigestBytes(int kind) {
switch (kind) {
case 1: return 16;
case 2: return 20;
case 3: return 28;
case 4: return 32;
case 5: return 48;
default: return 64;
}
}
const EvpMd* EmulatorDigest(int kind) {
switch (kind) {
case 1: return EVP_md5_nid_postfix();
case 4: return EVP_sha256_nid_postfix();
case 5: return EVP_sha384_nid_postfix();
case 6: return EVP_sha512_nid_postfix();
default: return nullptr;
}
}
std::string CryptoErrors(const std::function<unsigned long()>& next) {
std::string text;
while (const unsigned long code = next()) {
const std::uint64_t library = (code >> 24) & 0xff;
if (library != 4 && library != 6) continue;
text += " " + std::to_string(code);
}
return text;
}
void CompareDigestVerify() {
LibreSslReference::AddAllAlgorithms();
std::vector<VerifyKey> keys;
for (const int bits : {512, 1024, 2048}) {
void* rsa = LibreSslReference::GenerateRsa(bits);
if (!rsa) continue;
void* referencePkey = LibreSslReference::PkeyNew();
if (!referencePkey || LibreSslReference::PkeySet1Rsa(referencePkey, rsa) != 1) {
Record("EVP_DigestVerifyInit", false, [&] { return std::to_string(bits) + " bit key: the reference did not keep the RSA key"; });
LibreSslReference::RsaFree(rsa);
continue;
}
unsigned char* der = nullptr;
const int length = LibreSslReference::I2dRsaPubKey(rsa, &der);
if (length <= 0 || !der) {
Record("EVP_DigestVerifyInit", false, [&] { return std::to_string(bits) + " bit key: the reference wrote no public key"; });
LibreSslReference::RsaFree(rsa);
LibreSslReference::PkeyFree(referencePkey);
continue;
}
VerifyKey key {{der, der + length}, rsa, referencePkey, nullptr};
LibreSslReference::ReferenceFree(der);
const unsigned char* cursor = key.der.data();
LibreSslRsa* mineRsa = nullptr;
const auto error = Attempt([&] { mineRsa = d2i_RSA_PUBKEY_nid_postfix(nullptr, &cursor, static_cast<long>(key.der.size())); });
if (!error.empty() || !mineRsa) {
Record("EVP_DigestVerifyInit", false, [&] { return std::to_string(bits) + " bit key: " + (error.empty() ? std::string("the public key was not read") : error); });
LibreSslReference::RsaFree(rsa);
LibreSslReference::PkeyFree(referencePkey);
continue;
}
key.minePkey = EVP_PKEY_new_nid_postfix();
const int taken = key.minePkey ? EVP_PKEY_set1_RSA_nid_postfix(key.minePkey, mineRsa) : 0;
RSA_free_nid_postfix(mineRsa);
if (taken != 1) {
Record("EVP_DigestVerifyInit", false, [&] { return std::to_string(bits) + " bit key: the emulator did not keep the RSA key"; });
LibreSslReference::RsaFree(rsa);
LibreSslReference::PkeyFree(referencePkey);
continue;
}
keys.push_back(key);
}
if (keys.empty()) {
Record("EVP_DigestVerifyInit", false, [] { return std::string("no reference RSA key was generated"); });
return;
}
static const int verifiable[] = {1, 4, 5, 6, 7};
std::array<unsigned char, 256> hashState {};
std::array<unsigned char, 64> hash {};
std::array<unsigned char, 512> signature {};
std::array<unsigned char, 512> attempt {};
std::vector<std::uint64_t> theirs((LibreSslReference::MdContextSize() + 7) / 8);
for (int round = 0; round < 900; ++round) {
const VerifyKey& key = keys[static_cast<std::size_t>(round) % keys.size()];
ERR_clear_error_nid_postfix();
LibreSslReference::ErrClearError();
const int signKind = 1 + static_cast<int>(generator() % 6);
const int verifyKind = verifiable[generator() % (sizeof verifiable / sizeof verifiable[0])];
const auto message = Bytes(1 + static_cast<std::size_t>(generator() % 120));
auto signedBytes = message;
if (generator() % 3 == 0) signedBytes = Bytes(signedBytes.size());
LibreSslReference::DigestInit(signKind, hashState.data());
LibreSslReference::DigestUpdate(signKind, hashState.data(), signedBytes.data(), signedBytes.size());
LibreSslReference::DigestFinal(signKind, hash.data(), hashState.data());
unsigned int signatureLength = 0;
if (LibreSslReference::RsaSign(DigestNid(signKind), hash.data(), static_cast<unsigned int>(DigestBytes(signKind)), signature.data(), &signatureLength,
key.referenceKey) != 1 || signatureLength == 0 || static_cast<std::size_t>(signatureLength) > signature.size())
continue;
attempt = signature;
std::size_t attemptLength = signatureLength;
switch (static_cast<int>(generator() % 8)) {
case 0:
break;
case 1:
attempt[generator() % attemptLength] ^= static_cast<unsigned char>(1ull << (generator() % 8));
break;
case 2:
attemptLength = generator() % attemptLength;
break;
case 3:
attemptLength += 1 + generator() % 4;
break;
case 4:
attemptLength = 0;
break;
case 5:
attempt[attemptLength - 1] = static_cast<unsigned char>(generator());
break;
case 6:
std::swap(attempt[0], attempt[attemptLength - 1]);
break;
default:
for (std::size_t at = 0; at + 8 < attemptLength; at += 8) std::swap(attempt[at], attempt[at + 8]);
break;
}
const std::string caseText = "sign " + std::to_string(signKind) + " verify " + std::to_string(verifyKind) + " length " + std::to_string(attemptLength)
+ " of " + std::to_string(signatureLength) + " signature " + Hex(attempt.data(), std::min<std::size_t>(12, attemptLength));
EvpMdContext mine {};
void* minePctx = nullptr;
void* theirPctx = nullptr;
std::string mineText;
std::string theirText;
int mineResult = 0;
auto mineError = Attempt([&] { mineResult = EVP_DigestVerifyInit_nid_postfix(&mine, &minePctx, EmulatorDigest(verifyKind), nullptr, key.minePkey); });
int theirResult = LibreSslReference::DigestVerifyInit(theirs.data(), &theirPctx,
verifyKind == 7 ? nullptr : LibreSslReference::DigestMethod(verifyKind), key.referencePkey);
mineText = (mineError.empty() ? std::to_string(mineResult) : mineError) + (minePctx ? " pctx" : " none") + CryptoErrors(ERR_get_error_nid_postfix);
theirText = std::to_string(theirResult) + (theirPctx ? " pctx" : " none") + CryptoErrors(LibreSslReference::ErrGetError);
Record("EVP_DigestVerifyInit", mineError.empty() && mineText == theirText,
[&] { return caseText + " message " + std::to_string(message.size()) + "\n mine " + mineText + "\n theirs " + theirText; });
if (round % 5 == 0 && mineError.empty() && mineResult == 1 && theirResult == 1) {
mineResult = 0;
mineError = Attempt([&] { mineResult = EVP_DigestVerifyInit_nid_postfix(&mine, &minePctx, EmulatorDigest(verifyKind), nullptr, key.minePkey); });
theirResult = LibreSslReference::DigestVerifyInit(theirs.data(), &theirPctx,
verifyKind == 7 ? nullptr : LibreSslReference::DigestMethod(verifyKind), key.referencePkey);
mineText = (mineError.empty() ? std::to_string(mineResult) : mineError) + (minePctx ? " pctx" : " none") + CryptoErrors(ERR_get_error_nid_postfix);
theirText = std::to_string(theirResult) + (theirPctx ? " pctx" : " none") + CryptoErrors(LibreSslReference::ErrGetError);
Record("EVP_DigestVerifyInit again", mineError.empty() && mineText == theirText,
[&] { return caseText + "\n mine " + mineText + "\n theirs " + theirText; });
}
if (mineError.empty() && mineResult == 1 && theirResult == 1) {
const std::size_t split = generator() % (message.size() + 1);
mineResult = 0;
mineError = Attempt([&] {
mineResult = EVP_DigestUpdate_nid_postfix(&mine, message.data(), split) &&
EVP_DigestUpdate_nid_postfix(&mine, message.data() + split, message.size() - split);
});
theirResult = LibreSslReference::DigestUpdateContext(theirs.data(), message.data(), split) &&
LibreSslReference::DigestUpdateContext(theirs.data(), message.data() + split, message.size() - split);
mineText = (mineError.empty() ? std::to_string(mineResult) : mineError) + CryptoErrors(ERR_get_error_nid_postfix);
theirText = std::to_string(theirResult) + CryptoErrors(LibreSslReference::ErrGetError);
Record("EVP_DigestVerifyUpdate", mineError.empty() && mineText == theirText,
[&] { return caseText + " split " + std::to_string(split) + "\n mine " + mineText + "\n theirs " + theirText; });
if (mineError.empty() && mineResult == 1 && theirResult == 1) {
mineResult = 0;
mineError = Attempt([&] { mineResult = EVP_DigestVerifyFinal_nid_postfix(&mine, attempt.data(), attemptLength); });
theirResult = LibreSslReference::DigestVerifyFinal(theirs.data(), attempt.data(), attemptLength);
mineText = (mineError.empty() ? std::to_string(mineResult) : mineError) + CryptoErrors(ERR_get_error_nid_postfix);
theirText = std::to_string(theirResult) + CryptoErrors(LibreSslReference::ErrGetError);
Record("EVP_DigestVerifyFinal", mineError.empty() && mineText == theirText,
[&] { return caseText + "\n mine " + mineText + "\n theirs " + theirText; });
}
}
mineResult = 0;
mineError = Attempt([&] { mineResult = EVP_MD_CTX_cleanup_nid_postfix(&mine); });
theirResult = LibreSslReference::MdContextCleanup(theirs.data());
mineText = (mineError.empty() ? std::to_string(mineResult) : mineError) + CryptoErrors(ERR_get_error_nid_postfix);
theirText = std::to_string(theirResult) + CryptoErrors(LibreSslReference::ErrGetError);
Record("EVP_MD_CTX_cleanup after verify", mineError.empty() && mineText == theirText,
[&] { return caseText + "\n mine " + mineText + "\n theirs " + theirText; });
}
for (const auto& key : keys) {
LibreSslReference::PkeyFree(key.referencePkey);
LibreSslReference::RsaFree(key.referenceKey);
EVP_PKEY_free_nid_postfix(key.minePkey);
}
}
}
int main() {
std::array<void*, 10> heap {};
ApplicationHeapRegister_nid_no_patch(heap.data());
CompareAesKeys();
CompareAesModes();
CompareDigests();
CompareDigestVerify();
CompareDesParity();
CompareStrings();
CompareCreatedObjects();
@@ -8,6 +8,7 @@
#include <openssl/objects.h>
#include <openssl/ocsp.h>
#include <openssl/sha.h>
#include <openssl/rsa.h>
#include <openssl/ssl.h>
#include <openssl/x509.h>
#include <cstddef>
@@ -90,4 +91,40 @@ int I2tAsn1Object(char* buffer, int length, const void* object) { return i2t_ASN
unsigned long ErrGetError() { return ERR_get_error(); }
void ErrClearError() { ERR_clear_error(); }
std::size_t MdContextSize() { return sizeof(EVP_MD_CTX); }
void MdContextInit(void* context) { EVP_MD_CTX_init(static_cast<EVP_MD_CTX*>(context)); }
int MdContextCleanup(void* context) { return EVP_MD_CTX_cleanup(static_cast<EVP_MD_CTX*>(context)); }
void* DigestMethod(int kind) {
switch (kind) {
case 1: return const_cast<EVP_MD*>(EVP_md5());
case 2: return const_cast<EVP_MD*>(EVP_sha1());
case 3: return const_cast<EVP_MD*>(EVP_sha224());
case 4: return const_cast<EVP_MD*>(EVP_sha256());
case 5: return const_cast<EVP_MD*>(EVP_sha384());
default: return const_cast<EVP_MD*>(EVP_sha512());
}
}
void* GenerateRsa(int bits) { return RSA_generate_key(bits, 65537, nullptr, nullptr); }
void RsaFree(void* rsa) { RSA_free(static_cast<RSA*>(rsa)); }
int RsaSign(int type, const unsigned char* message, unsigned int messageLength, unsigned char* signature, unsigned int* signatureLength, void* rsa) {
return RSA_sign(type, message, messageLength, signature, signatureLength, static_cast<RSA*>(rsa));
}
int I2dRsaPubKey(void* rsa, unsigned char** output) { return i2d_RSA_PUBKEY(static_cast<RSA*>(rsa), output); }
void ReferenceFree(void* pointer) { OPENSSL_free(pointer); }
void* PkeyNew() { return EVP_PKEY_new(); }
int PkeySet1Rsa(void* pkey, void* rsa) { return EVP_PKEY_set1_RSA(static_cast<EVP_PKEY*>(pkey), static_cast<RSA*>(rsa)); }
void PkeyFree(void* pkey) { EVP_PKEY_free(static_cast<EVP_PKEY*>(pkey)); }
int DigestUpdateContext(void* context, const void* data, std::size_t length) { return EVP_DigestUpdate(static_cast<EVP_MD_CTX*>(context), data, length); }
int DigestVerifyInit(void* context, void** pctx, const void* digest, void* pkey) {
return EVP_DigestVerifyInit(static_cast<EVP_MD_CTX*>(context), reinterpret_cast<EVP_PKEY_CTX**>(pctx),
static_cast<const EVP_MD*>(digest), nullptr, static_cast<EVP_PKEY*>(pkey));
}
int DigestVerifyFinal(void* context, unsigned char* signature, std::size_t signatureLength) {
return EVP_DigestVerifyFinal(static_cast<EVP_MD_CTX*>(context), signature, signatureLength);
}
}
+5 -5
View File
@@ -5,8 +5,6 @@
- [EVP_PKEY_new](../../../core/libs/prx/libSceLibreSsl/src/PkeyLifecycle.cpp) - PS5 behavior has not been independently measured. The 56-byte LP64 layout and initial values follow LibreSSL 2.5.4 [evp.h](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/evp/evp.h) and [p_lib.c](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/evp/p_lib.c). LibreSSL3 uses its own 32-byte constructor and release with references at offset 4. Objects from the two modules must not be mixed.
### Functional
- [EVP_DigestVerifyInit](../../../core/libs/prx/libSceLibreSsl/Export.cpp#L223) not measured on a PS5: key-backed or existing public-key contexts throw. With a null key and no key context, returns 0 without changing context, output or error queue. ABI/layout inferred from pinned LibreSSL 2.5.4: [wrapper/init](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/evp/m_sigver.c#L69-L125), [early exit](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/evp/pmeth_lib.c#L152-L161), [id=-1](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/evp/pmeth_lib.c#L317-L321), [context](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/evp/evp.h#L260-L269).
- [File and socket BIO adapters](../../../core/libs/prx/libSceLibreSsl/src/BioFileSocket.cpp) (`BIO_s_file`, `BIO_new_fp`, `BIO_new_socket`) extend the guest-ABI-compatible memory BIO implementation from #9536 using guest libc `FileStream` and `libSceNet` descriptors. File and socket BIOs have not been compared against the firmware or exercised on a console. Socket retry flags, socket pending-byte queries and extended file/socket control commands are not implemented; unsupported method controls return 0. File and socket ownership follows the caller's close flag.
- [SSL_select_next_proto](../../../core/libs/prx/libSceLibreSsl/src/ProtocolSelection.cpp) (libSceLibreSsl) follows LibreSSL 3.4.1 [`ssl_lib.c`](https://github.com/libressl/openbsd/blob/d7513e7d4daf94905fd4cb0a5e5c89109d2874f7/src/lib/libssl/ssl_lib.c), which validates neither list: a zero-length entry is negotiated, no overlap returns `supported + 1` with the unchecked length byte `supported[0]`, read even for an empty supported list, and each pair of entries with equal length bytes is compared over that many bytes, past the end of a truncated list. [Firmware 13.42 host-PC evidence](https://github.com/boykopovar/AnyPS5/pull/9785#issuecomment-6406712390) of `libSceLibreSsl.sprx` (`0xda6d0`) reports the same status, pointer and length for 700,000 valid pairs and for the six unvalidated cases. Null outputs, a null supported list and a null peer list with a non-zero length throw, where the module faults; nothing is measured on a console.
- [GENERAL_NAME_free and GENERAL_NAMES_free](../../../core/libs/prx/libSceLibreSsl/src/GeneralName.cpp) (libSceLibreSsl) - release all nine GENERAL_NAME choices and STACK_OF(GENERAL_NAME) using the guest allocator, following [LibreSSL 2.5.4 `v3_genn.c`](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/x509v3/v3_genn.c) and its [ASN.1 free dispatcher](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/asn1/tasn_fre.c). ASN1_STRING and dynamically allocated OID contents are wiped before freeing; NDEF strings and static OIDs retain their borrowed memory. Nested X509_NAME entries and cached data are freed as in 2.5.4. Guest allocator tests check owned/borrowed memory and disposal of nested allocations. PS5 native module behavior and malformed-memory failure cases are not verified; negative owned data lengths throw rather than risk out-of-bounds memory erasure.
@@ -31,7 +29,9 @@
- [OCSP_response_status_str, OCSP_cert_status_str and OCSP_crl_reason_str](../../../core/libs/prx/libSceLibreSsl/src/Ocsp.cpp) (libSceLibreSsl) - the module's strings are not measured on the console. The tables follow LibreSSL [ocsp_prn.c](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/ocsp/ocsp_prn.c), unchanged from revision 1.8 (2015) to 1.12 (2025), with codes from `ocsp.h`; the argument is a 64-bit `long` and every value not in a table returns `(UNKNOWN)`
- [SSL_get_ex_new_index, SSL_CTX_get_ex_new_index, SSL_get_ex_data_X509_STORE_CTX_idx and CRYPTO_cleanup_all_ex_data](../../../core/libs/prx/libSceLibreSsl/src/ExData.cpp) (libSceLibreSsl) - unverified on a PS5. The stored `argl`, `argp` and callbacks are never called, because no export creates an `SSL` or `SSL_CTX` and `SSL_get_ex_data`/`SSL_set_ex_data` still throw. Index numbering follows LibreSSL 2.5.4's [ex_data.c](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/ex_data.c#L310-L406), [ssl_lib.c](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libssl/ssl_lib.c#L2828-L2854) and [ssl_cert.c](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libssl/ssl_cert.c#L133-L160): per class from 0, the verify-callback index allocated once and kept across `CRYPTO_cleanup_all_ex_data`, which restarts every class at 0.
- [RSA_padding_add_PKCS1_PSS, RSA_verify_PKCS1_PSS](../../../core/libs/prx/libSceLibreSsl/src/Rsa.cpp) (libSceLibreSsl) - nothing is checked on the console. They follow LibreSSL 2.5.4's [rsa_pss.c](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/rsa/rsa_pss.c) and `PKCS1_MGF1` in [rsa_oaep.c](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/rsa/rsa_oaep.c), queueing the RSA errors of `rsa_pss.c` but not the EVP ones for a null or over-64-byte digest. The salt is host entropy, not `arc4random_buf`. They throw where LibreSSL has undefined behaviour or loops: `int` overflow in `hLen + sLen + 2` or `emLen - hLen - 2`; in `RSA_padding_add_PKCS1_PSS`, an `sLen` of -2 that leaves a negative salt length; in `RSA_verify_PKCS1_PSS`, an empty masked DB and a 0-bit modulus with a 0-byte digest and `sLen` -2 (read before `EM`); MGF1 with a digest size of 0; and a null key, modulus or `EM` it reads
- [EVP digest and HMAC functions](../../../core/libs/prx/libSceLibreSsl/src/Evp.cpp) (libSceLibreSsl) - follow LibreSSL 2.5.4's [digest.c](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/evp/digest.c) and [hmac.c](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/hmac/hmac.c). They and the `EVP_MD`, `EVP_MD_CTX` and `HMAC_CTX` layouts behave the same up to 3.4.1, so this holds for 2.5.4 (the firmware 13.40 measurements) and for 2.7 or later (its `SSL_get0_param` export). Nothing is checked on the console. `sign` and `verify` in the `EVP_MD` tables remain null, failures add nothing to the error queue, and a failed allocation leaves the context without a digest, where LibreSSL keeps it. An `ENGINE`, an `EVP_PKEY_CTX`, a null context, `EVP_DigestInit_ex` without a type on a context that has a digest, and an update or final without a digest throw
- [EVP digest and HMAC functions](../../../core/libs/prx/libSceLibreSsl/src/Evp.cpp) (libSceLibreSsl) - follow LibreSSL 2.5.4's [digest.c](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/evp/digest.c) and [hmac.c](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/hmac/hmac.c). They and the `EVP_MD`, `EVP_MD_CTX` and `HMAC_CTX` layouts behave the same up to 3.4.1, so this holds for 2.5.4 (the firmware 13.40 measurements) and for 2.7 or later (its `SSL_get0_param` export). Nothing is checked on the console. `sign` and `verify` in the `EVP_MD` tables remain null, failures add nothing to the error queue, and a failed allocation leaves the context without a digest, where LibreSSL keeps it. An `ENGINE`, a null context, `EVP_DigestInit_ex` without a type on a context that has a digest, and an update or final without a digest throw
- [EVP_DigestVerifyInit and EVP_DigestVerifyFinal](../../../core/libs/prx/libSceLibreSsl/src/DigestVerify.cpp) (libSceLibreSsl) - unverified on PS5. Results, reason codes and offsets follow pinned LibreSSL 2.5.4 [m_sigver.c](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/evp/m_sigver.c) and its `pmeth_lib.c`. With an RSA key, init creates the key context, raises the key references, writes `pctx` and defaults to SHA-1 when `type` is null; a null key with no key context still returns 0 without reading `type` or `engine`. Final copies the context, finalizes the digest and verifies through `RSA_verify` with PKCS#1 v1.5, including corrupt, truncated and wrong-digest signatures. An `ENGINE`, a non-RSA key, a key context this library did not create and RSA-PSS and X9.31 padding throw: no export reaches them. Not queued: the `d2i_X509_SIG` ASN.1 errors and the digest and copy malloc failures.
- [EVP_PKEY_CTX and the RSA key method](../../../core/libs/prx/libSceLibreSsl/src/DigestVerify.cpp) (libSceLibreSsl) - `EVP_PKEY_CTX_new`, `_dup`, `_free` and `_ctrl` are not in the PS5 export table, so these `_nid_no_patch` helpers and the 208-byte `EVP_PKEY_METHOD`, 80-byte `EVP_PKEY_CTX` and 64-byte `RSA_PKEY_CTX` LP64 layouts are checked only against pinned LibreSSL 2.5.4 [rsa_pmeth.c](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/rsa/rsa_pmeth.c). Key and peer references and the `EVP_R_MALLOC_FAILURE` of a failed context follow it. `EVP_MD_CTX_cleanup` frees the key context and the context copy that `EVP_DigestVerifyFinal` and the HMAC paths use duplicates it as `EVP_PKEY_CTX_dup` does, while a failed duplicate or digest allocation frees it and 2.5.4 leaves it set. The method's sign, verify-recover, encrypt, decrypt, keygen and `ctrl_str` slots throw, as no export calls them.
- [EC_GROUP_new_by_curve_name, EC_GROUP_free, EC_GROUP_get_degree, EC_KEY_new, EC_KEY_new_by_curve_name, EC_KEY_free, EC_KEY_set_group, EC_KEY_get0_group, ECDSA_size](../../../core/libs/prx/libSceLibreSsl/src/Ec.cpp) (libSceLibreSsl) - not checked on the console. They follow LibreSSL 2.5.4's [ec](https://github.com/libressl/openbsd/tree/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/ec) and [ecs_lib.c](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/ecdsa/ecs_lib.c) over mbedtls, which has 11 of LibreSSL's 90 curves (NIDs 409, 415, 711 to 716, 928, 932, 934). The other 79 throw; other NIDs return null without queuing `EC_R_UNKNOWN_GROUP`. Keys use libSceLibreSsl3's EC layout and `EC_KEY_new`'s defaults. `EC_KEY_set_group` to another curve throws on a key that has a public or private key. Setting a key's own group keeps it, where LibreSSL frees it first. Null groups and keys throw where LibreSSL dereferences them
- [EC_POINT_new, EC_POINT_free, EC_POINT_point2oct, EC_POINT_oct2point, EC_KEY_generate_key, EC_KEY_check_key, EC_KEY_get0_public_key, EC_KEY_set_public_key, ECDSA_sign, ECDSA_verify, ECDH_compute_key](../../../core/libs/prx/libSceLibreSsl/src/Ec.cpp) (libSceLibreSsl) - not checked on the console. They follow LibreSSL 2.5.4's [ec, ecdsa and ecdh](https://github.com/libressl/openbsd/tree/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto) on the curves above and queue no error code. A point used with a group of another curve throws: LibreSSL's result depends on the curve methods of its build. Compressed points on NIDs 712 and 713 throw (mbedtls decompresses only for primes that are 3 mod 4). `ECDSA_verify` with a public key at infinity or off the curve and `ECDH_compute_key` with a peer key off the curve throw, where LibreSSL computes with them. Setting a key's own public key copies it, where LibreSSL frees it first. Null points and keys throw where LibreSSL dereferences them
@@ -41,8 +41,8 @@
- [RSA_flags, RSA_size](../../../core/libs/prx/libSceLibreSsl/src/Rsa.cpp) (libSceLibreSsl) - nothing is checked on the console. Layouts and results follow [LibreSSL 2.5.4](https://github.com/libressl/openbsd/tree/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto) `rsa.h`, `rsa_crpt.c` and `bn_lib.c`, the version in the [firmware 13.40 measurements](https://github.com/boykopovar/AnyPS5/discussions/8981#discussioncomment-19111214). `RSA_size` counts the modulus bytes from its top word, as `BN_num_bytes`, so a zero top word is not skipped. A null method, a null key or modulus, and a positive word count with null words, which LibreSSL dereferences, throw, as do a negative word count and a bit count that overflows `int`
- [RSA_new, RSA_free](../../../core/libs/prx/libSceLibreSsl/src/Rsa.cpp) (libSceLibreSsl) - nothing is checked on the console. They follow [LibreSSL 2.5.4](https://github.com/libressl/openbsd/tree/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/rsa) `rsa_lib.c` and `rsa_eay.c`: the key comes from the guest `malloc` with the default method `"Eric Young's PKCS#1 RSA"` (method flags 0, key flags `RSA_FLAG_CACHE_PUBLIC | RSA_FLAG_CACHE_PRIVATE`) and one reference, and `RSA_free` drops a reference, runs the method's `finish` and clears and frees each `BIGNUM` as `BN_clear_free` does. The method's slots are host functions; its private-key operations, `rsa_mod_exp` and `bn_mod_exp` throw, as no export sets a private key yet. With no `ENGINE`, ex_data or blinding implemented, `RSA_free` throws for a key holding one, and for a Montgomery context, which this module never caches
- [d2i_RSA_PUBKEY](../../../core/libs/prx/libSceLibreSsl/src/Rsa.cpp) (libSceLibreSsl) - nothing is checked on the console. It decodes a SubjectPublicKeyInfo as [LibreSSL 2.5.4](https://github.com/libressl/openbsd/tree/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto)'s `x_pubkey.c`, `rsa_ameth.c`, `rsa_asn1.c` and `tasn_dec.c` do, without building the `X509_PUBKEY` and `EVP_PKEY` they use on the way: the `rsaEncryption` or `rsa` OID, any well-formed parameter, the masked BIT STRING and `n` and `e` read as unsigned `BIGNUM`s on a fresh `RSA_new` key, with the length, tag and header quirks of that decoder. A registered algorithm OID throws. The BER forms it also accepts throw: indefinite lengths, constructed strings and parameters, and a BIT STRING with 32 or more unused bits, whose mask is undefined C. A null input pointer, and a null input with a positive length, throw
- [RSA_public_encrypt, RSA_public_decrypt](../../../core/libs/prx/libSceLibreSsl/src/Rsa.cpp) (libSceLibreSsl) - nothing is checked on the console. They call the key method's slots; the default ones follow [LibreSSL 2.5.4](https://github.com/libressl/openbsd/tree/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/rsa) `rsa_eay.c`, `rsa_pk1.c`, `rsa_oaep.c` and `rsa_none.c`: the modulus and exponent limits, encryption with PKCS#1 v1.5, OAEP (SHA-1, empty label) or no padding, decryption checking PKCS#1 v1.5 type 1 or no padding, and -1 for other paddings, without the error codes LibreSSL queues. Random padding comes from host entropy and the arithmetic from mbedtls, whose 8192-bit limit makes a larger modulus throw; the Montgomery context is never cached. `RSA_SSLV23_PADDING` encryption and `RSA_X931_PADDING` decryption throw, as do a method with its own `bn_mod_exp`, a negative `BIGNUM` and a null key, method or slot
- [RSA_verify](../../../core/libs/prx/libSceLibreSsl/src/Rsa.cpp) (libSceLibreSsl) - nothing is checked on the console. It follows [LibreSSL 2.5.4](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/rsa/rsa_sign.c) `RSA_verify` and `int_rsa_verify`: the method's `rsa_verify` under `RSA_FLAG_SIGN_VER`, the signature length, `RSA_public_decrypt` with PKCS#1 v1.5 padding, the 36-byte `NID_md5_sha1` case and the `X509_SIG` decode with its trailing-data, parameter, object and digest checks, without the error codes LibreSSL queues. `OBJ_obj2nid` is modelled by the 15 digest objects of that version's object table, so a digest type and an object both outside them, `NID_undef` included, throw, and a signature OID registered with `OBJ_create` throws. The BER forms of the `d2i_RSA_PUBKEY` entry throw here too, as do a null key, a null method under `RSA_FLAG_SIGN_VER`, and a null digest or signature that LibreSSL reads
- [RSA_public_encrypt, RSA_public_decrypt](../../../core/libs/prx/libSceLibreSsl/src/Rsa.cpp) (libSceLibreSsl) - nothing is checked on the console. They call the key method's slots; the default ones follow [LibreSSL 2.5.4](https://github.com/libressl/openbsd/tree/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/rsa) `rsa_eay.c`, `rsa_pk1.c`, `rsa_oaep.c` and `rsa_none.c`: the modulus and exponent limits, encryption with PKCS#1 v1.5, OAEP (SHA-1, empty label) or no padding, decryption checking PKCS#1 v1.5 type 1 or no padding, and -1 for other paddings; PKCS#1 v1.5 decryption queues the `rsa_pk1.c` and `rsa_eay.c` reason codes, encryption does not. Random padding comes from host entropy and the arithmetic from mbedtls, whose 8192-bit limit makes a larger modulus throw; the Montgomery context is never cached. `RSA_SSLV23_PADDING` encryption and `RSA_X931_PADDING` decryption throw, as do a method with its own `bn_mod_exp`, a negative `BIGNUM` and a null key, method or slot
- [RSA_verify](../../../core/libs/prx/libSceLibreSsl/src/Rsa.cpp) (libSceLibreSsl) - nothing is checked on the console. It follows [LibreSSL 2.5.4](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/rsa/rsa_sign.c) `RSA_verify` and `int_rsa_verify`: the method's `rsa_verify` under `RSA_FLAG_SIGN_VER`, the signature length, `RSA_public_decrypt` with PKCS#1 v1.5 padding, the 36-byte `NID_md5_sha1` case and the `X509_SIG` decode with its trailing-data, parameter, object and digest checks, and the `rsa_sign.c` and `rsa_pk1.c` reason codes for those failures. `OBJ_obj2nid` is modelled by the 15 digest objects of that version's object table, so a digest type and an object both outside them, `NID_undef` included, throw, and a signature OID registered with `OBJ_create` throws. The BER forms of the `d2i_RSA_PUBKEY` entry throw here too, as do a null key, a null method under `RSA_FLAG_SIGN_VER`, and a null digest or signature that LibreSSL reads
- [X509_STORE_CTX_get_error, X509_STORE_CTX_set_error, X509_STORE_CTX_get_error_depth, X509_STORE_CTX_get_current_cert, X509_STORE_CTX_get_chain](../../../core/libs/prx/libSceLibreSsl/src/X509StoreContext.cpp) (libSceLibreSsl) - the 240-byte `X509_STORE_CTX` layout and the results follow [LibreSSL 2.5.4](https://github.com/libressl/openbsd/tree/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/x509) `x509_vfy.h` and `x509_vfy.c`, the version identified in [published firmware 13.40 measurements](https://github.com/boykopovar/AnyPS5/discussions/8981#discussioncomment-19111214); nothing is checked on the console. No export of this module creates or fills a context yet, so only contexts the caller builds reach them. A null context, which LibreSSL dereferences, throws
- [X509_STORE_CTX_get_ex_data, X509_STORE_CTX_get1_chain](../../../core/libs/prx/libSceLibreSsl/src/X509StoreContext.cpp) (libSceLibreSsl) - unverified on a PS5, and no export of this module sets ex_data or builds a chain yet. A chain whose count is negative or above its allocation, or that holds a null certificate, throws before copying; LibreSSL 2.5.4 overruns or dereferences it. Otherwise both follow its [x509_vfy.c](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/x509/x509_vfy.c#L1978-L2026): entry `idx` of the ex_data stack as [`CRYPTO_get_ex_data`](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/ex_data.c#L627-L636) reads it, and a chain copied as [`sk_dup`](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/stack/stack.c#L83-L136) copies it, raising each certificate's `references` (`X509` offset 28) by one.
- [UI_set_result](../../../core/libs/prx/libSceLibreSsl/src/Ui.cpp) (libSceLibreSsl) - unverified on a PS5, and no export of this module creates a `UI` or `UI_STRING` yet. The "You must type in %d to %d characters" text LibreSSL 2.5.4 attaches to the size errors is not kept, because the error queue holds codes only. A null `UI` or result, or null boolean characters that must be compared, throws; LibreSSL dereferences them. The rest follows its [ui_lib.c](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/ui/ui_lib.c#L816-L879) over the 40-byte `UI` and 64-byte `UI_STRING` of [ui_locl.h](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/ui/ui_locl.h#L104-L148): a result outside the bounds sets `UI_FLAG_REDOABLE` and queues `UI_R_RESULT_TOO_SMALL` or `UI_R_RESULT_TOO_LARGE`.