Daniel Bae
Menu

Keypad Oracle: rebuilding a Swift PIN cipher from arm64 disassembly

Start reading

An oracle that never says no leaves the solver to supply one. The answer is the only PIN whose output reads as language.

DEADFACE’s development pipeline has leaked an iOS app. It runs in the iOS Simulator and shows a keypad, but “nobody can break the code”. The task is to recover the secret message. The prompt writes the flag as deadface {flag_text}, but the space is a typo: the recovered message is a normal deadface{...} string.

This walkthrough solves the challenge entirely by static analysis. It doesn’t launch the app, the simulator or a debugger. The tools are unzip, plutil, strings, nm, swift-demangle, otool and a short Python script.

1. What is in the bundle

Shell
unzip -q Keypad-Oracle.app.zip
cd Keypad-Oracle.app
wc -c Info.plist Keypad-Oracle Keypad-Oracle.debug.dylib KeypadConfig.json PkgInfo __preview.dylib
plutil -p Info.plist | grep -E '"CFBundleIdentifier"|"DTPlatformName"'
file Keypad-Oracle *.dylib
    1238 Info.plist
   58272 Keypad-Oracle
  342752 Keypad-Oracle.debug.dylib
     690 KeypadConfig.json
       8 PkgInfo
   34800 __preview.dylib
  "CFBundleIdentifier" => "com.deadface.keypadoracle.rick"
  "DTPlatformName" => "iphonesimulator"
Keypad-Oracle:             Mach-O 64-bit executable arm64
Keypad-Oracle.debug.dylib: Mach-O 64-bit dynamically linked shared library arm64
__preview.dylib:           Mach-O 64-bit dynamically linked shared library arm64

This is a Debug build for the Simulator. Recent Xcode versions split a debug app into a small launcher executable plus a <App>.debug.dylib that holds the real code; this layout is what lets SwiftUI previews hot-swap code. The launcher contains nothing of interest:

Shell
otool -L Keypad-Oracle
Keypad-Oracle:
	@rpath/Keypad-Oracle.debug.dylib (compatibility version 0.0.0, current version 0.0.0)
	/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1356.0.0)

The launcher has no app symbols and is mostly SwiftUI-previews plumbing (__debug_main_executable_dylib_entry_point, __PREVIEWS_JIT_LINK, …). It’s a common trap to load the 58 KB launcher into a disassembler, find nothing, and conclude the app is obfuscated. Everything below comes from Keypad-Oracle.debug.dylib.

Debug builds are also convenient for analysis: they aren’t stripped, they aren’t optimised, and Swift symbol names survive intact.

2. The data file

KeypadConfig.json is the only non-code resource:

JSON
{
  "digits": {
    "0": "8e07513d09e6379a5b14f845137456c5f4974967c678c07e1a9025",
    "1": "d179fa8cf908d9ed599ab5967c4f8d362de70c1a791babc9b75bcc",
    "2": "1c60ab80ca2bd61dc0b05a28c0d72197f59872aa43a0d812d782e2",
    "3": "579ccd23e8e1ff417714a928eaf2e88760a396584709d5c10569f5",
    "4": "0855a20fcf7805ca106de2c9127ea50af1d8ff5464e8bce81d3df4",
    "5": "507998d742ac7bf1c94eb5dde2ceb0c2cffdde970eece802825fe0",
    "6": "0063d94323e356b264fb2772a9b854404e0a5584447d14119d6a82",
    "7": "a56f6e4cc84a99d623718761361aeaeb75e763f89f0f1ae08f52dc",
    "8": "e126c2cbae0a19ef10d3f1395ed1a27ebae42ef49103652aee083a",
    "9": "5992f0ee2c8c682daa6038ef393108b28a40548fc97f99b33f1d88"
  }
}

Every digit maps to exactly 27 bytes. Note that number now: deadface{ plus a short phrase plus } fits comfortably in 27 characters, which already suggests the PIN somehow selects and combines these blobs into a 27-byte message.

3. Strings: the UI tells you the rules

Shell
strings -n 4 Keypad-Oracle.debug.dylib | grep -v '^_\$s' | grep -iE 'pin|digit|config|answer|%02x'
digits
KeypadConfig
Missing KeypadConfig.json
Could not load KeypadConfig.json: 
Enter a 4-digit PIN. Digits may not repeat.
Repeated digits are not allowed.
The answer you seek is...
%02x
DigitConfig
...
PinCipherEngine
...

These lines tell you three things:

  • The PIN is four digits with no repeats, so the search space is 10·9·8·7 = 5040.
  • The result is shown under “The answer you seek is…”.
  • %02x means the result is printed as hex bytes.

No string says “wrong PIN”, “access denied” or “correct”. That is the first hint that the app never judges the PIN at all.

4. Symbols: finding the cipher

