<?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 Rohit Gurunath on Medium]]></title>
        <description><![CDATA[Stories by Rohit Gurunath on Medium]]></description>
        <link>https://medium.com/@rohitg5249?source=rss-92b303b6f413------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*hTPX7rZkg8AeXERS</url>
            <title>Stories by Rohit Gurunath on Medium</title>
            <link>https://medium.com/@rohitg5249?source=rss-92b303b6f413------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 20:59:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rohitg5249/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[A MAC is not a HASH: Reproducing the Crypto Core of EntrySign]]></title>
            <link>https://medium.com/@rohitg5249/a-mac-is-not-a-hash-reproducing-the-crypto-core-of-entrysign-9383d12d6aa3?source=rss-92b303b6f413------2</link>
            <guid isPermaLink="false">https://medium.com/p/9383d12d6aa3</guid>
            <category><![CDATA[hashing]]></category>
            <category><![CDATA[digital-signatures]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[cpu]]></category>
            <category><![CDATA[amd]]></category>
            <dc:creator><![CDATA[Rohit Gurunath]]></dc:creator>
            <pubDate>Mon, 10 Aug 2026 00:31:19 GMT</pubDate>
            <atom:updated>2026-08-10T00:31:19.209Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q07byP3dI7soabTSfFwvuQ.png" /><figcaption>MAC vs HASH</figcaption></figure><p>A few months ago I went down a rabbit hole reading Google’s <a href="https://bughunters.google.com/blog/zen-and-the-art-of-microcode-hacking">Bug Hunters write-up </a>on <strong>EntrySign</strong> (CVE-2024–56161) — the AMD Zen microcode signature verification bug. Every generation from Zen 1 through Zen 5 turned out to be vulnerable to forgery because of one very specific cryptographic mistake: <em>using a MAC where a hash function belongs</em>.</p><p>I was more interested in the crypto(graphy) as opposed to the microcode side of things (writing custom micro-ops is its own deep rabbit hole, and AMD’s zentool already does that far better than I could). What hooked me was the crypto primitive itself. So I built my own small, self-contained proof-of-concept to understand the cryptography details — no microcode, no RSA key recovery, just the core trick that makes the whole exploit possible. This post walks through that trick.</p><h3>Summary: What went wrong ?</h3><p>AMD’s microcode update process is supposed to work like this:</p><ol><li>Every CPU has a public key baked into it at manufacture time — or rather, a <strong>hash</strong> of that public key, fused into hardware.</li><li>A microcode patch ships with a full RSA public key, plus an RSASSA-PKCS1-v1.5 signature over the patch contents.</li><li>The CPU hashes the embedded public key and checks it against the fused hash. If it matches, the CPU trusts that key.</li><li>The CPU then uses that key to verify the signature over the patch contents.</li></ol><p>Step 3 is where it falls apart. AMD didn’t use a real cryptographic hash function (SHA-256, SHA-3, etc) to hash the public key. They used <strong>AES-CMAC</strong> — a <em>Message Authentication Code </em>(MAC), not a hash function — with the same fixed key baked into every single Zen CPU. To make things worse, that fixed key turned out to be the textbook example key straight out of NIST SP 800–38B.</p><p>That distinction (MAC vs. hash) sounds pedantic until you internalize what a MAC actually guarantees. A hash function is supposed to be collision-resistant <em>for anyone</em>, key or no key. A MAC’s security guarantee is more narrow: it’s unforgeable <em>to anyone who doesn’t have the key</em>. It says nothing about what someone holding the key can do — and CMAC (<em>like its predecessor, raw CBC-MAC</em>) is built from a chained block cipher, which is a <em>linear, invertible</em> structure. Anyone with the key can run the chain backwards, forwards, or splice new blocks into the middle of it. Recall, the key itself was public knowledge effectively, since it was the same fixed key for all Zen CPUs, and it had to be that way since AES-CMAC was intended to be used as a hash function.</p><h3>Primer: how CBC-style MACs actually chain</h3><p>Both <a href="https://en.wikipedia.org/wiki/CBC-MAC">CBC-MAC</a> and <a href="https://en.wikipedia.org/wiki/One-key_MAC">CMAC</a> are built the same way under the hood: split the message into fixed-size blocks, encrypt block 1, XOR the result into block 2, encrypt that, XOR into block 3, and so on. The final ciphertext block is the tag.</p><p>For a single block message <em>m</em>, with zero IV, the tag is trivially:</p><pre>tag = AES_encrypt(key, m)</pre><p>For a two-block message <em>m1 || m2</em>:</p><pre>state = AES_encrypt(key, m1)<br>tag   = AES_encrypt(key, m2 XOR state)</pre><p>Notice the structure: the “state” flowing between blocks is just the previous block’s ciphertext. If you know the key, you can compute that intermediate state for <em>any</em> message you like — which means you can <em>choose</em> a later block specifically to cancel it out and land on whatever value you want. That’s the entire attack, in one sentence: <strong>pick your extra block so that decryption-chain math forces the final tag to collide with a target tag you already know.</strong></p><p>CMAC proper adds subkey derivation and a different treatment of the final block specifically to prevent naive length-extension games like this. But that only defends against extension <em>of a message CMAC was designed to hash</em>. It says nothing about the deeper misuse in EntrySign: using CMAC as a general-purpose hash function, where an attacker who knows the key can still engineer <em>two different inputs</em> (a real public key and a forged one) that land on the same output, by inserting a “compensating block” that absorbs the difference.</p><h3>The PoC: Finding a collision, minus the microcode</h3><p>Here’s the reduced version I wrote to convince myself I understood the mechanics, independent of the RSA/microcode plumbing:</p><p>python</p><pre>from Crypto.Cipher import AES<br>from Crypto.Hash import CMAC<br>from Crypto import Random<br><br>def get_cmac_hash(key: bytes, msg: bytes) -&gt; bytes:<br>    assert (len(msg) % AES.block_size) == 0<br>    cipher = CMAC.new(key=key, ciphermod=AES)<br>    cipher.update(msg)<br>    return cipher.digest()<br><br>def aes_cbc_encrypt_zero_iv(key: bytes, msg: bytes) -&gt; bytes:<br>    assert (len(msg) % AES.block_size) == 0<br>    iv = b&#39;\x00&#39; * AES.block_size<br>    cipher = AES.new(key=key, iv=iv, mode=AES.MODE_CBC)<br>    return cipher.encrypt(msg)<br><br>def test_preimage_collision() -&gt; None:<br>    key = Random.get_random_bytes(32)<br>    msg1 = &quot;pay alice 100000&quot;<br>    tag1 = get_cmac_hash(key=key, msg=msg1.encode(&#39;utf-8&#39;))<br>    msg2 = &quot;pay bob 10000000&quot;<br>    assert len(msg1) == len(msg2)<br>    tag2_intermediate = aes_cbc_encrypt_zero_iv(key=key, msg=msg2.encode(&#39;utf-8&#39;))<br>    # fixup block: cancel out the intermediate CBC state so the<br>    # chain collapses back onto msg1&#39;s tag<br>    fixup_trailer = bytes(a ^ b for a, b in zip(tag2_intermediate, msg1.encode(&#39;utf-8&#39;)))<br>    fixup_msg = msg2.encode(&#39;utf-8&#39;) + fixup_trailer<br>    tag2 = get_cmac_hash(key=key, msg=fixup_msg)<br>    assert tag1 == tag2<br>    print(f&quot;msg1 = {msg1}&quot;)<br>    print(f&quot;msg2 = {fixup_msg}&quot;)<br>    print(f&quot;tag1 = {tag1.hex()}&quot;)<br>    print(f&quot;tag2 = {tag2.hex()}&quot;)</pre><p><strong>Walking through the math:</strong></p><p>msg1 is one 16-byte AES block (&quot;pay alice 100000&quot; is exactly 16 bytes — no coincidence, I picked it that way to keep the block math clean). So:</p><pre>tag1 = AES_encrypt(key, msg1)</pre><p>msg2 is a different 16-byte block (&quot;pay bob 10000000&quot;). I compute its raw CBC encryption under a zero IV — for a single block, that&#39;s just:</p><pre>tag2_intermediate = AES_encrypt(key, msg2)</pre><p>Now the fixup trailer block is defined as:</p><pre>fixup_trailer = tag2_intermediate XOR msg1<br>               = AES_encrypt(key, msg2) XOR msg1</pre><p>Append that trailer to msg2 to build a two-block message, then run it through <em>real</em> CMAC. Following the CBC-chain math from the primer above:</p><pre>state = AES_encrypt(key, msg2)                      # same as tag2_intermediate<br>tag2  = AES_encrypt(key, fixup_trailer XOR state)<br>      = AES_encrypt(key, (AES_encrypt(key, msg2) XOR msg1) XOR AES_encrypt(key, msg2))<br>      = AES_encrypt(key, msg1)<br>      = tag1</pre><p>The two AES_encrypt(key, msg2) terms cancel out via XOR, and we&#39;re left with exactly tag1. A two-block message I built from scratch produces the <em>identical</em> tag as a completely different one-block message — despite AES and CMAC both being individually sound primitives. Nothing is &quot;broken&quot; about AES here; the flaw is entirely in treating a keyed, invertible chaining construction as a cryptographic hash function.</p><p>This is the same trick, at miniature scale, that lets an attacker with AMD’s known CMAC key take a <em>trusted</em> RSA public key, and construct a <em>different</em> RSA public key — one they can factor and derive a private key for — that hashes to the exact same fused value. The real attack (documented in AMD’s advisory and Google’s write-up) appends its own compensating block to a candidate modulus, brute-forcing the earlier blocks until the resulting number is smooth enough to factor, using the same cancel-out-the-intermediate-state trick shown above. I deliberately stopped short of reproducing that part — Google already documented it in full, and reproducing a working forgery against real silicon isn’t the point of this post. The point is the primitive, and the primitive fits in about fifteen lines of Python.</p><h3>Real-world lessons</h3><ol><li><strong>A MAC is not a hash function, and the difference isn’t academic.</strong> First, a secure cryptographic hash function must resist collisions from anyone i.e. you must not be able to produce any 2 arbitrary inputs that hash to the same output. A MAC only promises unforgeability to attackers who <em>don’t</em> have the key — a very different property from collision resistance. Secondly, even that guarantee breaks down when the key is public. If you’re using a ‘Keyed’ primitive, the key must be kept secret (<em>unless it’s a public key of course</em>). If your design requires making a secret key public, that should already sound alarms.</li><li><strong>Chained/linear MAC constructions are dangerous in the hands of a key-holder.</strong> CBC-MAC and CMAC derive their entire security from being deterministic and invertible under the key — which is precisely what makes them unsafe as general-purpose hash functions. If you need to hash something, reach for SHA-2/SHA-3/BLAKE — constructions explicitly designed to resist this class of attack even against someone who fully controls the input.</li><li><strong>Never ship an unmodified textbook example as a production key.</strong> The AES-CMAC key AMD used was the literal example key from NIST SP 800–38B. This is the cryptographic equivalent of leaving the demo password in a config file — it’s not a subtle mistake, and it’s trivially detectable by anyone who’s read the same spec. NOTE: The microcode vulnerability would’ve existed even if a different key were used; The ‘demo key’ just made the chain easier in this case.</li></ol><h3>References</h3><ol><li><a href="https://bughunters.google.com/blog/zen-and-the-art-of-microcode-hacking">Zen and the Art of Microcode Hacking — Google Bug Hunters</a></li><li><a href="https://www.amd.com/en/resources/product-security/bulletin/amd-sb-7033.html">AMD-SB-7033 Security Bulletin</a></li><li><a href="https://csrc.nist.gov/pubs/sp/800/38/b/final">NIST SP 800–38B — CMAC Specification</a></li><li><a href="https://github.com/google/security-research/security/advisories/GHSA-4xq7-4mgh-gp6w">google/security-research — EntrySign advisory</a></li><li><a href="https://en.wikipedia.org/wiki/One-key_MAC">https://en.wikipedia.org/wiki/One-key_MAC</a></li><li><a href="https://en.wikipedia.org/wiki/CBC-MAC">https://en.wikipedia.org/wiki/CBC-MAC</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9383d12d6aa3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Whispers in the clock: why crypto implementations matter]]></title>
            <link>https://medium.com/@rohitg5249/whispers-in-the-clock-why-crypto-implementations-matter-89c34b7d5590?source=rss-92b303b6f413------2</link>
            <guid isPermaLink="false">https://medium.com/p/89c34b7d5590</guid>
            <dc:creator><![CDATA[Rohit Gurunath]]></dc:creator>
            <pubDate>Mon, 06 Oct 2025 00:12:15 GMT</pubDate>
            <atom:updated>2025-10-26T22:59:12.666Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you had an accurate stopwatch that gives you precise information about the execution of a decryption program. You don’t have the secret keys used to encrypt messages, but you get to know precisely how much time each step of that decryption program took to execute. Do you think that’s sufficient to decrypt an encrypted message? Side channel attacks have been the bane of modern cryptographic implementations. This post is an educational attempt to draw attention to the importance of adopting cryptographic implementations that guarantee <a href="https://en.wikipedia.org/wiki/Side-channel_attack">side-channel</a> safety.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OM-OHNuZqQORdcjpR3x-Pg.png" /><figcaption>whispers in the clock</figcaption></figure><p>This post is inspired by ‘Hack The Box Global Cyber skills benchmark’ CTF where our team at Microsoft placed 8th (<a href="https://ctftime.org/event/2707/">https://ctftime.org/event/2707/</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*REGX1RF8VSCQ5T2DFvlB3A.png" /></figure><p>I had solved 3 crypto challenges — this write-up covers <strong>Early Bird</strong>, which uses an RSA-OAEP encrypted cookie. The goal was to recover the admin secret embedded inside the encrypted cookie without access to the private key, by exploiting a timing leak in the server’s RSA decryption: we submit mauled ciphertexts and use timing differences (<em>a </em><a href="https://archiv.infsec.ethz.ch/education/fs08/secsem/manger01.pdf"><strong><em>Manger</em></strong></a><em>-style technique</em>) to iteratively recover the plaintext.</p><p>As always, there are some good lessons to learn for real-world software development. To skip the details of the challenges and jump to the conclusions <a href="https://medium.com/@rohitg5249/whispers-in-the-clock-why-crypto-implementations-matter-89c34b7d5590#dc05">click here</a>.</p><h3><strong>What is RSA-OAEP (Optimal Encrypted Asymmetric padding)?</strong></h3><p>RSA relies on the difficulty of factoring large numbers. Since encryption is deterministic — two encryptions of the same message yield identical ciphertexts — padding is required to randomize results. Early padding (PKCS#1 v1.5) added random bytes before the message but was broken by Bleichenbacher, which exploited padding validation as an oracle. To prevent such leaks, <a href="https://en.wikipedia.org/wiki/Optimal_asymmetric_encryption_padding">OAEP</a> was introduced, ensuring ciphertexts can’t be modified without detection and protecting plaintext confidentiality.</p><p>Bleichenbacher observed that padding validation after decryption acts as an oracle revealing if a message is PKCS-conforming — key to understanding Manger’s attack. For a deeper look at OAEP, see “<a href="https://blog.cryptographyengineering.com/2018/07/20/wonk-post-chosen-ciphertext-security-in-public-key-encryption-part-2/">Chosen Ciphertext security in public key encryption</a>” by Matthew Green.</p><h3>Manger’s Technique</h3><p>RSA-OAEP has been mathematically <a href="https://eprint.iacr.org/2000/061/">proven</a> to be secure against chosen ciphertext attacks. However, weak implementations could leak information about the structure of the plaintext via side-channels such as timing. In this post, I’ll provide an intuition for why this works without going into details(<em>read more about Manger’s technique </em><a href="https://link.springer.com/content/pdf/10.1007/3-540-44647-8_14.pdf"><em>here</em></a>). There are various types of side-channel leaks (<em>If you don’t know what a side-channel is, read </em><a href="https://en.wikipedia.org/wiki/Side-channel_attack"><em>here</em></a>) but in this post, we’ll assume timing based side-channels where it’s possible to observe and measure execution time of the decryption algorithm accurately.</p><p>Let’s assume the following</p><ul><li><em>N</em> be an RSA modulus</li><li><em>e</em> the public exponent</li><li><em>d</em> the private exponent</li><li><em>m</em> a message unknown to the adversary,</li><li><em>c</em> is the ciphertext after encrypting message <em>m</em> using the public key <em>(e, N)</em></li><li>B =2^{k-1}(<em>with k the modulus byte-length</em>)</li></ul><p>RSA requires messages/ciphertexts in the range (<em>0, N</em>). Manger’s idea is to submit varied ciphertexts and use a decryption timing side-channel to infer whether the resulting plaintext <em>m</em> is below <em>B</em>. Repeating this process narrows the possible message range until only a single candidate solution remains.</p><h4>Why does this even work?</h4><p>The RSA cryptosystem is multiplicatively <a href="https://en.wikipedia.org/wiki/Homomorphic_encryption">homomorphic</a> — multiplying ciphertext <em>c </em>by a number <em>(s^e) mod N </em>to generate <em>c’ = (c * s^e) mod N</em> and sending <em>c’</em> to the server, would lead to the server decrypting <em>c’</em> into <em>(m * s)</em>, where <em>m</em> is the original message. By observing timing differences between decryptions of different values of <em>c’</em> (<em>generated as </em><a href="https://link.springer.com/content/pdf/10.1007/3-540-44647-8_14.pdf"><em>described</em></a><em> by Manger</em>), an adversary could identify when the decrypted <em>(m * s) </em>was<em> </em>lesser than <em>B</em> and consequently narrow down the range of possible values for <em>m</em>.</p><h3>The CTF Challenge</h3><p>We’re provided with a webserver that contains the following method to decrypt and verify an input token that contains a secret message encrypted using RSA-OAEP. We’re able to send a ciphertext as input and get the server to perform ‘decrypt_and_verify’. However, the server does not return the decrypted message. Our objective is to somehow recover the plaintext message, encrypted by the server and use that to obtain the flag.</p><pre>def decrypt_and_verify(self, C):<br>        if len(C) != self.k or self.k &lt; 2*self.hLen + 2:<br>            return { &quot;ok&quot;: False, &quot;error&quot;: &quot;decryption error&quot; }<br>        c = self.os2ip(C)<br>        if c &gt;= self.key.n:<br>            return { &quot;ok&quot;: False, &quot;error&quot;: &quot;decryption error&quot; }<br>        m = pow(c, self.key.d, self.key.n)<br>        EM = self.i2osp(m, self.k)<br>        Y = EM[0]<br>        maskedSeed = EM[1:self.hLen+1]<br>        maskedDB = EM[self.hLen+1:]<br>        seedMask = MGF1(maskedDB, self.hLen, HF)<br>        seed = xor(maskedSeed, seedMask)<br>        dbMask = MGF1(seed, self.k - self.hLen - 1, HF)<br>        DB = xor(maskedDB, dbMask)<br>        PS = DB[self.hLen:].split(b&#39;\x01&#39;)[0]<br>        if Y == 0:<br>            print (f&quot;C= {c}, Y={Y}&quot;)<br>        if Y != 0 or not self.H_verify(self.L, DB[:self.hLen]) or self.os2ip(PS) != 0:<br>            return { &quot;ok&quot;: False, &quot;error&quot;: &quot;decryption error&quot; }<br>        M = DB[self.hLen+len(PS)+1:]<br>        return { &quot;ok&quot;: True, &quot;msg&quot;: M}</pre><p>Towards the very end, notice how the implementation performs validation using the logical ‘or’ operator</p><pre>1. Y != 0 or<br>2. not self.H_verify(self.L, DB[:self.hLen]) or<br>3. self.os2ip(PS) != 0<br></pre><p>If the first check returns <strong>False</strong>, the code skips later statements, making the response faster. By measuring response times, an attacker can tell whether the decrypted message starts with 0x00. This timing oracle reveals whether a ciphertext’s plaintext begins with 00, enabling <strong>Manger’s attack</strong> to iteratively narrow the plaintext range until the exact message is recovered.</p><h3>Are Timing measurements even practical?</h3><p>This is a question that bugged me for a long time. This CTF challenge was an eye-opener, and my conclusion is that they’re not as hard as I had once thought they would be.</p><p>My first attempt at profiling the response times lead to the following noisy distribution, (<em>likely due to network jitter</em>) where the response times were somewhat erratic, making it hard to distinguish which decryption operations lead to messages that started with 0x00.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p1Ws2qpE0fjHBPeHwZjVfQ.png" /></figure><p>To reduce network jitter we colocated our client in a VM in the server’s region, producing a much cleaner timing profile that showed a clear 1.2s gap between decryptions with and without a leading 0x00.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nmRH_UIKfIoc5bDsJWATrw.png" /></figure><p>Implementing manger’s technique with a threshold set to 1.2s yielded the correct secret token, that could be used to obtain the following flag:</p><blockquote>HTB{w34k_1mpl3m3nt4t10ns_m4y_l34d_t0_t1m1ng_4tt4cks_105c04f91f7ce069d50a3b94d49f8b05}</blockquote><h3>Lessons Learnt</h3><p>This was a great example of theory vs practice, demonstrating why side-channel safe cryptographic implementations are crucial in an otherwise theoretically secure construction. Ensuring this kind of safety in implementations is further complicated by compiler optimizations that could potentially <a href="https://www.usenix.org/system/files/usenixsecurity23-xu-jianhao.pdf">re-introduc</a> side-channels.</p><p>In 2003 Dan Boneh and David Brumley noted that “<a href="https://crypto.stanford.edu/~dabo/papers/ssl-timing.pdf"><em>remote timing attacks are practical</em></a>” and demonstrated private key extraction over a local network. Extending their conclusions, IMHO it seems remote measurements follow something like moore’s law and only get better over the years.</p><p>As a software developer/architect, the most important take-away is to use cryptographic libraries that are well maintained and provide guarantees against side-channels.</p><h3>References:</h3><ol><li>Manger’s Technique: <a href="https://archiv.infsec.ethz.ch/education/fs08/secsem/manger01.pdf">https://archiv.infsec.ethz.ch/education/fs08/secsem/manger01.pdf</a></li><li>RSA OAEP security proof: <a href="https://eprint.iacr.org/2000/061/">https://eprint.iacr.org/2000/061/</a></li><li>Remote timing attacks are practical: <a href="https://crypto.stanford.edu/~dabo/papers/ssl-timing.pdf">https://crypto.stanford.edu/~dabo/papers/ssl-timing.pdf</a></li><li>Chosen Ciphertext Security in Public Key encryption: <a href="https://blog.cryptographyengineering.com/2018/07/20/wonk-post-chosen-ciphertext-security-in-public-key-encryption-part-2/">https://blog.cryptographyengineering.com/2018/07/20/wonk-post-chosen-ciphertext-security-in-public-key-encryption-part-2/</a></li><li>Hack the Box 2025: <a href="https://github.com/hackthebox/business-ctf-2025">https://github.com/hackthebox/business-ctf-2025</a></li><li>Chosen ciphertext security: <a href="https://en.wikipedia.org/wiki/Adaptive_chosen-ciphertext_attack">https://en.wikipedia.org/wiki/Adaptive_chosen-ciphertext_attack</a></li><li>Return of the Bleichenbacker’s Oracle Threat (ROBOT): <a href="https://robotattack.org/">https://robotattack.org/</a></li><li>Side-Channel security: <a href="https://en.wikipedia.org/wiki/Side-channel_attack">https://en.wikipedia.org/wiki/Side-channel_attack</a></li><li>NIST PQC Side-channel security guidance: <a href="https://csrc.nist.gov/csrc/media/Projects/post-quantum-cryptography/documents/pqc-seminars/presentations/2-side-channel-security-saarinen-04042023.pdf">https://csrc.nist.gov/csrc/media/Projects/post-quantum-cryptography/documents/pqc-seminars/presentations/2-side-channel-security-saarinen-04042023.pdf</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89c34b7d5590" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to split a secret?]]></title>
            <link>https://medium.com/@rohitg5249/how-to-split-a-secret-d92c0a57b62e?source=rss-92b303b6f413------2</link>
            <guid isPermaLink="false">https://medium.com/p/d92c0a57b62e</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[error-correction]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Rohit Gurunath]]></dc:creator>
            <pubDate>Mon, 26 Aug 2024 02:56:37 GMT</pubDate>
            <atom:updated>2024-09-02T23:50:03.280Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Split a Secret?</h3><p>Imagine you have a sum of money that you want to split among 10 family members. The money is in an account protected by a password. You could give the password to all 10 of them, but here’s a condition: you want to ensure that the money is accessible <em>only if at-least (say) 6 out of the 10 family members agree and get together</em>. How do you share this password with the 10 members in such a way that unless 6 or more of them get together, nobody can retrieve the original password to access the account with the money?</p><p><a href="https://en.wikipedia.org/wiki/Adi_Shamir">Adi Shamir</a> published a <a href="https://web.mit.edu/6.857/OldStuff/Fall03/ref/Shamir-HowToShareASecret.pdf">technique</a> known as <a href="https://en.wikipedia.org/wiki/Shamir%27s_secret_sharing">Shamir’s Secret Sharing (SSS) </a>that achieves just that. It turns out that this simple, yet extremely powerful technique is very useful in many situations. In fact, here are some well known examples of Shamir’s secret sharing being used in the real world:</p><ol><li>Hashicorp Vault (<em>a cloud service for managing and protecting cryptographic keys</em>) <a href="https://developer.hashicorp.com/vault/tutorials/operations/rekeying-and-rotating"><strong><em>uses</em></strong></a> Shamir’s Secret Sharing to split a secret key into multiple shares that could be distributed across different machines for improved security.</li><li><a href="https://www.popsci.com/technology/article/2010-07/order-seven-cyber-guardians-around-world-now-hold-keys-internet/">DNSSEC root keys</a> are held by 7 guardians such that the root key could be retrieved only if (any) 5 of them get together and decide to recover the key. (From <a href="https://www.schneier.com/blog/archives/2010/07/dnssec_root_key.html">Schneier’s blog</a> it looks like Shamir’s Secret Sharing is probably being used here).</li><li>How about Detecting and correcting data corruption in transit or storage? Well, it turns out that the <a href="#a9b5">underlying</a> mathematical techniques used in Shamir’s Secret Sharing are also used by popular Error Correction Algorithms, such as the <a href="https://en.wikipedia.org/wiki/Reed%E2%80%93Solomon_error_correction">Reed-Solomon Error Correction Codes</a> used for disk error corruption.</li></ol><p>In this post, we’re going to understand the simple but interesting math behind this technique and implement it.</p><h3>What is Shamir’s Secret Sharing?</h3><p>Imagine you’re given 2 points (x1, y1) and (x2, y2). It’s pretty easy to recover the equation of the unique line that connects these two points as</p><blockquote>(y — y1) / (y2 — y1) = (x — x1) / (x2 — x1)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/0*p6gS88FUAxcwN9tD.png" /><figcaption>Given 2 points, there’s a unique line that passes through them</figcaption></figure><p>Now what if you were given only 1 point (x1, y1)? There’s no way you could recover the above line given just one point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/0*nAvbhB6j46m8u0O4.png" /><figcaption>infinitely many lines can pass through a single point</figcaption></figure><p>Now extend the same concept to an arbitrary polynomial of degree n. You need at least n + 1 points to recover this polynomial. This is the basis for Shamir’s Secret Sharing technique.</p><blockquote><em>of course, the actual computation involves arithmetic in a </em><strong><em>finite field</em></strong><em> where division is equivalent to multiplication by a modular inverse</em>, <em>but let’s ignore that nuance here to keep things simple</em></blockquote><p>Shamir noted, that given a secret value ‘k’, you could encode it as a constant coefficient of a polynomial F(x) with ‘t’ randomly chosen coefficients (other than the constant term of course). This gives a degree ‘t’ polynomial.</p><p>Now we generate ’n’ points from this polynomial as</p><blockquote>&lt;1, F(1)&gt;, &lt;2, F(2)&gt;…..&lt;n, F(n)&gt;</blockquote><p>and distribute them among the ’n’ participants. Whenever any t + 1 out of the n participants get together, they could use those points to recover the polynomial equation and then retrieve the secret (which is the coefficient of the constant term).</p><p>That sounds simple, right? Well.. given these ’n’ points how do you actually reconstruct the original polynomial equation for any arbitrary ‘n’?</p><p>Read on…..</p><h3>Lagrange’s Interpolation</h3><p>Lagrange provides a method to construct such a ‘t’ degree polynomial, given at least t + 1 points on the curve. In fact, as explained in my <a href="https://medium.com/@rohitg5249/vault-of-hope-htb2024-write-up-d48cc3530ddc">previous blog post</a>, we actually ended up using <a href="https://en.wikipedia.org/wiki/Lagrange_polynomial">Lagrange’s interpolation</a> to solve the Hack The Box (HTB 2024) challenge. We used sage to save time, but here we’ll actually understand the math and write (non-sage) code to implement it.</p><p>The basic idea is to generate a lagrange basis polynomial for each point that was provided, such that the basis polynomial evaluates to 1 at the given point, but 0 at every other point.</p><p>How do we generate the Lagrange Basis Polynomial?</p><blockquote>P0(x) = (x — x1)(x — x2)…(x — xn) / (x0 — x1)(x0 — x2)…(x0 — xn)</blockquote><blockquote>P1(x) = (x — x0)(x — x2)…(x — xn) / (x1 — x0)(x1 — x2)…(x1 — xn)</blockquote><p>You can easily check that P0(x0) = 1, but for any other values of x (x1, x2, … xn) P0(x) = 0. Likewise P1(x1) = 1, but for any other values of x (x0, x2, … xn) P1(x) = 0.</p><p>Now, we simply scale each of these Lagrange Basis polynomials by the Value Yi = F(Xi) and add them up to obtain the original polynomial equation as :</p><blockquote>P(x) = Y0P0(x) + Y1P1(x) + … + YnPn(x)</blockquote><p>Since I had used Lagrange’s polynomial interpolation in the challenge Crypto Bloom Bloom in HTB2024 CTF as detailed in this <a href="https://medium.com/@rohitg5249/vault-of-hope-htb2024-write-up-d48cc3530ddc">post</a>, I’m going to reuse those values as a test vector to test our implementation of Lagrange’s polynomial interpolation. If our implementation is correct, we should output the flag (that was hidden in a polynomial of degree 4) that we had obtained from that challenge.</p><pre>from math import prod<br>from typing import List<br>import itertools<br>from Crypto.Util.number import inverse, long_to_bytes<br><br>def construct_polynomial_lagrange_interpolation(x: List[int], y: List[int], p: int = None) -&gt; List[int]:<br>    &quot;&quot;&quot;<br>        Given a list of &lt;Xi, F(Xi)&gt; we construct the polynomial F(X)<br>        and return a list of coefficients &lt;a0, a1, a2... at&gt;<br><br>        p is the prime for the Finite Field Fp if provided<br>    &quot;&quot;&quot;<br>    def generate_basis_polynomial(x: List[int], v: int, p: int = None) -&gt; List[int]:<br>        &quot;&quot;&quot;<br>            How do we generate a lagrange basis polynomial for v?<br><br>            Pv(x) = (x - x1)(x - x2)..(x - xt) / (v - x1) (v - x2)..(v - xt)<br>            Note that Pv(x) = 1 when x = v, but 0 otherwise.<br><br>            Also, division is replaced by modular inverse if we&#39;re dealing<br>            with a finite field defined by prime p<br>        &quot;&quot;&quot;<br>        r = prod( (v - j if v != j else 1 for j in x) )<br>        xv = [val for val in x if val != v]<br>        t = len(xv)<br>        coeff = []<br>        sign = 1<br><br>        # eg: To compute  (x - x1)(x - x2)(x - x3)<br>        # observe that the final equation has the following coefficients<br>        # x^3  - (x1 + x2 + x3)x^2 + (x1x2 + x2x3 + x1x3)x - x1x2x3<br>        # Note that the coefficients are determined by the respective<br>        # sum of the products of combinations of x1, x2, x3 <br>        # taken 0, 1, 2 and 3 at a time respectively<br>        for i in range(t + 1):<br>            coeff.append(sign * sum (prod(comb) for comb in itertools.combinations(xv, i)) )<br>            sign *= -1<br>        <br>        if p is not None:<br>            mi = inverse(r, p)<br>            return [ (c * mi) % p for c in coeff]<br>        return [c / r for c in coeff]<br><br>    # generate each lagrange basis polynomial and scale by corresponding y[i]<br>    lagrange_basis_polynomials = [<br>        [ (y[i] * g) % p for g in generate_basis_polynomial(x, v, p) ] for i, v in enumerate(x)<br>    ] if p is not None else [<br>        [ (y[i] * g) for g in generate_basis_polynomial(x, v, p) ] for i, v in enumerate(x)<br>    ]<br>    assert (len(lagrange_basis_polynomials) != 0)<br><br>    # add respective coefficient values of each Lagrange basis Polynomial<br>    # to obtain the original polynomial equation<br>    poly = [0] * len(x)    <br>    for j in range(len(x)):<br>        for i in range(len(lagrange_basis_polynomials)):<br>            poly[j] = (poly[j] + lagrange_basis_polynomials[i][j]) % p if p is not None else (poly[j] + lagrange_basis_polynomials[i][j])<br>    <br>    return poly<br><br><br>if __name__ == &quot;__main__&quot;:<br>    # The following values were taken from challenge Crypto Bloom Bloom in<br>    # https://medium.com/@rohitg5249/vault-of-hope-htb2024-write-up-d48cc3530ddc<br><br>    x = [1, 2, 3, 4, 5]<br>    y = [<br>        27006418753792019267647881709336369603809025474153761185424552629526746515909,<br>        76590454267924193303526931251420387908730989759486987968207839464816350274449,<br>        67564500698667187837224046797217120599664632018519685208508601443605280795068,<br>        57120102994643471094254225269948720992016639286627873340589938545214763610538,<br>        87036956450994410488989322365773556006053008613964544744444104769020810012336<br>    ]<br>    <br>    # We&#39;re operating in GF(88061271168532822384517279587784001104302157326759940683992330399098283633319)<br>    p = 88061271168532822384517279587784001104302157326759940683992330399098283633319<br><br>    poly = construct_polynomial_lagrange_interpolation(x, y, p)<br>    res = long_to_bytes(poly[-1]).decode(&#39;utf-8&#39;)<br><br>    # if all goes well, we should decode to the FLAG from challenge Bloom Bloom<br>    assert (res == &#39;1_4m_y0ur_k3y_t0_g3t_th3_fl4g123&#39;)<br>    print ( res )</pre><p>When we run the above code, we see the output <strong>1_4m_y0ur_k3y_t0_g3t_th3_fl4g123</strong> as expected.</p><h3>How Secure is this?</h3><p>Shamir’s secret sharing is known to provide <a href="https://en.wikipedia.org/wiki/Information-theoretic_security">information-theoretic security</a> unless ‘t’ out of ’n’ secret shares have been revealed. Such schemes are secure against an adversary with infinite computing resources and time. This is interesting, especially given the recent NIST announcements to standardize <a href="https://www.nist.gov/news-events/news/2024/08/nist-releases-first-3-finalized-post-quantum-encryption-standards">Post-Quantum ciphers</a> . But that’s a topic for another day….. Stay tuned!</p><h3>References:</h3><ol><li>How to share a secret? <a href="https://web.mit.edu/6.857/OldStuff/Fall03/ref/Shamir-HowToShareASecret.pdf">https://web.mit.edu/6.857/OldStuff/Fall03/ref/Shamir-HowToShareASecret.pdf</a></li><li>Lagrange’s Polynomial Interpolation: <a href="https://pages.cs.wisc.edu/~sifakis/courses/cs412-s13/lecture_notes/CS412_12_Feb_2013.pdf">https://pages.cs.wisc.edu/~sifakis/courses/cs412-s13/lecture_notes/CS412_12_Feb_2013.pdf</a></li><li>Shamir’s Secret Sharing: <a href="https://en.wikipedia.org/wiki/Shamir%27s_secret_sharing">https://en.wikipedia.org/wiki/Shamir%27s_secret_sharing</a></li><li>Reed-Solomon Codes: <a href="https://en.wikipedia.org/wiki/Reed%E2%80%93Solomon_error_correction">https://en.wikipedia.org/wiki/Reed%E2%80%93Solomon_error_correction</a></li><li>Shamir’s Secret Sharing graph references: <a href="https://distributeddatastore.blogspot.com/2016/03/a-way-to-understand-shamirs-secret.html">https://distributeddatastore.blogspot.com/2016/03/a-way-to-understand-shamirs-secret.html</a></li><li>Galois Field: <a href="https://en.wikipedia.org/wiki/Finite_field">https://en.wikipedia.org/wiki/Finite_field</a></li><li>NIST post-quantum encryption and signature algorithms: <a href="https://www.nist.gov/news-events/news/2024/08/nist-releases-first-3-finalized-post-quantum-encryption-standards">https://www.nist.gov/news-events/news/2024/08/nist-releases-first-3-finalized-post-quantum-encryption-standards</a></li><li><a href="https://research.ibm.com/blog/nist-pqc-standards#-fn-5">https://research.ibm.com/blog/nist-pqc-standards#-fn-5</a></li><li><a href="https://www.schneier.com/blog/archives/2010/07/dnssec_root_key.html">https://www.schneier.com/blog/archives/2010/07/dnssec_root_key.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d92c0a57b62e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vault of Hope: HTB2024 Write-up]]></title>
            <link>https://medium.com/@rohitg5249/vault-of-hope-htb2024-write-up-d48cc3530ddc?source=rss-92b303b6f413------2</link>
            <guid isPermaLink="false">https://medium.com/p/d48cc3530ddc</guid>
            <category><![CDATA[hackthebox-writeup]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rohit Gurunath]]></dc:creator>
            <pubDate>Tue, 28 May 2024 04:39:44 GMT</pubDate>
            <atom:updated>2024-05-30T04:30:44.855Z</atom:updated>
            <content:encoded><![CDATA[<p>I almost missed taking part in the <a href="https://ctf.hackthebox.com/event/details/htb-business-ctf-2024-the-vault-of-hope-1474">HTB2024:Vault of hope</a> this year, but finally managed to get a few hours one night dedicated to trying out some of these challenges. I was able to solve 2 crypto challenges but didn’t have time for the others due to family visiting. Overall, our team at Microsoft, <a href="https://ctf.hackthebox.com/event/1474/scoreboard">ranked 15</a> (we were rank 24 last year) :-)</p><p>As always, there are some good lessons to learn for real-world software development. To skip the details of the challenges and jump to the conclusions click <a href="#c17d">here</a>.</p><h3><strong>Challenge 1: Crypto Bloom Bloom</strong></h3><p><strong>Summary</strong>: Imagine you’re building a web application and you need to encrypt some sensitive data. You need to generate a secret key. You invoke a library from your programming language of choice (such as <a href="https://pycryptodome.readthedocs.io/en/latest/src/random/random.html">Crypto.Random</a> in python), which under the hood uses the operating system’s source of entropy (such as <a href="https://linux.die.net/man/4/urandom">/dev/urandom</a> on Linux or<a href="https://learn.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom"> BCryptGenRandom</a> on windows etc).</p><p>How is that underlying random number generator itself implemented? This challenge gives one such implementation with a few tweaks. (<em>Btw, The Linux kernel’s cryptographic random number generator implementation is in </em><a href="https://github.com/torvalds/linux/blob/master/drivers/char/random.c"><strong><em>random.c</em></strong></a>)</p><p>In this challenge we’re provided with an implementation of the <a href="https://en.wikipedia.org/wiki/Blum_Blum_Shub"><strong><em>Blum Blum Shub</em></strong></a> Pseudo-Random Number Generator (PRNG) that’s used to generate keys for encrypting messages. We’re also provided with the encrypted files and the objective is to decrypt them to reveal the flag.</p><p><strong>Primer on Blum-Blum-Shub and Pseudo-Random-Generators:</strong></p><p>Blum-Blum-Shub (BBS) is based on Rabin’s one-way function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/134/0*LZaRefCT7i_P44lp" /><figcaption>Blum Blum Shub</figcaption></figure><p>where M is the product of 2 primes and x is initialized with a random value between (1, M) and must be co-prime to M. The last few bits (typically the Least Significant Bit (LSB) a.k.a parity bit) are used as the ‘outputs’ of the Blum-Blum-Shub PRNG.</p><blockquote><em>How secure is this PRNG? What does Security even mean in this context?</em></blockquote><p>To give a very generalized and informal overview, any adversary could predict a single bit (say the LSB) correctly with 1/2 probability. The PRNG is considered secure if the adversary’s advantage in predicting the LSB is</p><p>1/2 + e, where e is negligible. See <a href="https://en.wikipedia.org/wiki/Pseudorandom_number_generator">Pseudo-Random-Generators</a> for more details. In other words, the PRNG is secure if the adversary couldn’t gain any non-negligible advantage in distinguishing the output of the PRNG from a truly random distribution.</p><p>Given all this information, how secure is Blum-Blum-Shub?Well, there’s a <a href="https://shub.ccny.cuny.edu/articles/1986-A_simple_unpredictable_pseudo-random_number_generator.pdf">proof</a> that effectively reduces it’s security to the computational hardness of factoring.</p><p>So, as long as we initialize BBS with parameters of appropriate sizes, there’s no computationally feasible way to break the security of this PRNG.</p><p>Now, let’s move on to the source code…..</p><p>Challenge: (<em>I’ve added some comments within this source to add more context</em>)</p><pre>from random import randint, shuffle<br>from Crypto.Util.number import getPrime<br>from Crypto.Cipher import AES<br>from Crypto.Util.Padding import pad<br>from hashlib import sha256<br>from secret import *<br>import os<br><br>assert sha256(KEY).hexdigest().startswith(&#39;786f36dd7c9d902f1921629161d9b057&#39;)<br><br>class BBS:<br>    def __init__(self, bits, length):<br>        # 512 bits<br>        self.bits = bits<br>        self.out_length = length<br><br>    def reset_params(self):<br>        self.state = randint(2, 2 ** self.bits - 2)<br>        self.m = getPrime(self.bits//2) * getPrime(self.bits//2) * randint(1, 2)<br>    <br>    def extract_bit(self):<br>        self.state = pow(self.state, 2, self.m)<br>        return str(self.state % 2)<br><br>    def gen_output(self):<br>        self.reset_params()<br>        out = &#39;&#39;<br>        # extract 256 bits after this loop<br>        for _ in range(self.out_length):<br>            out += self.extract_bit()<br>        return out<br><br>    def encrypt(self, msg):<br>        out = self.gen_output()<br>        print (f&quot;key: {out}&quot;)<br>        # key generated using blum-blum-shub cryptosystem<br>        key = sha256(out.encode()).digest()<br>        iv = os.urandom(16)<br>        cipher = AES.new(key, AES.MODE_CBC, iv)<br>        return (iv.hex(), cipher.encrypt(pad(msg.encode(), 16)).hex())<br><br>encryptor = BBS(512, 256)<br><br>enc_messages = []<br>for msg in MESSAGES:<br>    enc_messages.append([encryptor.encrypt(msg) for _ in range(10)])<br><br>enc_flag = AES.new(KEY, AES.MODE_ECB).encrypt(pad(FLAG, 16))<br><br>with open(&#39;output.txt&#39;, &#39;w&#39;) as f:<br>    f.write(f&#39;{enc_messages}\n&#39;)<br>    f.write(f&#39;{enc_flag.hex()}\n&#39;)</pre><p><strong>Intuition for a solution:</strong></p><p>A slightly tweaked version of Blum-Blum-Shub is used to generate cryptographic keys. Every character of the key is generated from a call to <em>extract_bit(), </em>which returns the LSB (i.e. parity bit) from BBS’ internal state ‘x’ after performing the square mod M.</p><p>The intuition comes from the definition of <em>self.m</em> inside the <em>reset_params </em>function, where we note that 50% of the time, m is set to 2 * p * q instead of p * q, where p and q are primes 256 bit primes.</p><p>Why is this significant? if M is even, then</p><ol><li>if x is odd, then <em>x², x⁴, x⁸… (mod M</em>) will always be odd =&gt; parity bit is always 1</li><li>if x is even, then <em>x², x⁴, x⁸… (mod M</em>) will always be even =&gt; parity bit is always 0</li></ol><p><strong>Solution:</strong></p><p>Putting all this together, we see that about 50% of the time, the final symmetric key generated by this modified BBS is either 256 zeros or 256 ones depending on whether the initial random seed was even or odd.</p><p>Trying to decrypt all the ciphertexts with both keys of size 256 characters (0000…000 and 11111…111), we’re able to decrypt the messages:</p><pre>Welcome! If you see this you have successfully decrypted the first message. <br>To get the symmetric key that decrypts the flag you need to do the <br>following:<br>  1. Collect all 5 shares from these messages<br>  2. Use them to interpolate the polynomial in a finite field that will be <br>      revealed in another message<br>  3. Convert the constant term of the polynomial to bytes and use it to <br>     decrypt the flag. <br>Here is your first share!<br>Share#1#: (1, 27006418753792019267647881709336369603809025474153761185424552629526746515909)<br><br>Keep up the good work! Offered say visited elderly and. Waited period are <br>played family man formed. He ye body or made on pain part meet. You one delay <br>nor begin our folly abode. By disposed replying mr me unpacked no. As moonlight<br>of my resolving unwilling. Turned it up should no valley cousin he. Speaking <br>numerous ask did horrible packages set. Ashamed herself has distant can <br>studied mrs.<br>Share#2#: (2, 76590454267924193303526931251420387908730989759486987968207839464816350274449)<br><br>Only a few more are left! Of be talent me answer do relied. Mistress in on so<br>laughing throwing endeavor occasion welcomed. Gravity sir brandon calling can. <br>No years do widow house delay stand. Prospect six kindness use steepest new <br>ask. High gone kind calm call as ever is. Introduced melancholy estimating <br>motionless on up as do. Of as by belonging therefore suspicion elsewhere am <br>household described.<br>Share#3#: (3, 67564500698667187837224046797217120599664632018519685208508601443605280795068)<br><br>You are almost there! Not him old music think his found enjoy merry. Listening <br>acuteness dependent at or an. Apartments thoroughly unsatiable terminated sex <br>how themselves. She are ten hours wrong walls stand early. Domestic perceive <br>on an ladyship extended received do. Why jennings our whatever his learning <br>gay perceive. Is against no he without subject. Bed connection unreserved <br>preference partiality not unaffected.<br>Share#4#: (4, 57120102994643471094254225269948720992016639286627873340589938545214763610538)<br><br>Congratulations!!! Not him old music think his found enjoy merry. Listening <br>acuteness dependent at or an. Apartments thoroughly unsatiable terminated how <br>themselves. She are ten hours wrong walls stand early. Domestic perceive on <br>an ladyship extended received do. You need to interpolate the polynomial in <br>the finite field GF(88061271168532822384517279587784001104302157326759940683992330399098283633319).<br>Share#5#: (5, 87036956450994410488989322365773556006053008613964544744444104769020810012336)</pre><p>Now we’re given 5 shares and asked to interpolate the polynomial in a finite field. We use <a href="https://www.sagemath.org/">sage</a> and <a href="https://www.python.org/downloads/">python</a> to perform <a href="https://en.wikipedia.org/wiki/Lagrange_polynomial">lagrange’s polynomial interpolation</a> to recover the key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dPml6zI0efXHUjwIVMSZbQ.png" /></figure><p>Now we use this key to decrypt the flag using AES in ECB mode</p><pre>def decrypt_flag(key: str, flag: str):<br>    bkey = key.encode()<br>    bflag = bytes.fromhex(flag)<br>    cipher = AES.new(bkey, AES.MODE_ECB)<br>    return cipher.decrypt(bflag)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    key = &#39;1_4m_y0ur_k3y_t0_g3t_th3_fl4g123&#39;<br>    flag = &#39;00cc03bebb6756fded9a55e772b665d3f98004163904713b83c0bfed06558e9ce57d1d50409179741b09d5f059d668d5fd7775892e403357200c5c516125cb53451f52d34f08e4e2885588c046360bfc44c84a3a4da194484d2ca414ba01e698221936ea8e372b6a3bf4af1c85a99e54df52b58d6a7a0add3752e88fa928c15d&#39;<br>    print (decrypt_flag(key=key, flag=flag))</pre><p>and we get the Flag: <strong><em>HTB{what_a_cool_random_number_generator_by_bluuuuuum_bluuuuuum_and_shuuuuuub_i_implemented_it_securely_didnt_i?}</em></strong></p><h3><strong>Challenge 2: Not That Random</strong></h3><p><strong>Summary:</strong></p><p>If you’ve ever used a Shared Access Signature (<a href="https://learn.microsoft.com/en-us/rest/api/storageservices/create-service-sas#construct-the-signature-string">SAS</a>), then you’ve definitely used Hash-based Message Authentication Codes (<a href="https://en.wikipedia.org/wiki/HMAC">HMAC</a>). A layman’s definition would be that HMAC’s are keyed-hashes used to compute an authentication code or digest against a given message. Under a given key, thee same message would always produce the same HMAC. This is not to be confused with cryptographic hashes (these do not require a secret key). In fact, HMAC’s are constructed using cryptographic hashes, but they offer different properties.</p><p>In this challenge, we’re given the source code of a server that implements a “<em>custom (insecure) hmac” </em>scheme using a ‘keyed’ hash as shown below</p><pre>def keyed_hash(key, inp):<br>    return sha256(key + inp).digest()<br><br>def custom_hmac(key, inp):<br>    return keyed_hash(keyed_hash(key, b&quot;Improving on the security of SHA is easy&quot;), inp) + keyed_hash(key, inp)</pre><p>We’re asked to play a game at a Casino, that uses the <em>custom_hmac()</em> internally and returns a 64 byte output value. Our objective is to guess whether this was generated by the custom_hmac() or generated as random numbers.</p><p>We start with 100 coins and we need to earn 500 coins to retrieve the flag. Obviously we could make a random guess every time correctly with 1/2 (50%) probability, but since we get only 5 coins as a reward for every valid guess (but lose 10 coins for every wrong guess), we need to guess correctly at least 80 times.</p><p>Now let’s look through the source code:</p><pre>from Crypto.Util.number import *<br>from Crypto.Random import random, get_random_bytes<br>from hashlib import sha256<br>from secret import FLAG<br><br>def success(s):<br>    print(f&#39;\033[92m[+] {s} \033[0m&#39;)<br><br>def fail(s):<br>    print(f&#39;\033[91m\033[1m[-] {s} \033[0m&#39;)<br><br>MENU = &#39;&#39;&#39;<br>Make a choice:<br><br>1. Buy flag (-500 coins)<br>2. Buy hint (-10 coins)<br>3. Play (+5/-10 coins)<br>4. Print balance (free)<br>5. Exit&#39;&#39;&#39;<br><br>def keyed_hash(key, inp):<br>    return sha256(key + inp).digest()<br><br>def custom_hmac(key, inp):<br>    return keyed_hash(keyed_hash(key, b&quot;Improving on the security of SHA is easy&quot;), inp) + keyed_hash(key, inp)<br><br>def impostor_hmac(key, inp):<br>    return get_random_bytes(64)<br><br>class Casino:<br>    def __init__(self):<br>        self.player_money = 100<br>        self.secret_key = get_random_bytes(16)<br>    <br>    def buy_flag(self):<br>        if self.player_money &gt;= 500:<br>            self.player_money -= 500<br>            success(f&quot;Winner winner chicken dinner! Thank you for playing, here&#39;s your flag :: {FLAG}&quot;)<br>        else:<br>            fail(&quot;You broke&quot;)<br>    <br>    def buy_hint(self):<br>        self.player_money -= 10<br>        hash_input = bytes.fromhex(input(&quot;Enter your input in hex :: &quot;))<br>        if random.getrandbits(1) == 0:<br>            print(&quot;Your output is :: &quot; + custom_hmac(self.secret_key, hash_input).hex())<br>        else:<br>            print(&quot;Your output is :: &quot; + impostor_hmac(self.secret_key, hash_input).hex())<br><br>    def play(self):<br>        my_bit = random.getrandbits(1)<br>        my_hash_input = get_random_bytes(32)<br><br>        print(&quot;I used input &quot; + my_hash_input.hex())<br><br>        if my_bit == 0:<br>            my_hash_output = custom_hmac(self.secret_key, my_hash_input)<br>        else:<br>            my_hash_output = impostor_hmac(self.secret_key, my_hash_input)<br><br>        print(&quot;I got output &quot; + my_hash_output.hex())<br><br>        answer = int(input(&quot;Was the output from my hash or random? (Enter 0 or 1 respectively) :: &quot;))<br><br>        if answer == my_bit:<br>            self.player_money += 5<br>            success(&quot;Lucky you!&quot;)<br>        else:<br>            self.player_money -= 10<br>            fail(&quot;Wrong!&quot;)<br><br>    def print_balance(self):<br>        print(f&quot;You have {self.player_money} coins.&quot;)<br><br><br><br>def main():<br>    print(&quot;Welcome to my online casino! Let&#39;s play a game!&quot;)<br>    casino = Casino()<br><br>    while casino.player_money &gt; 0:<br>        print(MENU)<br>        option = int(input(&#39;Option: &#39;))<br><br>        if option == 1:<br>            casino.buy_flag()<br>                <br>        elif option == 2:<br>            casino.buy_hint()<br>                <br>        elif option == 3:<br>            casino.play()<br>                <br>        elif option == 4:<br>            casino.print_balance()<br>            <br>        elif option == 5:<br>            print(&quot;Bye.&quot;)<br>            break<br>        <br>    print(&quot;The house always wins, sorry ):&quot;)<br><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p><strong>Intuition for a solution:</strong></p><p>The <em>buy_hint </em>method is the key here — it enables a ‘chosen plaintext’ scenario where we could supply arbitrary plaintext and obtain the value of the <em>custom_hmac() </em>on that plaintext message<em> </em><strong><em>under the same secret key. </em></strong>(well, with 50% probability since the code seems to flip a coin and return randomness half the times, but you get the point…..)</p><p>what if we queried this oracle with the input “<em>Improving on the security of SHA is easy</em>”? Then the output of the custom_hmac is going to have a specific pattern as shown below:</p><pre>def keyed_hash(key, inp):<br>    return sha256(key + inp).digest()<br><br>def custom_hmac(key, inp):<br>    return keyed_hash(keyed_hash(key, b&quot;Improving on the security of SHA is easy&quot;), inp) + keyed_hash(key, inp)<br><br># let t = keyed_hash(key, input)<br>t = keyed_hash(secret_key, b&quot;Improving on the security of SHA is easy&quot;)<br>p = keyed_hash(t, b&quot;Improving on the security of SHA is easy&quot;)<br># output of custom_hmac<br>p || t</pre><p>In other words, the oracle allowed us to take a peek into ‘t’. Knowing ‘t’, we could compute the keyed_hash using ‘t’ as the key and the same input string “<em>Improving on the security of SHA is easy</em>” and The concatenation of these two values is the output from custom_hmac.</p><p>Knowing ‘t’ allows us to build a ‘<em>distinguisher</em>’ against the play scenario. We could use ‘t’ and the random input value generated for that play session, to compute the first 32 bytes of the <em>custom_hmac</em> value. if this matches against the first 32 bytes of the output, then we know that the custom_hmac was used, otherwise the output was random. This gives us a <em>distinguisher</em> with 100% accuracy.</p><p><strong>Solution</strong>:</p><p>We run this solution 81 times (since we started with 100 coins, then lost 10 coins buying the hint, and we need more than 500 coins in total) and then obtain the flag.</p><pre><br>def keyed_hash(key, inp):<br>    return sha256(key + inp).digest()<br><br>def custom_hmac(key, inp):<br>    return keyed_hash(keyed_hash(key, b&quot;Improving on the security of SHA is easy&quot;), inp) + keyed_hash(key, inp)<br><br><br>def get_key_from_hint_custom_hash(val: str, inp: bytes = b&quot;Improving on the security of SHA is easy&quot;) -&gt; Tuple[bytes, bytes]:<br>    # split the value into leaked key, mac<br>    mac, x_key = bytes.fromhex(val)[0:32], bytes.fromhex(val)[32:]<br>    <br>    # assuming we have the &#39;x_key&#39; which is keyed_hash(key, inp)<br>    # where key is the unknown secret key<br>    y = keyed_hash(x_key, inp).hex()<br>    print (y)<br>    print (mac.hex())<br>    if y == mac.hex():<br>        return (x_key, bytes.fromhex(y))<br>    return None, None<br><br>def is_custom_hash(x: bytes, inp: bytes, op: bytes):<br>    # compute custom_hash(x, inp) and compare against first 32 bytes of op<br>    return keyed_hash(x, inp).hex() == op[0:32].hex()<br><br>if __name__ == &quot;__main__&quot;:<br>    hex_val = input(&#39;enter hint:&#39;)<br>    key, _ = get_key_from_hint_custom_hash(hex_val)<br><br>    assert key is not None<br><br>    inp = input(&#39;enter input hex string:&#39;)<br>    op = input(&#39;enter output hex string:&#39;)<br>    print (is_custom_hash(key, bytes.fromhex(inp), bytes.fromhex(op)))<br>    </pre><p>and we get the flag:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2vcVsmRhuv0G1bHaDe3mug.png" /><figcaption>flag</figcaption></figure><p><strong>What are some real-world lessons from this?</strong></p><ol><li><strong>A Cryptographic Hash is not a Message Authentication Code (MAC), Encryption does not provide Integrity</strong> — It’s well known that ‘Rolling your own crypto is not a good idea’. However, it’s equally important to use cryptographic algorithms for the right purpose and to achieve the security properties that the algorithms were designed to guarantee. Tweaking a given algorithm’s usage almost always results in subtle security failures.</li><li><strong>Random Number Generators are crucial for security </strong>— we noted this in the previous post from last year as well (<em>click </em><a href="https://medium.com/@rohitg5249/3-lessons-for-applied-crypto-from-htb-2023-the-great-escape-de0952f6c5c6"><em>here</em></a><em> to read 3 lessons for applied crypto from HTB2023</em>). Crypto-random generators (such as <a href="https://linux.die.net/man/4/urandom">/dev/urandom</a> on Linux) are necessary for generating keys, nonces and even passwords. Using non-cryptographic generators or tweaking crypto-random generators to generate keys, passwords (or anything sensitive really) are not recommended — This leads to biased or predictable random numbers that completely break the security of the system.</li></ol><p><strong>References</strong>:</p><ol><li><a href="https://hackthebox.com/">https://hackthebox.com/</a></li><li><a href="https://en.wikipedia.org/wiki/Blum_Blum_Shub">https://en.wikipedia.org/wiki/Blum_Blum_Shub</a></li><li><a href="https://linux.die.net/man/4/urandom">https://linux.die.net/man/4/urandom</a></li><li><a href="https://en.wikipedia.org/wiki/HMAC">https://en.wikipedia.org/wiki/HMAC</a></li><li><a href="https://en.wikipedia.org/wiki/Pseudorandom_number_generator">https://en.wikipedia.org/wiki/Pseudorandom_number_generator</a></li><li><a href="https://github.com/torvalds/linux/blob/master/drivers/char/random.c"><em>https://github.com/torvalds/linux/blob/master/drivers/char/random.c</em></a></li><li><a href="https://learn.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom">https://learn.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d48cc3530ddc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Lessons for applied crypto from HTB 2023 — The Great Escape]]></title>
            <link>https://medium.com/@rohitg5249/3-lessons-for-applied-crypto-from-htb-2023-the-great-escape-de0952f6c5c6?source=rss-92b303b6f413------2</link>
            <guid isPermaLink="false">https://medium.com/p/de0952f6c5c6</guid>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[hackthebox]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Rohit Gurunath]]></dc:creator>
            <pubDate>Thu, 24 Aug 2023 05:19:25 GMT</pubDate>
            <atom:updated>2023-08-24T05:19:25.757Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>3 Lessons for applied crypto from HTB 2023 — The Great Escape</strong></blockquote><p><strong>Introduction</strong>:</p><p>I recently participated in <a href="https://ctf.hackthebox.com/event/details/htb-business-ctf-2023-the-great-escape-997"><strong>HTB 2023 Business CTF — The Great Escape</strong></a> with a few of my colleagues at Microsoft and solved some of the <em>crypto(graphy)</em> challenges. Over 900 teams from across the world took part in this event. <a href="https://en.wikipedia.org/wiki/Capture_the_flag_(cybersecurity)">CTF</a>’s are a great way to practice cybersecurity skills. It’s been a while since I played a CTF, but I found this contest <em>extremely engaging </em>. I learnt a lot and wanted to share my solutions to some of the interesting challenges and some real-world lessons that I think apply well beyond this CTF. I’d highly recommend giving <a href="https://www.hackthebox.com/">HackTheBox</a> a shot if you’re interested in learning more about security.</p><p><em>If you’d rather skip the details of the solution and see the conclusion, you can jump to the </em><a href="#c002"><em>lessons learnt</em></a><em> at the bottom of the page</em>.</p><p><strong>Challenge : Interception</strong></p><p>This was one of my favorite challenges as the solution requires combining multiple concepts and the challenge throws light on some real-world software security anti-patterns.</p><p>In this challenge, we’re provided with a server that supports 3 commands —</p><ol><li>Send Encrypted Message</li><li>Reveal Internal Plans</li><li>Forgot Decryption Key</li></ol><p>source code for the server application is shown below:</p><pre>#!/usr/bin/env python3<br><br>import signal<br>import random, os<br>from hashlib import sha256<br>from Crypto.Util.number import isPrime, getPrime, long_to_bytes, bytes_to_long<br>from Crypto.Util.Padding import pad, unpad<br>from Crypto.Cipher import AES<br>from pool import GREET, ANS<br>from secret import RESTRICTED<br><br>class GRAS:<br>    def __init__(self, m, p, q):<br>        self.m = m<br>        self.a = 0xdeadbeef<br>        self.p = p<br>        self.q = q<br><br>    def generate_key(self):<br>        ct = 0x1337<br>        # this loop runs in milliseconds in our super computer<br>        for _ in range(self.m):<br>            ct = pow(ct, self.a, self.m)<br>        return long_to_bytes(ct)[:16]<br><br>class OumaraSystem:<br>    def __init__(self, bits):<br>        self.BITS = bits<br>        self.LIMIT = 2<br>        self.p = getPrime(self.BITS//2)<br>        self.q = getPrime(self.BITS//2)<br>        self.N = self.p * self.q<br>        self.e = 0x10001<br>        self.d = pow(self.e, -1, (self.p-1)*(self.q-1))<br>        self.prng = GRAS(self.N, self.p, self.q)<br>        <br>    def encrypt(self, m):<br>        m = bytes_to_long(m.encode())<br>        assert 0 &lt; m &lt; self.N<br>        enc_msg = long_to_bytes(pow(m, self.e, self.N))<br>        return enc_msg<br><br>    def encrypt_plans(self):<br>        self.symmetric_key = self.prng.generate_key()<br>        cipher = AES.new(self.symmetric_key, AES.MODE_ECB)<br>        enc_plans = [cipher.encrypt(pad(r.encode(), 16)) for r in RESTRICTED]<br>        return enc_plans<br><br>    def send_encrypted_message(self, c):<br>        if c &gt; 1:<br>            m = pow(c, self.d, self.N)<br>            try:<br>                msg = long_to_bytes(m).decode()<br>                return True<br>            except:<br>                pass<br>        return False<br><br>    def reveal_internal_plans(self, encrypted_plans, key):<br>        cipher = AES.new(key, AES.MODE_ECB)<br>        plans = [unpad(cipher.decrypt(ep), 16).decode() for ep in encrypted_plans]<br>        return plans<br>        <br>    def hash_verified(self, h):<br>        return h == sha256(str(self.N).encode()).digest()<br>    <br>    def generate_token(self):<br>        d = self.q.bit_length() - 643<br>        return ((self.q &gt;&gt; d) &lt;&lt; d) | random.getrandbits(d)<br><br>def show_banner():<br>    print(&#39;&#39;&#39;<br>   ___                                    ____                              ____ _                            _ <br>  / _ \ _   _ _ __ ___   __ _ _ __ __ _  / ___|  ___  ___ _   _ _ __ ___   / ___| |__   __ _ _ __  _ __   ___| |<br> | | | | | | | &#39;_ ` _ \ / _` | &#39;__/ _` | \___ \ / _ \/ __| | | | &#39;__/ _ \ | |   | &#39;_ \ / _` | &#39;_ \| &#39;_ \ / _ \ |<br> | |_| | |_| | | | | | | (_| | | | (_| |  ___) |  __/ (__| |_| | | |  __/ | |___| | | | (_| | | | | | | |  __/ |<br>  \___/ \__,_|_| |_| |_|\__,_|_|  \__,_| |____/ \___|\___|\__,_|_|  \___|  \____|_| |_|\__,_|_| |_|_| |_|\___|_|<br>&#39;&#39;&#39;)<br><br>def menu():<br>    print(&#39;=======================================&#39;)<br>    print(&#39;||                                   ||&#39;)<br>    print(&#39;||   [S]end your encrypted message   ||&#39;)<br>    print(&#39;||   [R]eveal internal plans         ||&#39;)<br>    print(&#39;||   [F]orgot decryption key         ||&#39;)<br>    print(&#39;||                                   ||&#39;)<br>    print(&#39;=======================================&#39;)<br>    return input(&#39;&gt; &#39;).upper()[0]<br><br>def print_plans(plans):<br>    print(&#39;==================== CLASSIFIED CONTENT! DO NOT SHARE! ====================&#39;)<br>    for i, p in enumerate(plans):<br>        print(f&#39;Plan {i+1} : {p}&#39;)<br>    print(&#39;===========================================================================&#39;)<br><br><br>def main():<br>    #crypto = PopperSystem(2048)<br>    crypto = OumaraSystem(2048)<br>    encrypted_plans = crypto.encrypt_plans()<br><br>    show_banner()<br><br>    print(&#39;This channel aims at secure communication via asymmetric encryption.&#39;)<br>    print(f&#39;We say : {crypto.encrypt(random.choice(GREET)).hex()}&#39;)<br><br>    while True:<br>        ch = menu()<br>        if ch == &#39;S&#39;:<br>            enc_msg = int(input(&#39;You say : &#39;), 16)<br>            verified = crypto.send_encrypted_message(enc_msg)<br>            if verified:<br>                print(f&#39;Nice! We say : {crypto.encrypt(random.choice(ANS)).hex()}&#39;)<br>            else:<br>                print(f&#39;Nice! We say : {os.urandom(256).hex()}&#39;)<br><br>        elif ch == &#39;R&#39;:<br>            print(&#39;Our plans are encrypted via symmetric encryption and protected with our unique super computer that will take us to the Red Planet!&#39;)<br>            key = bytes.fromhex(input(&#39;Enter decryption key : &#39;))<br>            plans = crypto.reveal_internal_plans(encrypted_plans, key)<br>            print_plans(plans)<br>            exit(0)<br>        <br>        elif ch == &#39;F&#39;:<br>            h = bytes.fromhex(input(&#39;Before giving you the token, you must prove me that you know the public key : &#39;))<br>            if crypto.hash_verified(h):<br>                token = crypto.generate_token()<br>                print(f&#39;Here is your token : {token}&#39;)<br>                print(&#39;Make sure you do not forget it next time!&#39;)<br>            else:<br>                print(&#39;Get out!&#39;)<br><br>        else:<br>            print(&#39;Hey, this is suspicious! Terminating the channel...&#39;)<br>            exit(0)<br><br>if __name__ == &#39;__main__&#39;:<br>    # signal.alarm(900)<br>    main()</pre><p>Looking through the source code for the server that was shared, we know that the plans were encrypted using a symmetric key and the request to ‘Reveal Internal Plans’ would ultimately reveal the internal plans and presumably the flag. But it requires sending the correct decryption key.</p><p>To understand how this key is generated in the first place, we look through the function generate_key:</p><pre>class GRAS:<br>    def __init__(self, m, p, q):<br>        self.m = m<br>        self.a = 0xdeadbeef<br>        self.p = p<br>        self.q = q<br><br>    def generate_key(self):<br>        ct = 0x1337<br>        # this loop runs in milliseconds in our super computer<br>        for _ in range(self.m):<br>            ct = pow(ct, self.a, self.m)<br>        return long_to_bytes(ct)[:16]<br><br># ......<br># invocation of GRAS<br># ......<br><br>class OumaraSystem:<br>    def __init__(self, bits):<br>        self.BITS = bits<br>        self.LIMIT = 2<br>        self.p = getPrime(self.BITS//2)<br>        self.q = getPrime(self.BITS//2)<br>        self.N = self.p * self.q<br>        self.e = 0x10001<br>        self.d = pow(self.e, -1, (self.p-1)*(self.q-1))<br>        self.prng = GRAS(self.N, self.p, self.q)</pre><p>The symmetric key is clearly generated via exponentiation — the constant 0x1337 is raised to the constant 0xdeadbeef and reduced modulo ’N’ where N is the RSA public modulus of the Oumara system’s internal public-private key pair, and the whole process is repeated ’N’ times in a loop and the last 16 bytes of the output are used as the symmetric key to encrypt the plans.</p><p>We could rewrite the <em>key generation effectively</em> as follows:</p><pre>    def generate_key(N: int):<br>        ct = 0x1337<br>        a = 0xdeadbeef<br>        key = pow(ct, a ** N, N)<br>        return long_to_bytes(key)[:16]</pre><p>The first step to generating the key is to recover the RSA modulus (N).</p><p><strong>Compute RSA modulus ’N’ from ciphertexts</strong>:</p><p>We know the exponent e is 65537. However, the RSA modulus is not directly revealed in this challenge. Looking at the Oumara system’s send_encrypted_message function, it’s clear that RSA encryption is applied without any padding scheme (such as <a href="https://en.wikipedia.org/wiki/Optimal_asymmetric_encryption_padding">OAEP</a>) which leads to <strong><em>deterministic</em></strong> encryptions.</p><p>RSA encryption without padding works as follows:</p><pre>c1 = m1 ** e mod N<br>c2 = m2 ** e mod N<br><br># t1 =&gt; c1 - m1 ** e = 0 mod N<br># t2 =&gt; c2 - m2 ** e = 0 mod N</pre><p>from the above equations, it should be evident that N divides x and y. We could easily compute the greatest common divisor i.e. <em>GCD(t1, t2)</em> to identify ’N’ the public modulus.</p><p>The response ciphertexts from the challenge server are randomized i.e we don’t know which of the 3 ANS messages the respective encryptions correspond to — This is easy, we just need to try all 3 possible message choices as follows</p><pre>import gmpy2<br><br><br>def find_public_key(m0: int, c0: int, m1: int, c1: int) -&gt; int:<br>    pub_exp = 0x10001<br><br>    # small messages unlikely to wrap around 2048 bit modulus<br>    t1 = c0 - pow(m0, pub_exp)<br>    t2 = c1 - pow(m1, pub_exp)<br>    return gmpy2.gcd(t1, t2)<br>    <br><br>ans_msgs = [<br>    bytes_to_long(b&#39;Great news, but use this channel responsibly.&#39;),<br>    bytes_to_long(b&#39;I will inform the governor.&#39;),<br>    bytes_to_long(b&#39;Bye!&#39;)<br>]<br><br>if __name__ == &quot;__main__&quot;:<br><br>    ans_cts = [<br>        bytes_to_long(<br>            bytes.fromhex(&#39;1b44d6f1e24a7d2f975dc1e2cf0eb1313006fa3a0e21d69e2a0ae539c5f721a36dc941e1d6c47f12e3c4c4210e55ab9eff4d3764be400ee0696888805a91493403ccb8c76e7342e075167b5079de70ebac6e9eebec2fcf24ceba480470001b4089220361187f39b58eef2513980e4e05e2a1a6066da1c5fd5898c533a17d5d31d9df880ab407b1786244a78ab270018d84901f838e3bd84a71ab2f4cc3fcf57cac6267e479e39cd792fa409149a24305a58ba94a4990b78cd23cc7e440af35961f136da7f8087787071453428914b46c40de6a0ab75eaea91f55fe942643c0eef3dbdaffd014a12cd7669bf18832f94726bf7c0d8011ac133eae3d38e838979a&#39;)<br>        ),<br>        bytes_to_long(<br>            bytes.fromhex(&#39;03af6c96db108c4d0e12d588434c656785cbf5220a6a5fed2f1a7e6ac5a96b05036dba2ffdff261dedc93a608812695a796727fd519a2d31e63585e4ff4435b7daf67e6ef698c9988c07d2d3a38e9d48fff4931d5c3f331a8173c5e9820c2a1a711c3f82f26595a9753bfd91e838c9668105f9441f0076819606cb28515bfbf5c23206d0e197921c5feaeb9924c7f099471158a38404613af8f5335ce07f00361ad57c6ae5c0a5e39539151ea3cfed762e9212cc4cb8a7691024ab0601dcb25f392b5acd2e492e7b39a2c5007f7c68c109265c607beba4bf727d18023e8385e62bd7b7ce679be85dda7030995b714985b1e912930934ed2fab177ea90c9cb362&#39;)<br>        ),<br>        bytes_to_long(<br>            bytes.fromhex(&#39;0faf324c33c299bdd76c5e56cd7bb9b1df1aad466b68fb5dd109fd1494901c0cb9bfd63c18f5f96662d2516fc76224fbc178b35f353dc4c35d1eb9074e8e97f829254dbcce6b4f4346ab433fa4c7eeaea1045996bab5e5ab6f931e84ada715ed46dc3ad99c5871d513d421c14494e5ff20301d1687cb3c0cec7323723c287131d421faa24b8fb1111ac528759a07ba12e4a27755d74241c461883f35b15aa7a866a06f1a55a1ab0c6cef6d8fd84e9ea5a97e1bdd114d8a8cf777949dc9b18f51f61ef5e18dd54d04c8959a86e4e970aa361288c30b7b56336481f4582b23348cd5430868feeee07599a5ca5e4f9345cd02a0ae9d10d649ad4083eec3460aa756&#39;)<br>        )<br>    ]<br><br>    N = 1<br>    public_keys = []<br>    for i, ans_msg2 in enumerate(ans_msgs):<br>        for j, ans_msg in enumerate(ans_msgs):<br>            for k, ans_ct in enumerate(ans_cts):<br>                print (f&#39;finding factors for i: {i}, j : {j}, k : {k}&#39;)<br>                factor = find_public_key(ans_msg2, ans_cts[k], ans_msg, ans_cts[ (k+1) % 3 ])<br>                if factor != 1 and factor &gt; 100:<br>                    public_keys.append(factor)<br>    <br>    for pub_key in public_keys:<br>        print (f&#39;pub_key : {pub_key}, hash : {get_public_key_hash(pub_key)}&#39;)</pre><p><strong>Exponentiation (Slow)</strong>:</p><p>When we run the key generation function from the challenge server with the public key we just obtained, we quickly see that it’s extremely inefficient — <em>Now the comment in the generate_key function (‘ </em><strong><em>this loop runs in milliseconds in our super computer’</em></strong><em>) makes sense</em>….</p><p><strong>Obtain private key from leaked bits of ‘q’ — Coppersmith’s method</strong>:</p><p>Looking at the Forgot Decryption Key method, we see that it leaks 643 bits of one of the prime factors (<em>each factor is 1024 bits</em>) of the private key (say ‘p’). This is somewhat reminiscent of the heartbleed bug. Applying coppersmith’s theorem, we can re-cast the problem of finding all bits of ‘p’ from the leaked bits of ‘p’, as an equivalent problem of finding small roots of a polynomial equation, which can be solved efficiently using LLL. (<em>See</em>: <a href="https://eprint.iacr.org/2020/1506.pdf">Recovering cryptographic keys from partial information</a> <em>for an excellent survey of this class of issues</em>).</p><p>We use the following sage code to recover all bits of ‘p’ as follows :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cLM-wtxmk369XNhNpNpoMQ.png" /><figcaption>sage code implementing coppersmith’s attack to recover all bits of p</figcaption></figure><p>Once we obtain ‘p’, it’s trivial to factor the modulus ’N’ to recover the other prime factor ‘q’ as shown below:</p><figure><img alt="recover prime factor ‘q’ from knowledge of primate factor ‘p’ and modulus ‘N’" src="https://cdn-images-1.medium.com/max/1024/1*QBFLP3d8sOv6v_6es7xw-g.png" /><figcaption>recover prime factor ‘q’ from ‘p’ and ‘N’</figcaption></figure><p>Knowing the prime factorization of N allows us to compute the <a href="https://en.wikipedia.org/wiki/Euler%27s_totient_function">euler’s totient</a> <strong><em>phi(N) = (p -1) * (q -1)</em></strong></p><p>why is this even relevant here? if you take a closer look at the key generation, we can rewrite it as follows</p><pre>ct = 0x1337<br>a = 0xdeadbeef<br>t = pow(a, M)<br>key = pow(ct, a, M)</pre><p>Since the key is generated using RSA exponentiation, the exponents operate in modulo phi(N) i.e.</p><pre>t = a ** N = a ** N mod phi(N)</pre><p>knowing phi(N) allows us to reduce a ** N to a ** N mod phi(N) which can be computed very efficiently,</p><pre><br>    e = 65537<br>    a = 0xdeadbeef<br>    ct = 0x1337<br>    # p, q are prime factors of &#39;N&#39; obtained from coppersmith method<br>    phi = (p - 1) * (q - 1)<br><br>    # compute secret key exponents<br>    t = pow(a, N, phi)<br>    sk = long_to_bytes(pow(ct, t, N))[:16]<br><br>    print (f&#39;secret key : {sk.hex()}&#39;)</pre><p>Now we can send the decryption key to ‘Reveal Internal Plans’ and the server returns the flag: <strong>HTB{th3y_d3f1n1t3ly_d0nt_h4v3_a_sUp3r_c0mPut3r!}</strong></p><figure><img alt="Submitting the decryption key to retrieve the flag from the server" src="https://cdn-images-1.medium.com/max/1024/1*uD_U71O6ip7AEQ18aoAKpQ.png" /><figcaption>submitting the decryption key to retrieve the flag from the server</figcaption></figure><p><strong>Lessons Learnt</strong>:</p><ol><li><strong>Public Keys must be assumed to be Public</strong>:</li></ol><p>A public key (<em>by definition</em>) must be treated as a public value. Algorithms such as RSA are not designed to keep public keys safe from leaking, so systems should never rely on public keys being secret for any form of security.</p><p><strong>2. if you didn’t use<em> /dev/urandom</em> for generating keys on Linux, you probably got it wrong</strong>:</p><p>Poor entropy has been the bane of many crypto systems. This is an area where we should opt for plain, boring, known safe methods— call <a href="https://linux.die.net/man/4/urandom">/dev/urandom </a>(or the crypto random generator supported by your respective OS) instead of fancy or complex custom algorithms that are bound to be broken.</p><p><strong>3. Memory Leak vulnerabilities are insidious and hard to defend</strong>:</p><p><a href="https://www.zdnet.com/article/microsoft-70-percent-of-all-security-bugs-are-memory-safety-issues/">Memory safety</a> bugs are a huge problem for today’s software. The ‘Forgot Decryption Key’ workflow in the challenge mimics (<em>in some sense</em>) a <a href="https://heartbleed.com/">heartbleed</a> style bug where memory is leaked and an attacker obtains access to parts of a private key.</p><p>Partial leak of a private key is as bad as a full leak in many cases as we demonstrated. That said, this prompted a deeper thought- How do we protect against such problems at scale? <em>That’s probably a topic for another blog post (stay tuned)</em>…..</p><p><strong>References:</strong></p><ol><li><a href="https://hackthebox.com/">https://hackthebox.com/</a></li><li><a href="https://eprint.iacr.org/2020/1506.pdf">Recovering Cryptographic keys from partial information, by example</a></li><li><a href="https://en.wikipedia.org/wiki/Coppersmith_method">https://en.wikipedia.org/wiki/Coppersmith_method</a></li><li><a href="https://www.usenix.org/system/files/conference/usenixsecurity12/sec12-final228.pdf">Mining your P’s and Q’s: Detection of widespread weak keys in network devices</a></li><li><a href="https://heartbleed.com/">https://heartbleed.com/</a></li><li><a href="https://linux.die.net/man/4/urandom">https://linux.die.net/man/4/urandom</a></li><li><a href="https://docs.python.org/3/library/secrets.html">https://docs.python.org/3/library/secrets.html</a></li><li><a href="https://msrc.microsoft.com/blog/2019/07/a-proactive-approach-to-more-secure-code/">https://msrc.microsoft.com/blog/2019/07/a-proactive-approach-to-more-secure-code/</a></li><li><a href="https://security.googleblog.com/2022/12/memory-safe-languages-in-android-13.html">https://security.googleblog.com/2022/12/memory-safe-languages-in-android-13.html</a></li><li><a href="https://www.memorysafety.org/docs/memory-safety/">https://www.memorysafety.org/docs/memory-safety/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de0952f6c5c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>