<?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 Phunter on Medium]]></title>
        <description><![CDATA[Stories by Phunter on Medium]]></description>
        <link>https://medium.com/@phunter?source=rss-9b5f5d1914ca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RWQMNi3FUQOFcGXPGVvEfg.jpeg</url>
            <title>Stories by Phunter on Medium</title>
            <link>https://medium.com/@phunter?source=rss-9b5f5d1914ca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 14:39:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@phunter/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[Guess the size of an atomic bomb and an iOS supply chain attack]]></title>
            <link>https://phunter.medium.com/guess-the-size-of-an-atomic-bomb-and-an-ios-supply-chain-attack-31d9fb7e5bc2?source=rss-9b5f5d1914ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/31d9fb7e5bc2</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[probability]]></category>
            <dc:creator><![CDATA[Phunter]]></dc:creator>
            <pubDate>Wed, 24 Aug 2022 00:00:07 GMT</pubDate>
            <atom:updated>2022-08-24T20:06:22.652Z</atom:updated>
            <content:encoded><![CDATA[<p>Disclaimer: Nothing in this blog is related to the author’s current day-to-day work. The content is neither affiliated nor sponsored by any companies. The story in this post is based on a true event that happened in two parts, six years apart, and is full of nostalgia.</p><p>In 1945, a famous physicist Enrico Fermi designed an experiment to measure the energy of an atomic bomb*:</p><blockquote><em>“About 40 seconds after the explosion the air blast reached me. I tried to estimate its strength by dropping from about six feet small pieces of paper before, during, and after the passage of the blast wave.” …… “The shift was about 2 1/2 meters, which, at the time, I estimated to correspond to the blast that would be produced by ten thousand tons of T.N.T.” — Wikipedia</em></blockquote><p>How did it relate to the iOS supply chain attack? Let’s jump ahead to 2015.</p><h3>Part I: 2015</h3><p>Back to 2015, I had a chance to join <a href="https://www.akamai.com/newsroom/press-release/akamai-completes-acquisition-of-nominum">a talented team</a> and we worked on DNS traffic analysis and machine learning models for cybersecurity. One day, our experimental anomaly detection system discovered a domain name we had never seen before, but which experienced a sudden traffic spike. It was init.icloud-analysis.com, which was later identified as the primary command-and-control domain for the XcodeGhost malware *, a large scale iOS supply chain attack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ln5gbV-qw89X-oDX.png" /></figure><p>We knew it would go viral because it was an anomaly that caused a spike of 220k unique IPs in a matter of hours, so we had to figure out the answer for our customers so they could take action as soon as possible:</p><blockquote><em>What was the </em><em>XcodeGhost impact, measured in number of infected devices?</em></blockquote><p>Fortunately, we had collected DNS traffic data from our global collaborative customers and discovered that it was trending globally. However, DNS traffic data was the only source of information. It was sampled at random, with a strong regional bias, and it lacked any device information, whether iOS or Android, PC or mobile. With such limited data, how could we calculate the number of infected devices?</p><p>Answering the question, “Customers won’t need the exact number to make decisions, right?” led to the breakthrough. No, they won’t need it because they’d take actions whether there were 9 million or 20 million. As a result, Fermi estimation * provided a clever solution.</p><blockquote><em>“An example is Enrico Fermi’s estimate of the strength of the atomic bomb that detonated at the Trinity test, based on the distance traveled by pieces of paper he dropped from his hand during the blast. Fermi’s estimate of 10 kilotons of TNT was well within an order of magnitude of the now-accepted value of 21 kilotons.” Wikipedia </em><em>*</em></blockquote><p>The exact procedure of Fermi’s example included some physics details* but long story short, we would need to find all scaling factors to connect our observations in the sample data to the target measurement. We needed these three factors to guess how the entire dataset would look:</p><ul><li>DNS data sampling rate</li><li>sampling bias in different regions</li><li>number of iOS devices of each client IP</li></ul><p>The first could tell the global scale of data sampling; the second could correct for bias; and the third was required because DNS data only records its client IP, which could be a router, phone station, school network, etc., but we wanted the number of iOS devices.</p><p>The first was simple, or we had little to do, but we had to accept 1%, as agreed with our customers. This 1% also included data collection efficiency. As a result, it had to be 1%.</p><p>The sampling bias by region was tricky: in 2015, we only had data from the EU, Latin America, Australia, and South Asia, with no idea of North America or China, the world’s two largest telecom regions. Fortunately, we had some snapshot samples from a pilot program with a list of customers, including customers from North America and China, about a year ago. Although data from North America and China were discontinued, some other customers remained with the program, so we used them as anchor points: we compared the ratio of North American and China vs anchor customers from a year ago to the global data vs anchor customers in 2015, and we concluded that the sampling bias rate was about 0.5.</p><p>The number of iOS devices for each client IP was solved by using probability. We studied that on average each IP had about 2 mobile devices, which could be either Android or iOS, and that the Android vs iOS market share was roughly 1:1. So, what was the expected number of iOS devices when we discovered the XcodeGhost domain, indicating at least one iOS device behind this IP? The answer was 1.33. Please consider it a good exercise and have some fun with it.</p><p>So the estimated number of XcodeGhost infected devices became</p><p>\[220k \times 100 \times 2 \times 1.333 = 58.7 M\]</p><p>Why do we need the Fermi estimation method if it appeared to be just some common sense factors? The method could provide an answer to the following question: what about the upper and lower limits? According to Fermi’s estimation, it was overestimating or underestimating by a factor of 2 to logarithmic scale. For 3 scaling factors, the upper limit should be $58.7 M \times 2^{\sqrt{3}} = 195.0 M$ and the lower limit $58.7 M \div 2^{\sqrt{3}} = 17.7 M$, so we could report to our customers:</p><blockquote><em>The global number of </em><em>XcodeGhost infected devices was approximately 59 million, with a range of 18 million to 195 million, so please take action.</em></blockquote><p>Yes, there could be up to 200 million infected devices! Without knowing each step above, it was impossible to believe.</p><h3>Part II: 2021</h3><p>How time flies! With just a finger snap of time, the company was acquired in 2017, the team also moved forward. Let’s fast forward to 2021, when there was a law suit between Epic Games and Apple, and some related Apple internal emails mentioning XcodeGhost were revealed as evidence in court:</p><blockquote><em>“In total, 128M customers have downloaded the 2500+ apps that were affected LTD. Those customers drove 203M downloads of the 2500+ affected apps LTD,”</em></blockquote><blockquote><em>“China represents 55% of customers and 66% of downloads. As you can see, a significant number (18M customers) are affected in the US.”</em></blockquote><p>The mystery of the number of XcodeGhost infected devices has been solved. We had a very accurate estimation with a tiny little biased sample of DNS traffic! It was within an order of magnitude of Fermi&#39;s 10 kilotons of TNT for the true value of 21 kilotons!</p><h3>Summary</h3><p>The population distribution could also be used to estimate regional sampling bias because we could assume one device per person, yielding a factor of about 0.3. We chose the anchor method so that we could better justify it to customers. Actually, a factor of 0.3 or 0.5 was sufficient for this task.</p><p>Surely, some details were changed to simplify the story. We were also looking for the source of this infection. The correlation model, later known as domain2vec, provided an answer. The anomaly domain init.icloud-analysis.com had a numerical dense vector as its distributed representation, and its learned vector had small open angles with a few other vectors for domains of popular Chinese apps. This observation also reminded us of the regional sampling bias.</p><p>Estimation with limited information, or “Guesstimation,” is widely used in many fields, including quantitative trading (such as market-sizing), astronomy (such as the number of planets on which aliens can live), and computer science (like the number of rows in a large table to optimize SQL queries). In each field, an estimate within an order of magnitude is considered accurate for making strategic decisions.</p><h3>Reference</h3><ul><li>Trinity Test <a href="https://en.wikipedia.org/wiki/Trinity_(nuclear_test)">https://en.wikipedia.org/wiki/Trinity_(nuclear_test)</a></li><li>XcodeGhost <a href="https://en.wikipedia.org/wiki/XcodeGhost">https://en.wikipedia.org/wiki/XcodeGhost</a></li><li>Fermi Problem <a href="https://en.wikipedia.org/wiki/Fermi_problem">https://en.wikipedia.org/wiki/Fermi_problem</a></li><li>How exactly Fermi estimated the atomic bomb <a href="https://physics.stackexchange.com/questions/19567/how-did-enrico-fermi-calculate-the-classical-fermi-problem">https://physics.stackexchange.com/questions/19567/how-did-enrico-fermi-calculate-the-classical-fermi-problem</a></li><li>Security firm publishes list of some of the iOS apps infected by XcodeGhost <a href="https://9to5mac.com/2015/09/21/xcodeghost-infected-apps/">https://9to5mac.com/2015/09/21/xcodeghost-infected-apps/</a></li><li>Emails reveal 128 million iOS users were affected by ‘XcodeGhost’ malware <a href="https://9to5mac.com/2021/05/07/emails-reveal-128-million-ios-users-were-affected-by-xcodeghost-malware/">https://9to5mac.com/2021/05/07/emails-reveal-128-million-ios-users-were-affected-by-xcodeghost-malware/</a></li></ul><p><em>Originally published at </em><a href="https://toooold.com/2022/08/24/guess_size.html"><em>https://toooold.com</em></a><em> on August 24, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31d9fb7e5bc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zero hacking problem: do we really protect the customers?]]></title>
            <link>https://phunter.medium.com/zero-hacking-problem-do-we-really-protect-the-customers-d504d6fb8d29?source=rss-9b5f5d1914ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/d504d6fb8d29</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Phunter]]></dc:creator>
            <pubDate>Wed, 17 Aug 2022 00:00:58 GMT</pubDate>
            <atom:updated>2022-08-24T20:03:28.700Z</atom:updated>
            <content:encoded><![CDATA[<p>Disclaimer: Nothing in this blog is related to the author’s day-to-day work. The content is neither affiliated nor sponsored by any companies.</p><p>A few weeks ago, Jason came to me with a question from his product manager buddy:</p><blockquote><em>How can we tell the effectiveness of our product if a customer used our cloud security solution to protect 100 cloud machines and saw no hacking?</em></blockquote><p>If my dear readers don’t know Jason, please refer to <a href="https://toooold.com/2022/07/25/measure_unmeasureable.html">the previous blog post</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qRphEVRDIkZZPjW7.png" /></figure><p>“So, if we don’t respond, the customer will stop renewing the protection subscription?” I said. Jason was virtually nodding on the screen.</p><p>Surely, business is business, so we must respond to this question. We could respond in this way: we knew the malware infection or hacking rate on the cloud was 5% before we implemented our security solution, and we reduced it to 1% after we implemented it.</p><p>“But the customer saw zero hacking events, and I mean <strong>ZERO</strong> in every way, even before using our product. So, how do we persuade them?” Jason said.</p><p>Let’s toss coins and understand the observation dilemma. If I tossed a fair coin for 100 times and see all heads no tails, the probability can be $\frac{1}{2^{100}}=7.9\times10^{-31}$. If I tossed a double-headed coin for 100 times and see all heads no tails too, the probability can be, surely, $1$. So, <strong>if I didn’t know which coin I picked</strong> and I just tossed 100 times and saw all heads, which coin did I choose, the fair one or the double-headed one?</p><p>“It sounds like the double-headed coin.” Jason said. “However, it’s still possible that you chose the fair one; it’s just very unlikely.”</p><p>Yes, and Jason’s intuition can be quantified in the probability way.</p><p>If we know the malware or hacking infection rate is 5% and no hacking occurred on 100 independent machines, the probability was $0.95^{100}=0.6\%$. With our security solution, the malware or hacking rate was reduced to $1\%$, and we saw no hacking, so the probability became $0.99^{100}=36.6\%$. We increased the likelihood of none of these 100 machines being hacked from $0.6\%$ to $36.6\%$!</p><p>“Please wait; I understand probability as well. We can’t convince the customer that $36.6\%$ is significantly better than $0.6\%$ because we saw no hacking events in the first place.” Jason stated.</p><p>Jason, you were correct. We had observations and had to state how confident we were by having the range of assumed adverse event rates leading to a probability of $5\%$ or more as a $95\%$ confidence interval.</p><blockquote><em>“Adverse event” meant that even after we applied the protection, the machine was still hacked. What a stroke of bad luck.</em></blockquote><p>When referring to <a href="https://en.wikipedia.org/wiki/Confidence_interval">confidence interval</a>, like $95\%$ confidence interval for most statistical problems, we use this equation for binomial distribution:</p><p>\[\widehat{p}\pm Z_{1-\alpha/2}\sqrt{\frac{p(1-p)}{n}}\]</p><p>But the zero observation case didn’t satisfy its underlining assumption of normal distribution. Fortunately, we could get back to the original definition of confidence interval. To get $95\%$ confidence interval, we will need:</p><p>\[(1-p)^n=0.05\]</p><p>where $p$ is the assumed probability of “bad luck” adverse events. Thus, we have</p><p>\[n\ln(1-p)=\ln(0.05)\]</p><p>Since $\ln(1-p)\sim-p$ using Taylor expansion for small $p$ value (“Yes, I remember it from my information theory class!” Jason said.), we have the upper bound of $95\%$ confidence level as</p><p>\[p=\frac{3}{n}\]</p><p>For $n=100$ in our case, $95\%$ confidence level required $p$ from $0$ to $0.03$ which meant it could tolerant $0\%$ to $3\%$ malware or hacking rate where we observed zero hacking event for 100 independent machines. If the customer didn’t have our security solution, $p$ was $5\%$ which was out of the boundary, very dangerous, and our security solution successfully reduced it to $1\%$ and it was within the $95\%$ confidence level boundary.</p><p>“So the customer should renew the product!” Jason said.</p><p>“But we have to clarify that the 100 machines must be independent because …… wait, get back to the meeting! Jason, can you hear me?” I said.</p><h3>Reference</h3><ul><li>Confidence interval with zero events <a href="http://www.pmean.com/01/zeroevents.html">http://www.pmean.com/01/zeroevents.html</a></li><li>Binomial confidence intervals for rare events: importance of defining margin of error relative to magnitude of proportion <a href="https://arxiv.org/pdf/2109.02516.pdf">https://arxiv.org/pdf/2109.02516.pdf</a></li></ul><p><em>Originally published at </em><a href="https://toooold.com/2022/08/17/one_hundred_machines.html"><em>https://toooold.com</em></a><em> on August 17, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d504d6fb8d29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linkedin spam: a case study of robust feature engineering]]></title>
            <link>https://phunter.medium.com/linkedin-spam-a-case-study-of-robust-feature-engineering-b5ae84602fb?source=rss-9b5f5d1914ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5ae84602fb</guid>
            <category><![CDATA[fraud-detection]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[linkedin]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Phunter]]></dc:creator>
            <pubDate>Wed, 03 Aug 2022 00:00:52 GMT</pubDate>
            <atom:updated>2022-08-03T23:52:24.132Z</atom:updated>
            <content:encoded><![CDATA[<p>Disclaimer: Nothing in this blog is related to the author’s day-to-day work. The content is neither affiliated nor sponsored by any companies. I am not employed by Linkedin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hI2sD4uqJAyPFlxk.png" /></figure><p>On Linkedin, I believe many of us have received such “please add me to your professional network” requests:</p><ul><li>job titles like “Technical Director” or “Technical Advisor”</li><li>profile pictures are all Asian ladies, most of them are Photoshop retouched</li><li>they work in tech industry; instead of MAANG companies, their companies are generally well known in each industrial category.</li><li>they graduated from some top rank universities, mostly in China</li><li>no much recent activity on Linkedin</li></ul><p>and a few other features that I hope everyone notices. I believe Linkedin’s fraud detection team has worked very hard, but such account fraud and spam attacks must be the work of a sophisticated attacker, because each feature is carefully crafted to be confusing enough as a single feature or in combination. Can we, as Linkedin users, help Linkedin in combating such fraud? We can use it as an example of robust feature engineering.</p><p>Features that appear to be so obvious may not be good features. It is a hard lesson learned in cybersecurity because such features do not ensure its robustness for classification in a dynamic environment. For example, one can deploy a feature such as “if the job title contains Technical Director” to detect such fraud accounts. Despite the model’s false positive rate, the attackers can simply monitor the fraud effectiveness to determine that “Technical Director” is no longer a good title and can quickly change to another one. Such feature drift as a result of an attack policy change can drag the defense team into a mud pit fight.</p><p>The same is true for the other features listed above. Do we want to create a deep learning model to detect if a profile picture has been Photoshopped? No, <a href="https://github.com/apchenstu/sofgan">GAN</a> can be used by attackers to generate new portrait images that no one can detect. Do we want to gather all of the good companies in each industrial category? No, the attackers can steal company names from legitimate resumes. Do we intend to shut down all Chinese universities? Universities are not guilty. Do we want to validate the recent Linkedin activity? No, the attackers can join numerous Linkedin groups and spam them, posing a larger problem than account fraud. So, what are our options?</p><p>In my previous post about <a href="https://toooold.com/2021/10/18/why_ml_fails_security_frag_en.html">feature engineering</a>, I cited a comment:</p><blockquote><em>“Only algorithms care about right or wrong, security is about cost.”</em></blockquote><p>One approach to robust feature engineering for adversarial environments is to increase the cost of attack so that the features are either difficult to change or impossible to change. Let’s think like an attacker and figure out “what makes my job difficult”: more engineering work, a longer payback loop, data I can’t access, and so on.</p><p>The profile URL pattern, for example, provides a small bar-raising feature. The profile ID ‘liu-y-44b114233’ is shown in the sample screenshot as a default ID generated by the onboard system, so “If using default ID” as a feature can force attackers to code their own profile IDs, which adds to the attacking cost.</p><p>Another example is recent connection vs lifetime connection, which suggests a recent connection spike to be more fraudulent. Because the account fraud and spam business prefers quick turnover, attackers focus on short-term gain. Features such as “new user pattern,” “connection request rate,” “connection approval rate,” and “connection patterns over time” can slow down an attack and discourage attackers.</p><p>Leveraging data that attackers do not have access to can generate new ideas. For example, attackers cannot see the overall Linkedin user pattern, but Linkedin can via the global connection graph. Attackers seek more connections, so they begin with people who always approve new connections for whatever reason, similarly in cybersecurity, machines with unpatched vulnerabilities can easily be infected with new malware. The model can leverage this “user-item” interaction feature from graph for classification by labeling “easy to approve” users with historical fraud detection data. The same concept can be applied to the user’s fingerprint versus the requesting connection fingerprint: do all request connections share the same profile patterns? Trust me, graph data features can significantly raise the bar for attack.</p><p>Certainly, robust feature engineering is a broad topic with many aspects to combat “drift” from data, including feature engineering, seasonal effect, black swan, adversarial attack, and so on. Furthermore, fraud detection cannot be accomplished by a single machine learning model. It necessitates a data system, feature, model, and operation. Aside from great feature engineering and models, the system should collect user feedback for the model, such as “ignore because I think it is fraud,” and improve the operational process, such as fraud prediction with reasons.</p><p><em>Originally published at </em><a href="https://toooold.com/2022/08/03/linkedin_fraud_account.html"><em>https://toooold.com</em></a><em> on August 3, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5ae84602fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nine cars, twenty-five horses and beyond]]></title>
            <link>https://phunter.medium.com/nine-cars-twenty-five-horses-and-beyond-bb2f82805848?source=rss-9b5f5d1914ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb2f82805848</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[puzzle]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Phunter]]></dc:creator>
            <pubDate>Sat, 11 Jun 2022 00:00:00 GMT</pubDate>
            <atom:updated>2022-06-13T23:46:01.210Z</atom:updated>
            <content:encoded><![CDATA[<h3>TL, DR</h3><p>“25 horses problem” and “9 cars problem” can have a general solution and a simple formula when we construct a max heap. The approach can be extended into higher dimension tensors and solved with a more general formula.</p><h3>The problem</h3><p>My favorite educational influencer, Li Yongle, has posted a puzzle of 9 race cars on Weibo ( <a href="https://m.weibo.cn/detail/4778730424109058">Link</a>):</p><blockquote><em>A second-grader posed the following question to him: There are nine cars in total, and the fastest two must be identified. We can run a race between no more than three cars to determine the </em><strong><em>relative speed</em></strong><em> without recording the actual speed. What is the minimum number of races required to obtain the top two cars?</em></blockquote><p>The answer is 5, which isn’t a big deal for a bright second grader. So, without loss of generality, what is the minimum number of races for N cars at track size T to get the top k cars? What happens if N isn&#39;t a square number? What if k exceeds track size T?</p><h3>Dig into a special case</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M55ib86laa2T7ahh.png" /></figure><p>Horses are divided into five groups and labeled A to E and 1 to 5 within each group. Following that, we organize the races in two batches:</p><ul><li>batch 1 to conclude top 3 within each group (colored in green) where A1 &gt; A2 &gt; A3 etc;</li><li>batch 2 for top 1s of all groups to conclude the overall top 1 (colored in red), plus an extra round for top 2 and 3 (colored in orange).</li></ul><p>Batch 1 is simple to understand because the overall top three must be at least the top three in each group. The first step in batch 2 is also simple, because the overall top 1 must be the fastest among all top 1. The trick is to use only one extra round for the top two and three horses: why do we need to compare A2 A3 B1 B2 and C1? Why do they appear diagonal in the matrix?</p><p>Consider the following scenario: we know A1 &gt; B1 from step 1 in batch 2, do we have to check B3 if B1 &gt; B2 is known in batch 1? It is obviously not necessary because we only look for the top three and have three elements, A1, B1, and B2, from two previous race results.</p><p>This leads to a widely used data structure: <a href="https://en.wikipedia.org/wiki/Heap_(data_structure)">heap</a>:</p><blockquote><em>“a heap is a specialized tree-based data structure which is essentially an almost complete[1] tree that satisfies the heap property: in a max heap, for any given node C, if P is a parent node of C, then the key (the value) of P is greater than or equal to the key of C.”</em></blockquote><ul><li>insert the first 5 races for top 3s;</li><li>insert one more race for all top 1s;</li><li>pop the root in the heap since it is the overall top 1;</li><li>and one extra race to pop the top 2 and 3.</li></ul><p>That explains why they appear diagonal in the matrix: the heap requires up to three levels of cross-group comparison. Surprisingly, it is the most efficient method for locating the top k elements in a sorted matrix. Test the code in <a href="https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/">leetcode #378</a>.</p><p>Meanwhile, we can see that the 9 cars problem can be solved by holding three races in batch one, one for first place and one for second place.</p><h3>Go beyond the 2nd grade</h3><p>Constraint #2 of T=(k-1)*(k+2)/2 can be derived by induction: when we have the overall top 1 and want to determine the next best k-1 horses/cars, we select T other horses/cars which have fewer than k horses/cars faster than them, so T must be constructed as (k-1)+(k-1)+(k-2)+...+2+1 which is (k-1)*(k+2)/2.</p><p>With these two constraint conditions, the approach above can always give the answer to the number of races as T+2. In short, when 9 cars race ( N=9, T=3, k=2), the number of rounds is T+2 = 5; when 25 horses race ( N=25, T=5, k=3), the number of rounds is T+2 = 7; when there are 58140625 dragonflies race for the top 123 ranks, the number of round must be 7627.</p><h3>Vector, matrix and tensor</h3><p>A more interesting extension is: does this approach still work if N = T^j where j can be 3,4,5 or more instead of 2? Let&#39;s stick with the heap construction method.</p><p>Vector can be considered a special type of matrix as 1xN matrix while matrix is a special type of tensor of NxM (2 tensor dimensions). When j=1 which means 5 horses finding top 1, obviously we only need to race once, but let&#39;s keep in mind the problem is finding max (top 1) in a sorted array ( <strong>vector</strong>); when j=2, the problem is top-3 in a sorted <strong>matrix</strong> and solution above as T+2 can be rewritten as T+j because the matrix form introduces T races for the batch 1 comparison and one extra race for the diagonal comparison, so 25 horses need 5+2 races; if j=3 or above, the problem becomes finding top k in the sorted <strong>tensor</strong> (yes, it is the same tensor in deep learning), and here it is how to deal with the tensor scenario:</p><p>By following the heap construction approach, when j=3 as a 3-D tensor, we need to run T^2 races to reduce the problem to j=2 because each dimension in the tensor need the ranks in individual group of T size vector and we also need one extra race for the top 1s of each higher dimension. After that, we reduce the problem to j_new=2 and we know the answer of T+j_new, so the total number of races becomes T^2+1+T+j_new which is T^2+T+j. So, my dear readers might have a wild guess, for tensor of dimension j, the number of races should be T^(j-1)+T^(j-2)+...+T^2+T+j which is (T^j-1)/(T-1)+(j-1)?</p><p>The guess is correct and easy to understand: for each higher tensor dimension, we need to compare each dimension for T^(j-1) times to reduce to a lower tensor dimension, and use one extra race for this tensor dimension&#39;s top 1, till we get to j=2, so the summation of races become (T^j-1)/(T-1)+(j-1). I don&#39;t have a good tool to visualize it but I believe my dear readers can use their imaginations to solve this high dimension tensor case.</p><h3>What about track size and top ranks</h3><h3>Summary</h3><p>If we would like to loose all constraints to a much more general problem, we can take a look at this difficulty discrete math topic “Sorting by k-ary Comparisons” *, however the exact solution is not guaranteed.</p><h3>Reference</h3><ul><li>“Sorting by k-ary Comparisons” <a href="https://faculty.math.illinois.edu/~west/regs/ksetsort.html">https://faculty.math.illinois.edu/~west/regs/ksetsort.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb2f82805848" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cybersecurity problem solving with explainable machine learning]]></title>
            <link>https://phunter.medium.com/cybersecurity-problem-solving-with-explainable-machine-learning-d26b24d2a0a2?source=rss-9b5f5d1914ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/d26b24d2a0a2</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Phunter]]></dc:creator>
            <pubDate>Tue, 15 Feb 2022 00:00:00 GMT</pubDate>
            <atom:updated>2022-02-16T16:57:49.951Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sBWXsQrT4qbrVWs8gWNkGQ.jpeg" /><figcaption>Queen Isabella peeking</figcaption></figure><p>Disclaimer: Nothing in this blog is related to the author’s day-to-day work. The content is neither affiliated nor sponsored by any companies.</p><p>Link to the original post: <a href="https://toooold.com/2022/02/15/explainable_w_shap_en.html">Cybersecurity problem solving with explainable machine learning | Toooold</a></p><p>Link to the Chinese version: <a href="https://toooold.com/2022/02/13/explainable_w_shap_cn.html">求解网络安全问题的可解释机器学习 | Toooold</a></p><p>Have you ever wondered why the model’s performance degrades after two months of initial deployment? Why does the model continue to make errors on certain samples? Why do bad cases from the operations team take so long to resolve? Such many ‘whys’ remind us that, explainable machine learning, which provides a way for human to understand what the model is doing on a given sample may be useful for cybersecurity problem solving.</p><p>The explainable model prediction is closely related to operations when solving cybersecurity problems. For example, firewall products must have sufficient confidence in the prediction results to block threats, and SIEM and SOAR systems on the cloud must introduce specific reasons and contextual associations of prediction results to support operational judgments. We can provide partial explainability of the prediction results to support operations based on the model’s explainability.</p><p>Explainable artificial intelligence (XAI) and its subfield, explainable machine learning, have been studied from a variety of perspectives in academia. This post introduces the black-box explainable model and some of its methods and applications in industry, as well as its design, usage, and limitations, among other things. My dear readers can delve deeper into this research topic by using the example of encrypted traffic detection, which causes the most headaches in cybersecurity.</p><h3>Feel the vibe of explainable machine learning</h3><p>In the cybersecurity industry, there are many machine learning models based on statistical features for network traffic detection and classification, such as the packet feature based detection model for encrypted DNS (DoH), mentioned in <a href="https://toooold.com/2021/07/04/doh_detection.html">my previous post</a> (and the <a href="https://github.com/phunterlau/code-in-blog/tree/main/doh">Jupyter Notebook</a>). These “counting” features are sliced to branch out the decision tree in boosting learner like xgboost, but the slicing strategy is decided by the learner, so the finer the slicing, the greater the risk of generalization to unknown data. The degradation of model performance and the instability of features from data drift needs continuous investment in maintenance by the data scientist team and even causes the data team to avoid solving traffic detection problems. Here, explainable machine learning can effectively solve such headaches.</p><blockquote><em>It is worth mentioning here about the existing best practice of such encrypted traffic classification problems in computational advertisement using </em><em>GBDT cross features. He et al &quot;Practical Lessons from Predicting Clicks on Ads at Facebook&quot;</em><em>* divides the counting features into sparse vectors and solves them with a simple linear model, which controls the slicing of statistical features to some extent; there are also cases where raw network traffic data is fed directly to a deep convolutional neural network to extract features; however, the neural network does not guarantee a reasonable extraction of encrypted traffic features and sufficient generalization, and the same design of fully connected layers for classification as in the computer vision problem doesn&#39;t always outperform the tree learner.</em></blockquote><p>To solve this problem, we employ the SHAP ( <strong>SH</strong>apley <strong>A</strong>dditive ex <strong>P</strong>lanations) algorithm *. SHAP addresses the economics of cooperative competition from a game theory point of view: how to fairly measure A B C&#39;s contribution to the $1,000 prize they receive by cooperating with one another? In this context, &quot;fair measurement&quot; takes into account three people&#39;s independent contributions, two people&#39;s cooperation (including the sequence), three people&#39;s cooperation, and the relationship between two people&#39;s cooperation and three people&#39;s cooperation. The SHAP algorithm analogizes the model&#39;s input features to cooperative individuals, and its interpretable contribution values are derived from the Nobel Prize-winning economics method Shapley value*. Because of the various combinations of contributors (feature vectors) that must be considered in the actual computation, the computational complexity of the exact solution is NP hard. The SHAP algorithm approximates the results in effective time using linear constraints, please feel free to find this interesting paper in the references.</p><p>In practice, the open source implementation of SHAP has been optimized for various types of prediction models, such as Tree SHAP for decision tree models. By simply adding these lines of code, the xgboost model for detecting encrypted DNS can use SHAP to interpret its prediction results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*1ycIjwdV5dstjB4t.png" /></figure><p>The figure of waterfall of SHAP values above shows that the expected value for all samples in the dataset is -0.725, while the model predicts -0.835 for sample 0. It’s because features like var_pkt_size_out and time push it from -0.725 to -0.835, while median_out feature pulls it back to the expectation of all samples. With back-n-forth pulling forces, the model eventually predicts -0.835 for sample #0 and correctly predicts it as a negative sample (non-encrypted DNS).</p><p>For positive sample #33 (encrypted DNS), median_out and median_in contribute significantly to its deviation from the expectation of all samples, lowering its prediction to -0.187 in a single kick and correctly predicting it as a positive sample.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/0*f4j-Wc3UYtFnDKlH.png" /></figure><p>The two features median_out and median_in are also important in distinguishing the majority of positive samples in this dataset, and var_pkt_size_out is dominating in distinguishing negative samples. This explanation serves as the foundation for the decision to use the model approach: the model must be deployed with strict monitoring of the adversarial attack against these three features, for example:</p><ul><li>Whether there is a new encrypted DNS service that obfuscates the median_out and median_in statistical features to escape from detection.</li><li>Whether the design data collection scenario includes a selection bias for features like var_pkt_size_out</li><li>Whether these determining features have a consistent statistical distribution across data collected at different time periods</li></ul><p>where “change in the statistical distribution of the determining features” is one of the primary causes of performance degradation after deployment and go-online. It is a type of data drift, and finding these features and monitoring their distribution can help detect and deal with it in real time. You can continue to investigate other SHAP functions, such as force_plot to better understand the basis of model classification. Of course, one can view the SHAP waterfall plot for each sample in the <a href="https://github.com/phunterlau/code-in-blog/tree/main/doh">Jupyter Notebook</a>, and one can also change the parameters of the prediction model to see how the SHAP waterfall plot changes with the new parameters.</p><p>The SHAP example demonstrates a general approach to the use of black-box explainable machine learning models, which essentially have the following properties:</p><ul><li>The modeling process requires developing a predictive model and then using another model to explain it, known as “post hoc” (explanation after the fact);</li><li>The explainable model always provides the explanation but is unconcerned about the prediction method or whether the results are correct or not;</li><li>The explainable model generates a waterfall plot of SHAP values for each sample rather than an overall explanation of the data set.</li></ul><p>Similar to SHAP, there are other methods such as LIME * that explain the classifer model in a post-hoc black box. One can refer to the book &quot;Interpretable Machine Learning&quot;* for further study.</p><h3>With feature importance, do we still need explainable models?</h3><p>What is the difference between the SHAP value and the permutation feature importance? The SHAP value of each feature is related to each sample, describing the marginal effect of the combination of features in classification for the specific sample, and the combination of features and their marginal effect may differ for positive and negative samples, whereas the feature importance describes the model’s overall understanding of the whole dataset, describing the model classification performance for the dataset, independent of any specific samples. We can use the distribution of SHAP values on different samples to improve model characteristics, and Kaggle competitors can also optimally adjust the competition model by understanding the distribution of SHAP values *. Please refer to SHAP Summary Plot and Dependence Plot.</p><p>Of course, SHAP is not the only approach. There are numerous alternatives on the path to explainable machine learning and XAI.</p><p>Some models are inherently interpretable, such as symbol-based AI models * such as logical reasoning, the results of which can be self-explanatory. My <a href="https://toooold.com/2021/11/28/why_ml_fails_security_ml_is_not_everything_cn.html">previous post</a> has mentioned my team&#39;s work &quot;Honeypot + graph learning + reasoning = scale up your emerging threat analysis&quot; in which a knowledge graph model uses logical reasoning to explain the results of the distributed embedding model. The results of logistic regression and linear regression are also represented by a single weight matrix that is self-explanatory; the results of kNN models are also self-explanatory.</p><p>Explainable models are further subdivided into generic models such as SHAP and LIME, as well as some scenario-specific models such as the attention mechanism, which can provide some explanation for the results of transformer families such as BERT/GPT, as recently demonstrated by Deepmind’s AlphaCode in its demo*. Some adversarial generative models (GANs) generate adversarial samples in order to confuse model classification and, to some extent, reveal potential flaws or implicit assumptions in models.</p><p>Please read and explore “Explainable AI Cheat Sheet”* listed in the references for a good overview of existing explainable AI (XAI) models.</p><h3>Keep calm and we still need other work</h3><p>I kind of agree that, Please Stop Doing “Explainable” ML !* Because...</p><p>Explainable models have a natural limitation: their scope is limited to solving the current problem and cannot extend beyond the defined problem and the given dataset. In a cybersecurity scenario, where the limitations of data collection and detection scenarios, as well as many tricky ways the attackers can try to conceal their behavior, it is just as important to look for external factors as it is to look for internal ones. Explainable models will not tell us that C&amp;C behavior was caused by an unknown zero-day vulnerability or an administrator account that was quietly created without logging. Similarly, explainable models such as SHAP are not the same as explainable results, and explanation of the predicted results for different scenarios may necessitate the use of explainable models, as well as third-party knowledge outside the scope of model or logs, etc.</p><p>Explainable models are only “explanatory”, not “causality”, and causal inference is still required. More importantly, an explainable model is only a “explanation”, not a logical argument: it does not guarantee that the model is correct, nor that its explanation is logical; it simply explains why model A is judged as it is on sample X. A common example is the tumor vs ruler joke*: when the model finds the ruler as a key feature of the rumor, which is only present in the positive sample images, its explanatory model can only state that &quot;it recognizes the ruler&quot; and cannot express that &quot;the ruler is not a reasonable basis for the judgment&quot;. Data science teams still need to identify problems, make logical arguments, and improve models on their own.</p><p>In the business world, we must also consider the cost of explainable models. The explanation provided by post hoc explanatory models comes with additional engineering costs such as development and deployment, as well as usage scenario limitations; many cases can be done well without explainable machine learning. Please consider the ROI of the operational cost versus the cost of explainable models, and use your own judgment to determine whether explainable models are required.</p><h3>Summary</h3><p>To some extent, explainable machine learning can help solve several cybersecurity problems in dynamic environments, not only by providing explanatory results to aid operations, but also by assisting data science teams in effectively maintaining stable model performance over time. This paper introduces the use of explainable machine learning from an engineering case perspective, omitting specific theoretical knowledge due to the post length constraints, but this does not imply that these theoretical foundations can be ignored.</p><h3>Reference</h3><p>* He et al, Practical Lessons from Predicting Clicks on Ads at Facebook &lt;<a href="https://quinonero.net/Publications/predicting-clicks-facebook.pdf">https://quinonero.net/Publications/predicting-clicks-facebook.pdf</a>&gt;<br>* SHAP paper, Lundberg and Lee “A Unified Approach to Interpreting Model Predictions” &lt;<a href="https://proceedings.neurips.cc/paper/2017/hash/8a20a8621978632d76c43dfd28b67767-Abstract.html">https://proceedings.neurips.cc/paper/2017/hash/8a20a8621978632d76c43dfd28b67767-Abstract.html</a>&gt;<br>* Shapley value &lt;<a href="https://en.wikipedia.org/wiki/Shapley_value">https://en.wikipedia.org/wiki/Shapley_value</a>&gt;<br>* SHAP in “Interpretable Machine Learning” &lt;<a href="https://christophm.github.io/interpretable-ml-book/shap.html">https://christophm.github.io/interpretable-ml-book/shap.html</a>&gt;<br>* SHAP github &lt;<a href="https://github.com/slundberg/shap">https://github.com/slundberg/shap</a>&gt;<br>* LIME &lt;<a href="https://github.com/marcotcr/lime">https://github.com/marcotcr/lime</a>&gt;<br>* Kaggle post “Advanced Uses of SHAP Values” &lt;<a href="https://www.kaggle.com/dansbecker/advanced-uses-of-shap-values">https://www.kaggle.com/dansbecker/advanced-uses-of-shap-values</a>&gt;<br>* Symbolic artificial intelligence &lt;<a href="https://en.wikipedia.org/wiki/Symbolic_artificial_intelligence">https://en.wikipedia.org/wiki/Symbolic_artificial_intelligence</a>&gt;<br>* AlphaCode demo &lt;<a href="https://alphacode.deepmind.com/">https://alphacode.deepmind.com/</a>&gt;<br>* Explainable AI Cheat Sheet &lt;<a href="https://ex.pegg.io/">https://ex.pegg.io/</a>&gt;<br>* Please Stop Doing “Explainable” ML — Cynthia Rudin &lt;<a href="https://www.youtube.com/watch?v=I0yrJz8uc5Q">https://www.youtube.com/watch?v=I0yrJz8uc5Q</a>&gt;<br>* When AI flags the ruler, not the tumor &lt;<a href="https://venturebeat.com/2021/03/25/when-ai-flags-the-ruler-not-the-tumor-and-other-arguments-for-abolishing-the-black-box-vb-live/">https://venturebeat.com/2021/03/25/when-ai-flags-the-ruler-not-the-tumor-and-other-arguments-for-abolishing-the-black-box-vb-live/</a>&gt;</p><p><em>Originally published at </em><a href="https://toooold.com/2022/02/15/explainable_w_shap_en.html"><em>https://toooold.com</em></a><em> on February 15, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d26b24d2a0a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Useful useless models: an approach to model complex cybersecurity problem solving]]></title>
            <link>https://phunter.medium.com/useful-useless-models-an-approach-to-model-complex-cybersecurity-problem-solving-b4f3c4d038d8?source=rss-9b5f5d1914ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4f3c4d038d8</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[scientific-method]]></category>
            <dc:creator><![CDATA[Phunter]]></dc:creator>
            <pubDate>Sun, 09 Jan 2022 00:00:00 GMT</pubDate>
            <atom:updated>2022-01-10T23:33:43.002Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ny2qtaeVTBKSbO9bO-JHA.jpeg" /><figcaption>Queen Isabella watching birds</figcaption></figure><p>Disclaimer: Nothing in this blog is related to the author’s day-to-day work. The content is neither affiliated nor sponsored by any companies.</p><p>The Chinese version is here <a href="https://toooold.com/2022/01/04/useful_useless_model_cn.html">https://toooold.com/2022/01/04/useful_useless_model_cn.html</a></p><p>When developing machine intelligence models to solve cybersecurity problems, we rarely find any cases that a problem can be solved by a single end-to-end model. Let’s take phishing detection for example: besides the data engineering tasks such as preparing and cleaning sufficient input data, the detector starts with identifying key image elements on the page such as logos, combine the HTML code analysis features and classification, for some case, it also needs to run javascript rendering and fight the page’s phantomjs detector (well, the phishing guys are smart too), plus some network features like DNS or URL patterns as well, applying some filters like Alexa rank, and provide sufficient evidence to support further operational policy, and repeat each week to recover the precision loss. Such examples frequently frustrate data science teams as well as company executives: building a phishing detector shouldn&#39;t be rocket science and every security company are making their phishing detectors, but why only we see more and more problems everyday on my detector? When can we finish it? With the pressure of time and resource, the team and management gradually developed burnout and started to regret a lot, so we have seen a lot of teams have to cop out great ideas and rush the deployment, which propagate the tech debt down to the security operation teams or the customers to repay.</p><p>The complexity of the problem in cybersecurity comes from its higher than normal requirement to “trustworthy”, due to both the dynamic environment of high-intensity adversary and the high cost of validation, as well as the consequence to incidents. Do we have to assign an SOC expert to respond to every alert predicted by a model? Is the model capable of providing IoC that I can trust and block my company firewall? Traditional cybersecurity methods insert well-trained human in the loop to ensure trust at every step by leveraging human experience; however, attackers know it too, and in addition to bypass methods, designing attack methods to exhaust SOC is also a hot topic in the attack method research. “How to reduce human cost in the trust chain” has become a research direction of modern cybersecurity solution methods, in which the model framework of cross-validation with multiple independent models is one of the effective methods, simply put, is to use multiple independent data sources with independent feature vectors of the model to form a jigsaw puzzle and put pieces together to solve a problem. This approach can also reduce the quality requirement of individual models, allowing as many weak models to be included to improve the scope of the problem solving, which can be discussed in another post separately. The question here is, how to combine multiple independent models to support trust effectively?</p><p>Combining the above two cases, we can look at this <strong>engineering</strong> problem from the system design point of view: when it is too expensive to design a set of models and tools from scratch and combine multiple models to solve a problem, it is better to build some <strong>generic</strong> models in the domain that can solve the common parts of a group of problems in the field, which can be functional modules or abstract parts of the problem. We can effectively solve multiple complex problems at scale by <strong>reusing</strong> these models and building problem-specific models for specific problems, and then combining them appropriately. This approach has proven to be very effective in solving complex problems in cybersecurity model building, and similar ideas have been seen in other fields too. These generic models are referred as “useful useless models.”</p><blockquote><em>The name “useful useless models” comes from the conversation with my colleagues, who said, many teams were building one model per problem and they could keep solving problems by multiple models each week, while these models your team was working on can’t even solve any real problems, and only a few models after years of work, you couldn’t even tell the false positive rate for them. So, wasn’t it “useless”? I appreciate their brilliant mind on naming these models.</em></blockquote><h3>What “useful useless models” mean</h3><p>“Useful useless models” are a type of models or tools that is designed to solve the shared common part of a list of domain-specific problems.</p><p>They can be called foundation models sometime. The paper “On the Opportunities and Risks of Foundation Models”* by Bommasani et al discusses the foundation models of deep neural networks in the fields of computer vision, voice recognition, and natural language processing etc, as well as their application methods and impacts. Deep neural networks can learn feature representations and transfer their pre-trained models across multiple similar problems, allowing pre-trained neural networks to solve multiple different problems within the same domain, with a little cost of fine tuning. In the same way that a ResNet model trained on the cat and dog ImageNet datasets in computer vision can detect tuberculosis by fine-tuning the input with lung X-ray images, a Webshell detection network trained on the TextCNN using the PHP script dataset can detect the malicious behavior of Powershell, a Windows-only script, by fine-tuning. Because both transfer tasks use deep neural networks to effectively characterize the <strong>local features</strong>, which is a common feature of this type of problems, the pre-trained model with fine-tuning approach performs well in these two seemingly disparate tasks. Of course, fine-tuning is only one method when use the pre-training models; other ways include zero-shot, few-shot, and a hot topic recently: prompting. Furthermore, fine-tuning based on network layer weights is one of a few methods of fine-tuning. For example, Transformer/BERT-like models are fine-tuned with their attention mechanism, please feel free to dig further on fine-tuning methods and pretrained models.</p><p>When we extend the approach of pre-training neural network models to more general cases, we can look for general properties that are required in problem solving for a specific domain, for example, attack patterns in cybersecurity. When analyzing patterns of attack behavior, we can ask a few question: what actions did the attacker take <strong>after</strong> action A, what actions did the attacker take <strong>before</strong> performing action A, what else they did within the time window or in the same network, and so on. The sequence properties of these atomic actions are general properties of this domain. Further more, we find that the sequence properties are independent of any specific problems, but only depend on the data sources that generate the sequences, such as the parent-child process in the endpoint command line logs, IP connect logs for netstats, the DNS logs, and so on. Each log source like the sequence DNS queries in DNS logs enables us to build a behavioral sequence model and apply it to solve a specific analysis problem. This is how the domain2vec model mentioned in the previous article is built, as a &quot;useless model&quot; that leverages a neural network to learn dense vector representation of each domain name and computes a statistical correlation as cosine similarity between any two domains, based on the query sequences. This correlation function can be used in a variety of scenarios:</p><ul><li>Discovery of potential DGA groups: DGA domains have strong sequential correlation in the DNS queries, with spectral clustering on the long tail domain name dense vectors, one can quickly find such groups.</li><li>Revealing CDN domains hidden behind websites: the homepage URL have strong sequence correlation with their CDN sites. One can search the vector of each homepage domain for other domains with high cosine similarity.</li><li>XcodeGhost* and supply chain attacks: Because the group cosine similarity between the app&#39;s primary and secondary API service domains is relatively stable, maintaining the history of this set and applying anomaly detection can find C&amp;C domains, like the XcodeGhost init.icloud-analysis.com and other supply chain attacks.</li></ul><p>Surely, the list of use cases is much longer than this. Because it provides a quantitative function for behavioral correlation as a <strong>task-independent representation</strong>, which is the key to solving such a class of problems, the domain2vec model, which serves as the foundation of several scenarios, can transform seemingly difficult problems into simple cosine calculation. Sequence-based behavioral models, of course, are not limited to domain name vector representation; they can be subgraph models or other entities such as IPs, URLs, and so on, and behavioral models are not only just sequences models.</p><p>Tools and models built on top of such tools can also provide the general properties to solve problems. Good examples include graph databases and knowledge graphs, as well as the algorithmic models built on top of them, such as ranking in graph, link prediction, subgraph pattern search and matching, and so on, some of which have been mentioned in previous blog posts. Building these tools needs time and engineering resources, so we better start early.</p><p>In general, solving complex cybersecurity problems needs building blocks, which can be domain-specific pre-trained models, more general computational functions with specific properties like task-independent representation, or useful tools and algorithms to partially solve a list of problems. The more building blocks, the more effectively lowers the threshold for solving complex problems, meanwhile, they encourage data scientists to bravely explore new ways of solving problems at a much low cost of failure. From the systems engineering prospective, each “useless model” can be invested with nice ETL and engineering optimization resources, and developed by a good engineering team to support its quality in a production environment. Here it is a fun story: domain2vec, a model created in 2014, has been maintained and further developed, and that it still keeps discovering new threat intelligence and having new application scenarios built on top of it, six or seven years later.</p><h3>How to build and use them</h3><p>Although “Genius is one percent inspiration and 99 percent perspiration” (Thomas Edison), inspiration doesn’t always come after much perspiration. Here are some scientific method examples to inspire more. The scientific methods described below are common in modern research, let’s re-discover them with a few cybersecurity problem solving cases.</p><h3>Inductive reasoning and deductive reasoning</h3><p>Inductive reasoning (also known as Induction) and deductive reasoning (also known as Deduction) are at the heart of the scientific method. Inductive reasoning can summarize general concepts by observing things in the objective world, for example, most intrusions require steps such as reconnaissance, intrusion, exploitation, privilege escalation, lateral Movement, obfuscation, denial of service, exfiltration, and some are after some others, so people generalize the concept of cyberattack killchain*; deduction gradually expands from logical judgment to a problem-solving model, for example, exfiltration behavior occurs after intrusion. A real-world example to leverage both reasoning methods can be that, exfiltration behavior must appear after intrusion and exploitation, then an exfiltration detection model must be look for earlier steps by locating them in the timeline with possible intrusion and exploitation features. Because the exfiltration has stronger features and good detection accuracy, it makes intrusion and exploitation detection easier by simple &#39;look back&#39; for anomalies. It also connects multiple steps which we can automate by building a knowledge graph of events with temporal attributes and linking prediction methods.</p><p>Induction (and some luck) can help us effectively come up with some shared commons in the field, after a broad dive into the domain and a deeper understanding of the field problems, sometimes can even find the root similarities between multiple problems. The domain2vec domain sequence correlation model, for example, is based on the observation that:</p><ul><li>Most websites use hard-coded CDN domains, and as the home page loads, requests for CDN domains are sent to DNS servers.</li><li>Malware that uses the DGA algorithm will send multiple DGA domain requests in bulk.</li><li>Modern browsers, such as Chrome, which prefetch some links on a page in advance, also initiate multiple DNS requests (not always true, but works most time)</li></ul><p>and so on. We discovered that they are related in the sense that <strong>DNS request sequences have certain correlation, and we don’t have a function to measure and compute such correlations</strong>, so such computational function could solve a list of problems in the field. This is the induction procedure led to the ‘domain2vec’ model. My dear reader, you’ve probably noticed that IPs and URLs follow a similar pattern, right? Yes, this is yet another example of “deduction”, and as you would generalize to ip2vec, url2vec, and whatever2vec models, please keep in mind the characteristics of specific entities&#39; behavior, like IP connections in netstats are different from DNS queries. Of course, deduction can be applied in a variety of ways: are there other problems in which the correlation function can be used? Will the computational function&#39;s spectral properties lead to other applications? Is there another correlation function that can bring about different spectral properties? And so on. In the thinking process, the two methods of induction and deduction can be iterated repeatedly. Please feel free to give it a try.</p><p>It is worth noting that induction yields only <strong>concepts</strong> instead of ground truth or theorems, which makes it potentially very subjective and vague, e.g. people lacking scientific training often like to reduce anything all the way to a few basic principles they have heard of, well, the combination of black body radiation, maxwell daemon and the second law of thermodynamics is not a good model to solve cyber security problems (no kidding, I have actually seen people do this!). Attempting to deduce during the induction process ensures the proper scale and direction of induction, because “More is different” * (problems of different scales and sizes require different solutions). Only a model that can be generalized and lead to a solution is a reasonable scale for induction, as Feynman stated about how to discover a new physical theory, &quot;First you need to discover it, then you need to generalize it as much as possible and falsify it with experimental facts.&quot; Similarly, the result of induction could be emperical and only apply to a narrow scope of problem solving, and the deduction can be tested by generalizing the inducted concept until it fails.</p><h3>ab initio and thought experiments</h3><p>Even when we are working on problem solving on a daily basis, there is no guarantee that we will be able to easily generalize approaches to these problems; after all, modern technology and the society have created these complex problems. Here’s a useful suggestion: “ab initio” (“from the beginning”) The term “ab initio” usually refers to a problem solving method in quantum physics, and you probably are more familiar with its buzzword: “First Principle”. Regardless of what it is called, the approach is basically <strong>removing unnecessary assumptions</strong>.</p><p>Having enough necessary assumptions can effectively limit the scope of problem solving, but some assumptions are not necessary and may be caused by historical experience and confused with other assumptions, often creating obstacles to problem solving. When Elon Musk used first principle in business models to analyze the cost of launching a rocket, he discovered that recycling the rocket was actually feasible, only because historical cost considerations of the NASA launch model made recycling under-researched, so he began to recycle the rocket. Most network security vendors have made the detection of malicious samples their primary function, and the debate over malware detection has raged on for decades. In the cloud era, many attacks start to use methods such as fileless attacks, forcing traditional vendors to add more detection targets as quickly as possible. While successfully capturing malware samples is important, cloud platforms can collect all sorts of logs and build behavior patterns detection models with machine intelligence, and “reliance on malware sample” is becoming an unnecessary assumption, making cybersecurity in the cloud computing era a behavior modeling-based path to success. Another interesting example comes from the domain2vec model, which is derived from the word2vec NLP model. While reading word2vec paper, we noticed that &quot;natural language as input&quot; in the model was an unnecessary assumption, so they replaced it with &quot;domain name sequences in DNS queries&quot; and optimized the hyperparameters for them. These are successful examples of having the courage to remove unnecessary assumptions. Of course, if one discovers that removing certain assumptions makes the problem more difficult, one may have discovered a necessary assumption.</p><p>We can simplify most complex problems by removing unnecessary assumptions, and then comparing simplified versions of these problems will make it easier to discover their commonalities. The work mentioned in the <a href="https://toooold.com/2021/12/20/why_ml_fails_security_ml_is_not_everything_en.html">previous article</a> “Honeypot + graph learning + reasoning = scale up your emerging threat analysis” uses a link prediction approach to prove that two URLs have exactly the same malicious behavior, in a way that is also consistent with the timeline-based approach to finding exfiltration and exploiting features mentioned above, because both problems infer associative features by looking for links in the knowledge graph, while both their entity identifiers are the same. As a result, we conclude that “link prediction is its commonality” in this set of problems, and it is feasible to develop and optimize a general toolkit of link prediction algorithms.</p><p>With a set of “useless models” for solving common problems, data science teams will not only be confident enough to solve the current problem, but will also be willing to try new ones. Not only do we get brilliant ideas from inspiration when we use these models, but we can also leverage <strong>thought experiment</strong> to find brilliant AND more feasible ideas. One of the most common methods used in physics is thought experiment, which simply means running something abstract and simplified in the imagination and observing its operation; for example, “Schrödinger’s cat” is one of the most famous thought experiments. There are many examples of thought experiments in cybersecurity, for example, as mentioned in the <a href="https://toooold.com/2021/12/20/why_ml_fails_security_ml_is_not_everything_en.html">previous article</a>, the attacker needs to experiment with N vulnerabilities corresponding to the target of K exploit methods, summarize a number of failed experiments, and get the correct sequence of exploitation, the thought experiment can be, there are numbered 1 to N balls thrown into K pits in order, by the way it bounces to determine the type of error, so use different types of thought experiments. How to throw them with active learning, mastermind strategy, multibandit strategy, which bounces they encounter, and which strategies would be better? Thought experiments can be used to play out all of these scenarios in the mind and we can conclude the next step afterward.</p><p>Using the “useless models” framework, we can use thought experiments to imagine combinations of models A, B, C, and so on, and introduce some hypotheses about a domain-specific problem, thus planning a solution to the problem. “Honeypot + graph learning + reasoning = scale up your emerging threat analysis” expresses the process of the thought experiment through two plus signs: The “useless model A” as graph embedding model can obtain the correlation features such as sequence and host of two URLs in HTTP traffic, which is equivalent to <strong>a dotted line connection</strong> between two nodes; while the “useless model B” as graph reasoning model can find possible reasoning links in any entity nodes, resulting in a detour path in graph as <strong>a solid line connection</strong>; furthermore, by filtering honeypot data, we can limit the types of entities in the graph to reduce search costs and the risk of ambiguity in inference, and the solution is a “combination of models to find solid links to prove dashed links”. It is important to note that these combinations of foundamental models provide the shoulders of giants, and we must also build the input data and subsequent models that fit the problem on top of the giant’s shoulders in order to refine the solution for the problem specificity.</p><p>Of course, ab initio and thought experiments are not limited to the methods listed above, and there is no secret recipe so we can all become proficient with practice. Meanwhile, my dear readers may have discovered that ab initio and thought experiments, as well as other related approaches, are also good practice of induction and deduction, and that by repeatedly practicing and exploring this approach, we will form more sets suitable for our own fields.</p><h3>Tips beyond technology</h3><p>“Useless models” are never created from the top down approach; instead, they require data scientists and security researchers to thoroughly understand the domain problem and generalize as they solve it. There is a time cost to obtain these models, as well as a higher engineering cost to build them, so I have some tips here for the management.</p><p>It may be difficult to find your first “useless model”, and learning from existing examples in the industry may be a good way to go. There is almost no “useless model” that will be perfect at the start, so there is no need to rush into engineering optimization too early; it is a big win to consider finding more problems in the domain and attempting to solve a small portion of them, no rush at all; every “useless model” must find some useful sample problems to solve at each milestone. This will not only allow us to delve deeper, but it will also help the model on sustainable resource investment from the senior management.</p><h3>Summary and small talk</h3><p>Cybersecurity teams are frequently faced with the dilemma of having a slew of unsolvable problems on one hand and racking their brains for new solutions on the other. I hope that this post can provide some inspiration. The complexity of problems is caused by a variety of factors, and this post attempts to solve the complexity caused by scale and diversity by developing a generic model that partially solves the common part.</p><p>A few “useful useless models” can support a large portion of problem solving work and people should not discount the contribution by the number of models, since “jewels are not weighed on a grocery scale”* Such models can significantly reduce the problem solving difficulty level and scale up the model production.</p><p>The idea of developing a domain general model that can partially solve the problem came from a conversation between me and 360netlab research team about domain name correlation model domain2vec and other graph models a few years ago, and my good friend Yiming Gong called the idea of applying this idea to the cybersecurity field without the trappings of NLP as &quot;cross-border,&quot; which inspired me to investigate the extension of this &quot;cross-border&quot; idea. I&#39;d like to thank the 360netlab team, they have a twitter account <a href="https://twitter.com/360netlab">https://twitter.com/360netlab</a> .</p><p>Additional comments why I wrote a few ‘problem solving’ blog post on ideas rather than technology recently. Besides “strong minds discuss ideas”* quote, the real-world problem solving is a superset of solving a given problem in contest, like Kaggle, where data has been cleaned up, evaluation metrics is given and, the most important, the target is set so people just run for it. The real-world problem solving needs to dig for the approach, find the data and clean it (and repeat for more data), understand its business impact to determine a good metrics before running to optimize the model. Data scientists at more senior positions also need to identify new problems in the field and open the door to a new direction. All of them need &quot;problem solving&quot;, which motivates me to post a few ideas and thoughts.</p><h3>Reference</h3><p><em>Originally published at </em><a href="https://toooold.com/2022/01/09/useful_useless_model_en.html"><em>https://toooold.com</em></a><em> on January 9, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4f3c4d038d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why your machine learning models fail to solve cybersecurity problems: being narrow-minded forth]]></title>
            <link>https://phunter.medium.com/why-your-machine-learning-models-fail-to-solve-cybersecurity-problems-being-narrow-minded-forth-375badc8f6?source=rss-9b5f5d1914ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/375badc8f6</guid>
            <category><![CDATA[system-engineering]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Phunter]]></dc:creator>
            <pubDate>Mon, 20 Dec 2021 00:00:00 GMT</pubDate>
            <atom:updated>2021-12-20T10:06:24.845Z</atom:updated>
            <content:encoded><![CDATA[<p>Disclaimer: Nothing in this blog is related to the author’s day-to-day work. The content is neither affiliated nor sponsored by any companies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dfPxrpb4WUcXgsvJpFyo3g.jpeg" /></figure><p>Link to the Chinese version <a href="https://toooold.com/2021/11/28/why_ml_fails_security_ml_is_not_everything_cn.html">https://toooold.com/2021/11/28/why_ml_fails_security_ml_is_not_everything_cn.html</a></p><p>After talking about the first 3 reasons: <a href="https://toooold.com/2021/09/30/why_ml_fails_sec_feat.html">wrong features</a>, <a href="https://toooold.com/2021/10/18/why_ml_fails_security_frag_en.html">fragility</a>, <a href="https://toooold.com/2021/12/12/why_ml_fails_security_evaluation_en.html">non-sense metric</a>, we have this last post in the blog series. Being narrow-minded on problem solving is yet another reason why machine learning models fail to solve cybersecurity problems. When machine learning is used to solve problems, sometimes the method is used incorrectly, and sometimes the method and the problem simply do not fit.</p><ul><li>Deep learning doesn’t work everywhere</li><li>Machine learning is a tip of the iceberg in AI</li><li>Have you thought of any simpler approaches?</li></ul><h3>Nope, deep learning is not your solution</h3><p>We see a lot of cases where people think machine learning only means deep learning. Deep neural networks have demonstrated a powerful advantage for representation learning in areas such as images and text, as well as the magical effect of transfer learning in solving multiple problems brought by neural networks, which brings many sparkles to the mind to solve cybersecurity problems. We’re all wondering if this can help cybersecurity: can I crack the hidden features in the encrypted traffic? can I transfer the features from windows PE to Linux ELF? However, “there is no such thing as a free lunch,” and deep learning has gained its proble solving magic at the expense of its applicability. Some failures that have emerged in recent years have taught us some lessons.</p><p>The selection of a neural network structure for feature representation must be based on a thorough understanding of the problem and the model. Sequential models appear to be the most popular in the cybersecurity domain, and RNN/LSTM has gotten a lot of attention due to its simple open source implementation, so we can see it in a variety of problems, such as the previously mentioned multiple work on LSTM prediction of DGA algorithms, where the goal is to find the pseudo-random number generator (PRNG) behind the model fitting DGAs. Aside from the fact that DGAs may use a variety of PRNG combinations such as XOR, shifts, prime number twists, and so on, making it difficult for shallow networks such as LSTM to effectively fit and interpret them completely, the memory and dependency of LSTM on the initial state also hurts PRNG fitting. In Hassan Mostafa “Using Machine Learning to Crack Random Number Generators — Part 1: xorshift128” *, we see that the PRNG based on xorshift128 can be well fitted using only Dense Network and no LSTM. The article also compares the experimental results of LSTM + Dense Network and analyzes the fitting results, please feel free to dig further in the reference list.</p><p>“Garbage in, garbage out,” as the saying goes in machine learning. Deep neural networks are not a general AI or an oracle about feature engineering; it requires appropriate inputs that the structure of that network can digest so features can be obtained through representation learning. A typical example is the previously mentioned malconv which attempts to feed raw bytecode from a binary file to a simple convolutional layer, like in most computer vision problems, and extracting and generalizing the underlying features, despite the fact that simple convolution is insufficient to perceive the compiler&#39;s combination of bytecodes, resulting in the network learning only file header signatures rather than the function call features associated with malicious binary code. The book &quot;Malware Data Science: Attack Detection and Attribution&quot;* by Joshua Saxe and Hillary Sanders analyzes opcode and opcode-based related modeling work, where instruction jumps or function output tables, etc., are used as input to the model to better support malware detection models.</p><p>The cybersecurity problem is highly adversarial and dynamic, which requires the model to make some assumptions in order to deal with the unknown situation and <strong>justify</strong> its prediction reason. However, because deep neural networks lack such inductive bias *, their prediction of the unknown situation is very uncertain and poorly explained, resulting in the &quot;black box&quot; when using deep models. In the case of linear regression, we can see the Y value as a linear function with the X vector as the parameter, and in the case of logistic regression, we can see the hyperplane cut for positive and negative samples, and these inductive biases can <strong>justify</strong> the model&#39;s prediction, whereas deep neural networks can only show that Y is some kind of nonlinear function of the X vector, which is related to data augmentation, network structure, activation function, normalization, and various other constraints imposed during the training process make it difficult to <strong>justify</strong> the predictions in practice, and cybersecurity problems frequently necessitate strong domain knowledge for more expensive validation and operation, and recent work to improve model interpretability like LIME could provide only limited mitigation for this problem. SpamAssassin, an open source spam detection project, is an interesting example because it has a history of a fun bug that identifies all post-2010 emails as spam. Does it mean the model makes no sense? In a strong adversarial scenario like spam detection, the attacker keeps updating the tricks and the Bayesian classifier adjusts the weight of each feature by year, which is a reasonable approach, but there is no training data for date after 2010, and the classifier judges all unknown emails as spam with an induction bias that it would rather block than pass. Of course, SpamAssassin&#39;s model bias provides an easy and understandable reason for justifying the prediction, and this issue was quickly identified and resolved.</p><p>Meanwhile, the individual characteristics of each problem in cybersecurity, as well as the strong requirement for domain knowledge, limit the usefulness of deep neural network in transfer learning by samples, in contrast to common scenarios such as images and text, where pre-trained models can be easily reused. Overall, deep learning, as a subclass of machine learning, is far from allowing people to hunt a rabbit from a blind shot, and its technical advantages are accompanied by application limitations. In short, ‘no free lunch’ requires smart approaches when use deep learning, we still need human for now.</p><h3>Machine Learning “ Artificial Intelligence</h3><p>If open the text book “Artificial Intelligence: A Modern Approach”, we can find “Learning from Examples”, so called “machine learning” in the media, appears in chapter 19. Before this chapter, there are, searching, knowledge representation, planning, reasoning, first order logic, and there are many chapters after it. When we apply the AI approach, we must combine multiple techniques rather than machine learning only, because it is such a small topic in AI. For example, the success of AlphaGo, a benchmark AI application, comes from the combination of deep neural networks and Monte Carlo tree search (MCTS), an algorithm mentioned in every AI textbook on state search, while AlphaGo adds deep network feature extraction and adversarial training, expanding the scope of the MCTS algorithm from the textbook to win of the Go game.</p><p>Other than machine learning, there are numerous examples of AI methods in the cybersecurity domain. Here’s another interesting example: the attacker attempts to test K intrusion points of the target using N vulnerabilities and their combinations, and each time must use exact K of the N vulnerabilities, with the order in which the vulnerabilities are exploited being correlated with the results. After several rounds of testing, the attacker only receives some failed combinations and the reasons for their failure: perhaps the selected K vulnerabilities failed partially (only the number of failed vulnerabilities is known, but it is difficult to determine which part), perhaps the sequence of vulnerability combinations is not right. Can we design a new attacking strategy based on the known test results for more effective vulnerability combinations? A more difficult version can be, whether it is possible to design an automated strategy that makes adjustments based on the previous round&#39;s results? Discrete search for solutions can be used to solve this problem. If we simplify it, it&#39;s similar to the 3-digit combination lock riddle * where one picks three numbers from 0-9 to form a password, conclude the pattern from the wrong password tries, and get the correct password. The three-digit password lock problem ( N=10, k=3) can be solved by brute force searching various combinations from 000 to 999 and validating whether they fall into the known errors, but if N and k are both large, we must use the MCTS search and design reasonable pruning conditions (e.g., combinations of vulnerabilities that may trigger partial invalidation of vulnerabilities, etc.) to reduce the search space. We can use an active learning approach to fine-tune the search direction and branches based on the proposed test method and its feedback. These are known as Mastermind * problems, please feel free to dig further in the reference link.</p><p>Machine learning and non-machine learning methods should not be mutually exclusive in problem solving, instead, they should collaborate! Learning from examples is always constrained by the sample set, and it requires the assistance of other models to “look elsewhere”. Entity disambiguation is a common example in NLP. For example, when an intelligent agent tries to understand the word “apple”, it needs to know from the context whether it is the fruit “apple” or the electronics company “apple”. There are many examples of similar approaches in cybersecurity that combine graph models and knowledge graphs, such as my team’s presentation in botconf 2020 “Honeypot + graph learning + reasoning = scale up your emerging threat analysis”* It begins by discovering the sequence association of two different URLs in network traffic, then connects the URLs, binary hashes, corresponding detection results, and other contextual information by building a knowledge graph, and then asks the graph to proof the knowledge connection by finding a semantic path using the link prediction algorithm. When sufficient but unnecessary and necessary but insufficient conditions exist, the first order logic inference method is used to ensure the rationality of the semantic path, resulting in the prediction of the download path of unknown malware.</p><p>However, this article cannot include all sub-methods and their combinations to solve cybersecurity problems using the artificial intelligence method. Please keep the momentum in the mind and find more approaches.</p><h3>“Have you tried a simpler approach?”</h3><p>Joshua Saxe asked a question in his tweet thread, “why they didn’t take a simpler approach than the approach they took” * Simpler approaches can result from understanding domain knowledge and representing it in general terms, pre-processing the data, careful understanding and splitting of the target problem, and a variety of other factors.</p><p>A good friend once raised an interesting question from his research: if the attacker uses dictionary word combinations to guess the target subdomain through subdomain enumeration during the reconnaissance, can we collect its DNS traffic and use machine learning to crack attacker’s subdomain enumeration dictionary for threat hunting? Before he tried to bring a few GPUs and jump into a deep model like BERT, I suggested that he could sort the data and guess a noisy dictionary using the longest common substring of the sorted consecutive records, where this noisy one is the superset of the true dictionary, then apply this noisy one to segment the subdomain and clean it up iteratively, transforming the dictionary problem into a string slicing problem. The follow-up experiments have shown that this simpler algorithm is not only effective in obtaining the vast majority of dictionaries, but it is also resistant to noise.</p><p>The advantage of machine learning is that it learns its statistical representation from data; intuitively, it fits the rules; however, problem solving does not exclude rules that come directly from domain knowledge, even if the rules only partially solve the problem. For example, Alexa Rank, a global website ranking that is frequently used as a reference for malware C&amp;C domain detection results, contains domain knowledge stating that “malware is unlikely to use high-ranking domains as C&amp;C”. Surely, the time is changing and Alexa Rank has been exploited by attackers, along with new business models and the escalated adversary. My colleagues have built our own domain reputation ranking through DNS traffic *, please feel free to read in the reference.</p><p>Sifting through the data can also lead to a more straightforward approach. Just as a good ingredient requires only simple preparation to bring out its flavor, good data requires only simple models to produce clear results. An interesting example comes from me discussing with my former colleague on his paper, Asaf Nadler et al “Detection of Malicious and Low Throughput Data Exfiltration Over the DNS Protocol”*, a method of data exfiltration used in APT attacks by detecting low throughput tunnels in DNS data streams. Because the signal of low throughput DNS tunnels is weak and rare, the anomaly detection by Isolation Forest requires good feature filtering, making it difficult to demonstrate its detection power under large-scale noisy data and limiting the scale of its problem solving due to limited computing power. We discovered that if all unseen domains in the DNS data stream are filtered and used as input to the Isolation Forest model, its prediction performance and runtime can meet the requirements of a large-scale data stream. With a deeper understanding of the target problem, We can apply more appropriate input data to take the existing model to the next level.</p><p>A simpler approach can also be reached by splitting the target problem, which could be a subgoal representing a portion of the target problem, or a reduction of the target problem, and so on. All of these follow the general problem solving approach, so please dig further on this topic. An interesting example is my team work presented at Botconf “Math + GPU + DNS = Cracking Locky Seeds in Real Time without Analyzing Samples”*, which detects Locky ransomware in DNS data streams, brute force cracks its DGA seeds using GPU, and successfully predicts all future domain names. We reduce this difficult problem into multiple steps, and reuse the anomaly and correlation models from related work:</p><ul><li>Because Locky DGA domains are all new, we detect and filter never-before-seen domains in DNS anomalies.</li><li>Because Locky DGA contains multiple domains, we use domain2vec to calculate the sequential correlation among the anomaly domains and test their DGA properties only for the groups that are most strongly correlated.</li><li>Locky generates a single long integer using a pseudo-random number generator (PRNG) and outputs the domain string as such, so we can inverse each candidate domain name to get its corresponding long integer, and then use the GPU to batch crack the seeds that may correspond to that integer at the current date.</li></ul><p>As a result, we successfully cracked dozens of Locky DGA random number seeds and submitted them to the cybersecurity research community.</p><p>Data science teams can think about solving each problem by reminding themselves that:</p><blockquote><em>Is there another way to solve this problem, in whole or in part?</em></blockquote><h3>Summary and Epilogue</h3><p>In the problem-solving process, we must stick to the main goal of “problem solving”, it is always the first, and the related technology selection is the method to support that goal, and collaboration among these methods should be preferred more than competition. This also necessitates data science teams broadening their horizons, paying attention to proven useful methods in other fields <strong>and the underlying reasons why they work in their fields</strong>, and attempting to implement them in the cybersecurity field. Simultaneously, we have observed many data science teams actively learning about the cybersecurity domain knowledge, which is the only way to be more effective in finding techniques appropriate for the problems in that domain.</p><p>We have received a lot of useful feedback and suggestions for this blog series, and we hope that all of you will contribute to the discussion by combining your own work and research with the topic of “why machine learning fails”. Data models in the field of cybersecurity have only recently been used on a large scale, bringing with them many issues and difficulties in the industry, which invariably entails numerous failures, all of which are predictable failures in accordance with modern scientific research methods. I also believe that by learning from the frustration of many failures and the surprise of a few successes, we together can draw enough lessons and create a general methodological framework for data modeling in cybersecurity.</p><h3>Reference</h3><p><em>Originally published at </em><a href="https://toooold.com/2021/12/20/why_ml_fails_security_ml_is_not_everything_en.html"><em>https://toooold.com</em></a><em> on December 20, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=375badc8f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why your machine learning models fail to solve cybersecurity problems: non-sense metrics third]]></title>
            <link>https://phunter.medium.com/why-your-machine-learning-models-fail-to-solve-cybersecurity-problems-non-sense-metrics-third-5f39c1a3e600?source=rss-9b5f5d1914ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f39c1a3e600</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[system-engineering]]></category>
            <dc:creator><![CDATA[Phunter]]></dc:creator>
            <pubDate>Sun, 12 Dec 2021 00:00:00 GMT</pubDate>
            <atom:updated>2021-12-17T08:10:23.795Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*enc8ZNjuEZTD2vG-ayMg-A.jpeg" /><figcaption>Queen Victoria taking nap</figcaption></figure><p>Disclaimer: Nothing in this blog is related to the author’s day-to-day work. The content is neither affiliated nor sponsored by any companies.</p><p>This is the 3rd one in the blog series. Please feel free to check out <a href="https://medium.com/@phunter/why-your-machine-learning-models-fail-to-solve-cybersecurity-problems-feature-space-first-32e40b924213">the first one</a> and <a href="https://medium.com/@phunter/why-your-machine-learning-models-fail-to-solve-cybersecurity-problems-fragility-second-ae9040bb3d79">the second one</a>.</p><p>The cybersecurity and risk management industry has always been viewed as a cost center, which growth hackers despise the most. Simultaneously, security professionals must ensure the overall security of their systems and operations in order to maintain the company’s long-term business value. From the standpoint of the importance of cybersecurity to long-term business value, we can discuss the third major reason for machine learning’s failure to solve cybersecurity problems: non-sense evaluation metrics. Simply put, when establishing evaluation metrics for data models for cybersecurity, we sometimes lose sight of the long-term business value mindset.</p><p>The discussion on the design of evaluation metrics is not commonly seen in the academic community, most likely because the problems studied in the papers are general and independent of the details of specific commercial products, and there are relatively generic evaluation metrics, whereas specific problems in industry are more closely related to their business value, and there is a greater need for data scientists to specify and relate these generic metrics to product and market value.</p><p>A special note to those who have read the Chinese version <a href="https://toooold.com/2021/11/13/why_ml_fails_security_evaluation_cn.html">https://toooold.com/2021/11/13/why_ml_fails_security_evaluation_cn.html</a>: the two versions share the same core content but present it in different ways. Upon the request of my Chinese-speaking friends, I paid special attention to data modeling research in the domestic market in the Chinese version, where the research sometimes has to compromise to fit into the revenue growth mind. Security should be considered assets and having a growth mind is never a problem, but the metrics should go beyond just the revenue, right?</p><h3>Why a good metrics is essential</h3><p>Metrics that are properly defined provide direction to guide data and security models toward their objectives. Metric improvements can be directly mapped to business value, driving targeted improvements to data and security models while the business value they bring ensures continued investment in the models. For example, a 1% increase in malware detection rate can prevent infection of thousands of cloud hosts, and a 0.01 second reduction in WAF detection time will increase the threshold of network throughput of customer hosts to more effectively protect against attacks and more.</p><p>Better detection, or better defense, that is the question. The cybersecurity industry must solve problems in dynamic and highly adversarial environments, and the uncertainty introduced by the attacker or the environment can also make setting evaluation metrics difficult. In the evaluation of intrusion detection models, for example, if the company is not effectively attacked, CISO can have a list of questions, is it because my detection model is doing a good job, or is it because the other side has not been able to break through the first few layers of defense, or simply does not bother to attack me, or even if it has been breached and I am unaware of it? These adversarial and dynamic environments frequently put data science teams in the darkness when developing models: on the one hand, they want to detect more attacks, while on the other, they want to ensure a better defense, but a better defense means fewer attacks, so how do they evaluate defense metrics? The same dilemma confronts various risk management teams, security and remediation teams, and so on. “Never in the field of human conflict was so much been owed by so many to so few” (Winston Churchill) *, how can we improve the design and evaluation metrics of detection and defense systems, like Royal Air Force and allied fighter crews who were at the time fighting the Battle of Britain?</p><p>We found numerous difficulties in establishing reasonable evaluation metrics: metrics that do not accurately reflect long-term business value frequently mislead the direction of data and security model research, and these metrics frequently cause conflicts between business growth and security protection. Overall, good evaluation metrics serve as an important link between good modeling efforts and their business value, effectively guiding the direction of modeling efforts, whereas bad metrics can cause good models to work in a totally wrong direction, exposing modeling efforts to unnecessary pressure.</p><h3>Top 1 mistake: metrics without objectives</h3><p>Objectives first, then metrics. It is part of data science foundation. Unfortunately, “metrics without objectives” has contributed the most in the pool of mistakes.</p><p>In the machine learning class, we must have seen such homework problem: why can’t we replace the loss function with precision/recall metrics when optimization? * Besides the statistical reason of a priori vs posteriori in the decision making, we can understand it in the intuitive way: a smart agent needs the loss function to guide the direction of optimization (objective) while precision/recall can only be used by human to judge its decision making (metrics), otherwise the agent could cheat to maximize <strong>outputs</strong> in a local minimal instead of optimizing for <strong>outcomes</strong>.</p><p>However, smart human beings sometimes get lost in decision making and confuse objectives with metrics, when they see profit. We’ve seen many students who are proud of not being caught cheating on exams, and we’ve also seen major APPs that send free perks to boost the new user trend but don’t have enough product features to retain users. Only with the goals of “solid knowledge” for students and “building a good product” for apps can the metrics be meaningful.</p><p>The goal of cybersecurity teams and cybersecurity products is to protect their own and customers’ assets from attacks, where different areas have different sub-goals and metrics to measure how well the goals are met. We have seen many metrics in the industry that do not accurately reflect the goal. For example, a SIEM product that claims to deploy 200 detection models and generate thousands of alerts for customers, rather than metrics that better reflect its business goals such as alert fatigue reduction, ease of use for threat hunting, and fast response. Such a metric as “how many alerts we generate for customers” may appear simple to quantify, but its absurdity is analogous to a fire station’s performance evaluation based on how many fires it puts out, as a metric that loses its goal is meaningless for business value. A few other examples can be, DDoS products to block 2 Tbps attacks without mentioning the cost until the customer receives a huge bill; a paid threat intelligence feed of 500 thousands of new IoCs each day without mentioning the use cases and the intelligence context (and turns out it is a precomputed DGA list plus a few OSINT).</p><p>Metrics without objectives can appear legit, which makes it dangerous for the modeling work because a wrong goal can waste much resource and drive smart people more wrong, sometimes let them gamify the system. If coverage is used as a metric in a threat intelligence model, the model can assume that all activity is malicious and generate a large number of events to flood the SOC team; if the detection accuracy is used as a metric, the model is better off reporting nothing, because no prediction, no mistake; and if alert volume is used as a metric in a SIEM product, the model will generate a large number of alerts without screening and triaging, just enough to slow down the customer. In practice, these seemingly irrational behaviors can take various forms.</p><h3>The 2nd one: metrics looks like ‘common-sense’</h3><p>Statistical learning models are intended to learn the target distribution’s statistical expectations, which means that the algorithm is always incentivized to predict the behavior of the majority group * because the majority group dominates the statistical expectations of the target distribution. Applying conventional accuracy-recall metrics as is, rather than understanding that the algorithm prefers to look for majority-group behavior and designing metrics to fit a specific problem, not only fails to solve the problem, but also raises concerns about the algorithm&#39;s effectiveness. For most time, the algorithm is good but it is used in the wrong way because of &#39;common-sense&#39; metrics.</p><p>In cybersecurity, the frequency distribution of attacks can be <strong>extremely unbalanced</strong>, with intrusion frequently at only one in ten million or less, while the difficulty of discovering each attack varies significantly. If the classifier model is assumed to have a 90% accuracy rate for attacks, it is better for the model to <strong>detect nothing</strong>, because negative samples are several orders of magnitude larger than positive samples, and a single sample misjudgment is enough to reduce the accuracy rate to near zero. Such issues cannot be solved using unbalanced sampling methods and need to jump out of the box.</p><p>In most cases of cybersecurity, such as the discovery of zero-day vulnerabilities, APT attacks, and so on, the ground truth is missing. In such cases, the data model necessitates a recall rate, or even a “recall rate of unknown threats,” a metric that can be described as “not even wrong”. “There are only two types of companies: Those that have been hacked and those that will be hacked.” * We, too, cannot wait to be hacked in order to calculate the recall rate. The impact of an intrusion attack on business, such as a data breach to be seen several years later, or the fact that compromised data is being sold on the dark web while the security team is unaware, is significant. The limited attack scenarios can also skew the model&#39;s effectiveness if it relies solely on certain attack benchmark tools, such as inviting the in-house red team attacks, to obtain benchmark facts. If a data science team committed to a similar metric for any reason, the team would expend a significant amount of resources on it, ultimately failing to solve the problem.</p><p>An interesting measurement “unique detection rate” is commonly used in the machine learning based detection evaluation, like the ML driven malware detection expects more malicious examples, the same with ML driven spam URL detection etc. “Unique detection rate” as the comparision on number of samples between machine learning methods and the current methods or intelligence feed seems ‘common-sense’, but practically no sense:</p><ul><li>The business value of the detected samples is based on the business assets they can influence rather than the number of samples, and the evaluation process ignores the impact of the detection time sequence.</li><li>The results from rule models or 3rd party threat feeds with missing quality assessments are insufficient as denominators to calculate the unique detection rates .</li><li>The two types of models use different features but the results of rules models and machine learning models frequently overlap significantly, and evaluating only machine learning models while ignoring the unique detection metrics of rule models frequently leads to debates about the fairness of the evaluation.</li></ul><h3>Honorable mention: good metrics, wrong problem</h3><p>We have also observed many cases where cybersecurity problems simply cannot be approached using machine learning or artificial intelligence, such as using third-party intelligence to detect unknown APT attacks; developing log-based threat discovery while ignoring the data collection and data warehousing efforts required; and certain problems themselves require massive investments that are not supported by existing resources, most often by companies eager to develop their in-house malwa. All of these problems may have clear metrics definitions, but the objective itself leads to the wrong problem to solve, resulting in failure for the data science team.</p><h3>A few tips for metrics design</h3><p>From the bloody lessons that we have learned, we have a few tips.</p><p>All metrics must be designed in tandem with the objectives. The objective defines the problem’s limited scope, and only within that scope can a reasonable metric be proposed. We must always ensure that the objective comes first, and metrics are only a means to an end when it comes to achieving the goal. Instead of rushing for a metric that appears to make sense, we must understand the business need to set objectives, and data scientists must clearly identify when such metrics appear and provide timely feedback to say “NO!”</p><p>When planning a problem and setting goals for objectives, it is important to consider whether the goal is too big or too small, whether the scenario is appropriate for the solution, and whether the solution’s goals are within a reasonable resource budget. It is suggested that one refer to industrial common practice in the field and allocate resources based on the current situation.</p><p>“Unique detection” is a very bad metric in general, pitting data models and rule models against each other or relying on external sourcing while ignoring the impact of detected samples on business assets, detection time latency, and other factors. We do not recommend using unique detection rate as the primary metric for the detection model; instead, we can use intersection and set to see the overall coverage of detection results and the impact on assets; if one needs to compare models, one should look at the detection time latency; we should also keep in mind that the machine learning model comes to improve the rule model result, so we should target for “greater than zero” rather than 10% more or 50% more, and consider the cost of iterative updates.</p><p>What if there is no such thing as a ground truth or a red team test? In the absence of ground truth, which is often the case, we should deploy as many anomaly detections as possible and evaluate recalls when explaining why these anomalies occur. “How many anomalies can be explained?” could be a better metric to use. In the absence of a red team test, attack detection metrics can be evaluated using the attack surface that the defender covers for the business asset. We must also be proactive and timely in adjusting our assessment strategies in the dynamic adversarial environment of cybersecurity.</p><h3>Summary</h3><p>Good metrics can effectively enable data and security models to demonstrate business value in their respective business domains, and we must establish reasonable metrics that meet our objectives. Data science teams must also understand that algorithms are always motivated to predict the behavior of the majority population and that evaluation metrics must be rationally designed to capitalize on the strengths of algorithmic models.</p><p>Reasonable metrics can also help to avoid unnecessary or incorrect model optimization. Whether or not the model’s optimization goal can make sense, a smart data scientist can do a fantastic job of modeling for this goal, and the more optimization out of reasonable metrics brings more errors, whose eventual business losses and work frustration must be more expensive to smooth out.</p><h3>Reference</h3><p><em>Originally published at </em><a href="https://toooold.com/2021/12/12/why_ml_fails_security_evaluation_en.html"><em>https://toooold.com</em></a><em> on December 12, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f39c1a3e600" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why your machine learning models fail to solve cybersecurity problems: fragility second]]></title>
            <link>https://phunter.medium.com/why-your-machine-learning-models-fail-to-solve-cybersecurity-problems-fragility-second-ae9040bb3d79?source=rss-9b5f5d1914ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae9040bb3d79</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[product-design]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Phunter]]></dc:creator>
            <pubDate>Mon, 18 Oct 2021 00:00:00 GMT</pubDate>
            <atom:updated>2021-10-18T23:40:29.613Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9TVr7GhrLq329YzNxqb3jA.jpeg" /><figcaption>Queen Isabella taking nap</figcaption></figure><p>Disclaimer: Nothing in this blog is related to the author’s day-to-day work. The content is neither affiliated nor sponsored by any companies.</p><p>Solving cybersecurity problems with machine learning and other algorithms frequently involves a battle between the effectiveness of data models and rule-based models, the balance between coverage and false positive rates, and the remote nature of model’s cool unique discovery and its product integration, all of which are bothering data scientists daily work. One day, a good cybersecurity friend of mine said to me, from the bottom of his heart:</p><blockquote><em>“Only algorithms care about right or wrong, security is about cost.”</em></blockquote><p>The fight of beautiful models vs limited use comes from that, many data models just throw a half-baked product to the security operations team or security product customers, resulting in “I can’t use this model in production”, “why should I trust your prediction “ and many other negative feedback. Applying algorithms, such as machine learning, to solve cybersecurity problems is not only the work of the algorithm itself, <strong>but also a system engineering task, with fragility arising at every stage of the process</strong>. Following on from the previous blog’s discussion on feature space and sample labeling, we discuss how to understand algorithmic fragility, engineering fragility, and operational fragility in a systems engineering framework and effectively avoid their negative impact on the solution of cybersecurity problems. The discussion here is also not limited to the cybersecurity industry; the majority of it also applies to other industrial scenarios that employ algorithmic models.</p><h3>Fragility from algorithm</h3><p>In addition to common prediction quality measurement such as precision vs recall, algorithms designed to address problems in the cybersecurity domain have several special requirements for robust prediction results, most notably identifying erroneous results and providing appropriate disposition, similar to machine vision-based autopilot, which must ensure that even if the model misjudges in any situation, it will not hit a wall. However, the industry has discussed this primary reason even less than other causes of algorithm fragility, such as unbalanced data and labeling small data sets.</p><p>“Wrong prediction” results exist objectively, and data scientists cannot ignore or fear their existence since we, the data scientists, are the only providers of these models. <strong>The conclusion of most acedamic papers as a seemingly perfect AUC is only the beginning of all industry’s work</strong>. The common 0.1 percent false positive rate in machine learning papers may be amplified by the billions of records into hundreds of thousands of results in the security operation queue, waiting to be picked up by a poor SOC guy (sorry about that), where each prediction result by model is related to the operation time and human resource cost. Sometimes, because of negative feedback from operations or product teams about the cost of false positives, data scientists fear false positives and limit their thinking when building algorithms, for example, by making 30% or larger compromises in recall for 0.1% or less marginal improvement of precision, or manually adding large numbers of list rules to filter model prediction results and suffering from the rule maintainance, or even giving up on a new model because it can only reaches 90 percent accuracy, and so on. The most common cause of algorithm fragility is ignoring or fearing wrong prediction results.</p><p>Instead of ignoring or fearing it, we should confront the root cause of “wrong prediction” and start thinking about how to properly deal with it. The most common cause of false positives or false negatives from an algorithmic point of view is incomplete information about security event observation, which is an objective disadvantage of cybersecurity on the defensive side. The attacker can design and invest heavily in attack resources from multiple perspectives, whereas the defenders can only model what they see. Even if the defender’s assets are completely covered with all detection points, it is difficult to fully analyze all of the attacker’s actions, not to mention that complete detection points are impossible, just like “The Blind Men and the Elephant”*, &quot;humans have a tendency to claim absolute truth based on their limited, subjective experience as they ignore other people&#39;s limited, subjective experiences which may be equally true&quot;*. The uncertainty associated with modeling with incomplete information necessitates tolerating uncertainty from a systems engineering point of view, as well as identifying and dealing with erroneous results.</p><p>Of course, algorithmic friagility can be caused by a variety of factors, including selection bias in the dataset, such as a crime prediction model’s default extremely high correlation of geography and skin color with crime rates, or statistical errors in sample collection and labeling, such as an insurance risk model predicts that the marriage rate of people over 100 years old is low, nor much expectation that “unknown unknown”* threats can be easily solved by known modeling, as some commercial products claim their AI models can detect and operate all types of APT attacks. Let us begin with the most important friagilities in the market today and work our way forward.</p><h3>Fragility from engineering</h3><p>The vast majority of papers will not mention the algorithm’s engineering implementation, and the engineering implementation to ensure the availability of model results is another major source of fragility, which includes the availability of upstream and downstream data, computing capacity support, monitoring and recovery systems, and so on, while data accessibility is also an important factor.</p><p>The majority of algorithmic models in the cybersecurity industry are based on data sources such as logs collected in-house or by customer platforms, which are produced by dedicated teams and saved in mutually exclusive file formats, from pcap to csv to some graph database to binary files on AWS S3, with different latency and reliability, and using different data platforms for output, coupled with various threat intelligence and third-party formats, as well as various field definitions and conflicts in the data. These data collection tasks, which are not mentioned in academic papers, are one of a few tricky topics that data scientists must face before modeling.</p><p>Even if a usable dataset is successfully collected and compiled, stable and timely computation is another engineering vulnerability. When we implemented the parent model of DGA detection,’domain2vec’*, a model that transforms domain name sequence co-occurrence probabilities into a geometric vector space, the computing power required to process approximately 1 billion DNS records per hour posed a significant engineering challenge. Because DNS data traffic can have completely different patterns for each time period, we must complete data collection and model computation within certain time period to avoid delays in results and computing platform clogging.</p><p>Data quality assurance and model building pipeline monitoring and recovery are also frequently overlooked, and their negative impact is not realized until a severe incident or intrusion occurs that the model could have detected and prevented, but the end result is ineffective due to lost or delayed upstream data, long job queues on shared computing platforms, incorrect version of the whitelisting policy, model runtime OOM, and so on. Some security teams and companies do not consider monitoring and recovery efforts to be in the core tasks, and as a result, they frequently invest insufficient resources and priorities, resulting in a classic case of “A small leak will sink a great ship.”*</p><p>Meanwhile, the data barrier leads to additional concern on fragility. Under ideal conditions, data science teams have unrestricted access to the data they require, but compliance and regulatory requirements, as well as the game of corporate interests do not perfectly integrate data holders and model teams, and such <strong>data barriers</strong> are an important factor in engineering fragility.</p><h3>Fragility from operation</h3><p>Most security operations teams lack the necessary mechanisms to process algorithmic model prediction results, which invariably raises <strong>the operational cost per case</strong>, which is the primary cause of operational fragility, and the cybersecurity domain knowledge makes it difficult for data science teams to further support. It is determined by two major factors: whether the algorithmic model supports the information required by operations and whether operations understand the model’s predicted results.</p><p>Data scientists frequently believe that the modeling task is limited to providing prediction results, and that if the prediction is correct, everything is fine; if it is not, the only thing that matters is recall-precision trade offs. However, <strong>the correct results must also be operational</strong>, such as when the model detects a video with violent content and the operation team has to find the video frame by frame for more than an hour, or when the model detects a new APT C&amp;C but the operations team must check dozens of hosts hundreds of processes and files one by one, manually! As rumored that Amazon’s packpage dispatch algorithm team had to ride with the courier truck for a month of package delivery work, the data science teams can not do effective data modeling if they put themselves out of the operational business.</p><p>Mechanisms, toolkits, and training for operations teams have also fallen behind the data science era. Most operations teams do not triage but instead devote all of their human resources to processing detection results, resulting in the random assignment of security researchers with varying levels of experience to the team regardless of the case’s complexity. Simultaneously, the contextual information required for incident investigation and subsequent action is dispersed throughout the data system and must be queried on-demand manually using multiple different tools. There are also challenges for security researchers in understanding and applying the algorithm’s prediction results, such as causality analysis, how to apply the prediction results in products such as firewalls, and rationalizing the impact of uncertainty in the prediction. The operational anxiety caused by these challenges makes it even more difficult for security researchers to use the results of data models, and conversations between data science and security operations teams frequently end with “you just tell me should I block it or not.”</p><p>In addition to the preceding two factors, communication barriers between the security operations team and the data science team due to different domain knowledge composition also resulted in the failure of the traditional method of “feedback loop”. The security teams concentrated on investigation descriptions, with unique features of each event, whereas the data science team struggled to extract and abstract the model’s commonality from these specific descriptions due to a lack of background knowledge, and the two sides of the communication always felt like they were talking about the two orthogonal views of the same thing, and the discussion became fruitless. The accumulation of these large and small factors leads to operational fragility.</p><h3>A few tips for less fragility</h3><p>Addressing fragility and its consequences necessitates nearly all of these efforts from a systems engineering perspective:</p><ul><li>Recognize incorrect results and provide explanations for both correct and incorrect ones.</li><li>Create a modern and mature data warehouse, as well as a related engineering framework, to ensure the model’s usability.</li><li>Create relevant mechanisms, tools, and training for the operation of model prediction results.</li></ul><p>Each step in this process is complementary to the others, and there are many real-world examples of how to improve the algorithm to solve dowstream engineering problems easier, redesign the security architecture to reduce the difficulty of the algorithm, and so on. Please consider the following tips in the context of systems engineering in general.</p><p>Algorithms require a channel to collect error results. A common misunderstanding stems from relying solely on user feedback for error results, which does little more than annoy users, as well as a massive number of alerts clogging up the operations queue, forcing the team using the security product or the operation team to discard the majority of the alerts by a list of in-house rules to keep the operations bandwidth up. In this case, not only does the security team lack the time to provide feedback, but it may also lead the model provider to believe that their model performs perfectly, when in fact, it is the user who is already too exhausted to care about the model feedback. The appropriate feedback channel may consist of several stages:</p><ul><li>Model feature based feedback: This is usually a heuristics rule or a machine-learning model based on other features. For example, if the algorithm predicts that a spear phishing page will be the Google home page, it can be cross-validated with a traffic ranking model and excluded based on the fact that “high traffic sites have a low correlation with spear phishing” in most cases (disclaimer: not always!). This type of feedback method makes use of a number of other features to effectively supplement the detection model’s limited view when observing attack patterns, providing a theoretical foundation for feedback and flagging the vast majority of errors.</li><li>Association knowledge based feedback: If a prediction is correct, the association result should be correct as well, unless the association is extended by several steps to produce an incorrect result. For example, if an algorithm predicts a domain name as a malware C&amp;C, the binary in VirusTotal or other detection engines’ or the security team’s binary analysis results can be extended by associating the IP record corresponding to the DNS lookup record with access to that IP in the sandbox until the entire chain is completed. This type of feedback relies on third-party knowledge outside of the feature space for independent verification; it is slightly more expensive than model feature feedback, but it is a useful supplement to model feature feedback methods.</li><li>User feedback: Following the previous stages, there are only very small amount of results that can reach the user who needs to operate. Users can make judgments about the results by combining their own experience and other intelligence with the help of contextual information provided by the algorithm. In this step, the user feedback includes not only the correctness or incorrectness of the results, but also the judgments made by the users based on which relevant information. In short, users must provide ‘what’ and ‘why’.</li></ul><p>The algorithm should also provide as much interpretability of the prediction results as possible, <strong>not just for incorrect results, but also for correct results</strong>. This includes explaining the algorithm’s features (common in deep learning models), marking and locating the basis of the judgment (which specific line of the malicious script snippet for example), and contextual information about the predicted result (like the associated knowledge mentioned above, such as that the binary was distributed by a URL implementation, other known malicious behaviors under that URL, etc.). Here’s a good example of the importance of interpreting results: it’s clear that when it comes to the effectiveness of data models versus rule models, security operations teams still prefer rule models, even though data models have nice metrics on paper in most cases. This is because operations staff can understand the model’s foundation by reading the rules themselves, as well as their own security experience, as well as additional research and other follow-up work from the model’s information, and eventually make a reasonable judgment. Based on this concept, Sophos AI team open-sourced a good repo to translate the relevant yara rules from the results of the machine learning model*, which is a very interesting work using the method of explaining with the features. Please follow the reference for further reading. It is worth noting that improving the explainability of model results is more than just translating into yara rules; the rule model does not provide perfect interpretation, and there is no silver bullet.</p><p>Algorithms must also provide a quick way to deal with erroneous results and partial automation, such as appropriate triage algorithms and enough contextual information to assist operations, among other things. Triaging algorithms are frequently overlooked in data science and security research, owing to a lack of discussion in academia and industry. A common scenario is that a good anomaly detection model is abandoned in production due to the large number of predicted events required to operate, which is a huge loss for both data science and security operations teams, whereas triaging algorithms can effectively rank the predicted results based on operational priorities and rationalize operational resources. One example is my colleague’s presentation at Botconf 2017, Asiaee et al “Augmented Intelligence to Scale Humans Fighting Botnets”*, which involved billions of DNS logs per hour. The system uses an anomaly detection model to output all unseen domains, &#39;domain2vec&#39; to construct access correlations between domains, and strong correlation patterns as operational importance metrics for triage ranking, and ten million anomalous events per hour were reduced to a dozen valid clusters and successfully applied to detect malware using DGA. The triaging algorithm has a number of metrics and methods, such as clustering and sorting, and it is a data science research direction related to security domain knowledge, which can be discussed in later posts if readers are interested.</p><p>Engineering fragility has a broader impact on the industry, and we can build a Data Quality Assurance (DQA) system along the lines of general solutions brought by other fields. Please read the references on your own for the DQA implementation*, there is no need to elaborate on this mature direction here.</p><p>Another cause of engineering fragility is the data barrier issue, which is becoming more prevalent in the cybersecurity industry. In addition to some open data organizations or alliances, engineering implementations of privacy-preserving data models are technically important to mention, which simply means that the models do not require decrypted data to learn and predict. Federated Learning is a popular approach that uses a server-client architecture to protect the model’s and data parties’ privacy while allowing the model to obtain the desired features without decrypting the raw data. These Federated Learning approaches are common in some NDR and XDR startup products, but are currently only used in simple scenarios. In terms of federated learning implementations, FATE* has established a strong foothold through a series of open source efforts, please check out the reference for further reading. To some extent, privacy-preserving computing uses higher computational costs to mitigate the data barrier problem, but there is still a long way to go to fundamentally solve the data barrier issue.</p><p>To resolve operational fragility, the data science team and the security operations team must work together. After the algorithmic model is interpretable to the results and the detection results are ranked in order of importance by the triage algorithm, the security operations team can make quick decisions and decide on the next steps based on the context provided. Simultaneously, some convenient data tools, such as a convenient and easy-to-use graph database system, which can be provided by the engineering team, can aid in the speed of operations. Simultaneously, we observe that security researchers who interested in data science can be excellent teachers, quickly and effectively providing data scientists with the necessary background knowledge to allow data science teams to better understand security problems and propose data models. These efforts across the knowledge gaps are addressing operational fragility in a step-by-step fashion.</p><h3>Summary</h3><p>The resolution of fragility issues is a high priority in cybersecurity. As experienced cybersecurity researchers may have discovered, the above discussion of fragility also applies to other aspects such as the use of third-party threat intelligence, with further automated validation of threat intelligence using cloud or telecom traffic, for example. Similarly, rule models based on security researchers’ domain knowledge and experience face fragility issues: smart detection rules require sufficient explanation, a large number of outdated whitelist rules must be maintained and updated in order to counter the trials and guesses of the red team, lack of triage and ranking of model detection results, and so on. These are the issues that rule models must contend with. We bring up the issue here and wish to shed light on the fragility of the rule model and its solutions devised by security researchers.</p><p>It is more important for data scientists to address fragility issues in system engineering way beyond proposing effective detection models. While we debated whether rule models or data models are more useful in production, we have seen many imperfect rules or data models produce good results with good engineering implementation and reasonable operational support, and rule models and data models validate and triage each other rather than compete. This also serves as a reminder to think beyond limitations when developing data models and to approach problems from a broader systems engineering perspective.</p><p>Similarly, we have discussed the vulnerability of models from a systems engineering perspective in response to the needs of the cybersecurity profession, and these discussions and their general solutions can also be applied to other industries that rely on data models, such as computer vision in image and video, voice recognition, risk and fraud control, and automation etc. Overall, industry data models are always a system engineering topic, and we must approach the design and solution from a system engineering perspective.</p><h3>Reference</h3><ul><li>The Blind Men and the Elephant <a href="https://en.wikisource.org/wiki/The_poems_of_John_Godfrey_Saxe/The_Blind_Men_and_the_Elephant">https://en.wikisource.org/wiki/The_poems_of_John_Godfrey_Saxe/The_Blind_Men_and_the_Elephant</a></li><li>Blind men and an elephant <a href="https://en.wikipedia.org/wiki/Blind_men_and_an_elephant">https://en.wikipedia.org/wiki/Blind_men_and_an_elephant</a></li><li>Uncovering The “Unknown Unknowns”: Why Threat Hunting is a Security Must-Have <a href="https://www.crowdstrike.com/blog/uncovering-the-unknown-unknowns-why-threat-hunting-is-a-security-must-have/">https://www.crowdstrike.com/blog/uncovering-the-unknown-unknowns-why-threat-hunting-is-a-security-must-have/</a></li><li>domain2vec was mentioned in this DGA detection blog <a href="https://toooold.com/2021/07/16/lstm_dga_is_wrong.html">https://toooold.com/2021/07/16/lstm_dga_is_wrong.html</a></li><li>A small leak will sink a great ship <a href="https://idioms.thefreedictionary.com/a+small+leak+will+sink+a+great+ship">https://idioms.thefreedictionary.com/a+small+leak+will+sink+a+great+ship</a></li><li>Sophos AI YaraML Rules Repository <a href="https://github.com/sophos-ai/yaraml_rules">https://github.com/sophos-ai/yaraml_rules</a></li><li>Augmented Intelligence to Scale Humans Fighting Botnets <a href="https://www.botconf.eu/2017/augmented-intelligence-to-scale-humans-fighting-botnets/">https://www.botconf.eu/2017/augmented-intelligence-to-scale-humans-fighting-botnets/</a></li><li>7 Steps to Ensure and Sustain Data Quality <a href="https://towardsdatascience.com/7-steps-to-ensure-and-sustain-data-quality-3c0040591366">https://towardsdatascience.com/7-steps-to-ensure-and-sustain-data-quality-3c0040591366</a></li><li>FATE (Federated AI Technology Enabler) <a href="https://github.com/FederatedAI/FATE">https://github.com/FederatedAI/FATE</a></li></ul><p><em>Originally published at </em><a href="https://toooold.com/2021/10/18/why_ml_fails_security_frag_en.html"><em>https://toooold.com</em></a><em> on October 18, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae9040bb3d79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why your machine learning models fail to solve cybersecurity problems: feature space first]]></title>
            <link>https://phunter.medium.com/why-your-machine-learning-models-fail-to-solve-cybersecurity-problems-feature-space-first-32e40b924213?source=rss-9b5f5d1914ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/32e40b924213</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[failure]]></category>
            <category><![CDATA[system-engineering]]></category>
            <dc:creator><![CDATA[Phunter]]></dc:creator>
            <pubDate>Thu, 30 Sep 2021 00:00:00 GMT</pubDate>
            <atom:updated>2021-10-09T04:21:52.531Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*koLXjojyyg0Aw4fL_V330Q.jpeg" /></figure><p>Disclaimer: Nothing in this blog is related to the author’s day-to-day work. The content is neither affiliated nor sponsored by any companies.</p><p>Original version in Chinese <a href="https://toooold.com/2021/09/27/why_ml_fails_solving_sec_algo.html">为什么机器学习解决网络安全问题总是失败：谈谈特征空间 | Toooold</a></p><p>Original version in English <a href="https://toooold.com/2021/09/30/why_ml_fails_sec_feat.html">Why your machine learning models fail to solve cybersecurity problems: feature space first | Toooold</a></p><p>The cybersecurity industry has been fascinated by the magic of machine learning in recent years, and with the success of deep learning in areas such as computer vision and natural language processing, we all want to find a silver bullet. However, what we’ve seen in the industrial is more disappointing than promising: “the model generates too many false positives, the security operation team can’t handle it,” “the model only generates two unique detection samples, why don’t I just add two more yara rules,” “your slides say it’s deep learning, self-evolution, but the code is set of ‘if-else’ “, and so on. Why do so many machine learning models fail when apply to solve cybersecurity problems?</p><p>The reasons behind such poor effectiveness can be attributed as:</p><ul><li>Incorrect feature space and sample labeling</li><li>Algorithmic fragility, engineering fragility, and security operational fragility</li><li>Incorrect benchmark metrics and optimization</li><li>Misconception that machine learning is the only type of algorithms of AI algorithms</li></ul><p>Let’s get started with feature space and sample labeling.</p><h3>What is an appropriate feature space</h3><p>Does it sound right that, the image recognition problem’s feature space means the pixels in a picture, the NLP feature space as the word in the text, and the cybersecurity features are the characters of every WAF attack log, the raw binary code of each malware binary file?</p><p>The use of the appropriate feature space to describe the true nature of the problem can make it easier to solve, whereas the use of the incorrect feature space can make the problem exponentially more difficult. Consider the following example: Anyone who has learned basic arithmetic will have no trouble answering “what is 5765760 plus 2441880&quot; as 8207640, no calculator is needed, but what if it is &quot; 5765760 <strong>times</strong> 2441880&quot;? Most people find it is difficult. This is due to the fact that decimal is not a multiplication-friendly representation, so the problem is made artificially difficult because we chose the incorrect feature space. Factorization is a more multiplication-friendly representation that is even easier than addition if the problem is replaced by the equivalent one: &quot;what is 11*12*13*14*15*16 multiplied by 17*18*19*20*21.&quot;</p><p>The deep learning algorithm Malconv for malware detection is a similar example, where a binarycode based convolutional approach does not learn the approprite feature space. In the paper &quot;Malware Detection by Eating a Whole EXE&quot; by Raff et al.*, the binary EXE file is used as input, and malconv attempts to build an end-to-end static detection classifier from a raw bytecode feature space like 010101 using convolutional networks, achieving over 90% AUC on the paper&#39;s test set. Leaving aside its unstable performance for new and adversarial sample detection, the paper &quot;DeepMalNet: Evaluating shallow and deep networks for static PE malware detection&quot;* introduces a new test set that compares several deep models, including malconv and a random forest model by the authors of the paper, and finds that a random forest model with manual feature engineering can almost match and even outperform malconv results. The reason is that convolutional networks in malconv doesn&#39;t learn the appropriate feature space from the bytecode block, so the effectiveness demonstrated in the malconv paper is more or less just luck. According to the paper from Fireeye Coull et al &quot;Activation Analysis of a Byte-Based Deep Neural Network for Malware Classification&quot;*, the convolution result of malconv actually treats the header information of static binary files as the dominant feature, and the combination of instruction jumps only contributes limited weight to the classification. For details, please follow Bose et al. &quot;Explaining AI for Malware Detection: Analysis of MalConv Mechanisms&quot;* for a detailed analysis and explanation.</p><p>If we leverage certain domain knowledge and tools, such as the function export tables, or some dynamic analysis features such as the function call sequences from sandbox, or using static disassembly to get instruction sequences, and converting the original binary to these feature spaces that can better characterize the malware runtime behavior, the machine learning model can be much more stable and better than that of the raw binary models like malconv.</p><p>Similarly, we cannot expect an accurate end-to-end model to predict attacks based solely on raw WAF log without slicing and filtering tokens, nor can we expect a model to learn the complex character combination of DGAs and accurately classify or even generate new DGA domains, nor can we imagine a deep learning model reading any HTTPS stream and accurately predicting its corresponding website. The failure of these industrial machine learning models to solve cybersecurity problems highlights the importance of the appropriate feature space: a model on the wrong feature space may produce so-called “good results” because it happens to fit a specific dataset, but these results are not stable or reliable enough to support the production environment and product quality.</p><p>Of course, the discussion does not diminish the importance of malconv paper in the industrial. It was one of the first papers to apply machine learning to cybersecurity problems, and it creatively applied a convolutional network to binary code, implying that more work would follow, most likely with a better network structure or a completely new feature layer. More pioneer ideas and papers like this are needed in modern scentific research to find the path to a solution.</p><p>The term “machine learning” is frequently used to refer to statistical learning by example, in which models learn the statistical expectation of the distribution of samples in their feature space. We can imagine looking across the mountain to understand the impact of feature space on model effectiveness. If the feature space does not describe the essential causes of the sample distribution, the numerical distribution of the features does not provide enough discriminative power; intuitively, the model can only “look across” a series of “ridges” but not “look sideways” to the independent “peaks”. Because the model can only “look” at a series of “ridges” but not at the independent “peaks”, it can only try the best to divide the “ridges” by fitting the existing data set, so it doesn’t know the “true face of the mountain”, and it loses the essence of what the “peaks” are supposed to represent.</p><p>The sample labeling method is also related to the feature space. A real-world lesson in statistical learning is that even the best models can only learn as much manual labeling as they can. “The model can only learn the samples labeled by my yara rules, so what is the use of your bloody machine learning model?” many cybersecurity researchers ask so. Many models, according to our observation, have the misconception that “labeled samples are only labeled <strong>raw</strong> samples,” whereas good data scientists will label samples corresponding to the feature representation space, which can be a mapping of the original samples in the new phase space, such as learning vector representation learned in various association graph models, a.k.a ‘graph embedding’ or ‘ something2vec &#39;, and label the vector, or it can be a sequence or a graph of tokens where token can be labeled to overcome the limitations of the original samples. Many ways to label samples beyond the raw format allow the problem to be solved with simpler and more reliable machine learning models.</p><h3>How to find my feature space</h3><p>Some feature space choices are self-evident, while others necessitate extensive brainstorming. The distinction between a “ridge” and a “peak” is not only limited to the feature selection within the same dataset or the transformation of feature hypersurface, but it is also critical to leave out the “obvious” and “taken-for-granted” features. It is more important to look for features that describe <strong>the essential causes</strong> of the sample distribution rather than the “obvious” ones. A typical example is the family of LSTM algorithms for detecting DGAs mentioned in the previous blog “Why using LSTM to detect DGA is a wrong idea”*, where the feature space is the combination of adjacent strings for each domain name and the LSTM model works twice as hard to fit the unknown DGA function for the combination pattern of these adjacent characters, far exceeding the LSTM learning capability. In fact, no yet any network structure can be intelligent enough to learn functions containing complex operations such as xor, bit shift, and so on from some small data sets. Most DGAs are characterized essentially by DGA algorithms that generate sequences of domain names, and their behavior can be better modeled by mapping domain name sequences into the embedding vector space or by using their co-occurrence probabilitiesin a graph, and good DGA detection can be achieved using simple graph embedding models or graph adjacency matrix calculations.</p><p>For the time being, finding the right feature space does not have a one-size-fits-all solution, nor is it automated by an advanced artificial intelligence. What it takes is a good data scientist who understands the principles of existing models as well as the fundamentals of the specific security domain from a data modeling perspective. Because we have seen far too much work based on faulty assumptions and feature spaces, it is recommended that data scientists keep this issue in mind and remind themselves of it on a regular basis while problem solving:</p><blockquote><em>“Can this feature space describe the essence of the problem?”</em></blockquote><h3>Summary</h3><p>Algorithms and modeling in cybersecurity do not have intuitive definitions of examples, unlike computer vision. It is more similar to speech recognition and spatial control problems in that data scientists must have a deeper understanding of domain knowledge, explore the feature space that <strong>can characterize the essential causes</strong> of the problem, and intelligently map the problem from its original shape to the problem solving feature space. Rather than praying for deep learning to bring the power from nowhere, we can find a more appropriate way to solve the problem by adding an appropriate sample labeling method to describe the distribution of these features.</p><p>This post examines the primary reasons why machine learning models fail to solve cybersecurity issues. Other topics, such as understanding and dealing with model fragility in a system-wide context, will be covered in future posts. Not only in cybersecurity, but also in many other fields, researchers and engineers place too much emphasis on model work*, ignoring the fact that algorithm and modeling are system engineering problems, and that finding more and better samples, more descriptive features, and dealing with prediction errors are all important steps in the system. We hope that by focusing on systems and engineering, machine learning and other artificial intelligence algorithms will be able to play a meaningful role in the field of cybersecurity.</p><h3>Reference</h3><p><a href="https://toooold.com/2021/07/16/lstm_dga_is_wrong.html">https://toooold.com/2021/07/16/lstm_dga_is_wrong.html</a></p><p><em>Originally published at </em><a href="https://toooold.com/2021/09/30/why_ml_fails_sec_feat.html"><em>https://toooold.com</em></a><em> on September 30, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32e40b924213" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>