Repository navigation
fix(libSceLibreSsl): store the AES_KEY schedule as little-endian words as the console does - #22842
Conversation
… on the console Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…s as the console does Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…e byte-swapped reference schedule Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
Probe source (built with ps5-payload-sdk v0.45; A second run of the same probe with the module The script probe.c#include <errno.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <ps5/kernel.h> /* only for kernel_get_fw_version() */
#ifndef PROBE_NAME
#define PROBE_NAME "unnamed"
#endif
#ifndef PROBE_BUILD
#define PROBE_BUILD "unbuilt"
#endif
/* Self limit: on timeout the runner can only close the connection, not end the process on the console.
The probe ends itself after at most PROBE_MAX_S seconds (the build script sets timeout - 10 s). */
#ifndef PROBE_MAX_S
#define PROBE_MAX_S 50
#endif
static void probe_alarm(int sig) {
static const char msg[] = "TIMEOUT\tprobe self limit\n";
(void)sig;
(void)!write(1, msg, sizeof msg - 1);
_exit(124);
}
static int cases = 0;
static void probe_header(void) {
char utc[32];
time_t now = time(0);
struct tm tmv;
gmtime_r(&now, &tmv);
strftime(utc, sizeof utc, "%Y-%m-%dT%H:%M:%SZ", &tmv);
printf("PROBE\t%s\tfw=0x%08x\tbuild=%s\tpid=%d\tutc=%s\n", PROBE_NAME, kernel_get_fw_version(), PROBE_BUILD,
getpid(), utc);
fflush(stdout);
}
/* CASE: id, description of the call, return value as long, errno (0 if not set), extra (hex/bytes). */
static void probe_case(const char* id, const char* call, long ret, int err, const char* extra) {
printf("CASE\t%s\t%s\t%ld\t%d\t%s\n", id, call, ret, err, extra ? extra : "-");
fflush(stdout);
cases++;
}
static void probe_end(void) {
printf("END\t%d\n", cases);
fflush(stdout);
}
#include <dlfcn.h>
#include <setjmp.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>
static sigjmp_buf guard_env;
static volatile int guard_sig = 0;
static volatile int guard_active = 0;
static volatile int guard_hits = 0;
static void guard_handler(int s) {
static const char msg[] = "FAULT\tprobe guard: fault outside a guarded call or too many faults\n";
if(!guard_active || ++guard_hits > 8) {
(void)!write(1, msg, sizeof msg - 1);
_exit(125);
}
guard_sig = s;
guard_active = 0;
siglongjmp(guard_env, 1);
}
static void guard_arm(void) {
struct sigaction sa;
memset(&sa, 0, sizeof sa);
sa.sa_handler = guard_handler;
sigaction(SIGSEGV, &sa, 0);
sigaction(SIGBUS, &sa, 0);
sigaction(SIGABRT, &sa, 0);
}
#define CALL(rvar, evar, expr) do { errno = 0; guard_sig = 0; rvar = -1; if(sigsetjmp(guard_env, 1) == 0) { guard_active = 1; rvar = (expr); } guard_active = 0; evar = errno; } while(0)
/* the COMPLETE AES key schedule of AES_set_encrypt_key and AES_set_decrypt_key of libSceLibreSsl.sprx (dlopen, dlsym) on firmware 11.60
(follow-up of an earlier run that measured only rd_key[0..3] of a 128 bit key). Only the public FIPS-197 example keys are used (bytes 00 01 02 ...
of 16, 24 and 32 bytes), never a real key. Prototype int AES_set_encrypt_key(const unsigned char* key, int bits, AesKey*) and the same for decrypt, AesKey
= {uint32 rd_key[60]; int rounds} (244 bytes); no SSL context or connection function is called. The key struct is pre-filled with 0xaa; per key size and
direction every used word (4*(rounds+1): 44, 52, 60) is printed as 8 hex digits, eight words per CASE line, followed by the return value, rounds and the
number of bytes beyond the used words that were changed (untouched = 0xaa). 6 key set calls plus an invalid key length 100 as the last call, all guarded. */
#include <stdlib.h>
typedef struct { uint32_t rd_key[60]; int rounds; } aes_key;
typedef int (*sk_fn)(const unsigned char*, int, aes_key*);
static void dump(const char* dir, int bits, const aes_key* k, int rc) {
int rounds = k->rounds;
int used = (rounds >= 10 && rounds <= 14) ? 4 * (rounds + 1) : 0;
char id[24], what[64], ex[260];
snprintf(id, sizeof id, "%s%d.h", dir, bits);
snprintf(what, sizeof what, "%s key %d bits: header", dir, bits);
size_t beyond = 0;
const unsigned char* raw = (const unsigned char*)k;
for(size_t i = (size_t)used * 4; i < 240; i++) if(raw[i] != 0xaa) beyond++;
snprintf(ex, sizeof ex, "rc=%d rounds=%d used_words=%d bytes_changed_beyond_used=%zu signal=%d", rc, rounds, used, beyond, (int)guard_sig);
probe_case(id, what, guard_sig ? -1 : rc, 0, ex);
for(int g = 0; g * 8 < used; g++) {
char* p = ex;
int n = 0;
for(int j = g * 8; j < used && j < g * 8 + 8; j++) n += snprintf(p + n, sizeof ex - n, "%08x ", (unsigned)k->rd_key[j]);
snprintf(id, sizeof id, "%s%d.w%d", dir, bits, g);
snprintf(what, sizeof what, "%s key %d bits: rd_key[%d..%d]", dir, bits, g * 8, (g * 8 + 7 < used ? g * 8 + 7 : used - 1));
probe_case(id, what, 0, 0, ex);
}
}
int main(void) {
signal(SIGALRM, probe_alarm);
alarm(PROBE_MAX_S);
probe_header();
guard_arm();
void* h = dlopen("libSceLibreSsl.sprx", RTLD_LAZY);
sk_fn se = (sk_fn)(h ? dlsym(h, "AES_set_encrypt_key") : 0);
sk_fn sd = (sk_fn)(h ? dlsym(h, "AES_set_decrypt_key") : 0);
char ex[8];
snprintf(ex, sizeof ex, "%d%d%d", !!h, !!se, !!sd);
probe_case("0", "dlopen libSceLibreSsl.sprx, dlsym AES_set_encrypt_key AES_set_decrypt_key (1 yes, 0 no)", 0, 0, ex);
if(!se || !sd) { probe_end(); return 0; }
unsigned char key[32];
for(int i = 0; i < 32; i++) key[i] = (unsigned char)i;
static aes_key k;
static const int sizes[3] = {128, 192, 256};
int rc, e;
for(int s = 0; s < 3; s++) {
memset(&k, 0xaa, sizeof k);
int r = -99;
CALL(rc, e, (r = se(key, sizes[s], &k)));
dump("enc", sizes[s], &k, r);
memset(&k, 0xaa, sizeof k);
r = -99;
CALL(rc, e, (r = sd(key, sizes[s], &k)));
dump("dec", sizes[s], &k, r);
}
memset(&k, 0xaa, sizeof k);
int r = -99;
CALL(rc, e, (r = se(key, 100, &k)));
snprintf(ex, sizeof ex, "%d", r);
char line[100];
snprintf(line, sizeof line, "rc=%d rounds=%d signal=%d", r, k.rounds, (int)guard_sig);
probe_case("bad", "AES_set_encrypt_key(key, 100 bits) (last call)", guard_sig ? -1 : r, e, line);
probe_end();
return 0;
}stdoutstdout of the run through libSceLibreSsl3.sprxfips_check.pyimport re, struct
# reads the raw output of the probe (file stdout.log) and compares the encryption schedules with a plain FIPS-197 key expansion
rows = [l.rstrip('\n').split('\t') for l in open('stdout.log', encoding='utf-8')]
def logged(tag):
words = []
for r in rows:
if r[0] == 'CASE' and re.fullmatch(tag + r'\.w\d', r[1]):
words += r[5].split()
return [int(w, 16) for w in words]
def gmul(a, b):
r = 0
for _ in range(8):
if b & 1:
r ^= a
hi = a & 0x80
a = (a << 1) & 0xff
if hi:
a ^= 0x1b
b >>= 1
return r
sbox = []
for x in range(256):
b = next((y for y in range(1, 256) if gmul(x, y) == 1), 0) if x else 0
s = b
for i in range(1, 5):
s ^= ((b << i) | (b >> (8 - i))) & 0xff
sbox.append(s ^ 0x63)
def expand(key):
nk = len(key) // 4
nr = nk + 6
w = [list(key[4 * i:4 * i + 4]) for i in range(nk)]
rc = 1
for i in range(nk, 4 * (nr + 1)):
t = w[i - 1][:]
if i % nk == 0:
t = [sbox[t[1]] ^ rc, sbox[t[2]], sbox[t[3]], sbox[t[0]]]
rc = gmul(rc, 2)
elif nk > 6 and i % nk == 4:
t = [sbox[x] for x in t]
w.append([a ^ b for a, b in zip(w[i - nk], t)])
return w
for bits in (128, 192, 256):
words = logged('enc%d' % bits)
expected = [struct.unpack('<I', bytes(x))[0] for x in expand(bytes(range(bits // 8)))]
print(bits, 'bits:', len(words), 'words logged, equal to the FIPS-197 expansion with every word stored little-endian:', words == expected)AI-assisted (Claude Code). |
PrivacyOnion
left a comment
There was a problem hiding this comment.
Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against f996fa29d5:
- Conventions:
tools/check_conventions.pypassed. - Build:
guest_libressl_aes_testsbuilt cleanly. - CTest (
guest_libressl_aes):1/1 Test #4317: guest_libressl_aes ............... Passed 0.01 sec 100% tests passed, 0 tests failed out of 1 - Negative control: with
core/libs/prx/libSceLibreSsl/src/Aes.cppreverted tomainand the new tests kept, the suite fails:Restoring the change makes it pass again.1/1 Test #4317: guest_libressl_aes ...............Subprocess aborted***Exception: 0.12 sec 0% tests passed, 1 tests failed out of 1 - Code reading:
- Verified ExpandKey and LoadLittle32 in core/libs/prx/libSceLibreSsl/src/Aes.cpp for 128, 192, and 256-bit key schedule generation matching PS5 console little-endian word layout
- Verified InverseMixWord byte unpacking and reconstruction shift orders (8 * row) in core/libs/prx/libSceLibreSsl/src/Aes.cpp for decrypt key inversion correctness
- Verified LoadState and AddRoundKey shift logic (8 * row) in core/libs/prx/libSceLibreSsl/src/Aes.cpp ensuring roundKey bits correspond to the state bytes identically for both encryption and decryption
- Verified error handling and return codes in SetKey (null userKey/key returns -1, invalid bit length returns -2) and memory safety with GuestCopyIn/GuestCopyOut and fault boundaries
- Verified technical debt documentation fragment in docs/dev/debt/changes/e-docs-libressl-aes-measured.md and Oracle/guest test coverage against AGENTS.md rules
Looks Good To Me
What
AES_set_encrypt_keyandAES_set_decrypt_keyinlibSceLibreSsl/src/Aes.cppexpand the key on the host and store the schedule in therd_keywords ofAES_KEYas big-endian words (LoadBig32, round constant in the top byte), the layout of LibreSSL's generic C code. A PS5 payload process on firmware 11.60 called the console'slibSceLibreSsl.sprxwith the FIPS-197 example keys00 01 02 ...of 128, 192 and 256 bits and printed every word of the schedule, for both directions: the words are little-endian, the layout of the amd64 assembly build (aes-x86_64), which copies the key bytes without swapping. For the 128-bit keyrd_key[0..3]of the encryption schedule is03020100 07060504 0b0a0908 0f0e0d0candrd_key[4]isfd74aad6(case enc128.w0, line 4); this library stored00010203 ...andd6aa74fd. Return value,rounds(10, 12, 14), the number of words written (44, 52, 60) and the untouched rest of the 244-byte structure were already the same. A title that only callsAES_set_*_keyand thenAES_encryptorAES_decryptgets the same results either way; the words matter to a title that reads, copies or serializes anAES_KEY, or that fills one itself.The fix (
Aes.cpp, 16 lines) loads the key bytes as little-endian words, rotates and applies the round constant in that word order (temp >> 8 | temp << 24, constant in the low byte), and reads state bytes from the round key with the matching shifts inInverseMixWord,LoadStateandAddRoundKey; the decryption schedule is still the encryption schedule in reverse order with the middle rounds inverse-mixed, now also in little-endian words. Encryption and decryption results do not change:guest_libressl_aes(the FIPS-197, CBC and CTR vectors) andguest_libressl_evp_aespass before and after. OnlylibSceLibreSslis changed.libSceLibreSsl3has noAES_set_*_keyof its own; it forwards both tolibSceLibreSsl(ParentExports.cpp), and a second probe through the console'slibSceLibreSsl3printed the same words; whether the console's module forwards or keeps its own copy is not shown by the probe.The test commit changes
GuestLibreSslAes.cpp: the helperWordreads little-endian, the pins of the FIPS-197 appendix A.1 wordsrd_key[4]andrd_key[43]become0x17fefaa0and0xa60c63b6, and six newRequireSchedulechecks pin the complete 44, 52 and 60 words of the encryption and the decryption schedules of the key00 01 02 ...for 128, 192 and 256 bits, written as the bytes of the words the probe printed. I checked these six pins against the logged words (byte for byte equal) and the logged encryption schedules against a plain FIPS-197 key expansion with each word stored little-endian (the script is in the first comment). The older schedule pins stay as byte sequences and hold for either layout. The Oracle commit changes one line in the optional comparison testlibSceLibreSsl/tests/Oracle.cpp(built only with-DANYPS5_LIBRESSL_ORACLE=ON, against LibreSSL 2.5.4): the reference schedule is byte-swapped word by word before the comparison, because the reference is the big-endian C layout. The documentation commit changes one sentence indocs/dev/debt/changes/e-docs-libressl-aes-measured.md, the fragment of #22017: theAES_KEYwords are little-endian as measured, the old sentence that a title's schedule differs here is gone, and it says thatlibSceLibreSsl3forwards here and what the console's module did.Not measured: other keys than
00 01 02 ..., the EVP path,AES_encryptwith a schedule from another source on the console, a title process, and whether the console'slibSceLibreSsl3forwards or keeps its own copy. The probe ran in a payload process.Tested
Measured on a PS5 with firmware 11.60 (
kernel_get_fw_version0x11600005), from a homebrew payload process (ps5-payload-sdk v0.45, elfldr) that loadslibSceLibreSsl.sprxand takesAES_set_encrypt_keyandAES_set_decrypt_keywithdlsym(line 2), on 2026-11-17 at 16:34 UTC; a second run throughlibSceLibreSsl3.sprxon 2026-11-17 at 19:05 UTC gave the same case lines (the module name in thePROBEline and in case 0 aside). A title process may differ. The cases are enc128 to dec256 and the invalid key length, lines 3 to 51 of the raw output in the first comment.00 01 02 ...)mainbefore (code read; the test commit fails on it)rd_key[0..3],rd_key[4]03020100 07060504 0b0a0908 0f0e0d0c,fd74aad6(lines 4, 4)00010203 04050607 08090a0b 0c0d0e0f,d6aa74fdrd_key[0..3]7f1d1113 174a94e3 8ba707f3 c5302b4d(line 11)roundsuntouchedWith the test commit alone,
guest_libressl_aesfails onmain(Windows: exit code 0xc0000409; Linux: subprocess aborted) andguest_libressl_evp_aespasses. Windows 10 Pro 10.0.19045, baseupstream/maina8fc237550a, 2026-11-18 from 09:40 UTC; one build per commit,ctestforguest_libressl_aes,guest_libressl_evp_aesandguest_libressl_oracle(the Oracle option on, against the LibreSSL 2.5.4 source tarball, hash checked, no new download): on the base both AES tests pass and the Oracle compares 17 cases each ofAES_set_decrypt_keyandAES_set_encrypt_keywith 0 differences; with the test commitguest_libressl_aesfails; with the fix commit both AES tests pass and the Oracle shows 3 differences each (the words, for 128, 192 and 256 bits, return value equal), which is why the Oracle commit is needed; with the Oracle commit and with the documentation commit both AES tests pass and the Oracle shows 0 differences for both functions. The wholeguest_libressl_oracletest fails in every phase, the base included, inSSL_CTX_set_cipher_list(799 of 3500 cases differ, the same number each time): that comes from before this change and is not touched here. Linux (WSL Ubuntu, g++ 13.3, Release, from 08:56 UTC,git amof the four patches onto the same base, trees3bb0a5b58f42,8592078b950a,c82437963263and856ddeface77equal to the four commits; without the Oracle option): 179 tests per run; the test commit alone fails 1 of 179 (guest_libressl_aes, subprocess aborted), the other three commits pass 179 of 179 in three runs each;tools/check_conventions.pypassed for each commit in that run, for the documentation commit with the one length warning named below. The Oracle commit was not run on Linux. Not tested: macOS, the Oracle on Linux, a title process, other firmware, and the cases listed above as not measured.tools/check_conventions.py --base upstream/mainpasses with no error and one warning that the entry in the fragment is over 1000 characters (now 2305, up from 2237, counted the same way; the warning was already there). The change is 4 files, +46/-11, with no new comments in code.Overlap: the other open pull requests that change the files of this branch (
core/libs/prx/libSceLibreSsl/src/Aes.cpp,core/libs/prx/libSceLibreSsl/tests/Oracle.cpp,core/libs/tests/GuestLibreSslAes.cppand the fragmentdocs/dev/debt/changes/e-docs-libressl-aes-measured.md, already onmainfrom #22017 and not yet folded) or the debt entry forAES_set_encrypt_keyandAES_set_decrypt_key, found by reading the changed files of all 1757 open pull requests at about 11:33 to 11:50 UTC, by reading what they change indocs/dev/debt/libSceLibreSsl.mdand the fragments underdocs/dev/debt/changes/forAES_set_encrypt_key,AES_set_decrypt_key,AES_KEY,ExpandKeyandLoadLittle32, and by searching their titles and branch names for the same names (no hit), were checked on 2026-11-18 at about 12:02 UTC againstmain0c1bb03d10dtogether with this head: the branch is based ona8fc237550a, an ancestor of it, merges intomainwithout a conflict, andtools/debt_fold.py --checkapplies the changed fragment together with every other fragment onmainwithout an error. No open pull request changesAes.cpp,GuestLibreSslAes.cppor the fragment. Thirteen pull requests list one of the files orlibSceLibreSsl.md; the eight that listOracle.cppor changelibSceLibreSsldebt text (#21701, #13877, #13547, #13546, #13285, #13266, #12315 and #11466) were each merged with and without this branch againstmain0c1bb03d10d, and none conflicts only with this branch: #13285, #12315 and #11466 conflict withmainby themselves, the other five merge cleanly with and without it. Six of them (#21701, #13877, #13547, #13546, #13285 and #13266) add cases to the Oracle test for other functions, the file in which the Oracle commit here adds one line. None of them changes a line that namesAES_set_encrypt_keyorAES_set_decrypt_key. The aliases of #17299 and #17303 are other names. The merge withmainwas not built or run; the runs below are on the basea8fc237550a.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)