<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Osama A. Almanasra on Medium]]></title>
        <description><![CDATA[Stories by Osama A. Almanasra on Medium]]></description>
        <link>https://medium.com/@osama.mansra?source=rss-ddb72d823c98------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*s2vgUrCV1qXpvigUEG_2ww@2x.jpeg</url>
            <title>Stories by Osama A. Almanasra on Medium</title>
            <link>https://medium.com/@osama.mansra?source=rss-ddb72d823c98------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:30:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@osama.mansra/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How I Built a Pure Swift Mach-O Code Signature Parser]]></title>
            <link>https://medium.com/@osama.mansra/how-i-built-a-pure-swift-mach-o-code-signature-parser-a88ea927dbd7?source=rss-ddb72d823c98------2</link>
            <guid isPermaLink="false">https://medium.com/p/a88ea927dbd7</guid>
            <category><![CDATA[signature-parser]]></category>
            <category><![CDATA[mach-o-code]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Osama A. Almanasra]]></dc:creator>
            <pubDate>Sun, 12 Jul 2026 11:45:54 GMT</pubDate>
            <atom:updated>2026-07-12T14:50:26.733Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Reading an iOS app’s signing identity straight from the binary — no </em><em>codesign, no dependencies — to catch repackaged apps.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gHWRomS3-QOA5JQklbXbwA.png" /></figure><h3>The problem that started it</h3><p>A penetration test on an iOS app I was hardening came back with a finding I hadn’t thought much about before:</p><blockquote><strong><em>Missing Application Repackaging Protection.</em></strong><em> The app can be unpacked, modified, re-signed, and repackaged into a new </em><em>.ipa.</em></blockquote><p>This is a real, common attack. An attacker takes your shipped .ipa, unzips it, patches the binary (strips your jailbreak checks, injects a hook, swaps a URL), <strong>re-signs it with their own certificate</strong>, and repackages it. Now there&#39;s a Trojan version of your app in the wild that looks exactly like yours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h95nDhX4oTFe9umdSapSJw.png" /></figure><p>The recommended fix sounds simple: <em>at launch, check that the app is still signed by you — and bail if it isn’t.</em> I ended up extracting that check into an open-source Swift package called <strong>MachOSignature</strong> — but first, let’s see how the format actually works, because the interesting part is <em>how</em> you read that signature at all.</p><h3>Why the obvious approach doesn’t work</h3><p>On your Mac, reading a binary’s signing identity is one command:</p><pre>codesign -dv --verbose=4 MyApp.app</pre><p>But your app can’t run codesign. It&#39;s sandboxed on the device — no shelling out, no spawning processes. The signing information you need is sitting right there <em>inside your own binary</em>, and you have no first-class API to read it.</p><p>So you parse it yourself.</p><h3>What’s actually inside the binary</h3><p>Every Mach-O executable carries its code signature in a load command called <a href="https://github.com/apple-oss-distributions/xnu/blob/main/EXTERNAL_HEADERS/mach-o/loader.h">LC_CODE_SIGNATURE</a>. Follow it and you get a nested structure:</p><pre>FAT header ─▶ arch slice ─▶ Mach-O header ─▶ load commands<br>                                                  └─▶ LC_CODE_SIGNATURE<br>                                                        └─▶ SuperBlob<br>                                                              ├─▶ CodeDirectory   → identifier, Team ID<br>                                                              └─▶ CMS BlobWrapper → distribution signature</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kcnVa3tOI8Z8EDCxxOd-FQ.png" /></figure><p>Three things in there tell you whether a binary is <em>yours</em>:</p><ul><li><strong>Identifier</strong> — usually your bundle id, e.g. com.example.app.</li><li><strong>Team ID</strong> — your 10-character Apple Developer Team ID.</li><li><strong>CMS signature</strong> — the cryptographic blob Apple attaches for App Store / TestFlight / Developer ID distribution.</li></ul><p>When an attacker re-signs your app ad-hoc, the identifier and Team ID change to <em>theirs</em>, and the distribution CMS blob is gone. That’s the tell.</p><p>The magic numbers and struct layouts for all of this live in Apple’s open-source <a href="https://github.com/apple-oss-distributions/Security/blob/main/OSX/libsecurity_codesigning/lib/CSCommon.h">Security framework headers</a> — CS_SuperBlob, CS_CodeDirectory, and the blob magics like CSMAGIC_EMBEDDED_SIGNATURE.</p><h3>Walking the structure</h3><p>The whole thing is just bytes at offsets, with two rules to keep straight:</p><ol><li><strong>Mach-O header fields</strong> are in the host’s byte order; <strong>code-signing blob fields</strong> are always big-endian.</li><li>Every single read has to be bounds-checked. This parser runs against a file an attacker fully controls — one unchecked offset is a crash (or worse).</li></ol><h3>Finding LC_CODE_SIGNATURE</h3><p>First, walk the load commands until you hit the signature one:</p><pre>var cmdOffset = sliceOffset + headerSize<br>for _ in 0..&lt;Int(ncmds) {<br>    let cmd     = readU32(data, cmdOffset,     bigEndian: bigEndian)<br>    let cmdSize = readU32(data, cmdOffset + 4, bigEndian: bigEndian)</pre><pre>    if cmd == LC_CODE_SIGNATURE {               // 0x1d<br>        let dataOff = readU32(data, cmdOffset + 8, bigEndian: bigEndian)<br>        return parseSignature(data, at: sliceOffset + Int(dataOff))<br>    }<br>    cmdOffset += Int(cmdSize)<br>}<br>// No LC_CODE_SIGNATURE at all → the binary is unsigned.</pre><h3>Parsing the SuperBlob</h3><p>At that offset sits an <strong>embedded-signature SuperBlob</strong> (magic 0xfade0cc0): a small index of sub-blobs. We scan it for two — the <strong>CodeDirectory</strong> (0xfade0c02), which holds the identifier and Team ID, and the <strong>CMS BlobWrapper</strong> (0xfade0b01), whose mere presence (non-empty) means the binary was signed for distribution rather than re-signed ad-hoc:</p><pre>for _ in 0..&lt;Int(count) {<br>    let blobMagic = readU32(data, blobStart, bigEndian: true)<br>    let blobLen   = readU32(data, blobStart + 4, bigEndian: true)</pre><pre>    if blobMagic == CSMAGIC_CODEDIRECTORY { codeDirectoryOffset = blobStart }<br>    if blobMagic == CSMAGIC_BLOBWRAPPER, blobLen &gt; 8 { hasCMSSignature = true }<br>    indexOffset += 8<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fx7U6U5Lu85N5wfiwwMXiA.png" /></figure><h3>Reading the CodeDirectory</h3><p>Inside the CodeDirectory, the identifier and Team ID are C-strings at offsets stored in the header — and the Team ID field only exists on version 0x20200+ signatures:</p><pre>let identifier = readCString(data, cd + Int(identOffset))   // cd + 20</pre><pre>var teamID: String?<br>if version &gt;= 0x0002_0200 {<br>    let teamOffset = readU32(data, cd + 48, bigEndian: true)<br>    if teamOffset != 0 {<br>        teamID = readCString(data, cd + Int(teamOffset))<br>    }<br>}</pre><p>That’s the core of it. Handle thin <em>and</em> FAT binaries, 32- and 64-bit, both byte orders — and you can read any Mach-O’s signing identity from pure Swift.</p><blockquote><em>No shelling out. No external dependencies. Just pure Swift reading the Mach-O format.</em></blockquote><h3>The one design decision that actually matters</h3><p>Here’s the part that’s easy to get dangerously wrong.</p><p>You’re writing a check that can <strong>kill the app</strong>. If it’s too aggressive, you don’t hurt attackers — you hurt <em>legitimate users whose</em> device happens to produce a byte layout you didn’t anticipate. A false positive here isn’t a bug report; it’s an app that won’t launch, for real customers, that you can’t hotfix remotely.</p><p>So the parser <strong>fails open, and only the policy fails closed — on proof</strong>:</p><ul><li>Can’t parse the binary? Truncated, unexpected layout, unreadable field? → .inconclusive. Never treated as an attack.</li><li>Identifier or Team ID present <em>and</em> wrong? Distribution signature missing on an otherwise valid signature? → .tampered. That&#39;s a real, provable mismatch.</li></ul><pre>switch MachOSignatureInspector.verifyMainExecutable(<br>    expectedIdentifierPrefix: &quot;com.example.app&quot;,<br>    expectedTeamID: &quot;ABCDE12345&quot;<br>) {<br>case .valid:<br>    break<br>case .tampered(let reason):<br>    // Wrong team, wrong id, unsigned, or ad-hoc re-signed.<br>    #if !DEBUG &amp;&amp; !targetEnvironment(simulator)<br>    abort()<br>    #endif<br>case .inconclusive:<br>    // Couldn&#39;t parse conclusively — do NOT treat as tampering.<br>    break<br>}</pre><p>And gate the enforcement to <strong>release builds on physical devices</strong>. Simulator and debug builds are ad-hoc signed — enforce everywhere and you’ll brick your own dev workflow first.</p><h3>The package</h3><p>I pulled the parser out into a small, dependency-free Swift package: <strong>MachOSignature</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hbnvJpmxQoxSROol_wGsrg.png" /></figure><p>Read your own app’s identity:</p><pre>import MachOSignature</pre><pre>let sig = try MachOSignatureInspector.inspectMainExecutable()<br>sig.identifier       // &quot;com.example.app&quot;<br>sig.teamID           // &quot;ABCDE12345&quot;<br>sig.hasCMSSignature  // true on distribution builds<br>sig.isAdHocSigned    // true when re-signed ad-hoc — a repackaging tell</pre><p>Or inspect any Mach-O on disk:</p><pre>let ls = try MachOSignatureInspector.inspect(url: URL(fileURLWithPath: &quot;/bin/ls&quot;))<br>// ls.identifier == &quot;com.apple.ls&quot;</pre><p>The reader (inspect…) only reports facts and throws on structural problems; the policy layer (verify…) sits on top for the anti-repackaging verdict. Two layers, so you can use the plain reader for tooling or diagnostics without buying into any security policy.</p><h3>Being honest about what it is</h3><p>This is <strong>one layer, not a silver bullet.</strong> A determined attacker who’s already patching your binary can patch out the check itself. Client-side integrity checks are a deterrent — they raise the cost — best combined with other runtime signals (jailbreak detection, anti-debugging, RASP) rather than relied on alone. What they genuinely stop is the low-effort case: the trivially repackaged clone.</p><h3>Closing thought</h3><p>Apple’s code-signing information has always been inside the executable. We usually let codesign read it for us and never think about the bytes underneath. But nothing stops us from understanding the format ourselves — and once you do, detecting a re-signed binary turns out to be surprisingly straightforward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8LSQ4Vw6WGxJxJJ_34z46g.png" /></figure><p><strong>MachOSignature</strong> on GitHub: <a href="https://github.com/mrosama96/swift-macho-signature">https://github.com/mrosama96/swift-macho-signature</a></p><p><em>Written by Osama Almanasra — </em><a href="https://www.linkedin.com/in/osamamanasra"><em>LinkedIn</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a88ea927dbd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Obfuscation: Hide Your String Literals from stringswith a One-Line Macro]]></title>
            <link>https://medium.com/@osama.mansra/swift-obfuscation-hide-your-string-literals-from-stringswith-a-one-line-macro-7d2f75429810?source=rss-ddb72d823c98------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d2f75429810</guid>
            <category><![CDATA[swift-macros]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Osama A. Almanasra]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 08:13:00 GMT</pubDate>
            <atom:updated>2026-07-09T08:13:00.169Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HdQ3j6DN5Cu6zhQ27nuMxw.png" /></figure><h4><em>A practical guide to compile-time string obfuscation in Swift. Your source stays readable; the binary ships XOR-encoded.</em></h4><p><strong>What this article is about:</strong> every string literal you write in Swift — your API domains, endpoint paths, embedded values — ends up in the compiled binary in plain text. This is a hands-on guide to hiding the sensitive ones using <strong>string obfuscation at compile time</strong>, with a single-line Swift macro called #obf.</p><p>First, let’s see the problem clearly. Build your iOS app, grab the binary, and run one command:</p><pre>strings YourApp</pre><p>Scroll the output and there they are — your API domains, your endpoint paths, that “temporary” debug URL you forgot to remove. All in clear text, readable by anyone poking at your .ipa. No jailbreak, no decompiler, no reverse-engineering skills needed. Just strings and a few seconds.</p><p>That’s what string obfuscation fixes. Instead of the plaintext, the binary carries an encoded version of the string, and your app decodes it at runtime. The catch is that doing this by hand is miserable — so I built a tiny Swift macro to do it for you: <a href="https://github.com/mrosama96/swift-obfuscation-macro"><strong>ObfMacros</strong></a>. You keep writing plaintext in your source; the compiler ships it XOR-encoded.</p><p>Here’s the whole workflow, step by step.</p><h3>The manual way, and why nobody does it</h3><p>You <em>can</em> obfuscate a string by hand. You pre-compute the encoded bytes and paste them into your code:</p><pre>let domain = Obf.x([0x25, 0x1B, 0x31, 0x23, 0x16, 0x59, 0x5A, 0x5D, 0x38,<br>                    0x1F, 0x68, 0x32, 0x15, 0x0A, 0x12, 0x13, 0x39, 0x0A])</pre><p>Good luck reading that six months from now. Good luck changing the URL. This is exactly the kind of thing that looks clever once and becomes a maintenance tax forever, so in practice, everyone just ships the plaintext and moves on.</p><h3>Enter #obf</h3><p>The macro does the tedious part for you. You write the string you actually mean:</p><pre>import ObfMacros</pre><pre>let domain = #obf(&quot;https://api.example.com&quot;)</pre><p>At runtime, #obf(&quot;...&quot;) behaves exactly like the string literal it wraps — it&#39;s still just a String. The encoding happens once, at compile time, so <strong>the plaintext argument never reaches the compiled binary</strong>. Run strings on that build, and the domain simply isn&#39;t there.</p><p>Let’s wire it up.</p><h3>Step 1 — Install via Swift Package Manager</h3><p>Add the package URL in Xcode (File → Add Package Dependencies), or drop it into your Package.swift dependencies:</p><pre>https://github.com/mrosama96/swift-obfuscation-macro.git</pre><p>Then import it wherever you need it:</p><pre>import ObfMacros</pre><h3>Step 2 — The one-time “Trust &amp; Enable” prompt</h3><p>The first time you build, Xcode will stop you with something like:</p><blockquote><em>Macro “ObfMacrosPlugin” from package “ObfMacros” must be enabled before it can be used.</em></blockquote><p>Click <strong>Trust &amp; Enable</strong>. This isn’t specific to this package — it’s Xcode’s standard, mandatory prompt for <em>any</em> Swift macro pulled in through SPM, including Apple’s own. It’s a one-time thing per macro package. Skip it and your build will keep failing with the same message until you enable it.</p><h3>Step 3 — Use it</h3><p>The typical pattern is a small config type holding your endpoints:</p><pre>import ObfMacros</pre><pre>struct API {<br>    static let baseURL = #obf(&quot;https://api.example.com/v1/&quot;)<br>    static let path    = #obf(&quot;/users/me&quot;)<br>}</pre><p>One rule to remember: #obf(_:) requires a <strong>static string literal</strong>. No interpolation, no variables:</p><pre>#obf(&quot;https://api.example.com&quot;)   // ✅<br>#obf(&quot;https://\(host).com&quot;)       // ❌ won&#39;t compile<br>#obf(someStringVariable)          // ❌ won&#39;t compile</pre><p>That constraint is deliberate. The encoding happens inside the compiler, on the literal text, before your code is even generated — there’s nothing for it to encode if the value isn’t known at that point. The upside: there’s no meaningful runtime cost beyond a cheap byte-XOR the first time the value is read.</p><h3>Step 4 — Set your own key (don’t skip this one)</h3><p>Here’s the step that actually makes the obfuscation <em>yours</em>. Out of the box, every project that hasn’t configured anything shares the same placeholder key — which means the obfuscation isn’t doing much until you change it. Set your own <strong>before you ship</strong>.</p><p>Pick whichever fits your workflow.</p><p><strong>Option A — an environment variable.</strong> Works for swift build / swift test, and for Xcode builds, if you propagate it through an .xcconfig:</p><pre>export OBFMACROS_KEY=&quot;something-only-your-project-uses&quot;<br>swift build</pre><p><strong>Option B — a key file.</strong> Drop a plain text file named .obfmacros-key in your project root, containing just the key:</p><pre>echo &quot;something-only-your-project-uses&quot; &gt; .obfmacros-key</pre><p>This is used when the environment variable isn’t set. And yes — it’s fine to commit this file to your (private) repo. Per the security model below, the key was never a secret an attacker couldn’t eventually reach; it just needs to not be <em>this package’s public default</em>.</p><p>If you set neither, #obf falls back to a deliberately obvious placeholder (CHANGE-ME-OBFMACROS-KEY) — loud on purpose, so you&#39;ll spot it (e.g. by running strings on your own build) if you forgot to configure a real one.</p><p><strong>One gotcha worth internalizing:</strong> if you change your key, do a clean build afterwards (swift package clean, or ⇧⌘K in Xcode). Swift&#39;s incremental build cache doesn&#39;t know your key file or env var is a build input, so a normal incremental build might not re-expand the macros.</p><h3>What’s actually happening under the hood</h3><p>#obf(&quot;text&quot;) expands, at compile time, into something like:</p><pre>Obf.x([0x.., 0x.., 0x.., ...])   // the XOR-encoded bytes of &quot;text&quot;</pre><p>The plaintext argument is consumed entirely inside the compiler plugin process — it’s never written into the generated code, so it never lands in the binary. At runtime, Obf.x decodes the bytes back using the same key, resolved through an internal macro at the point the runtime helper compiles for your project. Because both the call sites and the decoder resolve the key the same way, they always agree — even though encoding happens once at build time and decoding happens later, inside the shipped app, on a completely different machine.</p><h3>Be honest about what this protects — and what it doesn’t</h3><p>This matters enough to say plainly: <strong>this is obfuscation, not encryption.</strong></p><p>The XOR key ships inside your binary. It has to — the app needs it to decode the string at runtime. So anyone willing to actually reverse-engineer your binary can recover the key and, with it, the strings.</p><p>What this <em>does</em> shut down is the trivial case: someone runs strings YourApp, or greps a decompiled .ipa, and reads your API domains, endpoint paths, or embedded values in clear text. That&#39;s a real, common, low-effort attack path — and this closes it.</p><p>What it is <em>not</em> is a replacement for proper secret management. A value that’s a genuine secret — an OAuth client secret, a real API key — is better off not shipping in the client at all. No client-side transformation changes that. Use this for the stuff you’d rather not broadcast, not for the stuff that would actually hurt if it leaked.</p><p>Being clear about that boundary is the whole point. A tool that oversells itself is worse than no tool.</p><h3>Requirements</h3><ul><li>Swift 5.9+ (for macro support)</li><li>iOS 13+ / macOS 13+</li></ul><h3>Wrapping up</h3><p>If you’ve got API URLs, endpoint paths, or other strings you’d rather not hand out for free, #obf gets them out of plain sight for the cost of wrapping a literal — no hand-encoded byte arrays, no maintenance headache, no runtime penalty worth mentioning. Just remember to set your own key before you ship, and keep your expectations calibrated to what obfuscation actually buys you.</p><p>The package is MIT-licensed and open source:</p><p><strong>GitHub:</strong> <a href="https://github.com/mrosama96/swift-obfuscation-macro">github.com/mrosama96/swift-obfuscation-macro</a></p><p>If it’s useful to you, a ⭐ on the repo helps others find it. Issues and PRs welcome.</p><p><em>Built by Osama Manasra. Find me on </em><a href="https://www.linkedin.com/in/osamamanasra"><em>LinkedIn</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d2f75429810" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>