diff --git a/core/libs/prx/libSceLibreSsl3/CMakeLists.txt b/core/libs/prx/libSceLibreSsl3/CMakeLists.txt index ceb598d372e5..0fd6897efd60 100644 --- a/core/libs/prx/libSceLibreSsl3/CMakeLists.txt +++ b/core/libs/prx/libSceLibreSsl3/CMakeLists.txt @@ -1,4 +1,4 @@ -add_library(libSceLibreSsl3 SHARED EXCLUDE_FROM_ALL ${CMAKE_CURRENT_SOURCE_DIR}/Export.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/Digest.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/IntegerDecoder.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/Key.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/X509PubkeyParam.cpp) +add_library(libSceLibreSsl3 SHARED EXCLUDE_FROM_ALL ${CMAKE_CURRENT_SOURCE_DIR}/Export.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/Digest.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/IntegerDecoder.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/Key.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/X509PubkeyParam.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/NumericObject.cpp) target_include_directories(libSceLibreSsl3 PRIVATE ${LIBS_INCLUDE_DIR}) target_link_libraries(libSceLibreSsl3 PRIVATE libSceLibreSsl libc) configure_windows_unwind(libSceLibreSsl3) @@ -104,6 +104,12 @@ if(BUILD_TESTING) configure_windows_unwind(guest_libressl3_key_reference_tests) add_test(NAME guest_libressl3_key_reference COMMAND guest_libressl3_key_reference_tests) set_tests_properties(guest_libressl3_key_reference PROPERTIES TIMEOUT 20) + add_test_executable(guest_libressl3_object_parser_tests ${CMAKE_CURRENT_SOURCE_DIR}/tests/ObjectParser.cpp) + target_include_directories(guest_libressl3_object_parser_tests PRIVATE ${LIBS_INCLUDE_DIR}) + target_link_libraries(guest_libressl3_object_parser_tests PRIVATE libSceLibreSsl3 libSceLibreSsl libc) + configure_windows_unwind(guest_libressl3_object_parser_tests) + add_test(NAME guest_libressl3_object_parser COMMAND guest_libressl3_object_parser_tests) + set_tests_properties(guest_libressl3_object_parser PROPERTIES TIMEOUT 20) add_test_executable(guest_libressl3_version_tests ${CMAKE_CURRENT_SOURCE_DIR}/tests/OpenSslVersion.cpp) target_include_directories(guest_libressl3_version_tests PRIVATE ${LIBS_INCLUDE_DIR}) target_link_libraries(guest_libressl3_version_tests PRIVATE libSceLibreSsl3 libc) @@ -111,7 +117,7 @@ if(BUILD_TESTING) add_test(NAME guest_libressl3_version COMMAND guest_libressl3_version_tests) set_tests_properties(guest_libressl3_version PROPERTIES TIMEOUT 30) if(WIN32) - set_tests_properties(guest_crypto_memcmp guest_libressl3_digest guest_libressl3_asn1 guest_libressl3_key_reference guest_libressl3_version guest_libressl3_x509_pubkey_param PROPERTIES ENVIRONMENT_MODIFICATION + set_tests_properties(guest_crypto_memcmp guest_libressl3_digest guest_libressl3_asn1 guest_libressl3_key_reference guest_libressl3_object_parser guest_libressl3_version guest_libressl3_x509_pubkey_param PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() endif() diff --git a/core/libs/prx/libSceLibreSsl3/Export.cpp b/core/libs/prx/libSceLibreSsl3/Export.cpp index 8940b376d1c1..e5513f021357 100644 --- a/core/libs/prx/libSceLibreSsl3/Export.cpp +++ b/core/libs/prx/libSceLibreSsl3/Export.cpp @@ -199,11 +199,6 @@ int APS5_VABI OBJ_cmp_nid_postfix(void) { return 0; } -int APS5_VABI OBJ_txt2obj_nid_postfix(void) { - NotImplemented_nid_no_patch(__func__); - return 0; -} - int APS5_VABI OCSP_CERTID_free_nid_postfix(void) { NotImplemented_nid_no_patch(__func__); return 0; diff --git a/core/libs/prx/libSceLibreSsl3/include/Api.hpp b/core/libs/prx/libSceLibreSsl3/include/Api.hpp index f4a8b0735027..f75765f5a504 100644 --- a/core/libs/prx/libSceLibreSsl3/include/Api.hpp +++ b/core/libs/prx/libSceLibreSsl3/include/Api.hpp @@ -74,7 +74,7 @@ int APS5_VABI EVP_aes_256_wrap_nid_postfix(void); int APS5_VABI EVP_sha1_nid_postfix(void); int APS5_VABI EVP_sha224_nid_postfix(void); int APS5_VABI OBJ_cmp_nid_postfix(void); -int APS5_VABI OBJ_txt2obj_nid_postfix(void); +LibreSslAsn1Object* APS5_VABI OBJ_txt2obj_nid_postfix(const char* text, int noName); int APS5_VABI OCSP_CERTID_free_nid_postfix(void); int APS5_VABI OCSP_cert_to_id_nid_postfix(void); int APS5_VABI OCSP_resp_find_status_nid_postfix(void); diff --git a/core/libs/prx/libSceLibreSsl3/src/NumericObject.cpp b/core/libs/prx/libSceLibreSsl3/src/NumericObject.cpp new file mode 100644 index 000000000000..401fcf223c0f --- /dev/null +++ b/core/libs/prx/libSceLibreSsl3/src/NumericObject.cpp @@ -0,0 +1,147 @@ +#include "prx/libSceLibreSsl3/libSceLibreSsl3.hpp" +#include "prx/libSceLibreSsl/include/Error.hpp" +#include "prx/libc/include/Api.hpp" +#include "prx/libc/include/General.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr int invalidNumber = 187; +constexpr int invalidSeparator = 131; +constexpr int invalidDigit = 130; +constexpr int missingSecondNumber = 138; +constexpr int firstNumberTooLarge = 122; +constexpr int secondNumberTooLarge = 147; +constexpr int tooLong = 155; +constexpr int allocationFailure = 65; + +int readDecimalArc(const char*& cursor, std::uint64_t& value, int characterError) { + const char* begin = cursor; + value = 0; + while (*cursor != '\0' && *cursor != '.' && *cursor != ' ') { + const char character = *cursor; + if (character < '0' || character > '9') { + return characterError; + } + if (cursor != begin && value == 0 && character == '0') { + return invalidNumber; + } + if (value > std::numeric_limits::max() / 10) { + return tooLong; + } + value = value * 10 + static_cast(character - '0'); + ++cursor; + } + return cursor == begin ? invalidNumber : 0; +} + +int appendArc(std::vector& output, std::uint64_t value) { + unsigned char digits[10]; + std::size_t count = 0; + do { + digits[count++] = static_cast(value & 0x7f); + value >>= 7; + } while (value != 0); + if (count > static_cast(std::numeric_limits::max()) - output.size()) { + return tooLong; + } + while (count != 0) { + --count; + output.push_back(static_cast(digits[count] | (count == 0 ? 0 : 0x80))); + } + return 0; +} + +int parseNumericObject(const char* text, std::vector& output) { + const char* cursor = text; + std::uint64_t first = 0; + int error = readDecimalArc(cursor, first, invalidSeparator); + if (error != 0) { + return error; + } + if (*cursor == '\0') { + return missingSecondNumber; + } + const char separator = *cursor++; + std::uint64_t second = 0; + error = readDecimalArc(cursor, second, invalidDigit); + if (error != 0) { + return error; + } + if (first > 2) { + return firstNumberTooLarge; + } + const std::uint64_t secondLimit = first == 2 ? std::numeric_limits::max() - 80 : 39; + if (second > secondLimit) { + return secondNumberTooLarge; + } + error = appendArc(output, first * 40 + second); + if (error != 0) { + return error; + } + while (*cursor != '\0') { + if (*cursor != separator) { + return invalidSeparator; + } + ++cursor; + std::uint64_t arc = 0; + error = readDecimalArc(cursor, arc, invalidDigit); + if (error != 0) { + return error; + } + error = appendArc(output, arc); + if (error != 0) { + return error; + } + } + return 0; +} + +LibreSslAsn1Object* rejectNumericObject(int reason) { + LibreSslPutError_nid_no_patch(13, 0xfff, reason); + return nullptr; +} + +} + +extern "C" LibreSslAsn1Object* APS5_VABI OBJ_txt2obj_nid_postfix(const char* text, int noName) { + if (text == nullptr) { + throw std::invalid_argument("OBJ_txt2obj requires a non-null text pointer"); + } + if (noName == 0 && (text[0] < '0' || text[0] > '9')) { + NotImplemented_nid_no_patch(__func__); + } + try { + std::vector encoded; + const int error = parseNumericObject(text, encoded); + if (error != 0) { + return rejectNumericObject(error); + } + auto* data = static_cast(malloc_nid_postfix(encoded.size())); + if (data == nullptr) { + return nullptr; + } + auto* object = static_cast(calloc_nid_postfix(1, sizeof(LibreSslAsn1Object))); + if (object == nullptr) { + free_nid_postfix(data); + return rejectNumericObject(allocationFailure); + } + std::memcpy(data, encoded.data(), encoded.size()); + object->shortName = nullptr; + object->longName = nullptr; + object->nid = 0; + object->length = static_cast(encoded.size()); + object->data = data; + object->flags = 9; + return object; + } catch (const std::bad_alloc&) { + return nullptr; + } +} diff --git a/core/libs/prx/libSceLibreSsl3/tests/ObjectParser.cpp b/core/libs/prx/libSceLibreSsl3/tests/ObjectParser.cpp new file mode 100644 index 000000000000..47e3bd5a15e2 --- /dev/null +++ b/core/libs/prx/libSceLibreSsl3/tests/ObjectParser.cpp @@ -0,0 +1,182 @@ +#include "prx/libSceLibreSsl3/libSceLibreSsl3.hpp" +#include "prx/libc/include/Api.hpp" +#include "prx/libc/include/ApplicationHeap.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static_assert(sizeof(LibreSslAsn1Object) == 40); +static_assert(offsetof(LibreSslAsn1Object, shortName) == 0); +static_assert(offsetof(LibreSslAsn1Object, longName) == 8); +static_assert(offsetof(LibreSslAsn1Object, nid) == 16); +static_assert(offsetof(LibreSslAsn1Object, length) == 20); +static_assert(offsetof(LibreSslAsn1Object, data) == 24); +static_assert(offsetof(LibreSslAsn1Object, flags) == 32); + +namespace { + +std::unordered_map allocations; +int failAfter = -1; +int attempts = 0; + +void Require(bool condition, std::source_location location = std::source_location::current()) { + if (condition) return; + std::fprintf(stderr, "OBJ_txt2obj check failed at line %u\n", location.line()); + std::abort(); +} + +void* APS5_VABI Allocate_nid_no_patch(std::size_t size) { + if (attempts++ == failAfter) return nullptr; + void* pointer = std::malloc(size); + Require(pointer != nullptr); + allocations.emplace(pointer, size); + return pointer; +} + +void APS5_VABI Free_nid_no_patch(void* pointer) { + if (!pointer) return; + Require(allocations.erase(pointer) == 1); + std::free(pointer); +} + +void* APS5_VABI AllocateZeroed_nid_no_patch(std::size_t count, std::size_t size) { + Require(count == 1 && size == sizeof(LibreSslAsn1Object)); + void* pointer = Allocate_nid_no_patch(size); + if (pointer) std::memset(pointer, 0, size); + return pointer; +} +void* APS5_VABI UnexpectedReallocate_nid_no_patch(void*, std::size_t) { throw std::runtime_error("unexpected realloc"); } +void* APS5_VABI UnexpectedAlign_nid_no_patch(std::size_t, std::size_t) { throw std::runtime_error("unexpected aligned allocation"); } +void* APS5_VABI UnexpectedRealign_nid_no_patch(void*, std::size_t, std::size_t) { throw std::runtime_error("unexpected aligned reallocation"); } +int APS5_VABI UnexpectedPosixAlign_nid_no_patch(void**, std::size_t, std::size_t) { throw std::runtime_error("unexpected posix_memalign"); } + +void Release(LibreSslAsn1Object* object) { + Require(object && object->flags == 9 && object->nid == 0); + free_nid_postfix(const_cast(object->data)); + free_nid_postfix(object); +} + +void Check(const char* text, std::initializer_list expected) { + for (const int noName : {0, 1, -1}) { + auto* object = OBJ_txt2obj_nid_postfix(text, noName); + Require(object && !object->shortName && !object->longName); + Require(object->length == static_cast(expected.size())); + Require(std::equal(expected.begin(), expected.end(), object->data)); + Require(allocations.size() == 2); + Release(object); + Require(allocations.empty()); + } +} + +void Numeric() { + Check("0.0", {0}); + Check("1.39", {79}); + Check("2.0", {80}); + Check("2.999.3", {0x88, 0x37, 3}); + Check("1.2.840.113549.1.1.1", {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 1, 1, 1}); + Check("1 2 840 113549 1 1 1", {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 1, 1, 1}); + Check("01.02.03", {42, 3}); + Check("2.5.4.3", {85, 4, 3}); + Check("1.3.101.112", {43, 101, 112}); + Check("2.16.0.127.128.16383.16384", {96, 0, 127, 0x81, 0, 0xff, 0x7f, 0x81, 0x80, 0}); + Check("2.18446744073709551535", {0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f}); + Check("2.16.18446744073709551615", {96, 0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f}); + Check("2.16.18446744073709551616", {96, 0}); + Check("2.18446744073709551616", {80}); + Check("1.2.184467440737095516161", {42, 1}); + Check("1.2\0.3", {42}); + for (const char* text : {"", "0", "1.", "1..2", "1 2", "1.2.", "1 2 ", "1 2.3", "1.2 3", ".1.2", " 1.2", "1\t2", + "3.0", "0.40", "1.40", "00.2", "1.00", "1.2.00", "-1.2", "1.-2", "1.+2", "1.a", "1.2x", "2.18446744073709551536", + "2.16.184467440737095516159", "CN", "commonName", "unknown-name"}) { + Require(OBJ_txt2obj_nid_postfix(text, 1) == nullptr); + Require(allocations.empty()); + } + std::string text = "1.2"; + for (int index = 0; index < 1024; ++index) text += ".1"; + auto* object = OBJ_txt2obj_nid_postfix(text.c_str(), 1); + Require(object && object->length == 1025 && object->data[0] == 42); + Require(std::all_of(object->data + 1, object->data + object->length, [](unsigned char value) { return value == 1; })); + Release(object); +} + +void NameLookupUnavailable() { + for (const char* text : {"CN", "commonName", "Ed25519", "NULL", "not-a-known-object", ""}) { + ERR_clear_error_nid_postfix(); + Require(OBJ_txt2obj_nid_postfix("1", 1) == nullptr); + const int before = attempts; + bool threw = false; + try { OBJ_txt2obj_nid_postfix(text, 0); } + catch (const std::runtime_error& error) { + threw = std::string(error.what()).find("not implemented") != std::string::npos; + } + Require(threw && attempts == before && allocations.empty()); + Require(ERR_get_error_nid_postfix() == 0x0dfff08au); + Require(ERR_get_error_nid_postfix() == 0); + } + for (int noName : {0, 1, -1}) { + bool threw = false; + try { OBJ_txt2obj_nid_postfix(nullptr, noName); } + catch (const std::invalid_argument&) { threw = true; } + Require(threw); + } +} + +void Errors() { + struct Rejection { const char* text; int reason; }; + for (const Rejection rejection : {Rejection{"", 187}, {"1", 138}, {"1.", 187}, {"1.2a", 130}, + {"a.2", 131}, {"1 2.3", 131}, {"3.1", 122}, {"1.40", 147}, + {"2.18446744073709551536", 147}, {"2.1.184467440737095516159", 155}, + {"3.a", 130}, {"3.", 187}, {"3.00", 187}, {"1.40a", 130}, {"1.40.00", 147}, + {"1.2.184467440737095516160", 187}}) { + ERR_clear_error_nid_postfix(); + Require(OBJ_txt2obj_nid_postfix(rejection.text, 1) == nullptr); + Require(ERR_get_error_nid_postfix() == (0x0dfff000u | static_cast(rejection.reason))); + Require(ERR_get_error_nid_postfix() == 0); + } + Require(OBJ_txt2obj_nid_postfix("1", 1) == nullptr); + auto* object = OBJ_txt2obj_nid_postfix("1.2.3", 1); + Require(object != nullptr); + Require(ERR_get_error_nid_postfix() == 0x0dfff08au); + Release(object); +} + +void AllocationFailures() { + for (const int allocation : {0, 1}) { + failAfter = allocation; + attempts = 0; + ERR_clear_error_nid_postfix(); + Require(OBJ_txt2obj_nid_postfix("1.2.3", 1) == nullptr); + Require(ERR_get_error_nid_postfix() == (allocation == 1 ? 0x0dfff041u : 0u)); + Require(attempts == allocation + 1 && allocations.empty()); + } + failAfter = -1; + auto* first = OBJ_txt2obj_nid_postfix("2.5.4.3", 1); + auto* second = OBJ_txt2obj_nid_postfix("2.5.4.3", 1); + Require(first != second && first->data != second->data && allocations.size() == 4); + Release(second); + Release(first); + Require(allocations.empty()); +} + +} + +int main() { + const std::array api{ + reinterpret_cast(Allocate_nid_no_patch), reinterpret_cast(Free_nid_no_patch), reinterpret_cast(AllocateZeroed_nid_no_patch), + reinterpret_cast(UnexpectedReallocate_nid_no_patch), reinterpret_cast(UnexpectedAlign_nid_no_patch), reinterpret_cast(UnexpectedRealign_nid_no_patch), + reinterpret_cast(UnexpectedPosixAlign_nid_no_patch)}; + ApplicationHeapRegister_nid_no_patch(api.data()); + Numeric(); + NameLookupUnavailable(); + Errors(); + AllocationFailures(); + std::puts("OBJ_txt2obj tests passed"); +} diff --git a/docs/dev/debt/libSceLibreSsl3.md b/docs/dev/debt/libSceLibreSsl3.md index dac8e3e8aebd..8568935c680d 100644 --- a/docs/dev/debt/libSceLibreSsl3.md +++ b/docs/dev/debt/libSceLibreSsl3.md @@ -9,7 +9,7 @@ ### Unknown function info -- [libSceLibreSsl3 pending exports](../../../core/libs/prx/libSceLibreSsl3/Export.cpp) - 75 named callable exports, excluding `CRYPTO_memcmp`, `MD5`, `SHA1`, `d2i_ASN1_INTEGER`, `EVP_PKEY_up_ref`, `EC_KEY_up_ref`, `RSA_up_ref`, `EVP_PKEY_get0_RSA`, `EVP_PKEY_get0_DSA`, `EVP_PKEY_get0_DH`, `OpenSSL_version` and `X509_PUBKEY_get0_param`, remain unimplemented from the [PS5 3.20 export table](https://github.com/DNNDHH/PS5-3.20_Libs/blob/b2a77c09cd71c01f34c790cfbe98c751a13262ad/libSceLibreSsl3.c), cross-checked against the same module in PS5 firmware 13.60. Their signatures and behaviour are unverified; the declarations use the no-parameter unknown-signature convention and throw through `NotImplemented_nid_no_patch`. +- [libSceLibreSsl3 pending exports](../../../core/libs/prx/libSceLibreSsl3/Export.cpp) - 75 named callable exports, excluding `CRYPTO_memcmp`, `MD5`, `SHA1`, `d2i_ASN1_INTEGER`, `EVP_PKEY_up_ref`, `EC_KEY_up_ref`, `RSA_up_ref`, `EVP_PKEY_get0_RSA`, `EVP_PKEY_get0_DSA`, `EVP_PKEY_get0_DH`, `OpenSSL_version` and `X509_PUBKEY_get0_param`, remain wholly or partly unimplemented from the [PS5 3.20 export table](https://github.com/DNNDHH/PS5-3.20_Libs/blob/b2a77c09cd71c01f34c790cfbe98c751a13262ad/libSceLibreSsl3.c), cross-checked against the same module in PS5 firmware 13.60. Console signatures and behaviour remain unverified. Wholly unimplemented exports retain no-parameter unknown-signature declarations and throw through `NotImplemented_nid_no_patch`. ### Functional @@ -19,6 +19,7 @@ - [EVP_PKEY_up_ref, EC_KEY_up_ref and RSA_up_ref](../../../core/libs/prx/libSceLibreSsl3/src/Key.cpp) - console layouts and retain/release interoperability are unverified. The 32-byte EVP, 64-byte EC and 152-byte RSA layouts, with counters at offsets 4, 48 and 104, follow [LibreSSL 4.0.0](https://github.com/libressl/openbsd/tree/ce488b78e0bd994780569df718596b9776ff681a/src/lib/libcrypto) `evp/evp_local.h`, `evp/p_lib.c`, `ec/ec_local.h`, `ec/ec_key.c`, `rsa/rsa_local.h` and `rsa/rsa_lib.c`; the RSA layout has no `engine` field, unlike libSceLibreSsl's `LibreSslRsa`. Atomic retains replace its internal mutex; future releases must synchronize with the same counters. With no key constructors/destructors in this module, tests use caller-owned objects without validating allocator or destruction compatibility. Null keys and signed-counter overflow, undefined upstream, throw without mutation. Closes when: console layouts and lifetime interoperability are measured. - [EVP_PKEY_get0_RSA, EVP_PKEY_get0_DSA and EVP_PKEY_get0_DH](../../../core/libs/prx/libSceLibreSsl3/src/PkeyGetters.cpp) (libSceLibreSsl3) - a key of another type throws, where [LibreSSL 4.0.0](https://github.com/libressl/openbsd/blob/ce488b78e0bd994780569df718596b9776ff681a/src/lib/libcrypto/evp/p_lib.c#L630-L751) queues `EVP_R_EXPECTING_AN_RSA_KEY`, `EVP_R_EXPECTING_A_DSA_KEY` or `EVP_R_EXPECTING_A_DH_KEY` and returns NULL, because the LibreSSL3 error queue is not modelled; a null key throws, where LibreSSL dereferences it. A matching key returns the inner key pointer of the 32-byte layout without taking a reference: `EVP_PKEY_RSA` (6) or `EVP_PKEY_RSA_PSS` (912) for RSA, `EVP_PKEY_DSA` (116) and `EVP_PKEY_DH` (28). None of this is verified on a PS5 +- [OBJ_txt2obj](../../../core/libs/prx/libSceLibreSsl3/src/NumericObject.cpp) implements numeric OIDs only; with `noName == 0`, nonnumeric input throws `NotImplemented_nid_no_patch`. The implementation is checked against public-API observations from LibreSSL 4.0.0 via [observe_libressl3_oid.py](../../../tools/observe_libressl3_oid.py); no upstream parser source or object directory is included in this tree. Null input throws. Console object layout, cross-module error-queue sharing and the public `ASN1_OBJECT_free` lifecycle remain unverified. Numeric objects use the guest heap with dynamic flags 9, following the local ABI; allocation-failure handling is tested locally, not verified on console. Closes when: compatible name lookup and console ABI/lifecycle behaviour are verified. - [Parent export forwarding](../../../core/libs/prx/libSceLibreSsl3/ParentExports.cpp) exposes 395 parent-library exports on Windows through IAT tail jumps without changing their ABI. Non-Windows hosts use their existing dependency lookup. Static COFF inspection verifies names, parent imports and tail jumps; Windows loading and runtime behavior remain unverified. Parent functions retain their existing implementation limitations. - [EVP_MD_CTX_md](../../../core/libs/prx/libSceLibreSsl3/src/DigestContext.cpp) (libSceLibreSsl3) - nothing is checked on the console. As in [LibreSSL 4.0.0](https://github.com/libressl/openbsd/blob/ce488b78e0bd994780569df718596b9776ff681a/src/lib/libcrypto/evp/evp_digest.c) `evp_digest.c`, a null context returns null and any other returns its first field, `digest`. That field is first in 4.0.0's `evp_local.h` and in the [2.5.4 layout](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/evp/evp.h) of the contexts the forwarded libSceLibreSsl exports handle; the layouts differ after it, so the context and digest are declared opaque. Closes when: compared with the console. - [EVP_CIPHER_key_length and EVP_CIPHER_iv_length](../../../core/libs/prx/libSceLibreSsl3/src/Cipher.cpp) (libSceLibreSsl3) - nothing is checked on the console. They return `key_len` and `iv_len` from the 80-byte `EVP_CIPHER` of [LibreSSL 4.0.0](https://github.com/libressl/openbsd/tree/ce488b78e0bd994780569df718596b9776ff681a/src/lib/libcrypto/evp) `evp_local.h` and `evp_cipher.c`. The fields are at offsets 8 and 12, as in the [2.5.4 layout](https://github.com/libressl/openbsd/blob/2e2c612066aa993717528a0249c15c51128d61cb/src/lib/libcrypto/evp/evp.h) of the ciphers the forwarded libSceLibreSsl exports handle. A null cipher, which LibreSSL dereferences, throws. Closes when: compared with the console. diff --git a/tools/observe_libressl3_oid.py b/tools/observe_libressl3_oid.py new file mode 100644 index 000000000000..7b016140ea51 --- /dev/null +++ b/tools/observe_libressl3_oid.py @@ -0,0 +1,145 @@ +import argparse +import ctypes +import hashlib +import itertools +import json +import random +import sys +from pathlib import Path + + +RELEASE_URL = "https://github.com/libressl/portable/releases/download/v4.0.0/libressl-4.0.0.tar.gz" +RELEASE_SHA256 = "4d841955f0acc3dfc71d0e3dd35f283af461222350e26843fea9731c0246a1e4" +VERSION = "LibreSSL 4.0.0" + + +def bind(library, name, result, *arguments): + function = getattr(library, name) + function.restype = result + function.argtypes = list(arguments) + return function + + +class Oracle: + def __init__(self, path): + self.library = ctypes.CDLL(str(path)) + self.version = bind(self.library, "OpenSSL_version", ctypes.c_char_p, ctypes.c_int)(0).decode("ascii") + if self.version != VERSION: + raise ValueError(f"expected {VERSION}, received {self.version}") + self.convert = bind(self.library, "OBJ_txt2obj", ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int) + self.length = bind(self.library, "OBJ_length", ctypes.c_size_t, ctypes.c_void_p) + self.data = bind(self.library, "OBJ_get0_data", ctypes.c_void_p, ctypes.c_void_p) + self.free = bind(self.library, "ASN1_OBJECT_free", None, ctypes.c_void_p) + self.error = bind(self.library, "ERR_get_error", ctypes.c_ulong) + self.error_string = bind(self.library, "ERR_error_string_n", None, + ctypes.c_ulong, ctypes.c_void_p, ctypes.c_size_t) + self.a2d = bind(self.library, "a2d_ASN1_OBJECT", ctypes.c_int, + ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_int) + + def errors(self): + result = [] + while code := self.error(): + buffer = ctypes.create_string_buffer(256) + self.error_string(code, buffer, len(buffer)) + result.append({"code": code, "hex": f"{code:08x}", "text": buffer.value.decode("ascii")}) + return result + + def observe(self, raw, no_name): + self.errors() + object_pointer = self.convert(raw, no_name) + result = {"success": object_pointer is not None, "errors": self.errors()} + if object_pointer is not None: + try: + length = self.length(object_pointer) + data = self.data(object_pointer) + result.update({"length": length, "data_is_null": data is None, + "der_hex": ctypes.string_at(data, length).hex() if data else None}) + finally: + self.free(object_pointer) + return result + + def observe_a2d(self, raw): + raw = raw.split(b"\0", 1)[0] + buffer = ctypes.create_string_buffer(len(raw) + 16) + self.errors() + length = self.a2d(buffer, len(buffer), raw, len(raw)) + errors = self.errors() + count = self.a2d(None, 0, raw, len(raw)) + return {"length": length, "der_hex": buffer.raw[:length].hex() if length > 0 else None, + "errors": errors, "count_only_length": count, "count_only_errors": self.errors()} + + def observe_case(self, text): + raw = text.encode("ascii") + result = self.observe(raw, 1) + result = {"text": text, "no_name": 1, **result, + "negative_no_name_result": self.observe(raw, -1), "a2d": self.observe_a2d(raw)} + if raw and ord("0") <= raw[0] <= ord("9"): + result["zero_no_name_result"] = self.observe(raw, 0) + return result + + +def cases(): + inputs = {"", "0", "1", "2", "3", ".", " ", "0.0", "0.39", "0.40", "1.0", "1.39", "1.40", + "2.0", "2.40", "2.999", "3.1", "1.2.3", "1 2 3", "1.2 3", "1 2.3", "1..2", + "1 2", "1.2.", ".1.2", "1.2 ", " 1.2", "1\t2", "1.2\n", "+1.2", "-1.2", + "1.-2", "1.+2", "a.2", "1.a", "1.2a", "01.2", "001.2", "1.02", "1.002", + "1.00", "1.2.0", "1.2.00", "1.2.01", "1.2.001", "0.18446744073709551615", + "1.18446744073709551615", "2.18446744073709551535", "2.18446744073709551536", + "2.18446744073709551615", "2.18446744073709551616", "1.2.18446744073709551615", + "1.2.18446744073709551616", "1.2.18446744073709551619", "1.2.18446744073709551620", + "1.2.184467440737095516159", "1.2.999999999999999999999999", "3.", "3.a", "3..", + "3.40", "3.00", "3 00", "3 40", "00", "03", "03.", "18446744073709551620", + "1.40a", "3a.1", "1.40.00", "2.18446744073709551536.a", "1.2.3\0ignored", + "1\x002", "1.2\0.3", "1.2." + "9" * 1000, "1.2" + ".0" * 1000} + for first, separator, second, tail in itertools.product( + ["", "0", "1", "2", "3", "a", "00", "03", "18446744073709551616", "18446744073709551620"], + [".", " "], ["", "0", "1", "39", "40", "a", "00", "01", "18446744073709551616"], + ["", ".", ".a", " a"]): + inputs.add(first + separator + second + tail) + for arc in ["0", "00", "01", "09", "010", "0001", "0010", "10", "18446744073709551610", + "18446744073709551615", "18446744073709551616", "18446744073709551617", + "18446744073709551618", "18446744073709551619", "18446744073709551620", + "184467440737095516160", "184467440737095516161", "1844674407370955161600"]: + inputs.update([arc, arc + ".1", "1." + arc, "2." + arc, "1.2." + arc, "1.2." + arc + ".3"]) + for separator in [".", " ", "\t", "\n", "\r", "\v", "\f", ",", "/", ":", "+", "-", "_"]: + inputs.update(["1" + separator + "2", "1.2" + separator + "3", "1 2" + separator + "3"]) + rng = random.Random(4000) + for _ in range(3000): + inputs.add("".join(rng.choice("0123456789. a+-\t") for _ in range(rng.randrange(0, 25)))) + for arc in [0, 1, 39, 40, 79, 80, 127, 128, 129, 255, 256, 16383, 16384, 2097151, 2097152, + (1 << 32) - 1, 1 << 32, (1 << 63) - 1, 1 << 63, (1 << 64) - 1]: + inputs.update(["1.2." + str(arc), "2." + str(arc)]) + for _ in range(1000): + first = rng.randrange(3) + second = rng.randrange(40 if first < 2 else (1 << 64) - 80) + tail = [rng.randrange(1 << 64) for _ in range(rng.randrange(5))] + inputs.add(rng.choice([".", " "]).join(map(str, [first, second, *tail]))) + return sorted(inputs) + + +def main(): + parser = argparse.ArgumentParser(description="Observe numeric OID parsing through official LibreSSL 4.0.0 public APIs.") + parser.add_argument("--library", required=True, type=Path, help="path to the independently built LibreSSL 4.0.0 shared libcrypto") + parser.add_argument("--output", type=Path, help="write JSON here instead of stdout") + parser.add_argument("--text", action="append", help="observe this input instead of the generated corpus; may be repeated") + args = parser.parse_args() + try: + library_path = args.library.resolve(strict=True) + library_sha256 = hashlib.sha256(library_path.read_bytes()).hexdigest() + oracle = Oracle(library_path) + result = {"provenance": {"reference_release": {"url": RELEASE_URL, "sha256": RELEASE_SHA256}, + "observed_library": {"sha256": library_sha256, "reported_version": oracle.version}, + "source_archive_verified_by_this_tool": False, + "method": "public exported functions; opaque ASN1_OBJECT; numeric inputs only"}, + "cases": [oracle.observe_case(text) for text in (args.text if args.text is not None else cases())]} + output = json.dumps(result, indent=2) + "\n" + if args.output: + args.output.write_text(output, encoding="utf-8") + else: + sys.stdout.write(output) + except (OSError, AttributeError, UnicodeError, ValueError) as error: + parser.error(str(error)) + + +if __name__ == "__main__": + main()