The Swift symbols survive in the debug dylib. Demangle the ones in __text:

Shell
nm -m Keypad-Oracle.debug.dylib | grep '(__TEXT,__text)' | awk '{print $1, $NF}' \
  | xcrun swift-demangle --simplified | grep -E 'PinCipherEngine|pressDigit' | sort
00000000000019d0 variable initialization expression of PinCipherEngine.outputLength
00000000000019dc PinCipherEngine.outputLength.getter
00000000000019e4 variable initialization expression of PinCipherEngine.binarySalt
0000000000001b3c PinCipherEngine.binarySalt.getter
0000000000001b64 variable initialization expression of PinCipherEngine.seedTable
...
0000000000001e98 static PinCipherEngine.loadSeedTable()
00000000000026d0 PinCipherEngine.encode(pin:)
0000000000002f4c PinCipherEngine.derive(seed:digit:position:)
0000000000003848 PinCipherEngine.xor(_:_:)
0000000000003be8 PinCipherEngine.rotateLeft(_:by:)
...
00000000000065e8 KeypadViewModel.pressDigit(_:)

That is the whole design in outline: a PinCipherEngine with a seed table loaded from JSON, a salt, a fixed output length, and an encode(pin:) built from derive, xor and rotateLeft. Disassemble everything once and work through those functions in turn:

Shell
otool -tV Keypad-Oracle.debug.dylib > dis.txt

In the excerpts below, long mangled symbol names are shortened to ..name, and comments starting with ;; are annotations rather than otool output. Unoptimised Swift is verbose. Most of each function is overflow checks that branch to _assertionFailure (“Not enough bits to represent the passed value”, “Division by zero in remainder operation”…) and swift_beginAccess/swift_endAccess exclusivity checks. Skip those and follow the arithmetic.

5. The constants

outputLength is a single immediate:

_$s13Keypad_Oracle15PinCipherEngineC12outputLength...Sivpfi:
00000000000019d0	mov	w8, #0x1b
00000000000019d4	mov	x0, x8
00000000000019d8	ret

That is 27 bytes, matching the seed length. binarySalt allocates a 0x1c-element [UInt8] and fills it one strb at a time:

