<?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 Alborz Nazari on Medium]]></title>
        <description><![CDATA[Stories by Alborz Nazari on Medium]]></description>
        <link>https://medium.com/@alborznazari4?source=rss-ed01f24e0e3a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7_yahmDISzBslnNf-bpGUQ.jpeg</url>
            <title>Stories by Alborz Nazari on Medium</title>
            <link>https://medium.com/@alborznazari4?source=rss-ed01f24e0e3a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 19:32:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alborznazari4/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[Your Firewall Can’t Read English: What Linux and Windows Hardening Get Right, and Where It Breaks…]]></title>
            <link>https://medium.com/@alborznazari4/your-firewall-cant-read-english-what-linux-and-windows-hardening-get-right-and-where-it-breaks-6e38f9ed68a8?source=rss-ed01f24e0e3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e38f9ed68a8</guid>
            <category><![CDATA[vps-hosting]]></category>
            <category><![CDATA[ai-safety]]></category>
            <category><![CDATA[llm-safety]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linux-hardening]]></category>
            <dc:creator><![CDATA[Alborz Nazari]]></dc:creator>
            <pubDate>Mon, 19 Oct 2026 11:35:28 GMT</pubDate>
            <atom:updated>2026-10-19T11:35:28.446Z</atom:updated>
            <content:encoded><![CDATA[<h3>Your Firewall Can’t Read English: What Linux and Windows Hardening Get Right, and Where It Breaks for LLM Agents</h3><p><strong>1. The claim and its premises</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c7hIOjFYrg1F1xhodsNdOQ.png" /></figure><p>Most of what we do to harden Linux and Windows carries over to LLM systems. One rule does not, and that gap decides where LLM security controls have to live. Three points support this. First, hardening limits what an attacker can reach and do once inside. Second, on a <strong>vps cloud </strong>or a <strong>Windows host</strong>, the entry points are known and can be listed. Run <strong>ss -tulpn</strong> on a fresh server, and you get a short list of listening services. You can name, justify, or shut down each one. Third, an LLM application has no such list. Its input is any text that reaches the context window: the user’s message, a retrieved PDF, a web page, the output of a tool. So the question is not whether OS hardening applies to LLMs. The question is which parts of it survive the move from a short, known list of entry points to an open-ended one.</p><p><strong>2. Testing the analogy: where it holds</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iyow1aOKVtZQUKY1nwY5eA.png" /></figure><p>A Linux service account and an AI agent have one thing in common that matters: both act with delegated authority on someone else’s behalf. That is why least privilege transfers almost completely. A per-service Linux user maps to a per-agent identity. A restricted <strong>sudoers entry </strong>maps to scoped tool permissions.<strong> systemd’s NoNewPrivileges</strong> and <strong>ProtectSystem=strict</strong> map to a sandbox around code execution. Windows LAPS, which stops one stolen password from unlocking every machine, maps to short-lived API tokens issued per task. The mapping holds because the damage from a compromise depends on what the account was allowed to touch, not on how it was compromised. A web service exploited through a buffer overflow and an agent hijacked by a hostile email can both reach only what their permissions allow.</p><p><strong>3. Where the analogy breaks: a deductive case</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LV7dkeZBm_Ey9NCOdPmPOQ.png" /></figure><p>Default deny works when you can decide, before anything runs, whether it is allowed. A firewall checks a port and a protocol. <strong>WDAC </strong>checks a signed binary. An LLM cannot make that decision for text, because it cannot reliably tell instructions from data. A command hidden in an email is processed the same way as the system prompt. So you cannot <strong>allowlist</strong> what the model reads. The alternative is filtering, and a filter is a <strong>blocklist</strong>, which will always miss something when the input is open-ended language.</p><blockquote>History shows the same pattern. SQL injection was not solved by better filters. It was solved by parameterized queries, which keep code and data in separate places.</blockquote><p>LLMs have no such separation yet. So the defense has to move from inputs to actions. <strong>Simon Willison’s “lethal trifecta”</strong> gives the practical rule: an agent that has private data, reads untrusted content, and can send data out is exploitable. You cannot clean the content, so you remove one of the other two.</p><p><strong>4. How many examples prove a system is safe?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0NrM2NRLOOgEbEkKM58D2A.png" /></figure><p>On a server, one<strong> Lynis audit </strong>is enough, because the system is deterministic and running the scan twice gives the same result. LLM behavior is probabilistic, so one clean run proves much less. Suppose you run 50 prompt-injection attempts and all 50 fail. It is tempting to call the system safe, but the numbers do not support that. By the “rule of three,” zero successes in 50 trials only shows, with <strong>95%</strong> confidence, that the true success rate is below about<strong> 6%</strong>. At 6%, an attacker who retries 50 times succeeds at least once about 95% of the time. The result also expires. When the provider updates the model, you are testing a different system, much like a kernel upgrade that silently reverts your configuration.</p><blockquote>A sound benchmark reports the rate with a confidence bound, ties it to a pinned model version, and treats one confirmed bypass as stronger evidence than any number of failures.</blockquote><p><strong>5. The strongest objection, and the reply</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SwhGz5-U1pZGAYEf1qkZ0A.png" /></figure><p>The strongest objection is that <strong>prompt injection</strong> is a phase. Models are getting better at telling instructions from content, so in a few releases this will be a solved problem and the controls above will look like scaffolding. That objection depends on an assumption it never states: that a smarter system cannot be talked into things. Skilled engineers still ship memory bugs, which is why browsers run pages in a sandbox. Trained staff still click phishing links, which is why passing the training earns nobody admin rights.</p><p>In terms of cyber crisis management, the knowledge and capability lower the rate. It does not remove the cause, which is that instructions and data arrive through one channel. And a lower rate is not a safe rate. If one attempt in a thousand works, a thousand independent attempts succeed about 63% of the time, and each attempt costs the attacker almost nothing. The claim also cannot lose, because any model that gets injected can be dismissed as not the future one. A claim worth acting on names a model, an attack set, a success rate, and the result that would prove it wrong, and someone other than the vendor has to repeat it. The vendor’s incentive does not make the claim false. It only means the claim needs a second source. Until then, we are deciding without knowing, so decide by the worst case. If the objection is right, the controls cost some engineering time. If it is wrong, they are all that stands between a hijacked agent and your keys. And if the objection is right in its strongest form, a model with a boundary no text can talk it across, the fix is structural, the way parameterized queries were for SQL. That is the position of this article. Harden the VPS as before, treat the model as an untrusted user holding a service account, and build the wall out of permissions, rabbit-proof.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e38f9ed68a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lox Under the Microscope: Design Trade-offs, Measurable Faults, and What Real Languages Do…]]></title>
            <link>https://medium.com/@alborznazari4/lox-under-the-microscope-design-trade-offs-measurable-faults-and-what-real-languages-do-e01637e5fd7f?source=rss-ed01f24e0e3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e01637e5fd7f</guid>
            <category><![CDATA[dynamic-analysis]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[fuzzing]]></category>
            <category><![CDATA[security-engineering]]></category>
            <dc:creator><![CDATA[Alborz Nazari]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 15:58:11 GMT</pubDate>
            <atom:updated>2026-07-15T14:11:39.902Z</atom:updated>
            <content:encoded><![CDATA[<h3>Lox Under the Microscope: Design Trade-offs, Measurable Faults, and What Real Languages Do Differently</h3><blockquote>chapter 1/3: Theory, Language Features, Design Patterns, and Programmer’s Responsibility</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pPyMer7pCFKcJhjhzJSOPg.png" /><figcaption><em>What you actually learn from implementing one, and why most of it is about choices you never see.</em></figcaption></figure><p><em>Hint: The outcome metrics start in chapter 2/3.</em></p><p><em>Hint: Before reading, be aware that any terminology mentioned in the article appears in italics</em><strong><em>.</em></strong></p><blockquote>Core Design Principle</blockquote><p>Implementing a <em>compiler </em>or <em>interpreter </em>requires orchestrating a series of transformations: <em>lexical analysis, parsing, semantic analysis, </em>and <em>execution</em>. The most effective designs keep these stages clearly separated, with each component communicating through well-defined abstract interfaces. This <em>separation of concerns</em> is not just a compiler technique — it reflects broader principles of good <em>software architecture</em>, where<em> loose coupling</em><strong> </strong>and <em>clear abstractions</em> make systems easier to understand, extend, and maintain.</p><p><strong><em>Language design</em></strong> is governed by inherent trade-offs between <em>expressiveness</em> and<em> implementation complexity.</em> <em>High-level language</em> features such as <em>garbage collection</em>, <em>first-class closures,</em> and <em>dynamic dispatch</em> introduce substantial additional <em>machinery </em>in both the <em>compiler </em>and <em>runtime</em>. Languages that simultaneously pursue <em>high-level productivity</em> and fine-grained low-level control — such as <em>C++ </em>and <em>Rust </em>— must encode significantly more semantic rules and invariants into the compiler, resulting in greater implementation costs, verification difficulties, and long-term maintenance burdens compared to languages that make clearer trade-offs in either direction.</p><blockquote>Static vs Dynamic Typing</blockquote><p><em>Static </em>versus <em>dynamic typing </em>is one of the most visible differences. Statically typed languages perform<strong> </strong><em>type checking</em><strong> </strong>at<strong> </strong><em>compile time.</em> A type misuse produces an error before the program runs. <em>First compile, then run!</em><strong> </strong><em>Dynamically typed languages </em>defer most of this work to the runtime. In comp<em>arison with C</em>, for example, types are <em>declared explicitly</em> as a rule of thumb; functions often require<em> forward declarations </em><strong>— </strong>the function should be declared first at the top and then defined — thus the compiler enforces consistency when checking the definition block to ensure the function is declared. <em>Python </em>and similar languages remove these requirements, allowing more <em>flexibility </em>at the cost of catching certain errors only when the program runs.</p><p><em>Static typing</em> buys you <em>compile-time safety</em>, but you pay for it in the implementation: you have to write a whole type-checking pass that a dynamic language skips.<em> Dynamic typing</em> doesn’t make that work disappear; it just defers it to runtime, where values carry their own type tags, and checks happen as the program runs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*owwvuh8skPmm9_sTVyWdfQ.png" /><figcaption>Each feature aligns with the Design Philosophy, Hardware Limitations, Trade-offs, and Problems they aim to solve and help us achieve.</figcaption></figure><p>This is how <em>C++</em> supports the auto data type, which automatically infers the type instead of <em>manually declaring int, char, double, float, </em>and so on. The trade-off is that <em>readability </em>improves when we use declared data types in C during code review — honestly, there’s no choice but to use<em> type declarations</em>, as the language is <em>statically typed</em>. <em>Here, the point is to first know our objective, then go to the shelf for our language-pickup decision.</em> In <em>static typing</em>, the program can detect<em> bugs </em>through type mismatches at compile time<em>.</em> On the other hand, using <em>auto in </em>C++ reduces code redundancy by removing the need to write data type declarations while still catching errors at compile time, unlike <em>dynamic type matching,</em> which only checks types at <em>runtime</em>.</p><blockquote>Memory Management Paradigms</blockquote><p><em>Memory management</em> is a crucial paradigm to keep in mind when designing programming languages. Back in<em> C, memory allocation</em> and <em>deallocation</em> are the <em>programmer’s responsibility, </em>whereas in<em> Java, the garbage collector (GC) </em>handles<em> memory management </em>automatically through<em> the JVM (Java Virtual Machine), </em>rather than being<em> the programmer’s responsibility</em><strong>.</strong> Check the code segment in <em>C →</em></p><pre>// Static Array (Fixed size, compile-time)<br>int arr[100];<br><br>// Dynamic Array (size decided at runtime)<br>int n;<br>scanf(&quot;%d&quot;, &amp;n);<br>int* arr2 = malloc(n * sizeof(int));   // Dynamic array sized at runtime</pre><p>In<em> C</em>, memory must be managed manually using functions like <strong><em>malloc()</em></strong> and <strong><em>free()</em></strong>. <em>C++</em> inherits this manual memory management from <em>C</em> as a legacy feature. However, in modern <em>C++</em>, it is strongly recommended to use <em>smart pointers </em>instead, as they handle<strong> </strong><em>heap memory</em><strong><em> </em></strong>automatically and are much safer than manual allocation and deallocation. Look at the use of a smart pointer from a <em>.cpp file →</em></p><pre>// Dynamic Memory Allocation for Dynamic arrays<br>// Dynamic Array (Modern way - Recommended)<br>std::vector&lt;int&gt; arr;             // Can grow<br>arr.push_back(10);<br>arr.push_back(20);<br><br>// Another way (using smart pointer)<br>auto arr = std::make_unique&lt;int[]&gt;(100);</pre><p>The last line creates a <em>dynamic array</em> on the heap using a smart pointer. It allocates space for 100 integers on the heap at runtime. The variable <em>arr </em>is a smart pointer that manages this array. Unlike the stack, which is used for short-lived data with automatic allocation and deallocation in <em>C, C++</em>, <em>Java</em>, and <em>Rust</em>, the heap is used when memory needs to be allocated for a longer time at runtime. Yet in <em>Java, </em>for example, all objects are created on the heap and managed automatically by the garbage collector. →</p><pre>int size = 1000;              // Static Array (Size fixed at creation)<br>int[] arr = new int[size];    // Object created on heap at runtime</pre><pre><br>// Dynamic Array (Can grow) Since Java handles Dynamic Array on heap automatic<br>ArrayList&lt;Integer&gt; list = new ArrayList&lt;&gt;();<br>list.add(10);<br>list.add(20);</pre><p><em>Manual memory management</em>, introduced with <em>C</em> by <strong>Dennis Ritchie</strong>, delivered unprecedented <em>low-level control</em> and <em>performance</em>. That same power, however, placed the full burden of <em>allocation </em>and <em>deallocation </em>on the programmer, giving rise to entire classes of bugs — <em>memory leaks</em>, <em>dangling</em> <em>pointers</em>, <em>buffer overflows</em>, and <em>use-after-free errors</em> — that remain among the most common sources of vulnerabilities in systems code today.<em> Apparently, those problems existed long before C. </em>Manual allocation became the programmer’s routine chore. Rust flips that script: dynamic memory is governed by its <em>ownership system</em>, a built‑in safety net that actually works. <em>This is a strong comparison, as Rust solves a problem architecturally different from C’s, while keeping in mind that Rust is a much newer tech stack.</em></p><p>Knowing that most real‑world programs rely on <em>dynamic arrays</em><strong><em> </em></strong>— because input size is almost always an unknown variable — having a convenient, sane way to allocate memory isn’t optional. It’s a must. Any program worth writing depends on it. Here’s a Rust code segment →</p><pre>// Static Array (Fixed size) Not useful for most apps we wish to create<br>let arr: [i32; 100] = [0; 100];<br><br>// Dynamic Array<br>let mut vec = Vec::new();       // Can grow Since Rust manage that auto<br>vec.push(10);                   // by a complete safe-system<br>vec.push(20);</pre><blockquote>Key Insight</blockquote><p>Dynamic data structures are essential for most real programs. A convenient and safe way to manage them is not optional.</p><blockquote>Mutability and Its Consequences</blockquote><p>In <em>C</em>, <em>mutation </em>is<em> explicit, pervasive, and tightly coupled</em> to how memory and scoping work. <em>Variables </em>are <em>mutable </em>by default, and their values are changed through direct assignment. Because <em>C </em>uses manual memory management and <em>pass-by-value semantics </em>for most types, <em>mutation </em>usually requires either modifying a variable in the current scope or passing a pointer so the callee can modify the original data. This design makes mutation cheap and predictable at the hardware level, but it also makes it easy to introduce bugs. <em>Aliasing (having multiple pointers refer to the same memory location)</em> combined with mutation is a frequent source of subtle errors, as one part of the program can unexpectedly change data that another part is relying on. Unlike languages with strong <em>immutability</em> guarantees, <em>C </em>places the burden of tracking which data might be mutated — and when — entirely on the programmer. This is why careful use of <em>const</em>, <em>clear ownership semantics</em>, and <em>defensive copying</em> are considered essential practices when writing <em>Robust C</em> code.<br>In <em>C</em>, everything is <em>mutable </em>unless you mark it <em>const</em>. That default is convenient, and it’s also where a lot of the <em>unsafety </em>comes from. The feature can be applied through <em>values </em>or <em>pointers</em>. The simple causes a classic <em>buffer overflow →</em></p><pre>char buf[10];<br>strcpy(buf, &quot;This string is way too long&quot;); // overflows → memory corruption</pre><p><strong>Heartbleed (CVE-2014–0160)</strong>, disclosed in 2014, is a <em>buffer over-read vulnerability</em> in <em>OpenSSL’s implementation </em>of the <em>TLS/DTLS heartbeat extension. </em>The heartbeat request includes a client-supplied <strong>payload_length </strong>field alongside the actual <em>payload data. </em>The vulnerable code allocated a response buffer sized according to the <em>claimed</em> <strong>payload_length</strong> and copied that many bytes from memory — but never checked that <strong>payload_length </strong>actually matched the payload size the client had sent. An attacker could send a tiny payload (e.g., 1 byte) while declaring a <strong>payload_length </strong>of up to 64KB. The server would then copy 64KB starting from the payload, reading far past the actual request into adjacent heap memory — leaking private keys, session tokens, and other sensitive data back to the attacker in the response.</p><p>The fix added exactly the missing check: validate that the declared <strong>payload_length </strong>does not exceed the actual received record length before using it to determine how many bytes to copy.</p><pre>// Fix: reject the heartbeat if the claimed length is impossible<br>if (1 + 2 + payload + 16 &gt; s-&gt;s3-&gt;rrec.length)<br>    return 0;   // silently discard malformed/oversized request</pre><p>So the core bug wasn’t “trusting the payload value” in the abstract — it was <strong>trusting an attacker-controlled length field without validating it against the size of data actually present</strong>, <strong>and then using that untrusted length to drive </strong>an <em>out-of-bounds memory copy</em>.</p><p><em>Pointers</em> naturally collide with bugs:<em> 1)aliasing bug: </em>when more than one <em>pointer </em>points at a<em> memory location.</em> In this analogy, note that<em> Python dics </em>and<em> lists </em>are <em>mutable </em>for <em>performance reasons </em>irrespective of the hassle trade-off<em>; it’s a conscious decision —</em> can be avoided or picked up by the<em> programmer’s decision.</em></p><pre>a = [1, 2, 3]   # A list object is created; the name &#39;a&#39; is bound to it<br>b = a           # No copy is made - &#39;b&#39; is a second name bound to the SAME object (aliasing)<br>b.append(4)     # Mutates the one shared list, no matter which name you use<br>print(a)        # [1, 2, 3, 4] - &#39;a&#39; sees the change, because a and b ARE the same list</pre><p>2)<em>dangling pointer:</em> <em>use-after-free →</em></p><pre>int *p = malloc(sizeof(int));<br>*p = 42;<br>free(p);<br>*p = 100;        // ← Use-after-free (undefined behavior)</pre><p>3)<em>race problems:</em> <em>language-agnostic </em>approach<em>;</em> <a href="https://medium.com/@alborznazari4/threading-the-needle-race-conditions-atomic-violations-and-the-concurrency-flaws-that-break-b7bfdc2f7993"><em>click</em> </a>for a full article: when two threads mutate the same data with shared references<em>. In penetration testing, endpoints </em>may share resources.<em> [Predictable bug: avoid shared resources or secure them against the latter.] 4)No bounds checking: pointers </em>are limited to <em>C/C++</em>. If we want to offset the same mutable behavior — <em>mutability </em>in Rust- we get an obvious error. That’s why Rust stands out as a language that inherited <em>immutability. </em>Look at the erroneous design thinking that doesn’t fit →</p><pre>fn main() {<br>    let mut x = 5;           // must explicitly say mutable<br>    x = 10;                  // OK<br><br>    let y = 5;<br>    // y = 10;               // Compile error! y is immutable<br>}</pre><p>In conclusion, choosing <em>Rust </em>is more reasonable for both safety and<em> low-level access</em>. <em>C++</em> is vulnerable when using raw pointers (to Be Avoided) and <strong><em>memcpy</em></strong>, as modern <em>C++</em> uses <strong><em>std::span.</em></strong></p><p>These intricacies have been theorized and experimented in computer labs throughout the years. Most well-known languages were invented with unique design philosophies: <em>C, C++, </em>or <em>Go</em> are written for <em>speed</em>, <em>performance</em>, and <em>control</em>. <em>Haskell </em>is written for safety with no <em>side effects;</em> <em>Imperative programming </em>is about <em>how to do things step‑by‑step</em>, while<em> functional programming </em>is about <em>what result you want and which transformations get you there</em>.<em> Haskell </em>defined <em>mutation</em> through a different system called <em>monads</em>—quite<em> an exquisite abstraction and detour.</em><strong><em> </em></strong><em>Rust </em>also allows <em>explicit mutation </em>with <em>strict rules.</em> <em>Swift </em>encourages <em>immutability </em>through the <em>let</em> keyword over <em>var</em>.</p><p><em>JavaScript </em>is<em> memory-safe.</em> It uses <em>automatic garbage collection.</em> The <em>JavaScript </em>engine<em> </em>automatically tracks which objects are still needed and frees memory when it’s no longer used. It’s not permitted to directly manipulate raw memory pointers. You can’t allocate or deallocate memory manually. The language runs inside a <em>sandboxed virtual machine</em>, adding another layer of protection. Nevertheless, it’s<em> feasible </em>to carry out injection and exploitation<em> attacks. JavaScript</em> is fairly safe per se; by design, its exposure to the browser and cookies makes it prone to <em>attacks</em>. Mutability has nothing to do with injection; injection is about <em>untrusted input hitting eval</em>, <em>string-built queries</em>, <em>innerHTML</em>, and <em>immutability </em>doesn’t touch that problem.</p><p><em>Python </em>is designed for <em>simplicity </em>and fast <em>API </em>development: ‘everything is an object’ and ‘objects are mutable’ like lists, while<strong> </strong><em>strings, tuples, &amp; ints</em><strong> </strong>are immutable. <em>Python </em>made lists and dicts mutable for <em>ergonomics </em>and <em>speed</em>, trading away the safety that <em>immutability </em>would buy. It enhances the more <em>general-purpose language</em><strong><em> </em></strong>approach for Python. Why? As features of programming languages change — here <em>mutability </em>&amp; its antithesis — the <em>algorithmic thinking </em>and <em>code design</em> will be drastically influenced. One important part of adding <em>mutability </em>lies in the thinking mechanism and the more general-purpose set of thinking methods it adds. A mutable logic loop with a classic counter would be →</p><pre>// mutable loop <br>// Design Pattern Changes<br>int sum = 0;<br>for(int i = 1; i &lt;= 10; i++) {<br>    sum += i;           // mutate sum<br>    // can also mutate arrays, counters, flags, etc.<br>}</pre><p><em>Subsequent iterative</em> steps masquerading <em>as CPU clock movement </em>{1, 2, 3,…, 10}. In software design, it follows the same walkthrough as <em>CPU</em>. In deduction, the <em>counter’s value assignment </em>will increment. The loop logic is human-readable<em> </em>&amp; dry-testable<strong>. </strong>It’s imperative thinking that <em>C </em>Inherited<em>:</em><strong> </strong>you can predict each assignment as a single block step, whereas <em>immutable-inherited languages </em>use <em>recursion, higher-order functions</em>,<em> </em>or go behind the curtain by creating new values. To put the concept in contrast: Here is a <em>Haskell</em> <em>loop</em>,<em> </em>functionally immutable →</p><pre>-- Haskell<br>sumTo n = sum [1..n]                    -- or using fold<br>sumTo n = foldl (+) 0 [1..n]</pre><p>In <em>Rust</em>, it can be both, including <em>explicit recursion </em>or <em>functional →</em></p><pre>// Rust (can mix styles)<br>fn sum_to(n: i32) -&gt; i32 {<br>    (1..=n).sum()                       // iterator (high-level)<br>}<br><br>// Or explicit recursion<br>fn sum_to_rec(n: i32) -&gt; i32 {<br>    fn helper(i: i32, acc: i32) -&gt; i32 {<br>        if i &gt; n { acc } else { helper(i + 1, acc + i) }<br>    }<br>    helper(1, 0)<br>}</pre><p><em>Classic swapping examples,</em><strong><em> </em></strong>as described in Dennis Ritchie’s C book, are mutable and unsafe; even the logic of swapping relies on mutability, which fundamentally alters <em>algorithmic system design</em> when we use<em> immutable languages.</em> Simple<em> Fibonacci </em>without recursion demands <em>swapping</em>. The practice seems obsolete but essential to point out the contrast→</p><pre>int fib(int n) {<br>    int a = 0, b = 1;           // a = F(0), b = F(1)<br><br>    for(int i = 0; i &lt; n; i++) {<br>        int temp = a + b;       // calculate next number<br>        a = b;                  // shift a ← b<br>        b = temp;               // shift b ← next<br>    }<br><br>    return a;<br>}</pre><p><em>Java </em>balances <em>performance </em>and <em>safety </em>by allowing<em> object-level mutability,</em> but why is <em>Java </em>mutability safer than <em>Python</em>, even though they share the same behavior? Clearly, <em>Java </em>is<em> statically typed</em>, meaning errors are caught before the program runs, and its <em>encapsulation (private, protected, final)</em> is secure for enterprise architecture or a well-supported ecosystem, whereas <em>Python </em>lacks these features.</p><p>Making classes <em>immutable </em>(when appropriate) is often a good design choice in Java. It improves thread <em>safety and predictability</em> and can reduce certain classes of bugs. To achieve <em>immutability</em>, simply marking the class <em>final </em>is not enough — you must also make fields <em>final </em>+ <em>private</em>, <em>avoid setters</em>, and use <em>defensive copying. I</em>f the purpose is the user, the code would be exploitable; look at the erroneous design pattern→</p><pre>public class ImmutableUser {<br>    private final String name;<br>    private final int age;<br><br>    public ImmutableUser(String name, int age) {<br>        this.name = name;<br>        this.age = age;<br>    }<br><br>    public String getName() { return name; }<br>    public int getAge() { return age; }<br><br>    public ImmutableUser withName(String newName) {<br>        return new ImmutableUser(newName, this.age);<br>    }<br><br>    public ImmutableUser withAge(int newAge) {<br>        return new ImmutableUser(this.name, newAge);<br>    }<br>}</pre><p>This leads to unpredictable behavior. Code that thought it had a <em>stable User object</em> suddenly sees its data changed by someone else. That lies behind an object that, once created, cannot be changed in this block.</p><p><em>Aliasing </em>combined with <em>mutability </em>allows one part of the program to unexpectedly change data that another part relies on. An <em>immutable version</em> eliminates this class of bugs →</p><pre>// Immutable User class<br>public final class ImmutableUser {     // 1. class is final<br><br>    private final String name;         // 2. fields are final<br>    private final int age;<br><br>    public ImmutableUser(String name, int age) {<br>        this.name = name;<br>        this.age = age;<br>    }<br><br>    // Only getters, no setters<br>    public String getName() { return name; }<br>    public int getAge() { return age; }<br><br>    // Instead of modifying, we create a new object<br>    public ImmutableUser withName(String newName) {<br>        return new ImmutableUser(newName, this.age);<br>    }<br><br>    public ImmutableUser withAge(int newAge) {<br>        return new ImmutableUser(this.name, newAge);<br>    }<br>}<br><br><br><br>public class Main {<br>    public static void main(String[] args) {<br><br>        ImmutableUser user = new ImmutableUser(&quot;Alice&quot;, 25);<br><br>        // We cannot change it<br>        // user.setName(&quot;Hacker&quot;);   // Compile Error! No setter<br><br>        ImmutableUser olderUser = user.withAge(26);   // Creates NEW object<br><br>        System.out.println(user.getName() + &quot; is &quot; + user.getAge());        // Alice is 25<br>        System.out.println(olderUser.getName() + &quot; is &quot; + olderUser.getAge()); // Alice is 26<br><br>        // Original object is never changed<br>    }<br>}<br><br>// it copies the Alice and Update 26 in a new space</pre><p>Making a class immutable in Java is often a good <em>design decision</em> because it eliminates an entire category of bugs caused by unexpected changes to an object’s state. When an object cannot be modified after creation, it becomes inherently thread-safe, easier to reason about, and safer to share across different parts of a program or between threads. However, not every class should be immutable. Programmers deliberately design some classes as mutable when the object’s state is expected to change over time (for example, a shopping cart, a string builder, or a collection that grows). In these cases, forcing immutability would hurt performance and make the code much more complicated. Similarly, allowing inheritance (not marking a class as final) is a conscious design choice. It gives other developers the flexibility to extend the class and add new behavior. This is useful in <strong>frameworks, libraries, and large systems</strong> where <strong>extensibility </strong>is more important than strict <em>immutability</em>. In short, <em>immutability </em>is preferred for value objects and data that should never change, while <em>mutability + inheritance </em>is chosen when <em>flexibility, performance, or future extension</em> is more important than safety and predictability.</p><blockquote>Key Insight</blockquote><p><em>Immutability </em>makes objects inherently thread-safe and easier to reason about, but it is not always the right choice when frequent state changes are expected (shopping carts, builders, caches). Not every class should be immutable. The decision depends on whether flexibility and performance outweigh predictability and safety. As you can see, the user withAge(26)creates another object. Those choices made are <em>intentional</em>. The philosophy of the language is important!</p><blockquote>Compilers and Interpreters</blockquote><p><em>As we ran the gamut of some of the most important features and nuanced headlines in compiler design and programming languages, it’s about time to dive into compilers. It’s just the tip of the iceberg in applying our theory to chapters 2 and 3. </em>A <em>simple interpreter</em> can be understood as a pipeline of four main stages, according to <strong>Robert Nystrom’s </strong><em>book </em>about <em>Crafting Interpreters</em>. I forked it. <a href="https://github.com/AlborzNazari/Robert_Nystrom_craftinginterpreters"><em>Click </em></a>to access my repo. Perhaps you are curious to investigate the <a href="https://github.com/AlborzNazari/Robert_Nystrom_craftinginterpreters/blob/master/java/com/craftinginterpreters/lox/Lox.java"><em>Lox </em></a>and <a href="https://github.com/AlborzNazari/Robert_Nystrom_craftinginterpreters/blob/master/java/com/craftinginterpreters/lox/Scanner.java"><em>Scanner</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3JYBAPqqko44uTD4kBI-OA.png" /><figcaption><strong>A simple Interpreter</strong>, which is part of the compiler program.</figcaption></figure><p>1)<em>The scanner</em> performs<em> lexical analysis,</em> converting a raw character stream into a sequence of<strong> </strong><em>typed tokens. 2)The parser</em> then builds these tokens into an <em>Abstract Syntax Tree (AST),</em> which serves as the central <em>data structure f</em>or everything that follows. <em>3)The resolver </em>performs <em>static analysis</em> to resolve variable bindings using<em> lexical scoping,</em> avoiding the unpredictable behavior that arises from purely <em>dynamic name resolution.</em> Finally, the interpreter traverses the <em>AST </em>and executes the program.</p><p>Each stage has a narrow, well-defined responsibility. <em>Modular, loosely coupled,</em> and <em>designed minimally.</em> This structure reduces complexity and makes the system easier to reason about and maintain. The scanner, for instance, is responsible only for turning characters into tokens. In the<strong><em> </em></strong><em>Lox implementation</em> from<strong><em> Crafting Interpreters</em></strong>, the focus is on clarity and separation of concerns, using straightforward<em> state tracking </em>and<strong> </strong><em>token classification.</em></p><p>Most practical, versatile languages have already been created. The real value in studying language implementation lies in understanding why languages make the choices they do. Contrasting features across languages — such as static versus dynamic typing, or different approaches to <em>macros </em>— reveal the underlying <em>design decisions</em> and their consequences.</p><p>An <em>interpreter </em>or <em>compiler </em>is typically divided into a <em>frontend </em>and a <em>backend</em>. The frontend handles scanning, parsing, and static analysis. The backend deals with<strong> </strong><em>intermediate representations (IR), optimization, </em>and <em>code generation </em>or <em>execution</em>. Different execution models exist: <em>tree-walk interpreters</em><strong> </strong>— a simpler and friendlier approach, <em>bytecode virtual machines, just-in-time(JIT)</em><strong> </strong>compilers, and <em>transpilers</em>. Each model carries different trade-offs in <em>simplicity</em>, <em>performance</em>, and <em>implementation effort.</em> E.g., in <em>C </em>and <em>C++</em>, you have to define a <em>compile-time constant </em>for stack arrays. When do you need a compile-time constant? It’s a must-practice<em> in C++</em> as <em>stack arrays</em> always need<em> fixed sizes </em>or<em> ‘template parameters’</em>. In deduction, if we perform more computation and allocate more memory at<em> compile time</em>, we can easily optimize our program’s runtime.</p><pre>//1 Compile-time constant (Good for optimization)<br>const int SIZE = 100;          <br><br>//2 Runtime constant (Still constant, but value is NOT known at compile time)<br>const int SIZE = getUserInput();   // Value known only when program runs</pre><p><em>1 — </em>Another perk of using<em> constant typing </em>is <em>optimization</em>; yet we use that for <em>debugging</em>, as the code is <em>compiled </em>and is running hopefully legit, it eliminates<em> dead code</em> like a <em>debugger block</em>, as the <em>compiler </em>will skip the code as it does not run:</p><pre>const bool DEBUG = false;<br><br>if (DEBUG) {<br>    // This entire block can be completely removed by the compiler<br>    printDebugInfo();<br>}</pre><p>In up-to-date <em>C++</em> recommendations, <em>constexpr </em>is preferred over <em>const </em>when we want a guaranteed compile-time constant. It effectively enhances <em>performance</em>. Thus, it’s <em>safer</em>, as the value can’t change at <em>runtime</em>.</p><pre>constexpr int SIZE = 100;           // Guaranteed compile-time constant<br>constexpr int square(int x) { return x * x; }  // Can be used at compile time</pre><p>It’s clear why <em>constexpr </em>becomes the mandatory choice in many situations, since features like <em>switch statements, templates, and fixed‑size arrays </em>inherently require <em>compile‑time constants.</em></p><p>We use <em>compile-time constants</em> because they allow the compiler to do more work before the program runs — if DEBUG=true — resulting in faster, more efficient programs while also making the code <em>cleaner </em>and <em>safer</em>.</p><blockquote>Macros: Text Substitution vs Structural Transformation</blockquote><p>Even seemingly small features reflect deeper <em>design philosophies.</em><strong><em> </em></strong><em>C macros,</em> for example, perform simple <em>textual substitution. </em>It doesn’t compile, which can lead to unexpected behavior and prevent error checking. <em>Lisp macros,</em> by contrast, operate on the language’s own data structures at a higher level of <em>abstraction</em>. They run at compile time. These differences are not accidental — they stem from fundamental choices about how much power and safety a language should expose to the programmer.</p><pre>#define SQUARE(x) x * x   // text substitution<br>SQUARE(1 + 2)             // becomes 1 + 2 * 1 + 2 = 5, not 9</pre><p>Obvious how <em>macros </em>in<strong> </strong><em>Lisp code snippets highlight the contrast:</em></p><pre>;; Lisp code snippet<br>;; 1. Define the Macro<br><br>(defmacro repeat-times (n &amp;body body)<br>  &quot;Executes the body of code N times.&quot;<br>  (let ((counter (gensym))) ; Safely generates a unique variable name<br>    `(loop for ,counter from 1 to ,n<br>           do (progn ,@body))))<br><br>;; 2. Define a Main Function to Test It<br><br>(defun main ()<br>  (format t &quot;--- Starting Loop ---~%&quot;)<br>  <br>  ;; Use our custom macro<br>  (repeat-times 3<br>    (format t &quot;Hello from inside the macro!~%&quot;)<br>    (format t &quot;This is a second line of code.~%&quot;))<br>    <br>  (format t &quot;--- Loop Finished ---~%&quot;))<br><br>;; 3. Run the Program<br><br>(main)</pre><p>In <em>Lisp</em>, <em>a macro </em>is<em> actual running code</em> that executes at <em>compile time </em>and produces new <em>Lisp </em>code as output.</p><p><em>So you’re writing a program that writes programs. The macro </em>runs, produces some code, and that generated code is what actually gets compiled.</p><pre>;; Lisp code segment<br><br>(defun main ()<br>  (format t &quot;--- Starting Loop ---~%&quot;)<br>  <br>  (loop for #:G1234 from 1 to 3<br>        do (progn <br>             (format t &quot;Hello from inside the macro!~%&quot;)<br>             (format t &quot;This is a second line of code.~%&quot;)))<br>  <br>  (format t &quot;--- Loop Finished ---~%&quot;))</pre><p>Writing a language and then building <em>an interpreter </em>or <em>compiler </em>for it forces you to confront these choices directly. It provides a concrete way to understand the differences between languages such as <em>C, Java, Ruby, Python, Lisp</em>, and more — not just in <em>syntax</em>, but in how they are constructed and what that construction <em>enables </em>or <em>restricts</em>.</p><p>In the sections that follow, I examine these concepts through the <em>Lox language</em><strong> </strong>and its interpreter implementation. The goal is to move beyond <em>surface-level comparisons</em> and develop a clearer understanding of the <em>architectural decisions</em> that shape how programming languages actually work.</p><blockquote>Constructors and Initialization</blockquote><p>A meticulous comparison before diving deeper into <em>compiler theory: </em>nowadays, most code design is architected by engineers, whereas AI handles most code generation tasks. Back in the day, computer scientists used transpilers to translate <em>Lisp </em>into C, generating code that is functionally equivalent to what Lisp produces in C. Unsurprisingly, the resulting code uses intricate low-level structures, macros, or legacy parameters that are hardly <em>human-readable</em>. The main reason they used transpilers was <em>portability</em>: with a C compiler, you could run your program anywhere. That was the real perk: the <em>transpiled code</em> could be used to embed a larger <em>C/C++</em> program. For instance, <em>design limitations c</em>losely entangled <em>portability </em>and <em>transpilers</em>. Since <em>Lisp </em>is <em>dynamically typed</em>, the logic of <em>garbage collection</em> and closures is difficult to map accurately to <em>a statically typed language like C</em>. As you see, the world of<em> compiler theory</em> is a matter of trade-offs, and there’s a high level of theoretical rigor beneath it, since Edinburgh school ML was created in the 1970s by<strong> Robin Milner</strong> as a scripting language for the <em>LCF theorem prover</em>, not as a <em>general-purpose language. </em>Its focus on proof automation led to the introduction of <em>algebraic data types, pattern matching, </em>and <em>a strict, statically typed system </em>with <em>inference. </em>Its direct descendants are <em>Standard ML</em>, <em>OCaml,</em> and <em>Haskell</em>, while its influence appears in <em>Rust</em>, <em>Swift</em>, and <em>Scala </em>through the use of <em>Option/Result types </em>and<em> pattern matching.</em></p><p>When building language design features, the design structure inherits features from its ancestors, and in this way, trade-offs among usability, security, execution time, runtime overhead, and<em> load balancing make</em> sense. One major distinction is between languages that inherit <em>constructors</em> and those that don’t. This distinction is intertwined with <em>OOP</em>, whose concepts oblige us to understand its strong ties to <em>design philosophy</em>, especially the principle of <em>modularism</em>.</p><p>In<em> low-level languages</em> like <em>C</em>, variables can be uninitialized for <em>maximum speed </em>and <em>flexibility. </em>Apparently, it’s old-school thinking, and it’s not designed to provide security, but<em> low-level access, performance, </em>and <em>speed. </em>In <em>C</em>, int x; means the variable has a fixed address; its contents are <em>garbage</em> until initialized. <em>C++ </em>encourages the use of <em>modern uniform initialization, </em>which makes programs safer.</p><pre>int x{10}; // Create an integer called x and set its starting value to 10 right now.</pre><p>Newer languages like <em>Swift, Rust, or Java </em>don’t allow <em>uninitialized variables</em>. This distinction introduces the concept of a constructor in language design, which is closely tied to each language’s structure and definitions. <em>A constructor</em> is a special method that is automatically called when you create a new instance of a <em>class </em>or <em>struct</em>. It runs before everything else; its purpose is to resolve <em>uninitialized memory</em><strong><em>, </em></strong><em>as mentioned.</em></p><p>Why do some languages favor <em>constructor inheritance</em> or vice versa<strong><em>? </em></strong><em>Constructor inheritance</em> (or the lack of it) is a deliberate <em>design choice </em>that trades off convenience, safety, and control. <em>Modern C++ </em>allows this by using Base::Base (since C++11) to avoid duplicating constructors. If your<em> child class</em> doesn’t add new data, you can inherit all <em>parent constructors </em>in one line, then add your own if needed. This is great for <em>wrappers</em>, <em>exceptions</em>, or<em> simple extensions</em>. On the other hand, <em>Java</em> &amp; <em>Rust </em>don’t inherit constructors. <em>Swift </em>forces it by default. They force you to explicitly call <strong>super()</strong> or the parent initializer. Why? Because <em>automatic inheritance </em>can hide important decisions about how the object should be set up, especially in big class hierarchies. Requiring an<em> explicit call</em> ensures the programmer consciously handles the parent’s state and avoids sneaky bugs<em>.</em> In short: some languages prefer less <em>boilerplate</em>, while others prioritize clarity and safety. <em>C++ </em>gives you the option; the others say <em>“be explicit.”</em></p><blockquote>Key Insight</blockquote><p>Requiring explicit calls forces the programmer to consciously handle parent state, reducing hidden bugs in large class hierarchies.</p><blockquote>Introducing Lox</blockquote><p><em>Lox </em>is the language used throughout <a href="https://craftinginterpreters.com/"><em>Crafting Interpreters</em></a> to explore these concepts in practice. It is a small, <em>dynamically typed</em>, <em>class-based language </em>with<em> first-class functions</em> and <em>closures</em>. The <em>Java implementation (jlox)</em> follows the classic pipeline: <em>scanner, parser, resolver, and tree-walk interpreter.</em> Studying its implementation reveals why certain design choices were made and what machinery each feature requires. The real value in implementing a language lies in understanding the consequences of those choices — not just in syntax, but in how the language is constructed and what that construction enables or restricts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*RPffHihyn6ABqVJm24ZpVA.png" /><figcaption>Using <strong>Lox </strong>as a transparent lens to study classes of issues that appear in real interpreters, compilers, and dynamic languages — and why production systems add the mitigations they do.</figcaption></figure><blockquote>Why put a toy language through a security lens?</blockquote><p><em>Lox </em>is a deliberately <em>minimal</em>, <em>dynamically typed language </em>designed to teach how <em>interpreters </em>and <em>compilers </em>work. Its simplicity makes it an ideal subject for <em>security analysis.</em> Every <em>design decision</em> is visible, and every omission reveals what production systems must later add to stay safe. This chapter examines Lox through a security lens. It connects the language features discussed in Chapter 1 to concrete risks, then quantifies those risks with analysis approaches and measurable outcomes. Lox exposes the exact decisions that, when scaled to real systems, become attack vectors. These include <em>type confusion, uncontrolled aliasing, parser resource exhaustion, closure capture errors, </em>and <em>garbage collection correctness issues</em>. Because <em>Lox </em>has no <em>production constraints</em>, we can observe these problems in their purest form. The exercise is not about finding exploitable bugs in <em>Lox </em>itself. It is about understanding why mature languages invest heavily in <em>static analysis, ownership rules, immutability patterns, </em>and <em>hardened execution models.</em></p><p>Beneath its simple surface, <em>Lox </em>carries the <em>DNA </em>of its inspirations: the expressive freedom of <em>JavaScript</em>, the familiar<em> class inheritance</em> of <em>Java</em>, the lightweight scripting feel of <em>Lua</em>, and the no-nonsense clarity of <em>C</em>. Can you guess more features?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VcrfAZRKrotBmMZM4N4CXQ.jpeg" /><figcaption><strong>Lox </strong>through thick and thin with Its ancestors</figcaption></figure><blockquote>chapter 2/3: Input/Output Metrics, Fuzzing, Static and Dynamic Analysis→</blockquote><p>Enough about theory, and yes to more practical comparison! The comparison makes things understandable, which is necessary for clear pickup of the design pattern. Here we present the results and metrics, provide <em>practical lox</em>, and compare our analysis to the code-fathom part.</p><blockquote>1. Static Analysis: Jlox</blockquote><p>Let’s do<em> static analysis— </em>by running the latest version of <strong>SpotBugs </strong>on <em>Jlox </em>to analyze the code and its structure. Since <strong>SpotBugs </strong>runs on <em>compiled code</em>, <em>the source code must be</em> compiled to create <em>classes</em>. All<em> Java code </em>has been compiled <em>recursively </em>to avoid<em> I/O </em>and <em>exception errors.</em></p><p>Note that the <em>software </em>is developed and maintained <strong>not </strong>for production-level use <strong>but </strong>for educational use; for this reason, the simplicity of the Lox explained book by Nystrom does not address production-level intricacies and cautions. Of course, it’s a great<em> pedagogical framework </em>for seeing <em>errors</em> and surveying an analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*E4LQ4MxIs2iO3OZ2N4mQzg.png" /><figcaption><strong>Why are these bugs relevant to non-enterprise, non-production-scale compilers but not to the book&#39;s objective? {The answer lies behind the last paragraph.}</strong></figcaption></figure><blockquote>Jlox Static Analysis Result</blockquote><p>Let’s see the three bugs and what’s got sneaky beneath the gospel. As you can see:</p><p><strong>1. Dubious method used: System.exit() </strong><br><em>Location: Lox.runFile()</em></p><p><strong>2. Incorrect definition of Serializable class</strong><br><em>Location: RuntimeError</em></p><p><strong>3. Questionable use of reference equality (==) instead of .equals() </strong><br><em>Location: Boolean comparison in runtime handling</em></p><blockquote><strong>Educational Metric</strong></blockquote><p>For an educational invented language as a project, having only <em>three minor issues</em> in a <em>complete interpreter </em>is actually <em>impressive</em>. It shows the code is clean enough to serve as a clear teaching example while still demonstrating real-world <em>static analysis concepts.</em></p><blockquote>one-step-further</blockquote><p>Why do these issues matter in <em>enterprise production software?</em> Now let’s doubt the <em>software’s correctness </em>and assume this <em>compiler </em>is aimed at a very <em>large-scale system.</em> It’s not to dump the project, but to raise a question to expand our article’s <em>metrics</em>. These three findings trace back to specific <em>design choices </em><strong>Nystrom </strong>made for a teaching language — choices that are perfectly reasonable in that context but would need to change entirely if <em>jlox </em>were scaled into a<em> production system:</em></p><p><strong>System.exit() call →</strong>In <em>production systems (servers, microservices, cloud environments), </em>calling <em>System.exit()</em> can abruptly terminate the entire <em>JVM process</em>. This breaks graceful shutdown, disrupts container orchestration<em> (Kubernetes, Docker),</em> prevents proper logging, and can cause data loss or incomplete transactions. <em>Enterprise applications</em> must use controlled <em>shutdown hooks instead.</em></p><p><strong>Improper Serializable Implementation →</strong>In<em> distributed systems,</em> <em>caching layers, session replication, or RMI</em> frequently serialize objects. A <em>non-transient non-serializable field</em> can cause <em>NotSerializableException</em> at <em>runtime</em>, leading to <em>outages </em>in <em>high-availability setups.</em> This violates enterprise reliability standards.</p><p><strong>Reference Equality (==) on objects →</strong>Using == instead of<em> .equals() </em>on objects (especially Booleans or wrappers) can lead to subtle, hard-to-reproduce bugs, especially under autoboxing or in concurrent environments. In enterprise codebases, this pattern is considered a risk to maintainability and correctness.</p><blockquote><em>Enterprise Metric Perspective</em></blockquote><p>In a typical Fortune<em> 500 Java codebase, </em>tools like <em>SpotBugs</em>, <em>SonarQube</em>, or <em>Coverity </em>are configured to fail the build on <em>High-</em> <em>or Medium</em>-<em>severity</em> findings. Even three such issues would trigger mandatory<em> code review</em> and <em>fixes</em> before merging.</p><blockquote>2. Static Analysis on clox (C Bytecode VM)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_iLo9LkwgCifGbYj_nG08A.png" /><figcaption><strong>CPP Check</strong></figcaption></figure><p>You can download the full static analysis on<em> </em><a href="https://gist.github.com/AlborzNazari/244986ece292a34d9ef859148088547f.js"><em>clox_cppcheckflow_report.txt</em></a> from my <em>public GitHub gist</em>.</p><p>To suppress the noise (the annoying <strong>missingIncludeSystem messages</strong>), use this full command, and then the warnings disappear from our findings.</p><pre>cd C:\craftinginterpreters\clox<br><br>cppcheck --enable=all --inconclusive --report-progress --suppress=missingIncludeSystem .</pre><p>After <em>suppression</em>, it is recommended to run <em>cppcheck </em>with full checks on the <strong><em>clox (c) implementation</em></strong> from the directory. The results were reassuring: <em>the core virtual machine, compiler, and mark-sweep garbage collector</em> showed no major issues. The majority of findings were <em>style suggestions</em> — such as adding <em>const </em>to <em>parameters </em>and <em>variables</em>, or <em>marking</em> <em>unused functions. </em>There were no critical<em> memory safety violations</em> or obvious security problems in the main <em>interpreter </em>code.</p><blockquote><em>Findings</em></blockquote><p><strong>Null pointer dereference risk </strong>in <em>note/answers/chapter01_introduction/3/linked_list.c </em>— This is a classic memory safety issue if <strong>malloc</strong>() fails.</p><p><strong>Several style suggestions</strong> (<em>const parameters, const variables, unused functions, shadowing</em>).</p><p>According to <strong>Nystrom’s book</strong>:</p><blockquote>There are good arguments for not having a null value in a language since null pointer errors are the scourge of our industry. If we were doing a statically typed language, it would be worth trying to ban it. In a dynamically typed one, though, eliminating it is often more annoying than having it.</blockquote><p>That’s why he introduces <strong>Nil </strong>in <em>Lox </em>as a<em> data type</em>: to feel the difference between <em>Java’s null or C’s null. That’s why C/C++ has null, and languages like Rust, Haskell, Scala, Swift (with optionals), and Kotlin try to eliminate or control the billion-dollar mistake, as Tony Hoare, inventor of null, called it. To read why some languages don’t inherit null like Rust and Swift, and why some do.</em></p><blockquote>Educational Metric</blockquote><p>For an educational<em> C implementation</em> of a <em>doubly linked list </em>as a project exercise, having only two <em>null-pointer-dereference warnings</em> and a handful of minor <em>style issues</em> in a complete, working implementation is impressive. It shows that the code is clean enough to serve as a clear teaching example of <em>manual memory management </em>while still demonstrating real-world<em> static analysis </em>concepts related to<em> memory safety.</em></p><blockquote>one-step-further</blockquote><p>Why do these issues matter in <em>enterprise production software</em>? Now let’s doubt the software’s correctness and assume that this linked-list code (or the broader<em> C-style approach</em> it represents) is intended for a very <em>large-scale system.</em> It’s not to dismiss the project, but to raise the question of <em>one-step-further evaluation.</em> These bugs can force significant <em>design changes </em>in the language or implementation style the author developed for the book.</p><blockquote>Null Pointer Dereference on Failed malloc()</blockquote><p>In <em>production systems (high-throughput servers, databases, embedded controllers, kernels, or cloud microservices)</em>, a failed <strong>malloc()</strong> that returns <strong>NULL </strong>and is later dereferenced causes an immediate process crash or undefined behavior. This leads to sudden <em>service outages, request drops, potential data corruption</em> or loss during <em>in-flight operations,</em> and cascading failures in <em>container orchestration</em> (<em>Kubernetes pods restarting or entering crash loops</em>). Under memory pressure or adversarial conditions, it can become a <em>denial-of-service</em> vector; in rare<em> low-level </em>scenarios, it has enabled <em>memory corruption</em> or<em> code execution</em>. Enterprise reliability standards demand explicit handling or safer allocation strategies. <em>Style issues</em> <em>(missing const, shadowing, unused functions)</em> are lower severity but still degrade long-term <em>maintainability </em>in million-line codebases.<br>These findings directly tie back to language design choices: <em>raw pointers </em>+ <em>manual malloc/free</em> give maximum control and performance but require pervasive defensive checks. Scaling to production would push toward higher-level abstractions (<em>allocation arenas, error-returning constructors, or even switching to languages with built-in safety like Rust’s Option + ownership model</em>) — exactly the kind of evolution the book’s progression from <strong>tree-walk </strong>to <strong>bytecode </strong>hints at.</p><blockquote>Enterprise Metric Perspective</blockquote><p>In a typical enterprise<em> C/C++</em> <em>codebase </em>(<em>systems software, performance-critical services, or safety-related components</em>), tools such as<strong><em> </em>Coverity, Clang Static Analyzer, PVS-Studio, or SonarQube</strong><em> </em>are configured to fail builds or block merges on High- or Critical-severity findings. Even two <em>null-dereference issues</em> of this class would trigger mandatory code review, fixes, and often <em>architectural discussion</em> before any <em>production deployment</em>. <em>Memory-safety bugs </em>remain among the most expensive classes of defects in real-world systems.</p><blockquote>Dynamic Analysis</blockquote><p>Without further ado, let’s create <em>a baseline test </em>in our crafting interpreters in our system. Here, I use the <em>Windows OS</em> to show the analysis. Let’s create <em>a simple baseline test </em>and then go further.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rOaV0BZmXnZ_OTNvVq_jLQ.png" /><figcaption><strong>Baseline Test </strong>seems as annoying as ‘hello world!’</figcaption></figure><p>Let’s write a<em> deep nesting for the parser</em> in <em>Python</em>: There’s no <strong>depth limit </strong>in jlox. e.g., <em>Python </em>has a<em> depth limit</em> of 500 <em>nesting loops</em>. I tried nesting loops with two tests in a static analysis to check for a StackOverflow error, since <em>Lox</em> avoids<em> stack exhaustion.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*nGcPHwEJ1MmhZuN0olh_PA.png" /><figcaption><strong>Lox </strong>has no <strong>depth limit</strong> and this prevent <strong>Parser Ddos Risk</strong>.</figcaption></figure><p>Also, <em>the closure bomb test and depth Recursion test are available in</em> my GitHub Gist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*Q1vvLCOu9cZ48ziYtARiVQ.png" /><figcaption><strong>Closure Test</strong> and <strong>Recursion Test</strong></figcaption></figure><blockquote>Stress Test Metrics</blockquote><p>Meanwhile, we’ll write a <strong>measure.py </strong>script to <em>stress-test</em> our adversarial loop on our beloved <em>compiler</em>! Our <strong>measure.py</strong> file → <em>psutil is a dependency and must be installed.</em></p><pre>import subprocess<br>import psutil<br>import time<br>import sys<br><br>def measure_lox(filename):<br>    print(f&quot;Running: {filename}&quot;)<br>    start_time = time.perf_counter()<br>    process = subprocess.Popen(<br>        [&quot;java&quot;, &quot;-jar&quot;, &quot;jlox.jar&quot;, filename],<br>        stdout=subprocess.PIPE,<br>        stderr=subprocess.PIPE,<br>        text=True<br>    )<br><br>    ps_process = psutil.Process(process.pid)<br>    peak_memory_mb = 0<br><br>    while process.poll() is None:<br>        try:<br>            mem = ps_process.memory_info().rss / (1024 * 1024)<br>            if mem &gt; peak_memory_mb:<br>                peak_memory_mb = mem<br>        except psutil.NoSuchProcess:<br>            break<br>        time.sleep(0.01)<br><br>    stdout, stderr = process.communicate()<br>    duration = time.perf_counter() - start_time<br><br>    print(f&quot;Time taken     : {duration:.3f} seconds&quot;)<br>    print(f&quot;Peak Memory    : {peak_memory_mb:.2f} MB&quot;)<br>    print(f&quot;Exit code      : {process.returncode}&quot;)<br><br>    if stdout:<br>        print(&quot;Output:&quot;)<br>        print(stdout.strip())<br>    if stderr:<br>        print(&quot;Errors:&quot;)<br>        print(stderr.strip())<br><br>    return duration, peak_memory_mb<br><br>if __name__ == &quot;__main__&quot;:<br>    if len(sys.argv) &lt; 2:<br>        print(&quot;Usage: python measure.py filename.lox&quot;)<br>    else:<br>        measure_lox(sys.argv[1])</pre><p>After installing the<em> putil dependency,</em> the<em> peak memory usage</em>, <em>time taken</em>, and <em>outcome </em>show ‘success’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*byZLPNaBh-2J-lGtC0SwmA.png" /><figcaption>All three passed succesfully!</figcaption></figure><blockquote>Fuzzing for Jlox</blockquote><p>To go beyond hand-written adversarial tests, I built a <em>simple Python fuzzer </em>that generates random (and sometimes deeply nested) Lox programs.</p><pre>import random<br>import string<br><br>def generate_fuzzed_lox():<br>    templates = [<br>        &#39;print &quot;{0}&quot;;&#39;,<br>        &#39;var {0} = {1};&#39;,<br>        &#39;{0} + {1};&#39;,<br>        &#39;fun test() {{ {0} }}&#39;,<br>        &#39;if ({0}) {{ print 1; }}&#39;,<br>    ]<br>    <br>    fuzz = random.choice(templates).format(<br>        &#39;&#39;.join(random.choices(string.ascii_letters + &#39;(){}[]+-*/=;&#39;, k=random.randint(5, 50))),<br>        random.randint(-10000, 10000)<br>    )<br>    <br>    if random.random() &lt; 0.3:<br>        depth = random.randint(100, 600)<br>        fuzz = &#39;(&#39; * depth + &#39;1&#39; + &#39;)&#39; * depth + &#39;;&#39;<br>    <br>    return &#39;print &quot;=== FUZZ TEST ====&quot;;\n&#39; + fuzz + &#39;\nprint &quot;Fuzz end&quot;;&#39;<br><br>for i in range(50):<br>    with open(f&#39;fuzz_{i}.lox&#39;, &#39;w&#39;) as f:<br>        f.write(generate_fuzzed_lox())<br><br>print(&#39;50 fuzzed test files generated!&#39;)</pre><p>Let’s run a batch measurement at<strong> run_fuzz.py</strong> →</p><pre><br>import subprocess, glob, time<br>for file in glob.glob(&#39;fuzz_*.lox&#39;):<br>    print(f&#39;\\n=== Testing {file} ===&#39;)<br>    try:<br>        result = subprocess.run([&#39;java&#39;, &#39;-jar&#39;, &#39;jlox.jar&#39;, file], <br>                              capture_output=True, text=True, timeout=2)<br>        print(&#39;Time: OK&#39; if result.returncode == 0 else &#39;CRASH!&#39;)<br>        if result.stderr:<br>            print(&#39;Error:&#39;, result.stderr[:200])<br>    except subprocess.TimeoutExpired:<br>        print(&#39;TIMEOUT / HANG!&#39;)</pre><p>I then ran all <em>50 fuzzed files </em>through <em>jlox </em>using a measurement script. The results were interesting:</p><p>22 programs were syntactically valid and executed successfully.</p><p>28 programs were malformed and were correctly rejected by the <em>parser</em> with clear error messages.</p><p>No uncaught <em>exceptions, stack overflows, or hangs</em> occurred. The parser handled garbage input gracefully in every case. You can find the <em>full fuzzing log</em> in this <a href="https://gist.github.com/AlborzNazari/b5754aed56e501319a90aae50b49eac6.js"><em>gist</em></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*USyei7-JqxjgFyRKCFAFDA.png" /><figcaption>fifty <strong>fuzzing tests</strong> ran succesfully.</figcaption></figure><blockquote>AFL++ on clox</blockquote><p><em>Linux timing! </em>Since I’m working on <em>Windows</em>, I needed a way to run real <em>fuzzing tools</em> like <em>AFL++.</em> That’s where <em>WSL2 {Windows Subsystem for Linux} </em>comes in. <em>WSL2 </em>isn’t some slow <em>emulator </em>that translates <em>Linux calls</em> — it actually runs a real <em>Linux kernel </em>inside a<em> lightweight virtual machine.</em> This means tools like <strong>afl-clang-fast</strong> run at nearly full native speed. The best part? It shares files directly with Windows, so my <em>C:\craftinginterpreters </em>folder is instantly available inside <em>WSL</em> at<em> /mnt/c/craftinginterpreters.</em> I just ran {<strong>wsl — install}, and I had a full Linux environment up and running</strong> in minutes. Super convenient for this kind of testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yY5zfx3_n4XQUPpK8KFWcg.png" /><figcaption><strong>sudo </strong>is a root command of <strong>Linux</strong>, not Windows; without choosing a VM, we have <strong>Kernel Access </strong>to <strong>Ubuntu</strong> by <strong>WSL</strong>.</figcaption></figure><p>For serious <em>fuzzing </em>with <em>AFL++</em>, <em>Linux </em>is essentially required due to <strong>AFL&#39;s design.</strong> Its biggest speed advantage comes from the <em>fork server:</em> <em>AFL </em>starts the target binary once, then uses the <em>Linux fork() syscall </em>to quickly clone a fresh copy of the already-loaded process for every test case — something dramatically faster than starting a new process from scratch. Windows has no equivalent to <strong>fork()</strong>—it uses CreateProcess instead, so this core optimization doesn’t work. On top of that, <strong>AFL </strong>relies on <em>Linux-specific features</em> like <em>shared memory (shmget), signal handling </em>for crashes <em>(SIGSEGV, SIGABRT),</em> and <em>/proc filesystem access</em> to detect and classify crashes efficiently. <em>The compiler </em>wrapper <em>afl-clang-fast</em> also injects coverage tracking that depends on these <em>Unix mechanisms</em>. All in all, <em>Windows </em>uses a completely different <em>exception model (SEH)</em>, which breaks <em>AFL’s crash detection and classification logic.</em></p><blockquote>chapter 3/3: Conclusion</blockquote><p>The <em>dynamic analysis </em>and<em> fuzzing campaign </em>revealed that the <strong>Lox interpreter (jlox)</strong> is correct for valid inputs and reasonably robust to <em>malformed inputs.</em> The resolver effectively protects against closure bugs, and <em>the garbage collector </em>behaves predictably under stress.<br>However, <em>the recursive parser</em> is a clear attack surface for <em>stack exhaustion,</em> and error messages on fuzzed input can become noisy. These findings align with expectations for an educational interpreter. Future improvements could include <em>recursion depth limits, better error recovery, and differential testing against Clox.</em></p><blockquote>About the Author</blockquote><p><strong>Alborz Nazari </strong>is a software engineer specializing in systems robustness and language implementation. He wrote Lox Under the Microscope, applying static analysis, fuzzing, and dynamic testing to examine how interpreter design choices affect safety and scalability in real systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e01637e5fd7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thundering Herd via Inherited Scheduler: How My Fork Became Someone Else’s Threat Feed]]></title>
            <link>https://medium.com/@alborznazari4/thundering-herd-via-inherited-scheduler-how-my-fork-became-someone-elses-threat-feed-584db81a8ae4?source=rss-ed01f24e0e3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/584db81a8ae4</guid>
            <category><![CDATA[ddos]]></category>
            <category><![CDATA[supply-chain-attack]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[dependency-attack]]></category>
            <category><![CDATA[thundering-herd]]></category>
            <dc:creator><![CDATA[Alborz Nazari]]></dc:creator>
            <pubDate>Mon, 25 May 2026 13:16:26 GMT</pubDate>
            <atom:updated>2026-05-25T13:41:27.470Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Threat Report</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZeqK_ezhL_iBi9w1em2Tyw.png" /><figcaption>Patch Release Link: <a href="https://github.com/AlborzNazari/Shadowbroker/releases">https://github.com/AlborzNazari/Shadowbroker/releases</a></figcaption></figure><p><em>I got a LinkedIn message on a Saturday. Michael, an analyst at one of the larger open-source monitoring platforms running right now, said Shadowbroker was scraping their free tier. Their logs had my IP. Their platform was going down at 1pm UK time. Every day.</em></p><p>My first move was to audit the pipeline. I checked every fetcher, every ingestor, every scheduler in the codebase. Then I found it. backend/services/fetchers/crowdthreat.py. A dedicated GET request to <a href="https://backend.crowdthreat.world/threats">https://backend.crowdthreat.world/threats</a>. Scheduled at 12:00 UTC. Hardcoded. Written by the original maintainer, not my fork.</p><p>I stopped Docker on both machines. No Python, no Uvicorn, nothing running. I sent him my analysis and pointed him to the original maintainer’s repo. He forwarded it to their dev team. The creator removed it via a patch shortly after — but I had been running the old file locally, so every time I spun up my software to develop or test, it was still sending requests to that endpoint, tracing back to my IP. That’s what got mixed in with my legitimate open-source contribution. Some anonymous traces are still persisting from systems whose developers never pulled the update after the company name appeared in the codebase.</p><blockquote><strong>The actual problem wasn’t the scraper</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ei5PSfK3Bzn3eeaHmHfOw.png" /></figure><blockquote>The Scheduler That Didn’t Know It Had a Thousand Siblings: A thundering herd, an inherited scheduler, and what happens when open-source tooling becomes the anomaly in someone else’s threat feed.</blockquote><p>The scraper is a behavioral symptom. The actual problem is structural and it will happen again — in this repo or another — unless the pattern gets named properly.</p><p>The day the incident surfaced, <a href="https://github.com/AlborzNazari/Shadowbroker">Shadowbroker</a> had around 7,000 forks. The next day, that number crossed 7,100. Within 48 hours, it was sitting above 8,000. The repo was going viral — OSINT community, security researchers, hobbyists, journalists. Every new fork was another machine. Every new machine was another instance of that scheduler. Every instance pointed at the same endpoint at the same time.</p><p>When a piece of software carries more load than usual, any outbound request scheduler needs to distribute execution — batching decisions across time rather than firing simultaneously. Without that, the aggregate behavior masquerades as a DDoS-adjacent attack pattern. There is no coordination between instances, no communication, just a shared timestamp buried in source code replicating across thousands of independent machines in real time — a system that, in effect, funnels all its traffic into a single moment.</p><p>At noon UTC, CrowdThreat’s server receives what looks like a coordinated multi-source request spike. A thousand distinct IPs. Simultaneous. Repeating daily. From the outside that’s not a scraper. That’s a DDoS. And it’s nobody’s fault individually — the aggregate behavior is the attack.</p><p><em>This is a thundering herd. And it’s a race condition at the population level, not the thread level.</em></p><blockquote><strong>Why `.sleep()` doesn’t fix this — and why the GIL is irrelevant here:</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pab3rWMkbtNwesEc3L4rqQ.png" /></figure><p>When people talk about race conditions in Python, the conversation usually comes down to the GIL. The Global Interpreter Lock. The argument goes: Python threads don’t truly run in parallel, so you’re protected.</p><p>That argument doesn’t apply here.</p><p>The GIL governs threads within a single process. It has no jurisdiction over thousands of independent processes running on thousands of independent machines across dozens of countries. Same with `time.sleep()`.<em> Sleeping a thread inside one Docker container does nothing to the 2,999 others firing simultaneously elsewhere! </em><a href="https://medium.com/@alborznazari4/threading-the-needle-race-conditions-atomic-violations-and-the-concurrency-flaws-that-break-b7bfdc2f7993"><em>Click!</em></a></p><p><em>The race here isn’t between threads. It’s between instances. The synchronization point isn’t a shared memory address. It’s a shared line of code:</em></p><pre>schedule.every().day.at(&quot;12:00&quot;).do(fetch_crowdthreat)</pre><p>That’s the bug. Not the fetch. Not the scheduler logic. The hardcoded time with no <strong><em>jitter</em></strong>, deployed to a population of forks with no <strong><em>coordination layer</em></strong> between them.</p><blockquote><strong>The fix is five lines</strong></blockquote><pre><br>import random<br>import time<br>jitter = random.uniform(0, 300) # spread across 5 minutes<br>time.sleep(jitter)<br>fetch_crowdthreat()</pre><p>That’s it. Each instance sleeps for a random duration before firing. A thousand simultaneous requests become a thousand requests spread over five minutes. CrowdThreat’s server sees normal traffic. The thundering herd dissolves.<br>A proper implementation adds per-instance rate limiting on top — <strong><em>`slowapi`</em></strong> handles this within a single FastAPI process, though it won’t protect against the distributed case on its own. For that, you need jitter at the scheduler level, before the request is even built.</p><blockquote><strong>What this looks like from a threat intelligence perspective</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VcbqcPlMHUcvt3_-r0cUjg.png" /></figure><p>Here’s the part that matters beyond the fix.</p><p>My IP showed up in CrowdThreat’s logs as a threat actor. I was running legitimate open-source software, pulling from legitimate government data sources, and contributing to a legitimate OSINT project. And I appeared in a threat feed.</p><p>This is a <strong><em>supply chain attribution failure</em></strong>. You run someone else’s code. Their scheduler fires. Their undisclosed behavior hits a third-party platform. Your IP is the one in the log.</p><p>From Michael’s side, the intelligence was technically correct. The request came from my machine. The attribution was wrong. There was no way to distinguish a developer running a forked repo from a coordinated scraping campaign — because structurally, they look identical.</p><p>That’s the real enigma. Not the race condition. The fact that a <em>distributed thundering herd</em> and a <em>distributed botnet</em> produce the same signature.</p><blockquote><strong>What I actually contributed</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OgSltaN74tpz3eAyYqqPcQ.png" /></figure><p>For context on where I stood in all of this: my contribution to Shadowbroker was a Spain and USA CCTV intelligence layer — 769 cameras across Spain’s 18 autonomous communities pulling from DGT and Madrid City Hall, 450+ USA cameras across military corridor DOT feeds, a pixel-level change detection alert pipeline with STIX 2.1 `observed-data` export, and a `stix_exporter.py` endpoint wrapping GDELT events, GPS jamming zones, and holding patterns into structured intelligence bundles.</p><p>None of that touches CrowdThreat. None of it is a scraper. The PR is open on `BigBodyCobain/Shadowbroker` and the fork lives at `github.com/AlborzNazari/Shadowbroker`.</p><blockquote><strong>What needs to happen upstream</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUQ5BWSwRMqarIwGc4_lwg.png" /></figure><p>The source author removed the CrowdThreat fetcher. That resolves the immediate incident. But the pattern remains — any future integration using the same hardcoded scheduler architecture will reproduce this.</p><p>The maintainer needs jitter-injected scheduling as the default pattern for any automated data fetch. Not optional. Not documented in a README footnote. Built into the base abstraction so every fork inherits the fix the same way they inherited the bug.</p><p><strong><em>`slowapi</em></strong>` was added in v0.9.5 as a per-instance rate limiter. It doesn’t solve the distributed case. The jitter injection is a separate problem and it still isn’t addressed in the codebase as of this writing.</p><p>Until it is, every developer running Shadowbroker is a potential entry in someone else’s threat feed. Not because of what they did. Because of when.</p><blockquote><strong>The incident timeline</strong></blockquote><pre>| Day | Event |<br>|-----|-------|<br>| Daily | `fetch_crowdthreat()` fires across all Shadowbroker instances globally |<br>| Saturday | Michael contacts me via LinkedIn — logs show my IP, platform degrading daily at 1pm UK time |<br>| Saturday | I acknowledge, begin pipeline audit |<br>| Saturday evening | Full analysis sent — traced to upstream `crowdthreat.py`, Docker stopped on both machines |<br>| Saturday evening | Michael confirms, escalates to BigBodyCobain |<br>| Following Friday | I follow up asking about the root cause |<br>| Following Friday | Michael confirms: the creator had added a scraper to the free tier, it has now been removed |</pre><blockquote><strong>The patches I applied to my fork</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2Md2wdEyHn4WGUTsYHNuw.png" /></figure><p>While the upstream incident was being resolved, I had my own bugs to fix. My contribution introduced three files that needed patching before the pipeline ran cleanly. Here’s exactly what changed and why:</p><blockquote><strong>`cctv_alert.py` — longitude key mismatch</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o7hZB3BCgmv5NV3JdM52gg.png" /></figure><p>Military flight records in Shadowbroker use `lng` as the longitude key, not `lon`. The alert pipeline was silently dropping all military flight proximity checks because the coordinate lookup returned `None` on every pass.</p><pre># before<br>lat = flight.get(&quot;lat&quot;)<br>lon = flight.get(&quot;lon&quot;) # always None for military flights<br># after<br>lat = flight.get(&quot;lat&quot;)<br>lon = flight.get(&quot;lng&quot;) # correct key for military feed</pre><p>Silent failures like this are the worst kind — no exception, no warning, just empty results that look correct until you check the source data directly. The only way to provide secure code and endpoints is to check all code and its components and not fully trust code review tools that come with minor to major issues.</p><blockquote><strong>`data_fetcher.py` — alert pipeline not scheduled, ingestors not running on startup</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DhwsbP-ACp8AgkDgjFnhbw.png" /></figure><p>Two separate issues in one file. The CCTV alert pipeline was written but never wired into APScheduler, so it never ran. And the CCTV ingestors were only triggered by the slow-tier scheduler cycle — meaning on a fresh boot, the camera database was empty for up to ten minutes before the first feed populated it.</p><pre># added to scheduler init<br>scheduler.add_job(_run_cctv_alert_pipeline, &quot;interval&quot;, minutes=5, id=&quot;cctv_alert&quot;)<br># added to startup sequence<br>async def startup():<br>await _run_all_cctv_ingestors() # populate immediately on boot<br>scheduler.start()</pre><p>The startup eager-load means any analyst spinning up a fresh instance sees live cameras immediately instead of staring at an empty map.</p><blockquote><strong>`main.py` — two missing endpoints</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-27WRttIbmhit1mdeMEvyw.png" /></figure><p>The STIX export and CCTV alert endpoints existed as logic in their respective service files but were never registered as API routes. FastAPI doesn’t autodiscover — if you don’t register the route, the endpoint doesn’t exist regardless of what the service layer implements.</p><pre># CCTV image proxy - routes external DOT image requests server-side<br># fixes CORS/403 on all US state DOT camera feeds<br>@app.get(&quot;/api/cctv/proxy-image&quot;)<br>async def proxy_image(url: str):<br>async with httpx.AsyncClient() as client:<br>r = await client.get(url, headers={&quot;User-Agent&quot;: &quot;Mozilla/5.0&quot;})<br>return Response(content=r.content, media_type=r.headers.get(&quot;content-type&quot;, &quot;image/jpeg&quot;))<br># CCTV alert feed - exposes active anomaly detections from change-detection pipeline<br>@app.get(&quot;/api/cctv/alerts&quot;)<br>async def api_cctv_alerts(request: Request):<br>return get_active_alerts()</pre><p>The proxy endpoint also fixed a secondary issue — all US state DOT camera image URLs return 403 when fetched directly from the browser due to referer checks. Routing them server-side bypasses that entirely.</p><blockquote><strong>`_store.py` — missing key in GPS jamming defaults</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YnWUDL94mmZLsn8ilTLuLA.png" /></figure><p>The GPS jamming store was missing `gps_jamming` from its default state dictionary. On first boot before any jamming data had been fetched, any read of the store threw a `KeyError`. Small fix, consistent crash.</p><pre># before<br>_defaults = {<br>&quot;flights&quot;: [],<br>&quot;ships&quot;: [],<br>…<br>}<br># after<br>_defaults = {<br>&quot;flights&quot;: [],<br>&quot;ships&quot;: [],<br>&quot;gps_jamming&quot;: [], # added<br>…<br>}</pre><p>Four files. All targeted. None of them structural rewrites — just gaps between what was designed and what was actually wired up. That’s usually where the bugs are.</p><blockquote><strong>The broader pattern</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xyYRRXRiLwAHWJ4USN7yxw.png" /></figure><p>This isn’t unique to Shadowbroker. Any open-source tool with a scheduled outbound fetcher and a meaningful fork population has this attack surface. The more popular the repo, the more dangerous a hardcoded timestamp becomes.</p><p>The open-source OSINT ecosystem specifically is vulnerable to this because:</p><blockquote>1. Tools are built to collect data — outbound requests are core functionality, not a side effect</blockquote><blockquote>2. Fork populations are large and global — one repo, hundreds of independent runners</blockquote><blockquote>3. Schedulers default to clean round numbers — `12:00`, `00:00`, `every().hour` — which creates natural synchronization</blockquote><blockquote>4. No coordination layer exists between fork instances by design</blockquote><p>The fix pattern is simple. Jitter at init. Rate limit at the fetcher level. Document the expected request volume per instance so platform operators know what normal looks like. To recap:</p><p><strong>Jitter at init.</strong> Every instance picks a random delay before firing. Zero to five minutes. Suddenly, a thousand simultaneous requests become a thousand requests nobody notices. It solves the request distribution problem. Presumably, 1000 requests would have 300 seconds to run.</p><p><strong>Rate limit at the fetcher level.</strong> One instance, one request, one window. Even if the scheduler misfires — even if something drifts — there’s a ceiling. You can’t spam your way past it. Alongside this important feature:</p><p><strong>Document the expected volume.</strong> Tell the platform what normal looks like. One GET per day per instance. If they see three thousand hits, they know it’s three thousand developers — not one actor with a botnet. Without that number, every legitimate request looks like the opening move of something worse.</p><p><em>The point is:</em></p><p><em>None of that is hard. It just has to be the default.</em></p><p><em>*This report is based on a live incident involving the Shadowbroker OSINT platform and CrowdThreat. All technical details are drawn from direct analysis of the codebase and firsthand correspondence with the security team. The hypothesis regarding fork population behavior is structural — the exact number of active instances is unconfirmed, but the architectural argument holds regardless of the specific count.*</em></p><p><em>*Alborz Nazari is the author of </em><a href="https://github.com/AlborzNazari/open-intelligence-lab"><em>Open Intelligence Lab</em></a><em>, an open-source graph-based CTI platform with MITRE ATT&amp;CK alignment and STIX 2.1 / TAXII 2.1 compliance. His Shadowbroker fork with Spain CCTV, USA military corridor cameras, and STIX export is at github.com/AlborzNazari/Shadowbroker.*</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=584db81a8ae4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Threading the Needle: Race Conditions, Atomic Violations, and the Concurrency Flaws That Break…]]></title>
            <link>https://medium.com/@alborznazari4/threading-the-needle-race-conditions-atomic-violations-and-the-concurrency-flaws-that-break-b7bfdc2f7993?source=rss-ed01f24e0e3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7bfdc2f7993</guid>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[software-security]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[race-condition]]></category>
            <dc:creator><![CDATA[Alborz Nazari]]></dc:creator>
            <pubDate>Tue, 05 May 2026 12:41:07 GMT</pubDate>
            <atom:updated>2026-07-23T09:44:19.681Z</atom:updated>
            <content:encoded><![CDATA[<h3>Threading the Needle: Race Conditions, Atomic Violations, and the Concurrency Flaws That Break Production Systems</h3><p><em>The author applies these concurrency principles in production in </em><a href="https://github.com/AlborzNazari/open-intelligence-lab"><em>Open Intelligence Lab</em></a><em>, a </em><a href="https://alborznazari.github.io/open-intelligence-lab/"><em>graph-based cyber threat intelligence platform</em></a><em> built on STIX 2.1, TAXII 2.1, and FastAPI, where concurrent ingestion pipelines and shared graph state require the same class of atomicity guarantees analyzed in this article. Note: Nearly all jargon is highlighted in </em><strong><em>bold</em></strong><em>.</em></p><blockquote><em>1. Head ( Proof of Concept &amp; Foundation )</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YXxvzD1BkPGBud8mSW-5oA.jpeg" /></figure><p><a href="https://github.com/AlborzNazari/SECURE_ATM_BANK_SYSTEM/tree/main">Click </a>for the codebase.</p><p>When dealing with <strong><em>non-deterministic issues</em></strong> like <strong><em>race conditions</em></strong>, there are several ways to catch the bugs that cause these flaws early in the <strong><em>SSDLC</em></strong>. The fix has to be preventive, something that structurally cuts off the problem before it has a chance to surface, not something bolted on after production blows up.</p><p>To actually solve this class of bugs, you first need to understand what you are dealing with. This section defines the problem at its core. From there we jump into the body, which is a full code review of an application built around the <strong><em>Separation of Concerns Software Design Principle</em></strong>. Then we land at the conclusion, where the outcome metrics and takeaways speak for themselves.</p><p>Back to race condition, these errors are hard to reproduce by creating different results, and they run in milliseconds, causing interleaving processes to use shared resources without taking their turn. This leads to overriding of thread values at runtime. Non-deterministic behavior takes place, and each iteration can generate a different result. One way to detect it is <strong><em>code review</em></strong>, which this article is based on. Other techniques include <strong><em>automated DevSecOps implementations</em> </strong>such as<em> </em><strong><em>SAST tools </em></strong>for <strong><em>static analysis</em></strong> and <strong><em>dynamic tools</em></strong> like ThreadSanitizer. This article touches on those briefly, but mostly focuses on the nature of threads, which are the baseline of software and hardware and the OS layer sitting in between them.</p><p>Why does a race condition happen? Processes on computers need to take turns to function correctly. Modern CPUs are <strong><em>multi-core</em></strong> and support concurrent thread execution, meaning multiple threads can run simultaneously across cores without the hardware raising exceptions on its own. In computer science, threads perform read and write operations on shared memory. If thread one is reading a value, thread two should wait until that operation completes before writing to the same location. Without a <strong><em>proper lock</em></strong>, thread two does not know thread one is already working on it and does not wait. Thus, an override happens, and the result becomes wrong.</p><p>In Windows<em> </em><strong><em>thread and process management</em></strong>, the scheduler acts as a non-deterministic thread processor. Its decisions about which thread runs next depend on many dynamic factors including current system load, hardware interrupts, and priority settings. We are talking about thousands of threads taking turns to run. At the core, the Windows kernel is responsible for <strong><em>CPU thread scheduling, context switching, managing priority queues, and providing low-level synchronization primitives such as mutexes and events.</em></strong></p><p>It is worth noting that Python threads share a single CPU core at a time due to the <strong><em>GIL</em></strong>, the <strong><em>Global Interpreter Lock</em></strong>, which serializes bytecode execution. This makes Python an interesting case: even with the GIL in place, the race condition still occurs because the GIL can be released between bytecode instructions, which is exactly the gap where the context switch happens. The GIL does not protect you from races on shared mutable state. It only serializes bytecode execution one thread at a time, and “one at a time” still means threads take turns, which still means one thread can read a value, get switched out, and another thread writes to the same location before the first thread finishes its Store instruction. The GIL is not a substitute for a mutex:</p><pre>import threading                         # Note that threading package <br>                                         # Uses CPU resources through GIL</pre><p>In programming, race conditions produce real damage. Consider a financial ATM system. The classic case is the double payment bug: two concurrent threads read the same account balance at the same time, both decide the payment is valid, and both execute it. One overrides the other, and the account ends up in the wrong state. No error is shown. The program runs as if the transaction happened twice, depending on which side of the transaction you are sitting on: a client or a vendor. This is a <strong><em>placeholder concept</em></strong> used as a conceptual pillar, not a model of how real banking systems work. Financial systems utilize far more advanced techniques. <strong><em>The example exists to illustrate that if the interpreter executes three functions simultaneously and a thread gets switched, terminated, or paused, it produces an unpredictable result during each runtime iteration.</em> </strong>The example below postulates that it may produce a correct, deterministic result 9 out of 10 times idealistically, and on the one failed attempt the CPU switches or ends the other thread mid-runtime:</p><pre>import threading                         # Note that threading package <br>                                         # Uses CPU resources through GIL<br>                  <br>counter = 0<br><br>def add_one():<br>    global counter<br>    for _ in range(100):<br>                                         # The &#39;Race&#39;: Read -&gt; Add -&gt; Write<br>        temp = counter <br>        counter = temp + 1               # This line causes the race because  <br>                                         # In Python&#39;s interpreter, bytecode <br>                                         # runs three steps that <br>                                         # In the time of context-switch<br>                                         # Is hard to reproduce<br><br>                                         # Start two threads at the same time <br>`                                        # The chunk runs two thread objects <br>                                         # Simultaneously <br>t1 = threading.Thread(target=add_one)<br>t2 = threading.Thread(target=add_one)<br>t1.start(); t2.start()<br>t1.join(); t2.join()<br><br>print(f&quot;Final counter: {counter}&quot;)</pre><p>The line below is what makes the race happen:</p><pre>counter = temp + 1</pre><p>The Python interpreter executes this line in three steps represented by bytecodes: <strong><em>Load, Add, and Store</em></strong><em>.</em> A race condition happens when the CPU pauses a thread between those steps, then thread two overrides thread one without taking its turn, and the result becomes unpredictable and non-deterministic. We can dry-run this code in two scenarios. First, when everything works correctly: the threads take turns, each outputs 100, and the total is 200. If a context switch happens mid-operation, the result becomes hard to reproduce and will differ across runs.</p><p>The old workaround was inserting artificial delays between thread operations to reduce the chance of collision, essentially putting a gap of milliseconds and hoping the threads miss each other. The real solution is enforcing mutual exclusion through <strong><em>atomic operations</em></strong> or <strong><em>mutex locks</em></strong>, which makes turn-taking between threads explicit and guaranteed rather than something that works most of the time until it suddenly crashes. Without that, shared state is never truly protected, and correctness becomes a matter of luck rather than design.</p><p>A race condition can come from implementation or from design, and that distinction matters. When the algorithm itself is fundamentally wrong about the ordering of shared operations, locking at the implementation level does not save you. You are patching over a structural problem. The flaw has to be caught at the design stage, which is exactly why threat modeling around concurrency belongs in the SDLC before a single line of code is written, not after the bug shows up in production. This is called <strong><em>production hindsight</em></strong>. Note that in modern DevSecOps practice, there are usually a <strong><em>dev version</em></strong> and a <strong><em>prod version</em></strong>. Catching concurrency flaws at the design stage is the only way to avoid that so-called hindsight.</p><p>Let’s dive into the differences between two fundamentally flawed code examples and a bad implementation:</p><pre>0.1 + 0.2 == 0.3   → False<br># actual result: 0.2999999999999998</pre><p>Computers understand high-level code as zeros and ones, and some floating-point numbers produce a repeating sequence when converted to binary. Take 0.1: in binary it is an unending <strong><em>repeating sequence</em></strong>, and the same applies to 0.2, 0.3, and even 1/3, which is 0.333 <strong><em>recurring </em></strong>in decimal. Intuitively, 0.25 converts cleanly to 0.01 in binary because it terminates. Python displays 0.3 on the screen as a rounded representation, masking the actual stored value. It is a small lie: 0.3 in binary is 0.010011001 indefinitely. Thus, the result is always wrong relative to real arithmetic. The system is deterministic but built on fixed approximations. The left side of the equation is not mathematically equal to the right side, because each value carries its own frozen rounding error, and those errors do not cancel when combined.</p><p>For this reason, banks never use binary floating point for money. They use <strong><em>fixed point arithmetic</em></strong><em>, </em><strong><em>scaling values</em></strong> by a power of 10: representing $1.99 as the integer 199 for example, so all operations stay in whole numbers and rounding errors never accumulate. This is the same principle that applies to concurrency: structural correctness at the design stage matters more than any lock or patch applied after the fact. A floating-point result that is wrong by design cannot be fixed by rounding. A concurrent algorithm that is wrong by design cannot be fixed by adding a lock. Both failures originate at the same layer: the structural decisions made before implementation begins. We address precautions for these structural failures in the BODY section of the article.</p><p>When Python encounters 0.1 + 0.2 == 0.3, it parses each literal independently. The value 0.1 is immediately stored as the nearest <strong><em>64-bit IEEE 754 double</em></strong>, which is not exactly 0.1. The same happens to 0.2 and to 0.3. Then the addition runs: the two imprecise representations of 0.1 and 0.2 are summed, producing a third 64-bit value. That result and the independently stored approximation of 0.3 are then compared bit by bit. They are not the same bit pattern, so the expression returns FALSE. Python never sees the clean numbers you typed. It is a small lie told three times before the equation even runs.</p><p>Now let’s look at why adding<strong><em> time.sleep()</em> </strong>may reduce collision but is algorithmically flawed. <strong><em>Threads are working at the same time, but check and act are separate operations in two separate moments in time.</em></strong><em> </em>Let&#39;s dive into the codebase to see the real structural problem:</p><pre>import threading<br>import time<br><br># Bank account — the shared state - Dictionary <br>account = {&quot;balance&quot;: 100}<br><br>def withdraw(amount, person):<br>    # STEP 1: CHECK<br>    if account[&quot;balance&quot;] &gt;= amount:<br>        # the OS can pause the thread RIGHT HERE<br>        # another thread runs, also passes the check<br>        # both threads now believe they have permission<br>        <br>        time.sleep(0.001)  # simulates real processing delay<br>        <br>        # STEP 2: ACT<br>        account[&quot;balance&quot;] -= amount<br>        print(f&quot;{person} withdrew €{amount} | Balance: €{account[&#39;balance&#39;]}&quot;)<br>    else:<br>        print(f&quot;{person} DENIED — insufficient funds&quot;)<br><br># Two people withdraw simultaneously<br>t1 = threading.Thread(target=withdraw, args=(100, &quot;Alice&quot;))<br>t2 = threading.Thread(target=withdraw, args=(100, &quot;Bob&quot;))<br><br>t1.start()<br>t2.start()<br>t1.join()<br>t2.join()<br><br>print(f&quot;\nFinal balance: €{account[&#39;balance&#39;]}&quot;)</pre><p>result:</p><pre>Alice withdrew €100 | Balance: €0<br>Bob   withdrew €100 | Balance: €-100   ← bank just lost €100<br>Final balance: €-100<br># The method is also called TOCTOU: Time of Check to Time of Use</pre><p>Most importantly, the <strong><em>check </em></strong>and the <strong><em>act </em></strong>are two separate operations occurring at two separate moments in time. The design splits them apart and does not guarantee a <strong><em>race-free solution</em></strong>. Therefore, the classic delay solution is cancelled.</p><p>So what is the fix? Adding a <strong><em>lock</em></strong>. A race condition bug happens when the programmer forgets to place a lock before the operation to make it <strong><em>atomic</em></strong>. The solution is a <strong><em>mutex lock</em></strong>, which eliminates the gap between <strong><em>check </em></strong>and <strong><em>act</em></strong>:</p><pre># FLAW BY BUG FIXED<br><br>with lock:<br>    counter += 1                    # lock added → fixed<br><br>with lock:<br>    if balance &gt;= amount: # check<br>        balance -= amount # act   ← # now both l inside the lock,<br>                                    # gap eliminated</pre><p><strong><em>Futex</em></strong><em> is how the OS implements it efficiently by avoiding kernel calls in the common </em><strong><em>uncontested case</em></strong><em>. The OS uses futex as a </em><strong><em>low-level CPU-kernel hybrid</em></strong><em>: userspace atomics when uncontested, a kernel syscall only when blocked. The OS uses futex to make that mutex fast and optimized.</em></p><blockquote>What happened behind the curtain in <a href="https://github.com/AlborzNazari/open-intelligence-lab">Open Intelligence Lab v.0.6.0</a>? Manual readiness probe Concept</blockquote><p><strong><em>OIL </em></strong>is deployed on<strong><em> Fly.io </em></strong>servers in the Amsterdam region, a <strong><em>Platform as a Service</em></strong> that handles<strong><em> container orchestration</em></strong> at its bottom layer.<strong><em> The readiness probe pattern</em></strong> we implemented in this chunk is the same concept <strong><em>Kubernetes</em></strong> uses natively as a built-in primitive.</p><p>When writing tests for software, the preliminary step is always a<strong><em> smoke test</em></strong>. The goal is simple: verify that all endpoints are reachable and that<strong><em> httpx methods </em></strong>are healthy and workable. If anything goes wrong, the system should fail safely and explicitly.</p><p>Are the Open Intelligence Lab endpoints working correctly? That is the question the smoke test answers on every push. Here are all endpoints under test.</p><pre><br>BASE = &quot;http://localhost:8000&quot;<br><br>TESTS = [<br>    (&quot;GET&quot;, &quot;/health&quot;,                           200), # https status                                         <br>    (&quot;GET&quot;, &quot;/&quot;,                                 200), # 200 correct<br>    (&quot;GET&quot;, &quot;/intelligence/graph/summary&quot;,       200),<br>    (&quot;GET&quot;, &quot;/intelligence/graph/edges&quot;,         200),<br>    (&quot;GET&quot;, &quot;/intelligence/entities&quot;,            200),<br>    (&quot;GET&quot;, &quot;/intelligence/entities/ids&quot;,        200),<br>    (&quot;GET&quot;, &quot;/intelligence/analyze/TA-001&quot;,      200),<br>    (&quot;GET&quot;, &quot;/intelligence/analyze/FAKE-0000&quot;,   404),<br>        ]</pre><p>All we want to know: is the server up? Do the routes respond? Does a bad ID return 404? <strong><em>The smoke.py</em></strong> file includes a BASE constant as a <strong><em>single source of truth </em></strong>for the localhost address. The + operator concatenates BASE and PATH directly into a valid URL.</p><p>With knowledge of the structural flaw in <strong><em>sleep()</em></strong>, we can reason about the problem precisely. <strong><em>CI/CD pipeline load</em></strong> is variable and non-deterministic. A cold <strong><em>uvicorn </em></strong>startup may take more or less than five seconds depending on the runner state at that moment. The smoke test fires first on every run, before any deeper pytest suite, and if <strong><em>uvicorn </em></strong>has not finished binding to its port by the time the first request fires, the test fails for the wrong reason entirely.</p><p>This is where the fatal gap lives. A hardcoded <strong><em>sleep()</em></strong> is an approximation, not a guarantee. The design architecture is based on a guess about timing, not verified readiness.</p><p>In v0.6.0 this was addressed by replacing <strong><em>sleep()</em></strong> with a<strong><em> retry loop</em></strong> using <strong><em>try/break</em></strong>, polling the <strong><em>/health </em></strong>endpoint directly until the server confirms it is alive:t any explicit signal that something went wrong.</p><pre>for attempt in range(10):<br>    try:<br>        httpx.get(f&quot;{BASE}/health&quot;, timeout=2)<br>        break<br>    except Exception:<br>        print(f&quot;  Waiting for server... attempt {attempt + 1}/10&quot;)<br>        time.sleep(1)<br></pre><p>This also eliminates the silent <strong><em>fallthrough behavior</em></strong>, where all retry attempts could exhaust quietly and the test suite would proceed into guaranteed errors with no clear signal that the server never started. That fallthrough pattern is structurally similar to the classic C and C++<strong><em> switch/case</em></strong> fallthrough bug, where execution continues past a boundary without any explicit signal that something went wrong.</p><p>After ten failed attempts, the system exits cleanly rather than cascading into noise:</p><pre>else:<br>    print(&quot;  Server never came up after 10 attempts. Aborting.&quot;)<br>    sys.exit(1)</pre><p>Finally, the test loop iterates over the TESTS tuples. Each tuple unpacks into three variables: <strong><em>method, path, </em></strong>and <strong><em>expected</em></strong>. The method variable is not used to drive the request since all current tests are GET requests, but it is kept in the tuple structure so the table remains readable and extensible:</p><pre>for method, path, expected in TESTS:<br>    try:<br>        r = httpx.get(BASE + path, timeout=10)<br>        status = &quot;PASS&quot; if r.status_code == expected else &quot;FAIL&quot;<br>        print(f&quot;  {status}: {method} {path} → {r.status_code} (expected {expected})&quot;)</pre><blockquote><em>2. Body ( Code Review: How &amp; Why? )</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cWN00BwP1j4yFY2v2qSKKQ.jpeg" /></figure><p>The Head established the theoretical foundation: what a race condition is at the bytecode and OS level, why <strong><em>TOCTOU </em></strong>is a design flaw rather than an implementation oversight, and why structural correctness at the design stage is the only real fix. The Body applies all of that to a concrete codebase. Every class, every method placement, every lock boundary in the following review maps directly back to a principle from the Head.</p><p>Now that we reviewed an introductory head as a <strong><em>POC</em></strong>, we can dive into the project and understand where the patterns are that prevent us from having a design flaw. To keep in mind: the bank system allows denominations of 20/40/60 to ensure <strong><em>atomicity </em></strong>and avoid <strong><em>race conditions.</em></strong> We already established that floating-point numbers are not allowed in banking systems. Those financial systems use <strong><em>precise decimal libraries</em></strong> to maintain a robust, essentially invincible layer of protection. Threat modeling, risk mitigation, and security frameworks have a significant place in financial systems, but for this article, which is a simple code review, we’ll be nitpicky about <strong><em>exception handling</em></strong> and <strong><em>race-free design</em></strong>. So in this banking ATM system, which we write from scratch, we model the design as an ATM System Simulator.</p><p>Based on <strong><em>SoC (Separation of Concerns) </em></strong>Software Design Principle, the software possesses four layers:</p><pre>validate_denomination()   -- Business rules only<br>BankAccount               -- State and concurrency only  <br>ATM                       -- User interaction only<br>simulations               -- Orchestration only</pre><p>Each of these layers does a separate task without addressing each other. <strong><em>SoC </em></strong>is a modular programming helper model that isolates the access to other file components and regards the proper encapsulation between different segments of a bigger system. A bug cannot penetrate a well-built <strong><em>SoC system</em></strong>. You can see the whole <strong><em>Design Layer:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*XfAuJpE7xXrR6oNl.png" /><figcaption><strong>Execution order: Layer 4 fires first at runtime. Layer 1 runs on every request. Registration order: all layers registered top-to-bottom at load time before any execution begins.</strong></figcaption></figure><p><strong><em>Execution order:</em> <em>Layer 4</em></strong> fires first at runtime. Layer 1 runs on every request.</p><p><strong><em>Registration order:</em></strong> all layers registered <strong><em>top-to-bottom at load time</em></strong> before any execution begins. Now, Let’s review the registering:</p><blockquote>Layer 4 — Simulations</blockquote><p>The simulation layer is the outermost shell of the program. It runs when you type python <strong><em>atm_bank.py</em></strong>. Four functions called in sequence from if <strong><em>__name__ == “__main__”</em></strong>, which is a starting point of the file execution:</p><pre>sim_denomination_rules()<br>sim_concurrent_withdrawals()<br>sim_invalid_amounts_under_load()<br>sim_transfers()</pre><p><strong><em>sim_denomination_rules()</em></strong><em> </em>loops over a list of amounts and prints which pass or fail the denomination gate. No threads, no concurrency, just the math proven visually before anything else runs.</p><p><strong><em>sim_concurrent_withdrawals()</em></strong> releases 50 threads simultaneously via threading.Barrier, all withdrawing 20 from a 500-balance account. <strong><em>Worst-case concurrency</em></strong> <strong><em>stress test</em></strong>. <strong><em>Invariant: balance must be exactly 0, never negative.</em></strong></p><p><strong><em>sim_invalid_amounts_under_load()</em></strong><em> </em>fires 20 threads with mixed valid and invalid amounts at the same time. Invalid ones are rejected at the gate before touching the lock. Proves bad input under load cannot corrupt the account.</p><p><strong><em>sim_transfers()</em></strong> starts Alice and Bob each with 500 and fires 20 threads transferring in both directions simultaneously. Invariant: alice.balance + bob.balance must equal 1000.<strong><em> </em></strong>Proves <strong><em>atomicity </em></strong><em>and</em><strong><em> deadlock prevention </em></strong>hold under<strong><em> real concurrent load.</em></strong></p><blockquote>Layer 3 — ATM</blockquote><p>The ATM class is the interface between the user and the bank. It knows nothing about <strong>locks</strong>, <strong>ledgers</strong>, or how the balance is stored. Its only job is to receive a request, call the account, and handle whatever comes back.</p><p>Two methods. That is the entire class.</p><p><strong>withdraw()</strong> takes an account, an amount, and a user name. It calls account.withdraw(), logs the result if it succeeds, and catches whichever exception comes back if it fails. Returns True on success and False on any failure.</p><p><strong>transfer()</strong> does the same for transfers. Calls <strong>account.transfer_to()</strong>, logs the result, catches any exception, returns True or False.</p><blockquote>The ATM class is intentionally thin. It reads result[“notes”] and result[“new_balance”] from the dictionary the account returns but never writes to the account directly. It has no _balance, no _lock, no _ledger. It cannot corrupt state because it has no access to state.</blockquote><p>This is the <strong><em>SoC</em></strong> boundary doing real work. The account owns correctness. The ATM owns communication. Important is: A bug in the ATM output formatting physically cannot reach the lock or the balance because the interface is the only point of contact between the two layers. <strong><em>ATM.__init__ </em></strong><em>serves as a </em><strong><em>constructor</em></strong><em>.</em></p><pre>class ATM:                  # line 355<br>    def __init__(self, atm_id=&quot;ATM-001&quot;):  # line 358</pre><blockquote>Layer 2 — BankAccount</blockquote><p><strong>BankAccount </strong>manages concurrency through one rule applied consistently everywhere: one lock owns all mutable state, and every operation that reads or writes any of it must hold that lock for the entire duration of the operation.</p><p>The four fields under the lock:</p><pre>self._balance         # the money<br>self._ledger          # the audit trail<br>self._failed_attempts # the failure counter<br>self._locked          # the suspension flag</pre><p>These four never change independently. They change together inside one with <strong>self._lock</strong>: block, which means no thread can observe any of them in an intermediate state.</p><p>Three concurrency problems solved directly in the class.</p><p><strong><em>TOCTOU</em></strong><em> </em>is solved in <strong><em>withdraw()</em> </strong>by putting the balance check and the deduction inside the same lock. No thread can read the balance between the check and the deduct because the lock is still held. The gap that causes the race condition does not exist.</p><p><strong><em>Atomicity</em></strong><em> </em>is solved in <strong><em>transfer_to()</em> </strong>by holding both account locks simultaneously before touching either balance. Debit and credit happen inside the same double lock. No thread sees one account decremented without the other incremented.</p><p><strong><em>Deadlock</em></strong><em> </em>is solved in<strong> <em>transfer_to()</em></strong><em> </em>by always acquiring the two locks in the same order, determined by comparing account IDs. Every transfer involving the same two accounts always locks the lower ID first. A circular wait becomes structurally impossible.</p><p>One thing that sits outside the lock deliberately is<em> </em><strong><em>validate_denomination()</em></strong><em>.</em> It runs before the lock is acquired because it is pure math with no shared state. Fifty threads can run it simultaneously with zero contention. Only threads that pass validation ever compete for the lock, which keeps contention low and throughput high.</p><p><strong><em>Constructors </em></strong>run once and first at object creation to validate initial state: <strong><em>type checks, required fields, sensible defaults</em></strong>.</p><p><strong><em>BankAccount.__init__</em></strong> <strong><em>_ </em></strong><em>serves as a </em><strong><em>constructor</em></strong><em>. </em><strong><em>BankAccount.__init__</em></strong> is not just setting fields. It is creating <strong><em>self._lock</em></strong>, the single object that makes every withdrawal, deposit, and transfer thread-safe. No lock at construction means no safety guarantees at runtime. The whole concurrency model lives or dies at that one line.</p><pre>class BankAccount:          # line 148<br>    def __init__(self, owner, initial_balance=0, account_id=None):  # line 152</pre><blockquote>Layer 1a — validate_denomination() and Layer 1b — threading.Lock()</blockquote><blockquote>Layer 1 splits into two independent concerns sitting at the same level but with nothing to do with each other.</blockquote><p><strong><em>Layer 1a</em></strong>,<strong><em> validate_denomination()</em></strong>, is the business rule layer. Pure math, no shared state, no lock needed. It runs before any lock is acquired and fifty threads can execute it simultaneously with zero contention. Its only job is to reject bad amounts before they reach the bank.</p><p><strong><em>Layer 1b</em></strong>, <strong><em>threading.Lock()</em></strong>, is the concurrency enforcement layer. One mutex per account, created by the<strong><em> OS </em></strong>as a futex and flipped atomically via the<em> </em><strong><em>CMPXCHG CPU instruction</em></strong><em>.</em> It wraps the check, deduct, and ledger write as one indivisible unit. Nothing that lives above it can observe an intermediate state.</p><p>The power of <strong><em>SoC software design</em></strong> lies in its independence and compartments rule: One enforces the rules of money. The other enforces the rules of concurrency. Neither knows the other exists.</p><p>So now we have a strcutural picture of how our software works. Let’s<strong><em> go to</em></strong> <strong><em>registering </em></strong>&amp; be more profound:</p><blockquote><em>Lines 1–130: validate_denomination</em></blockquote><p>In this <a href="https://github.com/AlborzNazari/SECURE_ATM_BANK_SYSTEM/blob/main/atm-bank/atm_bank.py">chunk</a>, the <strong><em>ATM</em></strong> runtime exposes its structure clearly. The whole financial data flow goes through three functions:</p><blockquote><strong><em>validate_denomination()<br>BankAccount.withdraw()<br>BankAccount.transfer_to()</em></strong></blockquote><p>Each one handles a specific exception, defined with camel-case<strong> type labels</strong> across three separate classes:</p><pre>DENOMINATION = 20<br>MAX_WITHDRAWAL = 600<br>MIN_WITHDRAWAL = 20<br><br># These camel-cased type labels<br># with keywords &#39;Exception&#39; &amp; &#39;pass&#39; do the job.<br><br>class DenominationError(Exception):<br>    pass<br><br>class InsufficientFundsError(Exception):<br>    pass<br><br>class AccountLockedError(Exception):<br>    pass</pre><p>Once python loads<strong> <em>atm_bank.py</em></strong> file, it reads from <strong><em>top-down</em></strong> to register them all, compile it to <strong><em>bytecodes</em></strong>, and stores it. <strong><em>Reading/Registering</em></strong> lines of code is different from execution order. Here you can see all the <strong><em>execution orders:</em></strong></p><pre>1. if __name__ == &quot;__main__&quot;     -- line 629, this fires first execution order<br>2. sim_denomination_rules()      -- first simulation<br>3. sim_concurrent_withdrawals()<br>       BankAccount(&quot;Alice&quot;, 500) -- __init__ runs HERE<br>       50 threads released<br>       atm.withdraw()<br>           validate_denomination() -- runs HERE<br>           with self._lock<br>               balance mutated<br>4. sim_invalid_amounts_under_load() <br>5. sim_transfers()</pre><p>Here is the exact top-down approach <strong><em>Python’s interprete</em></strong>r reads during the registering process. Note that<strong> <em>execution order</em></strong><em> </em>is different from reading order. Here is how the file gets read:</p><pre>line 1-14    -- reads docstring, stores it<br>line 16-19   -- executes imports, loads threading/time/random/datetime<br>line 22-27   -- executes _pl = threading.Lock(), defines log()<br>line 54-56   -- executes DENOMINATION=20, MAX_WITHDRAWAL=600, MIN_WITHDRAWAL=20<br>line 58-68   -- registers DenominationError, InsufficientFundsError, AccountLockedError<br>line 71-128  -- registers validate_denomination() as a function object<br>line 142-392 -- registers BankAccount class and all its methods<br>line 403-450 -- registers ATM class and all its methods<br>line 457-655 -- registers all simulation functions<br>line 629     -- hits if __name__ == &quot;__main__&quot;: -- NOW execution begins</pre><p>Line 629, this fires first:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*tOBIvl0UqSXzRgdT.png" /></figure><p>So<em> </em><strong><em>validate_denomination()</em></strong> is registered at line 71 when Python reads it top to bottom. But it does not execute until something calls it, which happens inside <strong><em>withdraw()</em></strong>, which is called from <strong><em>ATM.withdraw()</em></strong>, which is called from the simulation, which starts at line 629.</p><p>Basically, as the execution order starts with <strong><em>__main__</em></strong>, the First function sim_denomination_rules() is called. Second sim_concurrent_withdrawals(). Check the second path by reading the computer eyeball to understand why <strong><em>__init__</em></strong><em> </em>runs as the call happens here:</p><pre>account = BankAccount(&quot;Alice&quot;, initial_balance=500)<br>    atm     = ATM()</pre><p><strong><em>validate_denomination(amount)</em> </strong>handles <strong><em>DenominationError</em> </strong>as part of a fully <strong><em>stateless </em></strong>function. <strong><em>Stateless </em></strong>means it reads or writes nothing outside its local variables: The function doesn’t touch the<em> </em><strong><em>InsufficientFundsError</em> </strong>or <strong><em>AccountLockedError</em>.</strong> It inspects the input and raises the correct exception if that input is invalid. This runs before any lock is acquired or any account state is touched:</p><pre>def validate_denomination(amount):<br><br># Rule 1: must be a number<br>    if not isinstance(amount, (int, float)):<br>        raise DenominationError(<br>            f&quot;Invalid input: {amount!r} is not a number&quot;)<br>    # Rule 2: must be a positive integer<br>    # Floats like 20.0 are accepted (converted), 20.5 is rejected<br>    if isinstance(amount, float):<br>        if not amount.is_integer():<br>            raise DenominationError(<br>                f&quot;Amount {amount} is not a whole number. &quot;<br>                f&quot;ATM only dispenses whole notes.&quot;)<br>        amount = int(amount)<br>    # Rule 3: must be positive<br>    if amount &lt;= 0:<br>        raise DenominationError(<br>            f&quot;Amount must be positive. Got: {amount}&quot;)<br>    # Rule 4: must not exceed maximum<br>    if amount &gt; MAX_WITHDRAWAL:<br>        raise DenominationError(<br>            f&quot;Amount {amount} exceeds maximum withdrawal &quot;<br>            f&quot;of {MAX_WITHDRAWAL} per transaction. &quot;<br>            f&quot;Visit a branch for larger amounts.&quot;)<br>    # Rule 5: must be a multiple of DENOMINATION<br>    # % gives the remainder after division.<br>    # If the remainder is not zero, the amount cannot be dispensed<br>    # as whole notes.<br>    remainder = amount % DENOMINATION<br>    if remainder != 0:<br>        lower = (amount // DENOMINATION) * DENOMINATION<br>        upper = lower + DENOMINATION<br>        raise DenominationError(<br>            f&quot;Amount {amount} is not a multiple of {DENOMINATION}. &quot;<br>            f&quot;ATM only dispenses {DENOMINATION}-unit notes. &quot;<br>            f&quot;Did you mean {lower} or {upper}?&quot;)<br>    # All checks passed -- amount is valid<br>    return amount  # return the (possibly int-converted) amount</pre><p>This segment ensures validation is pre-filtered: a failing input never reaches the lock. It’s clean architectural practice to encapsulate validation as its own <strong><em>stateless side-effect-free</em> </strong>gate. <strong><em>isinstance() </em></strong>is a built-in python to check the amount is integer or float otherwise it raises <strong><em>denomination error.</em></strong> From the compiler view, the line if not isinstance(amount, (int, float)) compiles to:</p><pre>LOAD_FAST    amount<br>LOAD_GLOBAL  isinstance<br>LOAD_GLOBAL  int<br>LOAD_GLOBAL  float<br>BUILD_TUPLE  2          -- build (int, float) tuple<br>CALL         2          -- call isinstance(amount, (int, float))</pre><p>The infrastructure the rest of the module depends on is the package imports and the <strong><em>log()</em></strong> function:</p><pre>import threading  # threading module essential <br>import time       # time of the system &amp; hardware<br>import random     # random functionality for ###### <br>import datetime # hardware date</pre><p>Because Python reads top-down, the universal lock must be defined before anything that calls it. <strong><em>_pl</em> </strong>is our <strong><em>module-private</em></strong> lock variable. When initialized, it calls into the <strong><em>OS kernel</em></strong> via Python’s C layer, and the OS creates a<em> </em><strong><em>kernel futex</em></strong>, <strong>a</strong> <strong><em>synchronization </em></strong>primitive with one bit of state: held or free.</p><pre>_pl = threading.Lock()  # module-private lock<br><br>def log(tag, msg, sym=&quot;-&quot;):<br>    with _pl:  # acquires the futex; thread consumes zero CPU until released<br>        ts = datetime.now().strftime(&quot;%H:%M:%S.%f&quot;)[:-3]  # reads hardware clock<br>        print(f&quot;  {ts}  [{tag:&lt;16}] {sym} {msg}&quot;)</pre><p>The runtime cost of <strong><em>log </em></strong>is<strong> <em>O(1)</em></strong> per call, roughly 100 nanoseconds under no contention. <strong><em>Contention</em></strong><em> </em>is minimal by design because the critical section is intentionally small, so the lock will never be the bottleneck.</p><blockquote>atm_bank.py lines 130–214, Class BankAccount:</blockquote><p>After <strong><em>validate_denomination() </em></strong>returns a clean amount, the compiler continues top-down and reaches class BankAccount starting from line 142. The compiler does not execute the class immediately — it registers the blueprint and stores all method definitions in <strong><em>BankAccount.__dict__</em></strong><em>.</em></p><p>When the simulation calls <strong><em>BankAccount(“Alice”, 500)</em></strong>, Python allocates a fresh object in memory and fires <strong><em>__init__</em> </strong>automatically. This happens inside <strong><em>sim_concurrent_withdrawals()</em></strong>, before any thread is created, before any barrier is set, and before any withdrawal is attempted. The constructor sets up all seven attributes: <strong><em>owner, account_id, _balance, _lock, _ledger, _failed_attempts, and _locked</em>.</strong> From this moment the account exists in memory with a balance of 500, an empty ledger, a live mutex, and a failure counter at zero. Only after the constructor returns does the simulation create the 50 threads, release them through the barrier, and begin firing withdrawal requests at the account.</p><p><em>Important note:</em></p><p>The clean amount from <strong><em>validate_denomination() </em></strong>does not go into <strong><em>__init__</em></strong><em>.</em> It travels through <strong><em>withdraw()</em></strong><em>,</em> which is already a method on that same object.<em> </em><strong><em>withdraw()</em></strong><em> </em>picks up the clean amount, acquires the lock, checks the balance, and deducts:</p><pre>class BankAccount:<br> <br>    def __init__(self, owner, initial_balance=0, account_id=None):<br>        self.owner      = owner<br>        self.account_id = account_id or f&quot;ACC-{random.randint(10000,99999)}&quot;<br>        self._balance   = initial_balance  # private -- never access directly<br> <br>        # The ONE lock that protects ALL balance operations.<br>        # Every method that reads OR writes _balance must hold this lock.<br>        # No exceptions. This is what makes the account thread-safe.<br>        self._lock = threading.Lock()<br> <br>        # Transaction history -- also protected by _lock<br>        self._ledger = []<br> <br>        # Failed attempt counter<br>        # If a thread hammers the account with bad withdrawals,<br>        # We lock it after 3 consecutive failures.<br>        self._failed_attempts = 0<br>        self._locked = False        # account suspended flag<br><br>    @property                       # decorator for code execution<br>    def balance(self):<br>        &quot;&quot;&quot;<br>        Thread-safe balance read.<br>        Even a simple read needs the lock -- without it, a thread<br>        could read a partially-written value if another thread is<br>        mid-update (torn read on some architectures).<br>        &quot;&quot;&quot;<br>        with self._lock:<br>            return self._balance<br> <br>    @property<br>    def is_locked(self):<br>        with self._lock:<br>            return self._locked</pre><p><strong><em>deposit() </em></strong>as a<strong><em> function</em></strong>, by contrast, runs on every transaction and carries two runtime guards that constructors fundamentally cannot cover: It checks that the incoming amount is a positive number, and it checks whether the account has been suspended due to accumulated failed withdrawal attempts. That suspension state does not exist at construction time. It is a condition that develops over the account&#39;s lifetime, which is exactly why <strong><em>deposit </em></strong>must re-check it independently on every call, inside the mutex, not once at startup.</p><pre>def deposit(self, amount, depositor=&quot;system&quot;):<br>    &quot;&quot;&quot;<br>    Deposit any positive amount. No denomination restriction<br>    on deposits -- you can deposit any amount (cheque, transfer).<br>    &quot;&quot;&quot;<br><br>    # ── STEP 1: VALIDATE INPUT (before acquiring the lock) ────────────────<br>    # Reject bad input immediately -- no point entering a lock for garbage.<br>    if amount &lt;= 0:<br>        raise ValueError(f&quot;Deposit amount must be positive. Got: {amount}&quot;)<br><br>    # ── STEP 2: ACQUIRE MUTEX ─────────────────────────────────────────────<br>    # threading.Lock() ensures only one thread can execute this block at a<br>    # time. Prevents race conditions if multiple deposits/withdrawals fire<br>    # concurrently (e.g. two threads both reading the same balance and both<br>    # writing back, causing one update to be silently lost).<br>    with self._lock:<br><br>        # ── STEP 3: ACCOUNT STATUS CHECK (inside the lock) ────────────────<br>        # Must be checked INSIDE the lock, not before it. If checked outside,<br>        # another thread could suspend the account in the gap between your<br>        # check and your write -- a classic TOCTOU (Time-Of-Check-Time-Of-Use)<br>        # race condition.<br>        if self._locked:<br>            raise AccountLockedError(<br>                f&quot;Account {self.account_id} is suspended.&quot;)<br><br>        # ── STEP 4: MUTATE BALANCE ────────────────────────────────────────<br>        # Snapshot old balance first -- needed for the return receipt and<br>        # for audit purposes without a second read after the write.<br>        old_balance    = self._balance<br>        self._balance += amount<br><br>        # ── STEP 5: WRITE TO LEDGER (inside the same lock) ────────────────<br>        # Critical design decision: ledger write is inside the same lock as<br>        # the balance update. This guarantees they are always in sync.<br>        # If the ledger write were outside the lock, a thread could read a<br>        # new balance with no corresponding ledger entry -- broken audit trail.<br>        self._ledger.append({<br>            &quot;type&quot;:      &quot;DEPOSIT&quot;,<br>            &quot;amount&quot;:    amount,<br>            &quot;balance&quot;:   self._balance,   # post-deposit snapshot<br>            &quot;by&quot;:        depositor,        # who triggered it (user or system)<br>            &quot;timestamp&quot;: datetime.now().isoformat(),<br>        })<br><br>        # ── STEP 6: RETURN RECEIPT ────────────────────────────────────────<br>        # Return a plain dict so the caller gets full before/after context<br>        # without needing to query the account again (avoids a second lock).<br>        return {<br>            &quot;success&quot;:     True,<br>            &quot;old_balance&quot;: old_balance,<br>            &quot;new_balance&quot;: self._balance,<br>            &quot;amount&quot;:      amount,<br>        }</pre><p>We already had built our <strong><em>deposit()</em> </strong>runs in six sequential steps, each placed deliberately.</p><p>Step 1 validates the input before touching anything shared. If amount &lt;= 0, a<strong><em> ValueError</em></strong> is raised immediately and the function exits. No lock acquired, no shared state touched. Garbage never reaches the mutex.</p><p>Step 2 acquires <strong><em>self._lock</em></strong>. From this point only one thread can be inside this block at a time. Every other thread attempting a deposit, withdrawal, or transfer on the same account parks at this line and waits.</p><p>Step 3 checks<strong><em> self._locked </em></strong>inside the lock, not before it. This placement is intentional. If the suspended check happened outside the lock, another thread could suspend the account in the gap between your check and your write. That is a textbook <strong><em>TOCTOU</em></strong> violation. Inside the lock, the status you read and the write you are about to make are one atomic unit.</p><p>Step 4 snapshots old_balance before mutating. This gives the return receipt an accurate before figure without needing a second read after the write. Then <strong><em>self._balance += amount</em></strong> runs, three bytecode instructions under one lock, so no other thread can observe the intermediate state between the read and the write.</p><p>Step 5 writes<strong><em> the ledger entry</em></strong> inside the same lock as the balance mutation. This is the critical design decision. If the ledger write were outside the lock, a thread could read a new balance with no corresponding ledger entry, and the books would not balance. Inside the same lock, balance and ledger change together as one indivisible unit. No audit can catch them disagreeing.</p><p>Step 6 returns a plain dictionary containing the before balance, after balance, and amount. The caller gets full context without needing to query the account again, which would require acquiring the lock a second time unnecessarily.</p><blockquote><em>atm_bank.py:lines 216–394: Withdraw Function Call</em></blockquote><p><strong><em>withdraw()</em> </strong>is the first method where a real user-initiated operation occurs. Before any balance mutation happens, it delegates to <strong><em>validate_denomination(amount)</em></strong>, which enforces denomination rules on the incoming amount. This is the first point in the execution flow where raw user input gets sanitized and constrained before account state is touched.</p><pre>def withdraw(self, amount, requester=&quot;unknown&quot;):<br><br>    # STEP 1: denomination check -- OUTSIDE lock<br>    try:<br>        amount = validate_denomination(amount)<br>    except DenominationError as e:<br>        log(requester, f&quot;REJECTED {amount} -- {e}&quot;, &quot;[X]&quot;)<br>        with self._lock:<br>            self._failed_attempts += 1<br>            if self._failed_attempts &gt;= 3:<br>                self._locked = True<br>        raise<br><br>    # STEP 2: everything inside ONE lock<br>    with self._lock:<br>        if self._locked:<br>            raise AccountLockedError(...)<br><br>        if self._balance &lt; amount:        # CHECK<br>            self._failed_attempts += 1<br>            if self._failed_attempts &gt;= 3:<br>                self._locked = True<br>            raise InsufficientFundsError(...)<br><br>        old_balance    = self._balance<br>        self._balance -= amount           # DEDUCT<br><br>        self._failed_attempts = 0<br><br>        self._ledger.append({...})        # LEDGER<br><br>        return {&quot;success&quot;: True, ...}</pre><p><strong><em>validate_denomination() </em></strong>has no knowledge of accounts, locks, or failure counters. It checks the number and raises if it is wrong.<strong> <em>‘raise’</em></strong> exits the function and propagates the exception upward to the caller. The software continues running. The <strong><em>ATM</em></strong> catches the exception, logs the rejection, and returns False to the simulation.</p><pre>except DenominationError as e:<br>    log(requester, f&quot;REJECTED {amount} -- {e}&quot;, &quot;[X]&quot;)  # tell the world<br>    with self._lock:<br>        self._failed_attempts += 1                       # punish the account<br>        if self._failed_attempts &gt;= 3:<br>            self._locked = True<br>    raise                                                # propagate upward</pre><p>The current design is single-attempt by architecture. Each call to <strong><em>withdraw() </em></strong>is one atomic request. The retry responsibility belongs at the caller level, not inside the bank. The minimal fix is to replace the single attempt in<em> </em><strong><em>sim_concurrent_withdrawals() </em></strong>with a loop over valid amounts<em>:</em></p><pre>def customer(cid):<br>    valid_amounts = [20, 40, 60, 80, 100, 120, 140, 160, 180, 200]<br>    for attempt in valid_amounts:<br>        success = atm.withdraw(account, attempt, user=f&quot;Cust-{cid:02d}&quot;)<br>        if success:<br>            break   # got money, stop trying</pre><p>The amount must be until 600. Therefore:</p><pre>valid_amounts = [20, 40, 60, 80, 100, 120, 140, 160, 180, 200,<br>                 220, 240, 260, 280, 300, 320, 340, 360, 380, 400,<br>                 420, 440, 460, 480, 500, 520, 540, 560, 580, 600]</pre><p>The important point is: <strong><em>hardcoding </em></strong>should be avoided when it comes to the number of arrays. Another way, computationally safer, no hardcoding means no <strong><em>memory allocation</em></strong> to tamper with. As 30 integers saved in the memory, <strong>availability of the design</strong> is maintained and is a must to secure turn-based systems. Generate it each time:</p><pre>valid_amounts = list(range(20, 620, 20))</pre><p><strong><em>range(20, 620, 20) </em></strong>means start at 20, stop before 620, step by 20. Produces exactly 30 values from 20 to 600. Same result, one line.</p><p><strong><em>range(x,y,z)</em></strong> is bounded by design and cannot go indefinite. It is smarter by design as it is tied to two constants:<em> </em><strong><em>Denomination </em></strong>and <strong><em>Max_Withdrawal</em></strong><em>.</em> We have flexibility to change the structural rules of the financial system without touching the retry logic. The retry range updates automatically because it derives from the same constants that define the business rules. That coupling is intentional: when the denomination changes, the retry behavior changes with it, and nothing breaks silently.</p><p>Here is the comparison of the operations:</p><pre>hardcoded array    -- 30 integers in memory, typo risk, manual maintenance<br>list(range(...))   -- 30 integers in memory, no typo risk, but still 30 integers<br>range(...)         -- 3 integers in memory, no typo risk, computes on demand, freed on break</pre><p>The current code makes a single withdrawal attempt per customer with no retry on failure. The most optimized fix is to replace that single attempt with a<strong><em> lazy generator </em></strong>using bare <strong><em>range(x,y,z)</em></strong>, which produces<strong> <em>one denomination value at a time</em></strong><em> </em>on demand and stops computing the moment a successful withdrawal occurs. Unused values are never generated at all.</p><p>Therefore, the <strong>customer(cid)</strong> is replaced with:</p><pre># AFTER -- retry loop using constants<br>def customer(cid):<br>    for attempt in range(DENOMINATION, MAX_WITHDRAWAL + DENOMINATION, DENOMINATION):<br>        success = atm.withdraw(account, attempt, user=f&quot;Cust-{cid:02d}&quot;)<br>        with results_lock:<br>            if success:<br>                results[&quot;success&quot;] += 1<br>                break<br>            else:<br>                results[&quot;failed&quot;] += 1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*6bZJh9ir_1jPWASu.png" /></figure><blockquote>atm_bank.py: A Quick Review</blockquote><blockquote><strong><em>ATM.withdraw(): The Handoff Layer</em></strong></blockquote><p><strong>The</strong> <strong><em>ATM </em></strong>catches all three exception types independently. This is deliberate. Each exception type carries different information and maps to a different failure mode:</p><blockquote><strong><em>denomination errors </em></strong>are input validation failures, insufficient funds are state failures, account locked is a security state.</blockquote><p>Catching them as one generic Exception would collapse that distinction and make logging useless.</p><p><strong><em>result[“notes”]</em></strong> is <strong><em>amount // DENOMINATION. </em>The</strong> <strong>ATM</strong> reads this from the return dict rather than computing it again. No second lock acquisition, no second read of _balance. The account handed back everything the ATM needs in one atomic return.</p><p><strong><em>user[:10] </em></strong>is a width cap for the log formatter. The<strong><em> [tag:&lt;16] </em></strong>format string in <strong><em>log()</em></strong> pads to 16 characters. Truncating at 10 keeps it clean under concurrent output where multiple threads are writing simultaneously through <strong><em>_pl</em></strong>.</p><blockquote><strong><em>transfer_to(): Two-Account Data Flow and Deadlock Prevention</em></strong></blockquote><p>Transfer touches two accounts, which means two locks. Two locks means potential <strong><em>deadlock </em></strong>if two threads acquire them in opposite order simultaneously.</p><p>The lock ordering is determined by <strong><em>account_id </em></strong>string comparison before either lock is acquired. Thread A doing Alice to Bob and thread B doing Bob to Alice will both compare IDs and both decide to lock the lower ID first. They compete for the same first lock, one wins, one waits. No circular wait. No deadlock. The ordering is consistent across every possible pair of accounts in the system.</p><p>The data flow inside the double lock:</p><pre>first_lock acquired<br>    second_lock acquired<br>        self._locked check                 -- source account status<br>        self._balance &gt;= amount check      -- source has funds<br>        self._balance -= amount            -- debit source<br>        target_account._balance += amount  -- credit target<br>        ts = datetime.now().isoformat()    -- one timestamp for both entries<br>        self._ledger.append(TRANSFER_OUT)<br>        target_account._ledger.append(TRANSFER_IN)<br>        return dict<br>    second_lock released<br>first_lock released</pre><p>Both balance mutations happen inside the same double lock. No thread can observe <strong><em>self._balance</em></strong> decremented without<strong><em> target_account._balance</em></strong> incremented. One timestamp ts is shared between both ledger entries so both sides of the transfer are traceable as one atomic event.</p><blockquote><strong><em>sim_invalid_amounts_under_load(): The Pre-Filter Gate Under Concurrency</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*ETjhqATk4W93MyqGeR7hiw.png" /></figure><p>20 threads, 10 valid amounts interleaved with 10 invalid ones. The invalid amounts hit <strong><em>validate_denomination() </em></strong>and raise <strong><em>DenominationError</em></strong> before a single lock is acquired on the account. They consume no lock time, produce no contention, and cannot <strong><em>corrupt _balance</em></strong> or <strong><em>_ledger</em></strong> because they never reach either.</p><p><strong><em>i % len(amounts)</em></strong> cycles through the list deterministically regardless of thread count. Thread 0 gets <strong><em>amounts[0]</em></strong>, thread 20 gets <strong><em>amounts[0] </em></strong>again. This gives a predictable mix of valid and invalid inputs across any number of threads without hardcoding a separate list per thread.</p><p>The three exception types map to three distinct result buckets. valid_ok means the amount was valid and funds were available.<strong><em> invalid_rejected</em></strong> means <strong><em>validate_denomination() </em></strong>killed it before the lock. insufficient means the amount was valid but the account ran low. Each bucket is a different failure mode, tracked independently inside<strong><em> r_lock.</em></strong></p><blockquote>sim_transfers(): Invariant Proof Under Concurrent Load</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*cfIcQ7eBp8ViRzyd1tb1Vw.png" /></figure><p><strong><em>Account IDs </em></strong>are hardcoded as ACC-0001 and ACC-0002 here, unlike the random IDs assigned by <strong><em>__init__</em> </strong>in other simulations. The reason is determinism in lock ordering. <strong><em>transfer_to()</em></strong> uses <strong><em>account_id string comparison</em></strong> to decide which lock to acquire first. <strong><em>Fixed IDs</em></strong> make the lock order predictable: <strong><em>ACC-0001 &lt; ACC-0002</em></strong>, so Alice’s lock is always acquired first regardless of transfer direction.</p><p>Even-numbered threads transfer Alice to Bob. Odd-numbered threads transfer Bob to Alice. Both directions run simultaneously across 20 threads. The invariant check is a<strong><em>lice.balance + bob.balance == 1000</em></strong>. If <strong><em>atomicity </em></strong>is violated even once, one transfer’s debit lands without its credit and the total drops below 1000. That is the bug this simulation is designed to catch deterministically.</p><p><strong><em>random.choice([20, 40, 60, 80, 100]</em></strong>) is not seeded, so amounts vary per run. The test passes regardless because the invariant does not depend on individual balances, only their sum. A concurrency test should not be fragile to the specific amounts transferred.</p><blockquote><strong>print_statement(): Read-Only Ledger Path</strong></blockquote><p><strong><em>list(self._ledger)</em> </strong>creates a shallow copy of the ledger inside the lock. The lock is released immediately after. The caller receives a snapshot consistent at the moment of the read. If the caller iterates the returned list after the lock is released they are iterating a copy, not the live ledger, so concurrent writes after the call do not affect the snapshot.</p><p><strong><em>entry.get(‘by’, ‘?’)</em></strong><em> </em>uses a default because not all ledger entry types guarantee the by field. Transfer entries carry to and from fields alongside by. The get with a fallback means print_statement does not crash on any <strong><em>ledger entry type</em></strong>, past or future. Defensive read on a dict that may evolve.</p><blockquote><strong><em>The Demo Account and Entry Point</em></strong></blockquote><p>The demo account runs single-threaded after all four simulations complete. Its purpose is to show the full lifecycle of one account in isolation: two valid withdrawals, two denomination rejections, one more valid withdrawal, then a printed ledger. The ledger shows three <strong><em>WITHDRAWAL entries</em></strong> and nothing for the two rejections, because rejected amounts never reach the lock and never touch the ledger.</p><p>quiet is parsed but not wired into the simulation functions in this version. It is a hook for a future mode where thread-by-thread log output is suppressed and only summary metrics print. The architecture supports it because all logging goes through <strong><em>log()</em></strong>, which is one function to gate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*gUT2jthHUhZ8ImiAZku_zA.png" /></figure><p>That block at the bottom of if <strong><em>__name__ == “__main__”</em></strong><em>:</em> is a standalone demo account that runs after all four simulations finish. It is not a stress test. It is a readable walkthrough showing one account’s full lifecycle in sequence.</p><p>A single account called “Demo” is created with 500 balance and a fixed ID so the output is predictable. Five withdrawal attempts are fired one by one, not concurrently. Two of them are intentionally wrong amounts, 33 and 15, which get rejected by validate_denomination() before touching the lock. Three succeed, 20, 100, and 60, which deduct a total of 180 from the balance.</p><p><strong><em>print_statement()</em> </strong>then prints the full ledger at the end, showing every transaction that was recorded, the amount, the running balance after each one, and who triggered it. The two rejected amounts never appear in the ledger because they never reached the lock and no ledger entry was written for them.</p><p>The demo account exists purely for human readability. Where the simulations produce parallel output from 50 threads interleaving, this block produces a clean sequential record you can read top to bottom and understand exactly what happened and in what order.</p><blockquote><strong><em>Full execution data flow in pseudo-code:</em></strong></blockquote><pre>```text<br><br>__main__<br>    sim_denomination_rules()          -- no threads, pure validation output<br>    sim_concurrent_withdrawals()      -- 50 threads, barrier, one account<br>    sim_invalid_amounts_under_load()  -- 20 threads, mixed valid/invalid<br>    sim_transfers()                   -- 20 threads, two accounts, double lock<br>    BankAccount(&quot;Demo&quot;, 500)          -- __init__, single account, no threads<br>    atm.withdraw(acc, 20)             -- valid, ledger entry written<br>    atm.withdraw(acc, 33)             -- DenominationError, no ledger entry<br>    atm.withdraw(acc, 100)            -- valid, ledger entry written<br>    atm.withdraw(acc, 15)             -- DenominationError, no ledger entry<br>    atm.withdraw(acc, 60)             -- valid, ledger entry written<br>    print_statement(acc)<br>        account.statement()<br>            lock acquired<br>            copy ledger               -- snapshot: 3 entries<br>            lock released<br>        iterate snapshot              -- prints 3 rows, no lock held<br>```</pre><p>Final balance: 500–20–100–60 = 320. Three ledger entries. Two silent rejections that left no trace in account state.</p><blockquote>3. Feet ( Conclusion and Outcome metrics )</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k827MPabhoNhGYaWwjSn8w.jpeg" /></figure><p><em>note: All metrics are in </em><strong><em>bold | Italic</em></strong><em>.</em></p><p>Based on everything covered in the article, here are the <strong><em>outcome metrics</em></strong> and <strong><em>conclusion points </em></strong>grouped by category.</p><p>The interpreter view shows where the race window physically exists. The architecture shows how <strong><em>SoC </em></strong>closes it structurally. The Python primitives show the exact tools used and their cost. The simulation metrics prove the invariants hold under worst-case concurrency.</p><blockquote><strong><em>Interpreter View</em></strong></blockquote><p><strong><em>counter = temp + 1</em></strong> compiles to three bytecodes:<strong><em> Load, Add, Store</em></strong>. The race window is the gap between any two of those three instructions.</p><p><strong><em>GIL</em></strong> serializes bytecode execution but releases between instructions. That release gap is where the context switch happens. <strong><em>GIL </em></strong>is not a mutex substitute.</p><p><strong><em>validate_denomination()</em></strong> compiles to<strong> <em>LOAD_FAST, LOAD_GLOBAL, BUILD_TUPLE, CALL.</em></strong> Pure stack operations, no shared memory touched, zero contention possible at bytecode level.</p><p><strong><em>Rejected amounts exit at bytecode</em></strong> <strong><em>level before any lock instruction is ever issued. </em></strong>The lock acquisition bytecode is never reached for invalid input.</p><blockquote><strong><em>Software Architecture</em></strong></blockquote><p><strong><em>SoC</em> </strong>enforced <strong><em>four </em></strong>hard boundaries. A bug in ATM formatting cannot reach _balance or _lock <strong><em>because the interface is the only contact point between layers.</em></strong></p><p>Two locks in scope simultaneously in sim_concurrent_withdrawals(): self._lock owns account state, results_lock owns result tracking. Merging them would serialize result recording with balance mutation, unnecessary contention with no correctness benefit.</p><p><strong><em>transfer_to() </em></strong>holds two locks simultaneously with consistent ordering by account_id. Circular wait is structurally impossible. Deadlock cannot occur regardless of thread count or transfer direction.</p><p><strong><em>Ledger </em></strong>write is inside the same lock as balance mutation. Balance and audit trail are one atomic unit. No audit can observe them disagreeing.</p><p><strong><em>validate_denomination()</em></strong> runs outside the lock. 50 threads can execute it simultaneously with zero contention. Only threads that pass validation ever compete for the lock. Lock contention is proportional to valid requests only.</p><blockquote><strong><em>Python Functions and Primitives</em></strong></blockquote><p><strong><em>threading.Lock()</em></strong> maps to OS futex: userspace atomic when uncontested, kernel syscall only when blocked. Runtime cost O(1), roughly 100 nanoseconds under no contention.</p><p><strong><em>threading.Barrier(50)</em></strong> holds all 50 threads until the last one arrives, then releases simultaneously. Without it threads stagger on startup and the stress test is not meaningful.</p><p><strong><em>list(self._ledger)</em></strong> inside the lock produces a snapshot. Caller iterates the copy after lock release. Concurrent writes after the call do not affect the snapshot.</p><p><strong><em>range(DENOMINATION, MAX_WITHDRAWAL + DENOMINATION, DENOMINATION)</em></strong> stores 3 integers in memory, computes on demand, frees on break. Tied to the same constants as the business rules so retry logic updates automatically when denomination changes.</p><p><strong><em>isinstance(amount, (int, float)) </em></strong>runs at bytecode level as BUILD_TUPLE then CALL. Stateless, no shared memory, safe to call from any number of threads simultaneously.</p><blockquote><strong><em>Simulation Metrics</em></strong></blockquote><p><strong><em>sim_concurrent_withdrawals()</em></strong>: 50 threads, 500 balance, 20 per withdrawal. 25 succeed, 25 rejected, final balance exactly 0 on every run. balance &gt;= 0 invariant never violated.</p><p><strong><em>sim_transfers():</em></strong> 20 threads, two accounts, random amounts, both directions. alice.balance + bob.balance == 1000 preserved on every run. Zero atomicity violations across all transfer combinations.</p><p><strong><em>sim_invalid_amounts_under_load():</em></strong> 20 threads, 10 valid, 10 invalid amounts. Invalid inputs cost one function call each. Lock contention produced by valid requests only. Account state uncorrupted across all runs.</p><p><strong><em>Demo account</em></strong>: 500 initial, three valid withdrawals of 20, 100, 60. Two denomination rejections of 33 and 15. Final balance 320. Ledger contains exactly 3 entries. Rejections left no trace in account state.</p><blockquote>The Proof of Correctness</blockquote><p><strong><em>Stress tests</em></strong> for threaded financial systems are not optional. <strong><em>Unit tests</em></strong> prove a function works in isolation. Integration tests prove components work together. Neither proves correctness under simultaneous load because they run sequentially by default. A race condition is a timing phenomenon. It does not exist in sequential execution. You can have 100 percent test coverage and zero race conditions caught because your tests never created the conditions where the bug appears.</p><p><strong><em>A stress test</em></strong> is different in kind, not just degree. It does not ask whether the code is logically correct. It asks whether the code is correct when ten, fifty, or ten thousand things happen at the same time. That is the only question that matters in a financial system where concurrent requests are not an edge case. They are the normal operating condition.</p><p>The consequences of skipping it in finance are specific and severe. A race condition in a withdrawal function does not throw an exception. It does not log an error. It silently produces a wrong balance. Money is created or destroyed with no trace in the ledger. The audit trail looks clean. The books appear to balance. The bug is invisible until someone notices the numbers do not add up, which in production could be weeks or months after the fact.</p><p><strong><em>The stress test </em></strong>surfaces that bug in development, in a controlled environment, with a deterministic invariant you can check programmatically. Balance must equal exactly zero. Total funds must equal exactly one thousand. Either it does or it does not. No ambiguity.</p><p>For threaded financial systems the stress test is not a quality gate you can defer. It is the proof of correctness. Everything else is optimism.</p><p>Build the lock first. Write the stress test second. Ship third. In that order, every time.</p><blockquote>Alborz Nazari is a cybersecurity engineer based in Barcelona specializing in threat intelligence and DevSecOps.<br>He is the author of Open Intelligence Lab, an open-source graph-based CTI platform built on STIX 2.1, TAXII 2.1, and FastAPI.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7bfdc2f7993" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Open Intelligence Lab v0.5.0: From Research Platform to Production CI/CD Pipeline]]></title>
            <link>https://medium.com/@alborznazari4/open-intelligence-lab-v0-5-0-from-research-platform-to-production-ci-cd-pipeline-4fb56cd21cd7?source=rss-ed01f24e0e3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fb56cd21cd7</guid>
            <category><![CDATA[threat-intelligence]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[application-security]]></category>
            <dc:creator><![CDATA[Alborz Nazari]]></dc:creator>
            <pubDate>Fri, 03 Apr 2026 22:10:38 GMT</pubDate>
            <atom:updated>2026-04-07T00:00:18.967Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QcFNM2mgyUFr78ualOBmzg.png" /></figure><h3>The Problem with Research-Grade Threat Intelligence</h3><p>Most threat intelligence platforms live in one of two states: a polished commercial product behind a paywall, or a research prototype that works on the developer’s machine and nowhere else. Open Intelligence Lab started as the latter. v0.1.0 through v0.4.0 built a serious intelligence engine — graph-based threat modeling, STIX 2.1 export, TAXII ingestion, MISP live feeds, and provenance validation. But none of it had a CI/CD pipeline. Every deployment was manual. Every push to main was a leap of faith.</p><h3>v0.5.0 Changes That</h3><p>v0.5.0 adds a full 5-stage GitLab CI/CD pipeline. Not a demo pipeline. Not a placeholder. A pipeline that actually runs lint, executes tests, builds a Docker image, scans for CVEs, and sits one manual button-press away from deploying to production.</p><p>GitLab CI/CD Pipeline: <a href="https://gitlab.com/alborznazari4/open-intelligence-lab/-/pipelines">https://gitlab.com/alborznazari4/open-intelligence-lab/-/pipelines</a></p><h3>The Intelligence Case</h3><p>The original goal of Open Intelligence Lab was dynamic attribution. Static datasets do not track emerging C2 infrastructure or zero-day campaigns. v0.3.0 added STIX 2.1 and TAXII transport — the standard protocol for threat intelligence exchange that mandates TLS, encrypting all data in transit end-to-end. v0.4.0 added MISP live feed ingestion and provenance validation. Most government agencies, CERT teams, and ISACs use MISP for community-oriented threat sharing. Embedding it makes automatic updates and community features feasible without adding unnecessary complexity.</p><p>Provenance validation is the trusted handshake. Where does the data come from? Each graph needs a chain of custody that organizations can trust. Fields like timestamp, reported_by, primary_source, and trust_level together give us the chain of custody needed for a gold standard threat intelligence project.</p><p>Every component exists because the ecosystem demands it: MISP needs a database and cache to function, TAXII mandates HTTPS, and a browser will not call an HTTP endpoint from an HTTPS page — so Caddy is not optional. The API runs on HTTP internally. Caddy handles HTTPS on port 8443 and forwards to port 8000, so the API never manages certificates itself.</p><h3>Pipeline Architecture</h3><h3><strong>Stage 1 — Validate</strong></h3><p>Two jobs run in parallel. lint checks code quality across api/ and backend/ using flake8, black, and isort. schema_validate hits every JSON dataset and STIX export file to confirm structural integrity before anything else runs. If your data model is broken, you know before you build.</p><h3><strong>Stage 2 — Test</strong></h3><p>unit_tests runs pytest with coverage reporting, producing JUnit XML artifacts that GitLab renders as a test report. api_smoke_test spins up the actual FastAPI server inside the CI container, waits five seconds, then fires HTTP requests at /health, /intelligence/graph/summary, and /intelligence/entities. If the API does not respond 200, the pipeline fails. This is not mocking. This is the real server, running against real datasets, proving the system works end to end on every push.</p><h3><strong>Stage 3 — Build</strong></h3><p>build_docker builds a Docker image tagged with the exact commit SHA and pushes it to the GitLab Container Registry. Every commit produces a traceable, immutable artifact. tag_release stamps a build.env dotenv artifact with the version string and build timestamp.</p><h3><strong>Stage 4 — Security</strong></h3><p>dependency_scan runs pip-audit and safety against requirements.txt, catching known CVEs in the dependency tree. container_scan runs Trivy against the Docker image itself, scanning for HIGH and CRITICAL vulnerabilities. Both are allow_failure: true — they warn without blocking, because a security advisory should trigger review, not an emergency rollback.</p><h3><strong>Stage 5 — Deploy</strong></h3><p>deploy_production is a manual job. It does not auto-trigger. You look at what passed, you decide it is ready, you click the play button. Continuous delivery is not continuous deployment. The rollback_production job takes a ROLLBACK_SHA variable and deploys any previous image from the registry in seconds.</p><h3><strong>Links</strong></h3><p>Source Code: github.com/AlborzNazari/open-intelligence-lab<br>GitLab CI/CD: gitlab.com/alborznazari4/open-intelligence-lab<br>Visual Lab: alborznazari.github.io/open-intelligence-lab<br>CHANGELOG: github.com/AlborzNazari/open-intelligence-lab/blob/main/CHANGELOG.md</p><p>#ThreatIntelligence #OpenSource #GitLabCICD #DevSecOps #STIX #MISP #Docker #Python #SecurityEngineering #OpenIntelligenceLab</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fb56cd21cd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shadowbroker: How Open-Source Intelligence Layers Turn Raw Signals Into Analyst Findings]]></title>
            <link>https://medium.com/@alborznazari4/shadowbroker-how-open-source-intelligence-layers-turn-raw-signals-into-analyst-findings-a54c770b3dac?source=rss-ed01f24e0e3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a54c770b3dac</guid>
            <category><![CDATA[flightradar24]]></category>
            <category><![CDATA[open-source-software]]></category>
            <category><![CDATA[signaljam]]></category>
            <category><![CDATA[military]]></category>
            <category><![CDATA[osint]]></category>
            <dc:creator><![CDATA[Alborz Nazari]]></dc:creator>
            <pubDate>Fri, 20 Mar 2026 19:50:27 GMT</pubDate>
            <atom:updated>2026-03-30T22:56:56.980Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A technical walkthrough of GPS jamming detection, CCTV ground truth, and STIX 2.1 export in a single open-source dashboard. Thanks to <a href="https://github.com/BigBodyCobain/Shadowbroker">https://github.com/BigBodyCobain/Shadowbroker</a> , the developer of the open-source software, I could add some adjuncts for better analysis.</blockquote><h3>Getting Started</h3><p>The project is available at <a href="https://github.com/BigBodyCobain/Shadowbroker">github.com/BigBodyCobain/Shadowbroker</a></p><p>My contributions — Spain CCTV integration and STIX 2.1 export — are in an open pull request. You can also install the project from my repository fork: <br><a href="https://github.com/AlborzNazari/Shadowbroker">https://github.com/AlborzNazari/Shadowbroker</a> for adds-on. Full installation instructions, analyst workflow documentation, and the CONTRIBUTING.md are in the PR.</p><p>Requirements &amp; Dependencies: Python 3.10+, Node.js 18+, free API keys from aisstream.io and n2yo.com for full functionality. The CCTV and STIX features work without any API keys.</p><p>Most OSINT tools give you one feed. A flight tracker. A ship tracker. A news aggregator. They are useful in isolation but limited — a single data source rarely tells you anything conclusive. The real intelligence value comes from correlation: when independent sources point to the same place, at the same time, with consistent signals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LJy_thETIZryOC94RLrdpg.png" /><figcaption>ver1.0.0: 377 CCTV CAMERA ADDED FROM PUBLIC DATA TO USE FOR ANALYTICS.</figcaption></figure><p>Shadowbroker is an open-source geospatial intelligence dashboard that aggregates over 15 public data feeds into one real-time map. Aircraft, ships, satellites, earthquakes, conflict events, CCTV cameras, and GPS jamming zones — all live, all layered, all cross-referenceable. This article walks through the specific capability I added as a contributor: Spain traffic camera integration and STIX 2.1 threat intelligence export, and explains exactly how an analyst uses them together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gg1WbvPC7mPSNCMexIB10g.jpeg" /><figcaption>ver1.2.4(Bugs Fixed): 2400 CCTV CAMERA ADDED THROUGH US &amp; THE WHOLE SPAIN.</figcaption></figure><h3>The Architecture</h3><p>Shadowbroker runs two processes simultaneously. A <strong>FastAPI backend</strong> fetches and caches data from public APIs on a 60-second fast cycle (flights, ships, satellites) and a 5-minute slow cycle (news, earthquakes, GDELT, CCTV). A <strong>Next.js frontend</strong> polls the backend and renders everything on a MapLibre GL WebGL map.</p><p>The backend serves compressed GeoJSON with ETag caching — a 11.6 MB payload compresses to roughly 915 KB. The frontend applies viewport culling so only features within the visible map bounds are rendered, which keeps the browser performant even with 25,000+ vessel positions and 5,000+ aircraft in memory simultaneously.</p><p>Every data source is a toggleable layer. Nothing is forced on screen. This matters for analyst workflow — you enable what you need when you need it.</p><h3>GPS Jamming Detection: Passive SIGINT from ADS-B</h3><p>The most technically interesting layer is GPS jamming detection — and it requires no special hardware.</p><p>Aircraft broadcast a field called <strong>NAC-P</strong> (Navigation Accuracy Category for Position) in their ADS-B transponder signal. NAC-P is an integer from 0 to 11 indicating the accuracy of the aircraft’s GPS fix. A value of 8 or above means the aircraft has a precise fix within 30 meters. Values below 4 indicate significant degradation.</p><p>Shadowbroker aggregates ADS-B data across thousands of aircraft simultaneously. When a statistically anomalous cluster of aircraft in the same geographic grid cell simultaneously report degraded NAC-P values, the platform flags that grid cell as a jamming zone and renders a red overlay on the map with a severity percentage.</p><p>This is entirely passive. No dedicated sensors, no special access, no cost. The signal intelligence is a side-effect of the existing ADS-B feed.</p><p>The limitation is important to understand: NAC-P degradation alone does not confirm intentional electronic warfare. It could be receiver malfunction, atmospheric interference, or a solar event. This is where the other layers become essential.</p><h3>Spain CCTV: Ground Truth</h3><p>I contributed two traffic camera ingestors to the project following the existing BaseCCTVIngestor pattern:</p><p><strong>DGT Spain</strong> — the national traffic authority publishes camera data through a confirmed image URL pattern: infocar.dgt.es/etraffic/data/camaras/{id}.jpg. These cameras cover national motorways including the A-2, A-4, A-6, and AP-7 corridors.</p><p><strong>Madrid City Hall</strong> — datos.madrid.es publishes a KML open data feed with 357 urban traffic cameras updated every 10 minutes. No API key required for either source. Both are published under Spain&#39;s open data framework implementing the EU PSI Directive 2019/1024.</p><p>The implementation is a standard Python class:</p><h3>python:</h3><pre>class MadridCityIngestor(BaseCCTVIngestor):<br>    def fetch_data(self) -&gt; List[Dict[str, Any]]:<br>        response = fetch_with_curl(https://medium.com/MADRID_KML_URL,%20timeout=20)<br>        # parse KML, extract coordinates and image URLs<br>        # return normalized list of camera dicts</pre><p>Each camera record stores id, source_agency, lat, lon, direction_facing, media_url, and refresh_rate_seconds in a SQLite database. The frontend renders them as green dots on the CCTV Mesh layer, clustered at low zoom and clickable for live still images at street level.</p><p>The cameras are not surveillance infrastructure. They are publicly operated traffic management cameras whose feeds are legally published for reuse. What they provide for an analyst is <strong>visual ground truth</strong> — something no amount of signals data can replace.</p><h3>The Intelligence Workflow: Correlation in Practice</h3><p>Here is the concrete analyst workflow when a GPS jamming zone appears:</p><p><strong>Signal 1 — NAC-P degradation.</strong> A red overlay appears over a corridor in northeastern Spain with 67% severity. By itself: interesting but inconclusive.</p><p><strong>Signal 2 — Military flight cross-reference.</strong> The military flights layer shows an RC-135 Rivet Joint in a holding pattern 40km northeast of the jamming zone. The platform flags holding patterns automatically when an aircraft accumulates more than 300 degrees of total turn. RC-135s are SIGINT collection aircraft. Their presence overhead during a GPS jamming event is not coincidental — it indicates active electronic warfare monitoring or participation. Confidence increases significantly.</p><p><strong>Signal 3 — CCTV visual confirmation.</strong> Enable the CCTV Mesh layer. A DGT camera on the AP-7 motorway shows unusually light traffic at peak hours. A Madrid City Hall camera three kilometers away shows a police presence at an intersection that is normally unremarkable. Neither image is dramatic. Together with the signals data, they indicate a surface-level cordon consistent with a security exercise or VIP movement.</p><p><strong>Signal 4 — GDELT geopolitical context.</strong> The Global Incidents layer shows two GDELT event markers in the same region from the past six hours, both with MILITARY theme tags and tone scores below -7. News articles are reporting increased security activity in the area.</p><p>Four independent sources. Four consistent signals. That is a finding an analyst can write with confidence.</p><h3><strong>USA: 7 Military Corridor States</strong></h3><p>The USA integration adds cameras across states selected for proximity to major military installations — Washington State (JBLM, Whidbey Island NAS), Virginia (Pentagon, Quantico, Langley AFB, Norfolk Naval), Texas (Fort Cavazos, Fort Bliss, Dyess AFB, Lackland AFB), Nevada/Utah (Nellis AFB, Area 51 corridor, Hill AFB, Dugway), Florida (MacDill AFB / CENTCOM, Patrick SFB, Eglin AFB), California (Camp Pendleton, Edwards AFB, Vandenberg SFB, MCAS Miramar), and Georgia (Fort Moore, Fort Eisenhower, Robins AFB, Moody AFB).<strong>Total cameras now indexed: 2,400+ across Spain and the USA.</strong></p><p>The strategic rationale is direct: when Shadowbroker detects GPS jamming or an ISR aircraft in a holding pattern over a US military corridor, nearby DOT cameras provide visual ground truth on highway traffic near base access roads, unusual vehicle concentrations, and security cordons.</p><h3><strong>The Proxy Architecture</strong></h3><p>A critical engineering decision: all camera images route through a backend proxy endpoint at `/api/cctv/proxy-image` rather than being fetched directly by the browser. DOT image servers block direct browser requests via CORS policies and missing Referer headers. The proxy fetches server-side with appropriate headers and serves the image bytes back to the browser.</p><h3>STIX 2.1 Export: Machine-Readable Intelligence</h3><p>The second contribution I added is a STIX 2.1 export endpoint at GET /api/stix/bundle.</p><p>STIX (Structured Threat Information eXpression) is the global standard format for sharing threat intelligence between organizations. A STIX bundle is a JSON document containing typed intelligence objects that any enterprise SIEM can ingest automatically.</p><p>The exporter wraps three data sources:</p><ul><li><strong>GDELT conflict events</strong> → STIX incident objects with tone score, country, themes, and source URL as external references</li><li><strong>GPS jamming zones</strong> → STIX location objects with severity percentage and affected aircraft count in a custom extension</li><li><strong>Military holding patterns</strong> → STIX indicator objects with aircraft callsign, type, coordinates, and turn degrees</li></ul><p>Each incident is linked to its geographic location via a STIX relationship object with located-at type. The bundle is served with application/stix+json content type and is directly consumable by Splunk Enterprise Security, Microsoft Sentinel, OpenCTI, and IBM QRadar.</p><p>Json file includes:</p><pre>{<br>  &quot;type&quot;: &quot;bundle&quot;,<br>  &quot;spec_version&quot;: &quot;2.1&quot;,<br>  &quot;objects&quot;: [<br>    { &quot;type&quot;: &quot;incident&quot;, &quot;name&quot;: &quot;Military activity northeastern Spain&quot;, &quot;severity&quot;: &quot;high&quot; },<br>    { &quot;type&quot;: &quot;location&quot;, &quot;name&quot;: &quot;GPS jamming zone (67% severity)&quot;, &quot;latitude&quot;: 41.38, &quot;longitude&quot;: 2.17 },<br>    { &quot;type&quot;: &quot;indicator&quot;, &quot;name&quot;: &quot;Military holding pattern: FORTE12&quot;, &quot;pattern&quot;: &quot;[aircraft:hex_code = &#39;AE1234&#39;]&quot; },<br>    { &quot;type&quot;: &quot;relationship&quot;, &quot;relationship_type&quot;: &quot;located-at&quot;, &quot;source_ref&quot;: &quot;incident--...&quot;, &quot;target_ref&quot;: &quot;location--...&quot; }<br>  ]<br>}</pre><p>The practical value here is automation. An analyst does not need to manually export findings and paste them into a SIEM. A scheduled task polling the endpoint every 15 minutes ingests new intelligence continuously. When the bundle updates — because a new jamming zone appears or a military aircraft enters a holding pattern — the SIEM receives it automatically.</p><p><strong>Spatial joining</strong> — the haversine() function that finds every camera within 25 km of an active jamming zone. This is the trigger logic: don&#39;t analyze all cameras, only the ones geographically relevant to an active event.</p><p><strong>Change detection</strong> — fetching consecutive still images as numpy arrays, normalizing dimensions, computing mean absolute pixel difference. A score above 0.15 on a traffic camera means something materially changed in frame. No model training, deployable today.</p><p><strong>STIX integration</strong> — writing camera anomalies back into the bundle as observed-data objects with a custom extension. Now the SIEM sees three correlated objects: jamming zone + military aircraft + camera anomaly within 25 km → one alert rule fires them all together.</p><p><strong>Honest limitations</strong> — pixel change cannot distinguish a military convoy from a traffic accident. Semantic understanding requires YOLOv8 or a CNN anomaly detector trained on baseline frames. The section names this clearly and positions it as the next contribution layer rather than pretending the simple approach is complete.</p><h3>What This Demonstrates About OSINT Methodology</h3><p>The specific capabilities I added — Spanish traffic cameras and STIX export — are individually minor. What they represent methodologically is more significant.</p><p>The cameras add a <strong>ground truth layer</strong> to a platform that was previously signals-only. Signals tell you something is happening. Cameras tell you what it looks like. The combination is qualitatively different from either alone.</p><p>The STIX export adds <strong>interoperability</strong>. An OSINT dashboard that produces findings locked inside its own UI has limited organizational value. A dashboard that exports machine-readable intelligence in an industry-standard format integrates into existing analyst workflows, SIEM correlation rules, and automated alerting pipelines. The data becomes actionable at scale.</p><p>Both contributions required no proprietary access, no API keys, and no data that is not freely and legally available to any researcher. The entire capability stack — from NAC-P jamming detection to STIX bundle export — is built on public infrastructure.</p><p>That is the core argument for open-source OSINT tooling: the information advantage does not come from exclusive data access. It comes from aggregation, correlation, and the engineering to make disparate public sources speak to each other coherently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FhkUSO91nH5synsLQd22Sw.png" /><figcaption>Global Incident &amp; High Res Map Activated</figcaption></figure><blockquote>Alborz Nazari is the author of <a href="https://github.com/AlborzNazari/open-intelligence-lab">Open Intelligence Lab</a>, an open-source graph-based OSINT platform with MITRE ATT&amp;CK alignment and STIX 2.1 / TAXII 2.1 compliance. His fork of Shadowbroker with Spain CCTV, USA military corridor cameras, and STIX export is at <a href="https://github.com/AlborzNazari/Shadowbroker">github.com/AlborzNazari/Shadowbroker</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a54c770b3dac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Open Intelligence Lab]]></title>
            <link>https://medium.com/@alborznazari4/open-intelligence-lab-on-git-from-a-black-box-to-a-transparent-modular-and-open-source-model-ffa154962964?source=rss-ed01f24e0e3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffa154962964</guid>
            <category><![CDATA[cyber-threat-intelligence]]></category>
            <category><![CDATA[threat-intelligence]]></category>
            <category><![CDATA[risk-factor]]></category>
            <category><![CDATA[risk-analysis]]></category>
            <dc:creator><![CDATA[Alborz Nazari]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 02:19:52 GMT</pubDate>
            <atom:updated>2026-05-19T18:33:03.254Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Abstract</strong></p><p>Security intelligence has historically been opaque, proprietary, and practically inaccessible to independent researchers. Open Intelligence Lab is a response to that problem: a modular, ethics-first OSINT research platform that models threat actors, attack patterns, and their relationships as a traversable knowledge graph — entirely from public data. This article describes the architecture, the data model, the analytical pipeline, and the deliberate design decisions that shape the project. It also outlines where the platform is headed and what it means for the broader field of explainable threat intelligence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDkKOntzWCTarV450hJMhw.png" /><figcaption>MISP Connected</figcaption></figure><h3>1. Introduction: The Black Box Problem in Threat Intelligence</h3><p>For a long time, real-world threat intelligence followed what practitioners informally call the “black box” approach: offensive and defensive security practices were treated as opaque containers — impenetrable to anyone outside a narrow chain of institutional access. A security analyst at a mid-sized organization could observe an attack, correlate a few indicators, and file a report. But the underlying models — who the actor was, how they operated, what their motivations were, how confident we should be in attribution — remained locked inside proprietary platforms, classified feeds, or vendor threat reports sold at five figures a year.</p><p>After the dot-com era, OSINT (Open Source Intelligence) databases began to fill part of that gap. Platforms emerged that allowed analysts to look up malicious IPs, trace usernames across social media, correlate email addresses to known breach datasets, or conduct passive reconnaissance without ever touching a target system. But the analysis layer — the ability to reason about threat actors, model their behavior, explain a risk score, and make that reasoning auditable — remained largely absent from the open-source ecosystem.</p><p>Open Intelligence Lab is an attempt to close that gap. It provides a clean, modular environment for researchers and engineers who want to explore intelligence signals without compromising privacy or ethics — using only public data, with every risk score backed by an interpretable rationale.</p><h3>2. Design Philosophy: Explainability Is Not Optional</h3><p>Most threat intelligence tools are built for consumption, not understanding. A feed tells you an IP is malicious; it rarely tells you why, with what confidence, or based on what evidence. When automated systems make blocking decisions using unexplained scores, false positives accumulate, institutional trust erodes, and the analyst is left with no meaningful recourse.</p><p>Open Intelligence Lab is built around five core principles:</p><p>• <strong>Public data only</strong> — no private, scraped, or sensitive information enters the system.</p><p>• <strong>Explainability first</strong> — every risk score must be traceable to its inputs and expressible in plain language.</p><p>• <strong>Modular architecture</strong> — each component (data ingestion, graph construction, scoring, API, visualization) can be replaced or extended independently.</p><p>• <strong>Research transparency</strong> — datasets, scoring logic, and relationships are fully visible in the repository.</p><p>• <strong>Ethical OSINT</strong> — aligned with academic norms, MITRE ATT&amp;CK attribution standards, and responsible disclosure principles.</p><h3>3. Architecture: Six Modules, One Pipeline</h3><p>The repository is organized into six layers with cleanly separated responsibilities. Data flows in one direction: from raw JSON datasets through a graph construction layer, into a risk analysis engine, out through an explainability module, and finally to an API and visualization layer.</p><p>datasets/ → core_engine/ → api/ → visualization/</p><p>The entry point is demo.py, which runs the full pipeline end-to-end and writes a structured intelligence report to research_docs/. The index.html at the repository root serves as the project’s public-facing documentation site — a deliberate choice to make the platform’s logic and data accessible to non-engineers.</p><h3>3.1 The Dataset Layer</h3><p>Five JSON files form the complete knowledge base. Every file cross-references others by ID, making the flat file structure inherently graph-shaped before any code runs. threat_entities.json is the entity registry: 22 objects across five types — 7 threat actors, 8 malware families, 2 infrastructure nodes, 2 CVEs, and 3 target sectors. attack_patterns.json contains 15 OSINT-specific attack patterns, each with a MITRE ATT&amp;CK technique reference, a kill chain phase, detection guidance, and mitigation notes. relations.json defines 28 directed edges — this is where the graph lives: actor uses malware, actor exploits CVE, actor targets sector, actor uses attack pattern. mitre_mapping.json maps each tracked actor to their ATT&amp;CK technique profile with frequency ratings. campaigns.json encodes seven real-world documented campaigns using the Diamond Model of Intrusion Analysis, the industry-standard four-node model (Adversary, Capability, Infrastructure, Victim) that describes a complete intrusion.</p><h3>3.2 graph_builder.py — From JSON to Knowledge Graph</h3><p>graph_builder.py is the data ingestion layer. It reads all five dataset files and constructs a directed property graph using NetworkX’s DiGraph. Each entity becomes a node with its full attribute set stored as node properties. Each entry in relations.json becomes a directed edge carrying a relation_type and a confidence score. MITRE TTP data is then attached directly to existing actor nodes — augmenting rather than replacing the base graph structure. The output is a rich, in-memory knowledge graph that downstream modules query without touching the raw files again. From v0.2.0 onward, datasets are loaded automatically in __init__() — no manual loading step required.</p><h3>3.3 risk_analyzer.py — The Scoring Engine</h3><p>The risk scoring model derives a composite score from three factors. The base risk is drawn from the entity’s risk_score field in the dataset. A degree factor is added proportional to the node’s connection count in the graph — entities with more relationships to other threat objects carry higher structural risk. An incident factor adds weight for each connected node of type incident_category. The three are summed and clamped to [0.0, 1.0]. The practical effect is correct: a highly connected threat actor accrues risk from its position in the graph, not just from its baseline score. An isolated entity with no relationships is penalized by its structural absence, regardless of its raw field value.</p><h3>3.4 intelligence_explainer.py — No Score Without a Rationale</h3><p>Every call to the API triggers intelligence_explainer.py, which queries the graph for the entity’s neighborhood and generates a structured plain-language rationale. A typical output reads: “‘APT28’ is a threat actor with 8 connections in the threat graph (0 incoming, 8 outgoing). Outgoing relations: uses X-Agent; uses X-Tunnel; uses C2 Infrastructure; targets Government &amp; Defense; uses_pattern Social Media Footprint Analysis. Origin: RU | Active since: 2007 | Motivation: espionage, influence_operations.”</p><p>This is a deliberately simple implementation — but the architectural commitment matters. By requiring every score to produce a rationale at generation time, the platform ensures that no risk score is ever a naked number without context. The explainer queries live graph structure, so it reflects the actual connectivity of the entity at query time rather than a cached summary.</p><h3>4. The Threat Model: What Does This Platform Actually Model?</h3><p>Threat model is an overloaded term in security. In this project it refers specifically to the structured answers to four questions: Who is the attacker? What is their motivation? What is their method of access and persistence? And have they succeeded in their mission? These four pillars — adversary, motivation, technique, and outcome — are encoded directly in campaigns.json using the Diamond Model, and they propagate through the graph via the edges in relations.json.</p><p>Take the SolarWinds campaign as a worked example. The adversary is APT29 (Cozy Bear), a Russian SVR-linked nation-state actor (TA-002 in threat_entities.json). The motivation is espionage — long-dwell, low-noise access to government and critical infrastructure targets. The capability is SUNBURST, a backdoor delivered via a trojanized SolarWinds Orion software update — encoded in attack_patterns.json as OSINT-T003 and linked via T1195.002 (Supply Chain Compromise) in mitre_mapping.json. The infrastructure is avsvmcloud.com, a C2 node blended with legitimate SolarWinds traffic. The victim scope — approximately 18,000 organizations including US Treasury, DHS, and Microsoft — is captured in SECTOR-003. Attribution confidence: 0.99.</p><p>This is not abstract modeling. Every field maps to a real data structure in the repository. The campaign entry in campaigns.json is the highest-level view; relations.json provides the connective tissue; the core engine turns all of it into a queryable, scored graph.</p><h3>5. Does Automation Enhance the Platform? A Deliberate Tradeoff</h3><p>Threat actors are not static. LockBit was disrupted by Operation Cronos in February 2024 — but by mid-2024, LockBit 3.0 was operational again with modified infrastructure and updated tooling. Cl0p’s MOVEit campaign emerged and concluded within weeks. IOCs (Indicators of Compromise) have effective half-lives measured in days. APT groups rebrand, shift targeting sectors, and adopt new TTPs. So the natural instinct is to ask: why not automate the data layer?</p><p>The answer through v0.1.0 was deliberate: the initial dataset was intentionally static. Adding a live ingestion pipeline to a research platform raises immediate questions about source verification, schema drift, and graph integrity. In a knowledge graph where nodes and edges carry confidence scores, an automated ingestion layer that pulls from poorly attributed OSINT feeds can silently corrupt the graph’s analytical validity. Adding more threat models indiscriminately also increases algorithmic complexity — in graph terms, each new node and edge set can increase traversal cost and introduce ambiguous relationship paths that degrade the quality of multi-hop reasoning.</p><p>STIX 2.1 export and TAXII 2.1 server support shipped in v0.3.0. The next constraint was feed ingestion with provenance validation — the v0.4.0 milestone. The principle remained the same: automation with guardrails, not automation for its own sake.</p><h3>5.1 v0.3.0 — Closing the Island Problem</h3><p>Section 5 described why automated ingestion was deliberately held back from v1. The flip side of that decision is worth naming directly: a research platform that cannot talk to the tools practitioners actually use is an island. Interesting to visit, difficult to act on. v0.3.0 addresses that.</p><p>The update ships two things. The first is a full STIX 2.1 export engine. Every entity, relationship, and campaign in the knowledge graph is now expressible in the industry-standard format for threat intelligence exchange — meaning the same data that powers the local graph can be consumed by Splunk, Microsoft Sentinel, OpenCTI, and IBM QRadar without any transformation work on the receiving end. The second is a TAXII 2.1 server built on FastAPI. Rather than shipping static files and calling it done, the server lets platforms poll a live feed on a schedule, the same way they would poll any commercial threat intelligence provider.</p><p>This matters for a practical reason. Most analysts do not spend their days inside research tools. They work inside SIEMs, inside threat platforms, inside dashboards that aggregate dozens of feeds. If intelligence lives only in a Python script and a local graph, it does not reach the people who need it. STIX and TAXII are the translation layer that closes that gap.</p><h3>What the export layer actually produces</h3><p>Running python backend/stix_exporter.py writes five files to an exports/ directory. The raw STIX 2.1 bundle works for any STIX-native tool, including OpenCTI. Alongside it, there are platform-specific outputs: a Splunk file formatted as sourcetype=stix events ready to index into a threat_intelligence index, a Sentinel file structured for the Threat Intelligence blade, and a QRadar file flattened into the row-oriented format that the STIX connector app expects.</p><p>The entity mapping is direct. Threat actors become STIX threat-actor objects with their confidence scores converted from the internal [0.0, 1.0] float range to the STIX integer range of [0, 100]. Malware families become malware objects. CVEs become vulnerability objects with NVD external references auto-attached. Graph edges from relations.json become relationship objects, typed and confidence-weighted. Diamond Model fields from campaigns.json carry over as x_oi_ extension properties, which keeps them accessible without corrupting the standard schema.</p><h3>Connecting the platforms</h3><p>For Splunk Enterprise Security, the path is through the STIX-TAXII connector under Configure &gt; Threat Intelligence &gt; Intelligence Downloads. Point it at the TAXII server URL, select the oi-lab-full-bundle-004 collection, set a polling interval, and risk scores become queryable fields in Splunk search. Correlation rules can reference x_oi_risk_score the same way they reference any other TI field.</p><p>For Microsoft Sentinel, the Threat Intelligence blade accepts TAXII feeds directly. Add the API root URL as a connector source and indicators start writing into the ThreatIntelligenceIndicator table. From there, KQL hunting queries can filter on confidence score, actor name, or MITRE technique ID. The integration requires no custom code on the Sentinel side.</p><p>OpenCTI is the most natural fit because it speaks STIX 2.1 natively. The simplest path is uploading exports/opencti_bundle.json through the Data &gt; Import interface. The relationship objects render as graph edges automatically, which means the knowledge graph that runs locally in NetworkX appears inside an OpenCTI workspace with its structure intact. For a live feed, OpenCTI’s TAXII ingestion connector works the same way as Splunk and Sentinel.</p><p>For IBM QRadar, the STIX Threat Intelligence app from IBM App Exchange handles the connection. The TAXII server URL goes into the Feed Management settings, and oi_risk_score maps to QRadar’s offense magnitude field in the connector configuration. For teams who prefer a one-time import over a live feed, exports/qradar_objects.json is a flat file that the connector can ingest directly.</p><h3>Why STIX specifically</h3><p>STIX (Structured Threat Information eXpression) is the format the intelligence community settled on after years of vendor-specific schemas that could not talk to each other. Before STIX, a threat actor object looked different depending on which platform generated it. After STIX, the schema is the same whether the source is a government ISAC, a commercial feed, or an open-source research platform. That standardization is what makes interoperability possible without custom glue code on every receiving end.</p><p>TAXII (Trusted Automated eXchange of Intelligence Information) is the transport protocol that sits on top. It defines the API shape that intelligence platforms use to discover feeds, list collections, and fetch objects on a schedule. Because all four platforms above implement TAXII 2.1 clients, the server they are connecting to does not need to know anything about them. It just serves valid STIX objects at the right endpoints.</p><h3>What this does not change</h3><p>The STIX layer sits on top of the existing graph engine. It does not replace it. The scoring logic in risk_analyzer.py and the graph structure in graph_builder.py are unchanged. STIX is the format the platform speaks outward. Internally, the graph is still the graph, the scores are still computed the same way, and every score still produces a plain-language rationale at generation time.</p><h3>5.2 v0.4.0 — Bidirectional Intelligence and the Provenance Problem</h3><p>v0.3.0 made the platform a publisher. v0.4.0 makes it a subscriber. The distinction matters more than it sounds.</p><p>Publishing intelligence is a one-way commitment: you control the data, you control the quality, you control what leaves. Ingesting intelligence from external feeds inverts every one of those controls. You are now accepting data from sources with varying reliability, different schemas, inconsistent confidence scoring, and no guaranteed freshness. Without a trust layer, ingestion is just noise absorption.</p><p>v0.4.0 ships four new backend modules that together form that trust layer.</p><h3>backend/misp_client.py — The Live Feed Source</h3><p>MISP (Malware Information Sharing Platform) is the open-source threat intelligence platform used by government agencies, national CERTs, and ISACs globally. Think of it as a structured, shared database of everything the security community has observed: malware samples, IP addresses, domains, file hashes, threat actor profiles, campaigns, vulnerabilities. Organizations connect to MISP instances, contribute intelligence they have seen, and consume intelligence from others. It is the de facto standard for community threat sharing.</p><p>misp_client.py connects to a live MISP server via API key over HTTPS, calls POST /events/restSearch to fetch recent events, and converts each MISP attribute into its corresponding STIX 2.1 object. IP addresses become indicator objects with STIX pattern expressions. Threat actor names become threat-actor objects. Malware types become malware objects. MISP’s threat level field (1 = High, 4 = Undefined) maps to a base confidence score; the distribution setting applies a modifier. An indicator from a org-only MISP event carries less weight than the same indicator published to the full community.</p><p><strong>Example</strong></p><p>A MISP event with threat_level_id=1 (High) and distribution=3 (All) produces a base confidence of 0.95 + 0.05 = 1.00. The same indicator from an org-only event (distribution=0) produces 0.95 − 0.15 = 0.80. The graph knows the difference.</p><h3>backend/provenance.py — Chain-of-Custody for Every Object</h3><p>Every STIX object ingested from MISP or a TAXII feed receives a ProvenanceRecord — a chain-of-custody stamp that travels with the object for its lifetime in the graph. It carries: the source platform (MISP-CISA, MISP-CIRCL, TAXII-OpenCTI, etc.), the organization that reported the event, the original publication timestamp, the ingestion timestamp, a computed trust level, the age of the intelligence in days, and a staleness flag triggered when the object exceeds 90 days old by default.</p><p>The trust level is not just the MISP confidence score. It is the MISP score multiplied by a source trust prior: MISP-CISA carries a prior of 1.00; an unknown TAXII source carries 0.60. This means the same indicator from CISA’s MISP feed and from an unverified community feed produces different trust levels in the graph — and both are auditable. Nothing below a minimum trust floor of 0.10 enters the graph at all.</p><h3>backend/taxii_ingestor.py — The Subscriber Side</h3><p>taxii_ingestor.py is the complement to v0.3.0’s TAXII server. Where the server publishes OI Lab’s intelligence outward, the ingestor subscribes to external TAXII feeds — other MISP instances, OpenCTI servers, commercial feeds — and pulls their STIX 2.1 objects into the local object store. Authentication is flexible: API key, HTTP Basic, or Bearer token. Every ingested object passes through the provenance engine before touching the graph.</p><h3>backend/feed_scheduler.py — Orchestration</h3><p>feed_scheduler.py runs as a background thread inside the FastAPI server. It maintains a registry of configured MISP and TAXII feed sources, executes ingestion cycles on a configurable interval (default: hourly), and logs every run with a full audit trail: how many objects were fetched, how many passed provenance validation, how many were rejected as stale or below the trust floor, and which feed produced them. The scheduler is the piece that makes the graph live rather than periodically refreshed.</p><p>Activating it requires two environment variables set before starting the server:</p><p>MISP_URL=https://your-misp-instance.org</p><p>MISP_KEY=your-api-key</p><p>Without them, the server starts cleanly on static datasets. With them, the graph begins updating automatically. For local development, a Docker Compose setup ships with the repository: docker compose up spins up both the OI Lab API and a full MISP instance together, with MISP initialized and ready to accept events within two minutes.</p><h3>Why MISP specifically</h3><p>MISP is not the only option for live threat feeds. VirusTotal, Shodan, and various commercial providers offer APIs. The reason MISP anchors the live feed layer is institutional credibility. MISP is run by national CERTs, government agencies, and ISACs — the same organizations that produce the highest-confidence threat intelligence. Connecting to a community MISP instance is connecting to the same data that feeds commercial platforms, without the commercial price tag. It also speaks STIX natively, which means the translation layer from Section 5.1 is already in place.</p><h3>What bidirectional means for the graph</h3><p>In v0.3.0, the knowledge graph was a fixed structure — well-built, well-documented, but static. In v0.4.0, it has two modes. When no live feed is configured, it behaves exactly as before: 22 entities, 28 relations, 7 campaigns, full scoring and explainability. When a MISP feed is active, ingested objects merge into the existing graph. A new malware family observed in a MISP event becomes a new node. A new C2 IP becomes an indicator connected to its parent threat actor if the attribution is confident enough. The provenance record on every ingested object means the graph can always distinguish its curated core from its live periphery.</p><h3>6. What Comes Next — and What to Write About</h3><p>The v0.4.0 roadmap closes the bidirectional loop. The milestones ahead point toward several areas worth following closely — each of which is also a standalone research topic.</p><h3>STIX 2.1 and the Standardization of Threat Intelligence</h3><p>STIX (Structured Threat Information eXpression) is the OASIS-standard schema for representing threat intelligence objects and relationships. The migration of the current JSON datasets to full STIX 2.1 compliance is ongoing. The design decisions involved — how to represent confidence, how to model campaigns, what to do with fields STIX doesn’t support natively — are worth a dedicated article. The x_oi_ extension prefix is the current answer to the last question: preserve non-standard fields without corrupting the schema.</p><h3>Graph Databases and Multi-Hop Actor Pivoting</h3><p>The current in-memory NetworkX graph is appropriate for a research prototype at 22 nodes. At scale — thousands of entities, tens of thousands of edges, live feed ingestion running hourly — it becomes a bottleneck. The future roadmap targets Neo4j, which natively supports Cypher queries for multi-hop traversal: “find all actors who share malware tooling with APT29 and have targeted the finance sector in the last 90 days.” That kind of query is where graph databases genuinely outperform relational or document stores.</p><h3>ML-Based Risk Scoring and the Explainability Tension</h3><p>The current scoring formula is deterministic and fully explainable by design. An ML-based scorer — trained on historical campaign outcomes, IOC co-occurrence patterns, and TTP sequences — could produce more accurate risk estimates. But it reintroduces the black box problem the platform was built to avoid. Navigating that tension using SHAP values, LIME explanations, or graph-native attention mechanisms (Graph Neural Networks) is an active research area, and one that maps directly onto the future direction of this project.</p><h3>The Diamond Model as a Formal Ontology</h3><p>campaigns.json uses the Diamond Model as its structural frame. But the Diamond Model is more than a reporting template — it’s a formal ontology for intrusion analysis with specific axioms about how adversary capability, infrastructure, and victim interact. Writing an article that formalizes this ontology in the context of a working codebase — explaining what each node type implies for graph traversal, attribution confidence, and campaign correlation — would be genuinely novel in the open-source security writing space.</p><h3>7. Conclusion</h3><p>Open Intelligence Lab is a working proof that threat intelligence does not have to be a black box. In its current form it delivers a graph-structured knowledge base of 22 entities, 28 relations, and 7 documented campaigns — fully scored, fully explainable, interoperable with Splunk, Microsoft Sentinel, OpenCTI, and IBM QRadar via STIX 2.1 and TAXII 2.1, and now connected to the live threat sharing ecosystem through MISP feed ingestion with provenance-validated chain-of-custody. That is not a starting point. That is a functional, standards-compliant threat intelligence platform built entirely in the open, on public data, by one person.</p><p>The architectural decisions made here — modular layers, trust-scored ingestion, explainability as a hard requirement, bidirectional interoperability — are the same decisions that underpin production platforms sold at enterprise price points. The difference is that every line of this is readable, every dataset is inspectable, and every risk score shows its work. That is the argument this project makes, and v0.4.0 makes it convincingly.</p><p>The broader argument is this: security intelligence does not have to be a black box. The data exists in the open. The frameworks — MITRE ATT&amp;CK, the Diamond Model, STIX, the kill chain — are public. The graph databases and ML tooling are open source. What has been missing is a project that assembles them into a coherent, auditable, and extensible platform without hiding the reasoning. That is what this project is trying to be.</p><p>Open Intelligence Lab is open source under the MIT License. Repository: github.com/AlborzNazari/open-intelligence-lab</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffa154962964" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Tech Reads That Changed How I Think in 2026]]></title>
            <link>https://medium.com/@alborznazari4/the-tech-reads-that-changed-how-i-think-in-2026-e7fd6739c62a?source=rss-ed01f24e0e3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7fd6739c62a</guid>
            <category><![CDATA[security-engineering]]></category>
            <category><![CDATA[neuroscience]]></category>
            <category><![CDATA[opengl]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Alborz Nazari]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 01:21:15 GMT</pubDate>
            <atom:updated>2026-02-23T11:59:35.343Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rCk_9IVV8qqi0Y4ebiQq0Q.png" /><figcaption>One of the best print reads and reference principles in 2025. I admire the writers, and if time allows, I would be happy to do a fully comprehensive review of them.</figcaption></figure><p>Thanks to CRC Press and the following individuals — <strong>listed in alphabetical order</strong>: <strong>Jamis Buck</strong>, <strong>Ross Anderson</strong>, <strong>Marilyn A. Reba</strong>, <strong>Robert Sapolsky</strong>, and <strong>Douglas R. Shier</strong>.</p><p>Each one of them is a trajectory maze to kick in; I’ll come back with more future-proof ideas about what I took in print this year.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7fd6739c62a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure-Apportionment-Voting-System v0.2.0]]></title>
            <link>https://medium.com/@alborznazari4/secure-apportionment-voting-system-v0-1-0-983054d369d5?source=rss-ed01f24e0e3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/983054d369d5</guid>
            <category><![CDATA[parliament]]></category>
            <category><![CDATA[politics]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[voting]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Alborz Nazari]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 20:12:51 GMT</pubDate>
            <atom:updated>2026-03-19T20:36:49.764Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iFX4FEpAsNCTCboqiUJ7Rw.png" /></figure><h3>Secure Parliamentary Seat Apportionment System</h3><p>A fair and tamper-resistant system for allocating parliamentary seats using the Huntington-Hill method (method of equal proportions). It combines mathematically proven seat allocation with AES-256-CBC encryption to protect sensitive vote data during storage and transmission.</p><p>Suitable for large-scale elections (200,000+ ballots) and educational demonstrations of algorithmic fairness, social choice theory, and applied cryptography.</p><h3>../Lab session: Congressional System</h3><p><em>— Secure Parliamentary Seat Apportionment System</em> — <a href="https://github.com/AlborzNazari/Secure-Apportionment-System">click here</a>!</p><p><strong>../Infrastructure: Docker, Three Bugs, and What Deployment Exposed</strong></p><p>Containerising the backend with Docker was supposed to be a packaging step. It turned into a bug audit.</p><p>The first bug: app.py imported allocate_seats from apportionment.py — a function that does not exist under that name. The actual implementation is huntington_hill. Local development never triggered this path cleanly. Inside a fresh Linux container, Flask crashed on every startup and the container restarted in an infinite loop. Fix was one line — an import alias. The bug had been sitting in the codebase since the initial commit.</p><p>The second bug: Flask was initialised from inside src/, so it searched for HTML templates at src/templates/ rather than the project root. Every request to / returned TemplateNotFound: index.html. Fix was explicit path declaration at the app factory. One line again. Docker didn&#39;t introduce either bug — it made them impossible to ignore.</p><p>The third issue was the cache. After fixing both, the browser kept serving the old interface. Docker’s image layer cache had not been invalidated. The correct sequence — docker-compose down → docker rmi &lt;image&gt; -f → docker-compose up --build → hard-refresh — is non-obvious but mandatory after any file change. This one isn&#39;t a bug. It&#39;s operational knowledge that only comes from shipping.</p><p>Three issues, all discovered in one deployment session. None were visible in local development. That’s the value of containers: not convenience, but the enforcement of a clean environment that treats your assumptions as failure conditions.</p><p><strong>../Dataset Library: Social Choice Theory Made Interactive</strong></p><p>v0.1.0 now ships with 11 research scenarios embedded in the frontend. Each one isolates a specific theorem or empirical property of parliamentary voting systems. Selecting a card loads the data, sets the correct seat count, and displays a scientific annotation in the results panel.</p><h3><strong>Alabama Paradox</strong></h3><p>run with 25 seats, then change to 26. Hamilton’s method causes one party to lose a seat when total seats increase. Huntington-Hill is monotone — it never does. This is the mathematical argument that replaced Hamilton in the US House of Representatives in 1941, proven formally by Balinski and Young in 1982.</p><h3><strong>Arrow’s IIA violation</strong></h3><p>run the strategic voting scenario with Green Party present, then withdrawn. Green’s 87,000 votes redistribute to Centre-Left and Social Democrats. Centre-Left’s seat count changes despite receiving no direct vote change. That shift is Arrow’s Independence of Irrelevant Alternatives failure — empirical rather than theoretical. No voting system with three or more candidates can avoid it.</p><h3><strong>EU degressive proportionality</strong></h3><p>22 member-states, 705 seats. Malta (120k votes) versus Germany (12.5M). Huntington-Hill’s initial one-seat allocation before priority scoring prevents small states from collapsing to zero representation, approximating the Lisbon Treaty’s minimum-seat guarantee without a hard legislative floor.</p><h3><strong>Bundestag coalition model</strong></h3><p>5% Sperrklausel eliminates two parties. The remaining allocation determines whether a grand coalition or traffic-light coalition holds majority. Sainte-Laguë (the actual Bundestag method) and Huntington-Hill produce a ±2 seat variance on this dataset — enough to change which coalition governs.</p><p>The Δ deviation chart is the most analytically useful view. Green bars are overrepresented parties, red underrepresented, grey within the ±0.5% geometric mean tolerance. On the IIA scenarios, comparing the Δ column between the two runs makes Arrow’s theorem visible in a way no textbook example does.</p><h3>../Overview</h3><p>Voting systems and decision-making theory need to be based on fair criteria. Arrow’s impossibility theorem demonstrates that no voting system can be completely fair if it has more than two candidates. We went over very classic methods: Major Method, Plurality, Plurality run-off, Instant run-off (IRV), sequential run-off, and pairwise comparison. They all can cause Pareto paradox versus Pareto efficiency or be relevant to other irrelevant alternatives and can alter the result. For example, one candidate’s resignation may cause another candidate to directly win, or if all voters prefer A over B, the latter should not get outdone by any chance. These laws create fairness criteria in real cases of parliaments or presidential candidacy. We see probabilistic strategic voting, pinpointing the weakness of each old-fashioned method to prevent unwanted outcomes. On topics like social choice theory, direct study of psychology as well as statistical contemplation is essential to understand how individual or collective choice can affect the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YRAsEwCt_v6GKaUrzVOAuw.png" /></figure><h3>../POC</h3><p>This document serves as a comprehensive Proof of Concept (POC) for the Secure Parliamentary Seat Apportionment System, a software tool designed to allocate parliamentary seats fairly using the Huntington-Hill method while incorporating AES-256 encryption for vote data security. Styled like an enhanced README.md, it follows the outlined steps to prove viability, brainstorm solutions, gather feedback, describe the prototype, and evaluate success criteria. This POC is tailored for a Medium article, explaining the algorithm and software workflow in an accessible, engaging way — focusing on fairness in democratic systems rather than voter “likeability,” as the core goal is legal and mathematical integrity in seat allocation. The system addresses real-world challenges in elections: unfair seat distribution due to mathematical paradoxes and biases, plus vulnerabilities in handling sensitive vote data. By combining proven apportionment math with modern cryptography, it demonstrates a workable, secure solution for parliamentary democracies.</p><h3>../Proving the Need: Demonstrating the Problem and Who It Affects</h3><p>Parliamentary seat apportionment — the process of dividing seats among parties or regions based on vote totals — is fundamental to proportional representation. However, traditional methods often fail due to mathematical flaws, leading to unfair outcomes. This isn’t just theoretical; it erodes trust in democracies and can skew political power.Key Problems Identified Mathematical Paradoxes and Biases: Many methods suffer from paradoxes like the “Alabama paradox,” where increasing total seats can cause a party or state to lose a seat. For example, Hamilton’s method (used historically in the U.S.) is prone to this, as noted in historical analyses. Jefferson’s method favors larger parties/states, while others like Dean’s favor smaller ones. In Europe, apportionment in multi-constituency systems can lead to arbitrary allocations, violating degressive proportionality (where smaller entities get relatively more representation). A 2025 study from MPI-INF highlights how these issues persist in global parliaments, affecting representation equality.</p><h3>../Architecture</h3><p><a href="https://github.com/AlborzNazari/Secure-Apportionment-System/releases/download/v0.2.0/Secure-Apportionment-System-v0_2_0.pdf">https://github.com/AlborzNazari/Secure-Apportionment-System/releases/download/v0.2.0/Secure-Apportionment-System-v0_2_0.pdf</a></p><h3>../Security Vulnerabilities in Election Data:</h3><p>Vote totals are sensitive; breaches can undermine elections. Challenges include outdated systems prone to hacking, malware, denial-of-service attacks, and lack of verifiable records.In the U.S., 41 states used decade-old equipment in 2018, risking failures and cyberattacks. Globally, electronic voting faces malware risks, with no fully secure internet-based system yet, per the National Academies. Voter registration databases are prime targets, as seen in Illinois (90,000 records compromised). The need is clear: A secure, paradox-free system ensures legal fairness, protecting democracies from bias and breaches.</p><h3>../Brainstorming Solutions: Alternatives, Costs, and Selection</h3><p>We evaluated multiple apportionment methods and security approaches, weighing pros, cons, and implementation costs (focusing on software development, as this is a digital POC). Apportionment Methods Brainstormed. Hamilton’s Method (Quota Method): Allocates based on quotas, rounding down then assigning remainders. Pros: Simple, avoids quota violations. Cons: Alabama paradox; favors no group consistently but unstable.</p><h3>../Tests</h3><p>Example: 3 parties (Votes: A=5000, B=3000, C=2000), 10 seats.</p><p><strong>Initial: </strong>Each gets 1 (3 seats used).</p><p><strong>Priorities:</strong> A=5000/√(1*2)≈3535; B≈2121; C≈1414.</p><p>Assign to A (now 2 seats), recalculate, repeat.</p><h3>../v0.1.0</h3><ol><li>Input: Load CSV (party votes) via io.py.</li><li>Encryption: AES-256-CBC encrypts totals (32-byte key, random IV, PKCS7 padding) for secure storage/transit via encryption.py.</li><li>Decryption: Trusted authority decrypts.</li><li>Apportionment: apportionment.py runs Huntington-Hill (heapq for priorities).</li><li>Output: JSON/console results.</li></ol><p><strong>Tests: pytest verifies round-trip encryption, paradoxes avoided.</strong></p><p><strong>Run: python src/main.py sample.csv — seats 50</strong></p><h3><strong>../v0.2.0</strong></h3><p><strong>v0.2.0 adds full containerisation via Docker, a standalone Windows executable, and a significantly expanded dataset library.</strong> Docker was introduced to eliminate environment fragmentation across operating systems, the single largest friction point in distributed tooling. A docker-compose.yml orchestrates the Flask backend and frontend in a single command, with audit logs mounted as a persistent volume so encryption records survive container restarts. The Windows .exe was built with PyInstaller to serve end-users who have neither Python nor Docker installed, packaging all dependencies into a single binary with no setup required. On the data side, 11 CSV datasets were added, each mapped to a foundational theorem in social choice theory, including Arrow&#39;s impossibility theorem, the Alabama paradox, and Condorcet winner failure, with per-dataset scientific annotations rendered in the results panel to ground outputs in theory rather than raw numbers. AES-256-CBC encryption was applied to all outputs to meet baseline security requirements for sensitive apportionment data. These additions build directly on v0.1.0&#39;s core architecture, which established the Huntington-Hill apportionment engine, CSV ingestion pipeline, fairness metrics, and the initial Flask API, and extend it into a deployable, multi-target system with clear separation between the Docker web interface, the portable binary, and the direct Python path for development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=983054d369d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithms Are Not Enough: By Herbert L. Roitblat Chapter 1–2 Overview]]></title>
            <link>https://medium.com/@alborznazari4/algorithms-are-not-enough-by-herbert-l-roitblat-chapter-1-2-overview-48419faab6ec?source=rss-ed01f24e0e3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/48419faab6ec</guid>
            <category><![CDATA[politics]]></category>
            <category><![CDATA[evolution]]></category>
            <category><![CDATA[world]]></category>
            <category><![CDATA[voting-methods]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Alborz Nazari]]></dc:creator>
            <pubDate>Tue, 03 Feb 2026 02:25:14 GMT</pubDate>
            <atom:updated>2026-02-13T23:58:21.994Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4tjKD0tOkwHdx4Pa6H1mHg.png" /></figure><h3><strong>../Project/</strong>Secure-Apportionment-Voting-System</h3><p><strong><em>Author Note:</em></strong><em> Humans have always been automating tasks since antiquity, like the creation of the calendar to track the timing of the day, hunting seasons, and automation of the day-month-year orbit — which is based on </em><strong><em>modular arithmetic</em></strong><em>, the foundational concept. I noticed that the knowledge acquired from books, e.g., the maths behind the </em><strong><em>AES-256 crypto algorithm</em></strong><em>, may give you a solid approach to solve a distinctive real-world problem harnessing the powers of algorithm and security. The implementation is separate as I run the project </em><a href="https://github.com/AlborzNazari/Secure-Apportionment-System"><em>here </em></a><em>on git.</em></p><p><em>On the other hand, the part you cemented has been outsmarted by computers with great speed and zero approximation error — e.g., AES-256 would be expensive in terms of resources to brute-force — but also can be broken in the future by the power of </em><strong><em>quantum computers</em></strong><em> that may change the gold standard narrative in security sector.</em></p><p><em>For the project, there is a separate article — </em><a href="https://medium.com/@alborznazari4/secure-apportionment-voting-system-v0-1-0-983054d369d5"><em>click here! </em></a><em>— that provides a step-by-step guide to the project implementation or the methods introduced therein. The practical project addresses the foundational problem inherent in parliamentary systems, with a focused emphasis on algorithms and security.</em></p><p><em>Back to article: Why may we have comebacks when technology is rapidly blooming? Answer: Logical thinking needs logical assets. Language — here mathematics, and tools of making logics run on OS: like programming languages come in handy; as two inevitable cornerstones cover research and praxis.</em></p><p><em>This article wants to have a roundabout at book :</em><strong><em> </em></strong><a href="https://direct.mit.edu/books/monograph/4957/Algorithms-Are-Not-EnoughCreating-General"><strong><em>Algorithms Are Not Enough: By Herbert L. Roitblat </em></strong></a><em>about human and machine intelligence. Basically, I just pinpointed some foundational concepts of first two chapters.</em></p><p><em>There was a huge tech jump from the first </em><strong><em>Turing machine </em></strong><em>— which is even more classic than Star Wars — to new machine learning methods that now play a pivotal role in tech monopoly — which are from the evolution of math to logic, logic to algorithm, and last but not least, from algorithm to AI system builders.</em></p><p><em>The content of the article is not fully from the book, as its discussed concepts have molded into my analytical surveys and interpretations. The creative project I built to drive a system that is secured by creating strong symmetric encryption — AES-256 — apportion systems, statistics, and social choice theory. Full project is accessible through </em><a href="https://github.com/AlborzNazari/Secure-Apportionment-System"><em>GIT</em></a><em>. Stay tuned, and share your stuff with me about it.</em></p><p><em>note: Nearly all jargon is highlighted in </em><strong><em>bold</em></strong><em>.</em></p><p><em>Alborz Nazari, Software Engineer</em></p><h3>We’ll explore:</h3><p><em>Part1)</em></p><h4>../Foundations<br>../Quantum Computation<br>../Formal versus Insight problems<br>../Palpable Examples</h4><p><em>part2)</em></p><h4>../Lab session: Congressional System</h4><h4>../Start</h4><p>From my experiences delving into the golden rules of mathematics — 5000 years, logic — 2500 years, algorithms — 1000 years, computer science — 90 years, and AI — ~70 years roughly, I can confidently say that all those chronological advancements and systems thinking matters! <em>May I know it all? How about building intelligent systems that will harness computer science, mathematics, and statistics to build an innovation eventually using all together? Check it here!</em></p><p>Back to humans and their thinking evolution: The time was imperative for the harvesters and hunters since antiquity. <em>Long before Uncle Charles dared to unravel our grandparents’ monkeys.</em> Early humans needed to invent a calendar to know the time of the prey. Calendars at least have a history of five thousand years if we assume the Neolithic Calendar as initial.<em> They automated days, months, and planetary orbits to come up with the concept of ageing, numbers, and a better grasp of time! But how has it become possible? As a child, I had this sort of thought about how humans achieved using old wisdom to finally build cameras, for example? Computers are inventions of ~100 years, but humans built machines with their human intelligence. </em>Human intelligence considers humans as rational, deliberative, and with a tinge of self-interest. Best performance of humans is when they use their native language when using rationality, counting, and math. When someone doesn’t act rationally, their behavior is contaminated by their emotions. <em>You remember the time Mr. Jones’s rationality was overshadowed by his emotions? May we talk about fallacies?</em></p><h3>../Moravec’s paradox: From Apocalyptic Hurdle to AI’s Solvable Frontier</h3><p>Then, the book points out <strong>Moravec’s paradox</strong>. <em>I know it’s old, but bear with me. phew… The topics that are lost completely amid groundbreaking AI technologies.</em> <em>Yet, it’s a very classic discourse in history.</em> Moravec’s paradox indicates the tasks on which computers outdo humans while they suck at them, and vice versa, e.g., detecting a walk-cycle is hard for conventional AI, but for humans is easy. Numerical calculations are easy for computers; as they cost a lot of time and effort for humans to achieve that. The fact that humans build computers, and now the computers have outsmarted their creators in many ways caused a chain of conspiracy theories that say computers will eventually take over human beings. As new technologies are evolving what once was hard for machines to process, the emergence of the <strong>singularity concept</strong> has surged suspicion over the discourse. <em>Should I watch Terminator 2 or message Spaz on Facebook again?</em></p><h3>../Formal or Path Problems</h3><p><strong>Formal problems</strong>, such as <strong>pathfinding algorithms</strong> like the <strong>classic 8-tile puzzle</strong>, <strong>Tower of Hanoi</strong>, <strong>Knight’s Tour</strong>, <strong>Jar-pouring issues</strong>, and <strong>Orcs and hobbits</strong> are crucial for developing human heuristic problem-solving skills. These problems provide a foundation for cognition and intuition, offering clues to solutions even if they aren’t always entirely accurate. In terms of algorithmic thinking, these foundations follow a structure of <strong>states</strong>, <strong>operations</strong>, and <strong>goals </strong>to build systems, for example, self-learned states. <em>Okay, I’m going to stop. I know </em><strong><em>automata theory</em></strong><em> is grandfather! </em>As more powerful computers only enhance the speed of traditional methods, such as brute force, thus; the problem of securing our belongings becomes more critical with the advent of quantum computers. So, this is where the old-fashioned limitations can be easily toppled by new super powerful hardware, that the computation speed would be beyond traditional methods. But let’s assume we have limited resources, and we prioritize <strong>usability </strong>over <strong>security</strong>. Therefore, the security turns out to be a more concerning issue. Security will be dismantled when new technology and practices outsmart any possible computation problem. Therefore, formal problems are just one way to speed up our workflow. <em>They’re not 100% battle-proof!</em></p><p>Back to formal problems: The system can tell whether it’s getting closer to success or not. The solver can usually assess how close the current state of the system is to the goal state. Most machine learning algorithms depend on this assessment. It emphasizes that, before jumping into pre-packaged tooling, what basically matters is history. Par exemple, <strong>the rule of inference</strong>. <em>Since it is mathematical, it is speculatively older than any modern algorithm. Convincing enough? </em>Mathematical language interprets this law in <strong>Euclidean geometry</strong> through the <strong>syllogism </strong>— partly the same logic applies to the famous Socratic method, as well as contemporary science history that revolves around <strong>Vienna Circle (1920s)</strong>, which they stressed the importance of logic and the meaninglessness of anything outside a scientific point of view. Then it goes to <strong>heuristic function</strong>. The examples are <strong>greedy bfs </strong>or <strong>A* algorithm</strong>. A heuristic is a practical method that generally works, but, unlike an algorithm, is not guaranteed to produce the correct result. We frequently fall into cognitive bias traps like the <strong>availability heuristic</strong>, which seeks the shortest path by drawing on the most readily available information to deliver a fast, plausible response.<em> As we cannot rely on integrity of the result.</em> While this can be effective, it frequently falls short of rigorous statistical evaluation.</p><h3>../Insight or Nonpath Problems</h3><p>Good computers may have the power to be computationally rapid and stronger, but stronger computers only make old methods faster, and all sorts of problems are not resolvable with the classic states, operations, and goals approach that were formerly resolved by computational methods. Non-path problems cannot typically be described as a step-by-step process. We need different approaches for machines to resolve <strong>insight problems</strong>. The insight problems that the human intelligence approach seem deceptively simple; although they can be learned differently for an AI system, not as straightforward as computational ways; which outsmarted humans for decades. <em>Here I can only say what an insight problem is not or what it does exclude. Reasonable enough?</em></p><h3>../Nonpath Problems Examples</h3><p>The first chapter starts with Spearman’s evolutionary method for school systems.<em> I don’t feel like jotting them down as I have written about it in detail in my </em><a href="https://www.linkedin.com/pulse/pathology-flawed-reasoning-newly-rebuilt-approach-critical-nazari-9otrf/"><em>LinkedIn</em></a><em>. The Spearman’s efforts apply to a wider range of discussions: psychometric test design. Scientists have researched a great deal to understand human intelligence. The study of human intelligence has largely been preoccupied with accounting for differences between individuals. Some people seem to have exceptional points, others may have Achilles’ heel. </em>The more you practice those tests, the better chance you’ll have to get a better score. This is called the <strong>Flynn effect</strong>, which makes the proposition that IQ level is a fixed number into controversy. Anyway, talking about this topic opens up cognitive and neuroscience discussions, and yet a vital need to ponder how cognition works. BTW, anybody can relate to the technical language of Robert Sapolsky among engineers? I personally need a lot more explanations and contexts!</p><p>The book opens up a discussion about <strong>aha moments</strong>. The thingy thing interpreted as epiphany once in literature, and Archimedes’ example has made ‘aha moment’ prominent. We still don’t fully understand exactly how people arrive at those sudden “aha!” moments when solving insight problems. It’s surprisingly hard to study this deeply in a lab setting because it’s tough to ask someone to put into words the subtle, often unconscious mental steps that lead to the breakthrough. At the same time, researchers keep finding something positive: When people take a real break from a tough problem, their chances of getting a clear insight later rise a lot. Those breaks let the mind quietly rearrange ideas in the background, and that often helps the solution click into place. The book calls that <strong>incubation</strong>.</p><p>Come back to natural intelligence: People can hold beliefs that aren’t accurate. Human language can express sentences that are neither true nor false, such as “This sentence is false.” When something is magnified and repeated by the news, it gives us red-herring that shadow our reasonable decesion-making and can dilute our perception. The reason lies behind the fact that human’s mind believes the news more than statistics: Plane crashes are safer than car crashes, but after emphasizing on plane crashes on news, we assume to choose the car path. The book discusses these topics in depth. <em>Take and read it!</em></p><h3>../Nonpath Problems Examples../Chapter 1–2</h3><p><em>Let’s dive directly to four problems:</em></p><ol><li><strong>Socks problem:</strong> You are told that a drawer contains black and brown socks in a ratio of five black socks for every four brown socks. The question is: How many socks must you pull out to be certain you have at least one matching pair (of either color)?<br><strong>Answer: </strong>We don’t know the exact number of socks. We just have the ratio. But to guarantee at least one matching pair, think about the worst case: you could pull out different colors first. If you take out two socks, they could be one black and one brown — no pair. But if you take out a third sock, it has to match one of the first two. So three socks guarantee a pair. The ratio? It’s a <strong>red herring</strong>! In the military they’d call it a deception operation. This kind of trick shows up a lot in insight tests — we need to spot when extra info is just distracting. Even though the ratio seems important, it actually hints that the numbers are uneven, but it doesn’t change the answer.</li><li><strong>The Königsberg bridge problem</strong>: <em>Visual cue recommended!</em> The city of Königsberg (now Kaliningrad, Russia) was built on both sides of the Pregel River. Seven bridges connected two islands and the two mainland sides. Can you walk through the city, crossing each of the seven bridges exactly once?<br><strong>Answer</strong>: Euler treated the land areas as points and the bridges as connections. With what we know today from Euler, an<strong> Eulerian path</strong> (visiting every edge exactly once) is only possible if exactly zero or two points have an odd number of connections; all even gives a circuit. Here we have four odd-degree points. So the answer is impossible(zero). <em>Euler changed mathematics as a father of graph theory, respect! Seriously, look Euler up more. The guy was a genius!</em></li><li><strong>Lateral thinking example: </strong>8, 5, 4, 9. Predict the next number!<br><strong><em>Answer:</em></strong><em> </em>This one’s a lateral thinking puzzle! It’s not about a mathematical pattern — it’s about how you interpret the question. The numbers are listed in alphabetical order of their English names: eight, five, four, nine… so the next is one.</li><li><strong>The mutilated checkerboard:</strong> <em>You probably need some visual cues for this to fully grasp! </em>First described by Max Black in 1946. A normal checkerboard has 32 black squares and 32 white squares. With 32 dominoes, each covering two adjacent squares, you can obviously cover the whole board. But if you cut off the corner square at the top-left and the corner square at the bottom-right (both the same color, say red), can you cover the remaining board with 31 dominoes?<br><strong>Answer:</strong> <em>Check on videos!</em> When you remove those two opposite corners, you’re removing two squares of the same color. So now you have 30 of one color and 32 of the other. Each domino covers one black and one white square. With unequal numbers of black and white squares left, it’s impossible — no way to pair them up perfectly. The answer is no, it can’t be done.</li></ol><p>These insight problems aren’t huge, but they’ve stayed classics for a reason. When you’re getting started with Kanban on bigger projects, you can use the same kind of thinking: start with a proof of concept, prototype, gather info, run validations, do interviews, collect feedback, and fold all that into the software development life cycle. It keeps things legal, logical, and valid as a product. I depicted the whole schema on the Secure Voting System.</p><h4>../Lab session: Congressional System</h4><p>Follow the next <a href="https://medium.com/@alborznazari4/secure-apportionment-voting-system-v0-1-0-983054d369d5">article</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48419faab6ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>