00000000000019f0	mov	w8, #0x1c
...
0000000000001a0c	mov	w8, #0x3a
0000000000001a10	strb	w8, [x0, #0x20]
0000000000001a14	mov	w8, #0x91
0000000000001a18	strb	w8, [x0, #0x21]
0000000000001a1c	mov	w8, #0x44
0000000000001a20	strb	w8, [x0, #0x22]
...
0000000000001ae4	mov	w8, #0x53
0000000000001ae8	strb	w8, [x0, #0x3b]

(The #0x20 offset is the Swift array header; element 0 starts there.) Reading all 28 stores gives:

3a 91 44 2f d0 18 6b c3 72 0e a9 5d 11 be 80 27 f4 66 39 9a 05 cc 70 1b 88 42 e1 53

The salt is 28 bytes, one more than the output. Keep that in mind for xor. The getters show the object layout: outputLength is read from [x20, #0x10] and binarySalt from [x20, #0x18] (x20 is self in the Swift calling convention).

loadSeedTable() does what you’d expect: it gets Bundle.main.url(forResource: "KeypadConfig", withExtension: "json"), decodes DigitConfig with JSONDecoder, then for each (key, value) calls Int(key) and value.hexDecodedBytes() and stores the result in a [Int: [UInt8]].

6. encode(pin:): the outer loop

The checks come first:

0000000000002748	bl	0x12bc8 ; symbol stub for: _$sSa5countSivg
000000000000274c	subs	x8, x0, #0x4            ;; pin.count == 4 ?
0000000000002750	b.ne	0x2b3c                  ;; no -> return ""
...
00000000000027c0	bl	0x12c4c ; symbol stub for: _$sSh5countSivg     ;; Set(pin).count
...
00000000000027dc	bl	0x12bc8 ; symbol stub for: _$sSa5countSivg     ;; pin.count
00000000000027e8	subs	x8, x0, x8
00000000000027ec	b.ne	0x2b18                  ;; duplicates -> return ""

Next comes an accumulator of outputLength zero bytes (Array(repeating: 0, count: self.outputLength), with ldr x1, [x8, #0x10] at 0x2800), followed by a for position in 0..<pin.count loop. Each iteration does this:

0000000000002924	bl	0x12c1c ; symbol stub for: _$sSayxSicig   ;; digit = pin[position]
000000000000299c	bl	0x12acc ; symbol stub for: _$sSDyq_Sgxcig ;; seedTable[digit]  (Optional)
00000000000029a8	cbz	x8, 0x2a3c              ;; nil -> return ""
00000000000029e0	bl	..derive(seed:digit:position:)
0000000000002a04	bl	..xor(_:_:)             ;; acc = xor(acc, derived)

After the loop, the salt is applied and the result is hex-encoded:

0000000000002a98	ldr	x0, [x20, #0x18]        ;; self.binarySalt
0000000000002aac	bl	..xor(_:_:)             ;; acc = xor(acc, salt)
0000000000002ae4	bl	_$sSa13Keypad_Oracles5UInt8VRszlE11toHexStringSSyF

7. derive(seed:digit:position:): where the work happens

The arguments arrive as x0 = seed, x1 = digit, x2 = position and are spilled to [sp,#0xe8], [sp,#0xf0] and [sp,#0xf8]. The function builds a fresh 27-byte array and loops i over 0..<outputLength. For each i:

Seed byte, cycling.

0000000000003200	sdiv	x9, x8, x10             ;; i / seed.count
0000000000003204	mul	x9, x9, x10
0000000000003208	subs	x0, x8, x9              ;; i % seed.count
0000000000003218	bl	0x12c1c ; symbol stub for: _$sSayxSicig   ;; s = seed[i % seed.count]

Three position/digit/index terms.

000000000000322c	adds	x8, x8, #0x1            ;; position + 1
0000000000003244	mov	w8, #0x21
0000000000003250	mul	x9, x9, x10             ;; (position+1) * 0x21  -> UInt8(...) with range check
...
000000000000332c	mov	w8, #0x13
0000000000003338	mul	x9, x9, x10             ;; digit * 0x13
0000000000003350	and	x9, x8, #0xff           ;; truncatingIfNeeded
...
0000000000003420	mov	w8, #0x7
000000000000342c	mul	x9, x9, x10             ;; i * 7
0000000000003444	and	x9, x8, #0xff

There is a subtle difference here. The 0x21 term goes through a checking UInt8(_:) conversion: the code checks for >= 0 and <= 0xff and traps otherwise. The other two terms are masked with & 0xff. For positions 0–3 the largest value is 4·0x21 = 0x84, so it never traps and the two behave the same.

Mix.

0000000000003528	eor	w10, w10, w13           ;; s ^ T(pos)
000000000000352c	eor	w10, w10, w12           ;;   ^ T(digit)
0000000000003530	eor	w10, w10, w11           ;;   ^ T(i)

Rotate by a position-dependent amount.

0000000000003538	adds	x8, x8, x9              ;; digit + position
0000000000003554	adds	x8, x8, x9              ;;   + i
0000000000003588	mov	w9, #0x8
0000000000003590	sdiv	x9, x8, x10
0000000000003598	subs	x8, x8, x9              ;; (digit+position+i) % 8
0000000000003668	bl	..rotateLeft(_:by:)

Final whitening and store.

000000000000367c	adds	x8, x8, x9              ;; i + digit
0000000000003694	mov	w8, #0xb
00000000000036a0	mul	x9, x9, x10             ;; position * 0xb
00000000000036bc	adds	x8, x8, x9              ;; i + digit + position*0xb
00000000000036d4	and	x9, x8, #0xff
00000000000037a0	eor	w8, w8, w9              ;; rotated ^ that
00000000000037d0	bl	0x12c10 ; symbol stub for: _$sSayxSiciM   ;; out[i] = ...

rotateLeft(_:by:) opens with and w8, w1, #0x7, returns the value unchanged when the result is 0, and otherwise combines an lsl by n and an lsr by 8 - n with orr. That is a standard 8-bit rotate.

xor(_:_:) calls Swift.min(a.count, b.count) (_$ss3minyxx_xtSLRzlF), allocates that many bytes and XORs element by element. Combined with the 28-byte salt, this means the salt’s last byte 0x53 is never used and the output stays at 27 bytes.

Putting it together in Swift-like pseudocode:

func derive(seed: [UInt8], digit: Int, position: Int) -> [UInt8] {
    var out = [UInt8](repeating: 0, count: 27)
    for i in 0..<27 {
        let mixed = seed[i % seed.count]
                  ^ UInt8((position + 1) * 0x21)
                  ^ UInt8(truncatingIfNeeded: digit * 0x13)
                  ^ UInt8(truncatingIfNeeded: i * 7)
        out[i] = rotateLeft(mixed, by: UInt8((digit + position + i) % 8))
               ^ UInt8(truncatingIfNeeded: i + digit + position * 0xb)
    }
    return out
}
// encode: acc = 0^27; for (pos, d) in pin: acc ^= derive(seed[d], d, pos); return hex(acc ^ salt)

8. Why the “oracle” never says no

KeypadViewModel.pressDigit(_:) explains why running the app gets you nowhere:

000000000000663c	subs	x8, x0, #0x4            ;; already 4 digits?
00000000000066c4	add	x0, x0, #0x340 ; literal pool for: "Repeated digits are not allowed."
...
0000000000006784	subs	x8, x0, #0x4            ;; now 4 digits?
00000000000067b4	bl	..PinCipherEngine.encode(pin:)
00000000000067e0	bl	..KeypadViewModel.encodedOutput.setter

Once four distinct digits are entered, the app encodes them and displays the hex. There is no comparison against a stored PIN and no success branch. Every PIN produces 27 bytes of hex that look equally plausible, which explains why the challenge author’s characters “can’t break the code”: the app gives no feedback either way.

So the real check happens outside the app: the right PIN is the one whose output decodes to text. Because each digit’s contribution depends on its position, order matters, so there are 5040 candidates (permutations, not combinations).

9. Re-implementing and searching offline

Python
#!/usr/bin/env python3
"""Re-implementation of Keypad_Oracle.PinCipherEngine (recovered statically)."""
import itertools, json, sys

OUTPUT_LENGTH = 0x1B
BINARY_SALT = bytes([
    0x3A, 0x91, 0x44, 0x2F, 0xD0, 0x18, 0x6B, 0xC3, 0x72, 0x0E, 0xA9, 0x5D, 0x11, 0xBE,
    0x80, 0x27, 0xF4, 0x66, 0x39, 0x9A, 0x05, 0xCC, 0x70, 0x1B, 0x88, 0x42, 0xE1, 0x53,
])

def load_seed_table(path):
    digits = json.load(open(path))["digits"]
    return {int(k): bytes.fromhex(v) for k, v in digits.items()}

def rotate_left(value, by):
    n = by & 7
    return value if n == 0 else ((value << n) | (value >> (8 - n))) & 0xFF

def xor(a, b):
    return bytes(x ^ y for x, y in zip(a, b))          # min(len(a), len(b))

def derive(seed, digit, position):
    out = bytearray(OUTPUT_LENGTH)
    for i in range(OUTPUT_LENGTH):
        mixed = (seed[i % len(seed)] ^ ((position + 1) * 0x21)
                 ^ ((digit * 0x13) & 0xFF) ^ ((i * 7) & 0xFF))
        out[i] = rotate_left(mixed, (digit + position + i) % 8) ^ ((i + digit + position * 0x0B) & 0xFF)
    return bytes(out)

def encode(pin, seeds):
    if len(pin) != 4 or len(set(pin)) != len(pin):
        return b""
    out = bytes(OUTPUT_LENGTH)
    for position, digit in enumerate(pin):
        out = xor(out, derive(seeds[digit], digit, position))
    return xor(out, BINARY_SALT)

if __name__ == "__main__":
    seeds = load_seed_table(sys.argv[1])
    for pin in itertools.permutations(range(10), 4):
        out = encode(list(pin), seeds)
        if all(0x20 <= c < 0x7F for c in out):
            print("PIN", "".join(map(str, pin)), out.hex(), out.decode())

The filter just asks for an all-printable result. A random 27-byte string is printable ASCII with probability about (95/256)^27 ≈ 10⁻¹², so any hit is almost certainly the intended one.

Shell
python3 keypad_oracle.py KeypadConfig.json
PIN 3719 64656164666163657b796f75722d70696e2d69732d76616c69647d deadface{your-pin-is-valid}

The search finishes in well under a second and finds exactly one PIN: 3719. A few other inputs show what the app would display otherwise, and how much order matters:

1234 cf4a7eeed6491a72f238ba8d97ce4791d880ed512a2de8ed7a800c
7319 26c22b4225c1b554...
3719 64656164666163657b796f75722d70696e2d69732d76616c69647d
3711 (empty: rejected)

7319 uses the same digits as the answer but produces noise, because each digit’s keystream depends on its slot. 3711 is rejected by the duplicate-digit check, so encode returns an empty string. Entering 3719 on the simulator’s keypad would show the hex 6465616466616365…7d. Hex-decoding that string gives the message, which is why the app has a “Copy” button.

10. Notes for similar challenges

  • Look for the .debug.dylib. In modern Xcode debug builds the executable is only a launcher, and all the code is in the dylib.
  • Debug Swift is generous. Function names, property names and even the private-discriminator suffixes survive, and swift-demangle turns them into a class diagram for you.
  • Separate the arithmetic from the safety checks. In unoptimised Swift, most instructions are overflow traps and exclusivity bookkeeping. The useful parts are the mul, eor, and #0xff, sdiv/msub (for %) and the calls between helpers.
  • No feedback means you supply the oracle. When an app never tells you whether a guess is right, the success condition is in the data (here, readable plaintext), and a small keyspace makes an offline search with a faithful re-implementation the intended route.

Flag: deadface{your-pin-is-valid}

Share

Written by Daniel Bae

Computer science student at UCLA. I build desktop, web and command-line software in Rust, Go and Python, and write here about how it is made. About this site