<?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 Luis Francisco Monge Martinez on Medium]]></title>
        <description><![CDATA[Stories by Luis Francisco Monge Martinez on Medium]]></description>
        <link>https://medium.com/@luckyluk3?source=rss-4268294f29eb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*LWJKziugiiwaxhlX</url>
            <title>Stories by Luis Francisco Monge Martinez on Medium</title>
            <link>https://medium.com/@luckyluk3?source=rss-4268294f29eb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:28:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@luckyluk3/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[Using LLMs and GPT to streamline data analysis in cybersecurity incidents.]]></title>
            <link>https://luckyluk3.medium.com/using-llms-and-gpt-to-streamline-data-analysis-in-cybersecurity-incidents-ebeb0d23e01b?source=rss-4268294f29eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebeb0d23e01b</guid>
            <category><![CDATA[gpt-3]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[incident-response]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Luis Francisco Monge Martinez]]></dc:creator>
            <pubDate>Wed, 10 May 2023 20:35:06 GMT</pubDate>
            <atom:updated>2023-05-10T20:35:06.566Z</atom:updated>
            <content:encoded><![CDATA[<h4>Or another way to forget programming 😁</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j41Ayse3xtBdSRtv" /><figcaption>Reddit user: MsElsaMars</figcaption></figure><h3>Introduction</h3><p>It is difficult to consider writing an article about ChatGPT and not feel like one of those who join the trend and try to talk about a topic simply because everyone else is doing it.</p><p>I think that since I started my working life, this has been the moment in which a technological advance has generated the most noise and, of course, I could not not try it and try to solve certain problems that may arise in the day to day of incident response.</p><p>For the development of this article I am going to use <a href="https://medium.com/towards-data-science/how-data-science-could-make-cybersecurity-troubleshooting-easier-firewall-logs-analysis-591e4832f7e6">one of my previous articles</a> to try to find a different way of obtaining the same results.</p><p>In this article I talked about how to analyse firewall logs during a ransomware incident using Python and my good friend the Pandas library.</p><p>Although Pandas was for me one of my greatest discoveries, it is true that the learning curve is not easy and that has meant that some of my colleagues never got to use the tools I had for the simple fact that understanding, modifying or generating Python/Pandas code is not easy.</p><p>During this article I am going to attempt a complicated goal. To abstract the analyst from the code and make him/her focus only on asking the right questions.</p><p>I hope this idea excites you as much as it does me and that I will be able to keep your attention during the article because it will be worth it.</p><h3>What is ChatGPT and how does it work?</h3><p>Just kidding, I’m not going to explain what ChatGPT is and how it works, I’m sure you’ve already read it too many times and if not, I’m sure there are people much more prepared than me to do it 😊.</p><p>The only thing I would like to mention in this section is that although since its inception the tool has been used as a source of truthful information, this is not the purpose of the tool and if we do not remember this, it is very likely that we will be disappointed and will not be able to understand the benefit we can get from it.</p><p>A few weeks ago, OpenAI together with DeepLearning.AI have released a free course called “ChatGPT Prompt Engineering for Developers”, I can’t recommend it more to anyone who is interested in this technology. It has really changed my understanding of the Large Language Model (LLM) and the enormous work of OpenAI.</p><h3>Getting started with Jupyter Notebooks 🪐</h3><p>The OpenAI team has developed a very intuitive Python SDK that we are going to use during the article, easily installed with pip.</p><pre>pip install openai</pre><p>To use the OpenAI API you need to have an API Key and to do so you must register at <a href="https://openai.com/">https://openai.com</a> and generate one in the section <a href="https://platform.openai.com/account/api-keys">https://platform.openai.com/account/api-keys</a>.</p><p>With the library installed and an API Key in our possession we can get started!</p><pre>import openai<br>openai.api_key = &quot;YOUR_API_KEY&quot;<br>def get_completion(prompt, model=&quot;gpt-3.5-turbo&quot;, temperature=0):<br>messages = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}]<br>response = openai.ChatCompletion.create(<br>model=model,<br>messages=messages,<br>temperature=temperature,<br>)<br>return response.choices[0].message[&quot;content&quot;]</pre><p>To quickly explain the previous code, after telling the openai library our apikey we have defined a function called get_completion that we will use to interact with ChatGPT and get its answers.</p><p>We will pass our information and questions to the function in text format and it will return the answers in text format. As parameters to modify we have the model to use, and the temperature.</p><p>On the OpenAI website they explain the different models they have available right now and their functionalities.</p><p>DESCRIPTION OF MODELS</p><p>GPT-4 — Limited beta — Set of models that improve GPT-3.5 and can understand and generate natural language or code.</p><p>GPT-3.5 — Set of models that enhance GPT-3.5 and can understand and generate natural language or code.</p><p>DALL-E — Beta — Model capable of generating and editing images from a natural language instruction.</p><p>Whisper — Beta — Model capable of converting audio to text.</p><p>Embeddings — Set of models capable of converting text into numeric form.</p><h3>Using GPT as intended 🤖</h3><p>One of the most common mistakes made when using ChatGPT is to attribute special powers to it that we do not usually attribute to any other type of programme, and this is perhaps the fault of all the noise that has been generated around it.</p><p>It is true that ChatGPT works really well with generic questions and helps us by providing solutions to quite complex problems if the situations are not extremely particular.</p><p>Things change when we go deeper and try to delve into complex problems, problems where experts have to spend time reasoning, understand the context and have enough information to be able to have the necessary tools to move forward.</p><p>Just like us, ChatGPT needs context and as much information as possible that we are able to give it to understand the problem and even, in necessary cases, guide it through the logical process so that it is able to reach the goal we are looking for.</p><p>Let’s start with a simple example to take the problem I mentioned above to the absurd.</p><pre>prompt = f&quot;&quot;&quot; How do I know the IP address of the command and control console? &quot;&quot;&quot;<br>response = get_completion(prompt)<br>print(reponse)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*1cPXGuxWNElNqFpr7otnVA.png" /></figure><p>As expected, the answer is not very useful for our research.</p><p>Let us list what went wrong with our approach:</p><ul><li>Lack of context.</li><li>Lack of necessary information.</li><li>Lack of indications of what we expect from her.</li><li>Lack of necessary instructions to give us what we want.</li></ul><p>Let’s continue little by little to solve these problems.</p><h3>The importance of context <a href="https://emojipedia.org/man-teacher/">👨‍🏫</a></h3><p>We often forget the particularity of our thoughts and tend to think that others, or in this case artificial intelligences, should understand how we think rather than the other way around, as would be logical.</p><p>When working with LLMs the context is perhaps the fundamental difference in improving the results obtained.</p><p>Following the example above, let’s provide context to our question.</p><pre>prompt = f&quot;&quot;&quot; Context: You have to provide Python code to be used in a Jupyter Notebook.<br>Your expected output is Python code to assist a cybersecurity analyst in an investigation during a ransomware attack on an enterprise network.<br>We are going to analyse a file containing traffic events from a Palo Alto brand firewall. The content is already in Pandas DataFrame format in a variable called &#39;data&#39;.<br>Question: How do I know the IP address of the command and control console? &quot;&quot;&quot;<br>response = get_completion(prompt)<br>print(response)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*lE3pE1IhRdL_npeCj5mZag.png" /></figure><p>As we can see, the result is taking shape, but it is certainly far from what we are looking for, if only it were as easy as knowing the addresses of the command and control consoles.</p><h3>If you have information, tell it <a href="https://emojipedia.org/notebook/">📓</a></h3><p>Although one of the reasons for using this technology is to obtain information, it is important to understand that this is not the main purpose. If we provide as much information as possible in our queries we will see a great improvement in the answers.</p><p>It is obvious that in this kind of situation, when you have GBs of logs and even a 200MB $MFT file, it is not realistic to have to send this information to the AI to process it, besides having problems with data protection, maybe we would have higher than expected costs with the API 😉 Instead we are going to tell the AI what our data looks like, giving it as much context information as possible so that the data itself is irrelevant.</p><p>In this case we are going to provide GPT with the columns that contain the logs and a description of each field and of course, to do the description we will use GPT 😊</p><pre>prompt = f&quot;&quot;&quot;<br>Creates a list of log fields from a Palo Alto brand firewall.<br>The fields to list are: {df.columns.tolist()} and the expected format is:<br>````Field name: Field description in less than 10 words.<br>&quot;&quot;&quot;<br>fields = get_completion(prompt)<br>print(fields)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*FN6ToDfFZPpPjrIFjwUW4A.png" /></figure><p>With this data and the private IP range information we can try again.</p><pre>prompt = f&quot;&quot;&quot;&quot;Context: You are a Python code generator to be used in a Jupyter Notebook.<br>You have to provide Python code to be used in a Jupyter Notebook.<br>Your expected output is Python code to assist a cybersecurity analyst in an investigation during a ransomware attack on an enterprise network.<br>We are going to analyse a file containing traffic events from a Palo Alto brand firewall. The content is already in Pandas DataFrame format in a variable called &#39;data&#39;.<br>The columns in this DataFrame are: {fields}<br>And the private IP address ranges are:<br>- 10.0.0.0 a 10.255.255.255<br>- 172.16.0.0 a 172.31.255.255<br>- 192.168.0.0 a 192.168.255.255<br>Question: How to know the IP address of the command and control console?&quot;&quot;&quot;<br>response = get_completion(prompt)<br>print(response)</pre><h3>Asking the right question 🙋</h3><p>After multiple tests with GPT it is clear to me that the role of the analyst is more than necessary. Not just someone who understands how the technology works, but someone who understands the problem and knows what questions to ask, even if they want to abstract from the intermediate process.</p><p>In this case we are going to change such a generic question as the one used above for much more precise clues that can guide us in our research process.</p><p>We will use the same context as before but change the question.</p><pre>Question: List for me the external IP addresses to which the most data has been sent.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*GZyfxy_FhUaLxzn24OumXg.png" /></figure><p>Although there are some things that are not well implemented, such as the filtering of private IP addresses, the proposed code works and returns a result that could be used to look for signs of data exfiltration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*ce_kDJwINWkGbPVcj4yfnA.png" /></figure><p>Now that we have obtained a satisfactory result, we are going to increase the complexity of our questions to obtain something more interesting and realistic. Go with a new question.</p><pre>Question: List the external IP addresses to which the most web-browsing connections were made between 18:00 and 8:00 and show me in a column the number of unique source IP addresses that made connections to each of the external IP addresses.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*x8QQXLZ_T060YnIsdKkpXQ.png" /></figure><p>In this case, we only received one IP address and that is quite suspicious. In an incident of this type, the fact that only two source IP addresses are making HTTP connections after hours is something we need to analyse in depth.</p><h3>Guiding AI in the right direction 🔍</h3><p>Another surprising thing we can do is to tell the AI the right way to get to the result we want.</p><p>In some cases, we are clear about the path to follow to reach the right goal but we do not want to spend time looking for the Python functions that would lead us to the result, i.e. we know the what, but not the how, and for that we can use GPT to help us.</p><pre>Question: We want to find external IP addresses suspected to be command and control consoles, so we are going to look for repetitive connections throughout the day between two IP addresses, follow these steps:<br>- Filter for connections to external IP addresses.<br>- Extract the time of the connection without taking into account the minutes.<br>- Group the IP connections by source and destination.<br>- During the above grouping it counts how many unique values exist in the connection times, the sum of the bits sent to the destination IP and counts the number of connections made between these two IP addresses.<br>- It displays the results in a table sorted in descending order by the number of connection hours.</pre><p>And the results is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*sI1bCYBTS0ZyJbMQDbzcaA.png" /></figure><p>When we run this code we get the following result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*ysmGohRAKUAkkCJ6SKVnkQ.png" /></figure><p>In the result we have IP addresses that we should analyse, as the fact that there are thousands of connections between two IP addresses between 13 different times of the day (all of those in the log) is suspicious, which could be a beacon to a command and control console.</p><p>Finally, as a last example we are going to look for long connections in the traffic, this kind of connections are usually something interesting to look at as more and more attackers are using remote assistance tools like TeamViewer to evade detection and maintain access to the organisation.</p><p>To do this we will use the following question.</p><pre>Question: We want to create a graph of long connections between an internal IP address and an external IP address by following the steps below.<br>- Filter the communications to external IP addresses.<br>- Sum the connection time to each destination IP and store it in a separate column called &#39;sum_time&#39;.<br>- Add the number of connections made to each destination IP and store it in a separate column &#39;sum_conn&#39;.<br>- Filter and keep the results with &#39;sum_conn&#39; greater than 10.<br>- Keep only one row for each destination IP address.<br>- Divide the number of connections by the sum of connections and store it in a column called &#39;avg_conn&#39;.<br>- Filter out the ten results with the highest &#39;avg_conn&#39;.<br>- Create a graph with matplotlib where on the &#39;x&#39; axis is the number of connections and on the &#39;y&#39; axis is the total connection time.</pre><p>This is GPT’s response</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*sE5WAO6Y_IeGje1npMxu1g.png" /></figure><p>And this the result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*zilSV-nTxzCbm82Q0tcgLg.png" /></figure><p>As can be seen in the image, the first result with an average duration of 840 seconds for each connection is something we should certainly analyse.</p><h3>Bonus</h3><p>Although the fact of working with Jupyter Notebooks makes the work much easier and very comfortable, we can create a small interface to abstract even more the analyst from the code and make it more intuitive.</p><p>I leave <a href="https://github.com/lucky-luk3/Infosec_Notebooks/blob/main/LLM_GPT_Public.ipynb">the Notebook in my Github</a> and I hope you will be encouraged to try GPT in your research and that you will enjoy it as much as I did.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebeb0d23e01b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hunting threats without leaving home- Part V]]></title>
            <link>https://luckyluk3.medium.com/hunting-threats-without-leaving-home-part-v-b11d7810fcb1?source=rss-4268294f29eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/b11d7810fcb1</guid>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[threat-hunting]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Luis Francisco Monge Martinez]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 17:03:45 GMT</pubDate>
            <atom:updated>2023-04-10T17:07:22.323Z</atom:updated>
            <content:encoded><![CDATA[<p>Jupyter Notebooks 🪐</p><p>Previus post: <a href="https://medium.com/@luckyluk3/hunting-threats-without-leaving-home-part-i-8bc537c80323">Intro I</a>, <a href="https://medium.com/@luckyluk3/hunting-threats-without-leaving-home-part-ii-1cd349ed2574">Intro II</a>, <a href="https://medium.com/@luckyluk3/hunting-threats-without-leaving-home-part-iii-87c000e9c5a">Analizing our data</a> and <a href="https://medium.com/@luckyluk3/hunting-threats-without-leaving-home-part-iv-7c618ef63f7f">Grafiki</a>.</p><p>Do you remember the first post when we talked about what is and what is not Threat Hunting? Well, an essential part of it is the generation of intelligence.</p><p>It’s good that we are the best at detecting abnormal behavior, but if all that acquired intelligence is not transformed into structured and repeatable information we lose one of the most valuable parts of the process.</p><p><strong>Structured</strong>, so that anyone other than the author can use it and understand it. <strong>Repeatable </strong>in the better way possible, so that the detection teams can generate alerts with it or so that any other analyst can perform the queries in the most comfortable way possible.</p><p>In our laboratory we are going to use another part of HELK, the all powerful Jupyter Notebook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8jqavQun4ZH_Ho9e.png" /></figure><h3>What is Jupyter Notebooks 🪐?</h3><p>To begin with, let’s imagine a notebook, in which we can write our advances, arguments and conclusions.</p><p>On the other hand, let’s imagine a program, a script, something functional that is able to process data, to connect to our laboratory… all the wonderful power of programming.</p><p>All that together is a Jupyter Notebook.</p><p>Whoever is already working with the project will be pulling the hair out of that description, but you’ll agree that the simplified idea is that ;-)</p><p>A more realistic explanation would be that Jupyter Notebooks is the evolution of the IPyhton Notebooks project, a project that was created with the purpose of creating documents capable of processing data and showing an aesthetic similar to a regular text document.</p><p>Jupyter works as a web service, which will process our files with “.<em>ipynb</em>” extension and will allow us to create, model, process and share our intelligence. This technology is applicable to any field imaginable, being very known in data processing.</p><p>We are going to forget about all the technology behind, since HELK makes the work much easier.</p><h3>Our first notebook 📓</h3><p>Let’s see how to access the console. When we installed HELK, at the end of the installation the addresses of all the services were shown, among which was Jupyter’s web console. Among other things:</p><pre>HELK JUPYTER SERVER URL: https://192.168.129.137/jupyter/ HELK JUPYTER<br> <br>CURRENT TOKEN: 8dd6ade6964ca56e6964ca5600b925e769192fca793b5</pre><p>Each installation will have a different IP and token.</p><p>The IP is the same as for the rest of the lab. If you don’t have the token, that’s okay, you have to execute this command in the virtual machine to get it back.</p><pre>sudo docker exec -ti helk-jupyter jupyter notebook list | grep &quot;token&quot; | sed &#39;s/.*token=\([^ ]*\).*/\1/&#39;</pre><p>By accessing Jupyter’s URL and entering the token, we enter Jupyter’s home folder.</p><p>As you can see, we have 4 folders.</p><ul><li>In the “<strong>datasets</strong>” folder, we save the events we work with.</li><li>In the “<strong>demos</strong>” folder there are preloaded examples of the HELK project.</li><li>In the “<strong>sigma</strong>” folder, the creator of HELK has done a titanic job to transform a total of 378 sigma rules into queries that can be made from these notebooks.</li><li>In the “<strong>tutorials</strong>” folder there are tutorials that, besides teaching us how Jupyter Notebooks work, allow us to learn about Python, Numpy, Pandas…</li></ul><p>It is highly recommended to spend some time on the tutorials. There is one tutorial to learn Python very 101, and besides learning Python it shows the incredible potential of Jupyter Notebooks.</p><p>Although it is not my intention to make an article detailing the use of notebooks, we will make a test one and if there is interest (say it in the comments) I will write an entry entering more in detail.</p><h3>Jupyter Notebooks creation</h3><p>Located in the “<em>demos</em>” folder, on the right side we see the “<em>New</em>” button, which gives the option to select the Kernel that will interpret our notebook. In this case we select “<em>Python 3</em>“.</p><p>We already have our first notebook! Now you just have to do what we want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*thrX3Cw4KvlO0Qfo.png" /></figure><p>In the second post we used one of the Mordor datasets, “<em>empire_wmic_add_user</em>“. Now we are going to automate the search for this technique.</p><p>In the first box we add a detailed title and description, so that anyone can understand our notes. Important to add the ATT&amp;CK tactic in the title.</p><p>Jupyter plays Markdown, so notebooks can be decorated as much as you want. Remember to check the “Markdown” selection in the toolbar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TeiCi0eBtgU-jhrA.png" /></figure><p>In the next cell we make the imports that we will need.</p><pre>from elasticsearch import Elasticsearch</pre><pre>from elasticsearch_dsl import Search</pre><pre>import pandas as pd</pre><pre>from IPython.display import display, HTML</pre><p>In another cell we created an Elastic Python client.</p><pre>es = Elasticsearch([&#39;http://helk-elasticsearch:9200&#39;])</pre><pre>searchContext = Search(using=es, index=&#39;logs-*&#39;, doc_type=&#39;doc&#39;)</pre><p>And with our client, the consultation is made to Elastic.</p><pre>s = searchContext.query(&#39;query_string&#39;, query=&#39;(event_id:&quot;1&quot; AND process_command_line:*wmic.exe* AND process_command_line:&quot;process call create *net user *add&quot;)&#39;)</pre><pre>response = s.execute()</pre><pre>if response.success():</pre><pre>    df = pd.DataFrame((d.to_dict() for d in s.scan()))</pre><p>Note that in the query I have entered the pattern of the command used by Empire. Although this technique could be used by other software or malware, it will always involve an attempt at persistence to create a user.</p><p>Now we have our data stored in a Panda DataFrame, and all that is left is to display it.</p><pre>display(HTML(df[[&#39;host&#39;,&#39;process_name&#39;,&#39;process_parent_name&#39;,&#39;process_command_line&#39;]].to_html()))</pre><p>Once the notebook is created, we save it with a name. In my case “<em>[ T1136] Empire WMIC create user</em>“.</p><p>When we leave and come back in, we will see our formatted text. I show mine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GbqRxQbOcHsuL_Hw.png" /></figure><p>Now, if we position ourselves in the first cell and press “Run” the commands will be executed. It’s okay to execute the ones with text.</p><p>As we go, each piece of code will be executed. When we reach the end, we will see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2xo98P4rHqmK5grG.png" /></figure><p>Bingo! We have caught the event that executed the persistence. Now, every time we want to perform that query on our lab, we just need to enter and execute our notebook: we have transformed knowledge into intelligence.</p><p><a href="https://posts.specterops.io/threat-hunting-with-jupyter-notebooks-part-1-your-first-notebook-9a99a781fde7">Here I leave a series of articles about the creator of HELK talking in detail about the Jupyter Notebooks</a>, essential to exploit this incredible tool to the fullest. Also, in <a href="https://github.com/lucky-luk3/Infosec_Notebooks">this link</a> you can find some notebooks that I created to another posts that maybe are useful for you 😉.</p><p>See you at the next hunt 🎯!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b11d7810fcb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hunting threats without leaving home — Part IV]]></title>
            <link>https://luckyluk3.medium.com/hunting-threats-without-leaving-home-part-iv-7c618ef63f7f?source=rss-4268294f29eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c618ef63f7f</guid>
            <category><![CDATA[threat-hunting]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[graph]]></category>
            <dc:creator><![CDATA[Luis Francisco Monge Martinez]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 16:55:12 GMT</pubDate>
            <atom:updated>2023-04-10T17:12:31.764Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hunting threats without leaving home — Part IV</h3><p>Grafiki 🐵</p><p>In this post I will cover something very special to me.</p><p>In the previous entries <a href="https://medium.com/@luckyluk3/hunting-threats-without-leaving-home-part-i-8bc537c80323">Intro I</a>, <a href="https://medium.com/@luckyluk3/hunting-threats-without-leaving-home-part-ii-1cd349ed2574">Intro II</a> and <a href="https://medium.com/@luckyluk3/hunting-threats-without-leaving-home-part-iii-87c000e9c5a">Analizing our data</a>, we saw the exploitation of information with Kibana and its usefulness in seeing potential anomalies at a glance. After a lot of work with Kibana, spending many hours creating visualizations and dashboards, there was one visualization that I missed: <strong>the graphs!</strong></p><p>In that sense, I read some time ago the sentence “<em>Defenders think in lists. Attackers think in graphs</em>“.</p><p>Although it can raise a lot of controversy, if that were true it would leave us, defenders, at a clear disadvantage. In a world where threats are increasingly complex, being able to “connect the dots” makes the difference between finding our threat or not.</p><p>From this idea and an increase in my free time due to lockdown, <strong>Grafiki </strong>emerged. Let’s take a look at it.</p><h3>Grafiki</h3><p>This project aims to create a new way of working with Sysmon events. Because the events are independent in themselves, as a developer I needed to store all that information in a relational database format to make queries more intuitively.</p><p>Thus, from each event, the entities that participate in it, processes, registry keys, files… are extracted and all of them are related independently, with one or several relationships for each event.</p><p>Once the information is organized, the logical evolution is to paint the data as what they are: entities relating to each other. As you can see, the result is amazing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/0*bc3CqfIeM7jP3Fxh.png" /></figure><h3>Installation 🖥️</h3><p>The first thing we will do is to install it in our laboratory machine. The installation is very simple; we open a terminal and enter the following commands:</p><pre>git clone https://github.com/lucky-luk3/Grafiki.git</pre><pre>cd Grafiki<br>sudo -- sh -c -e &quot;echo &#39;127.0.0.1 grafiki.local&#39; &gt;&gt; /etc/hosts&quot;<br>docker compose up --build &amp;<br>docker exec -it -d grafiki-app-1 /init_django.sh</pre><p>If everything went well, the application will ask to access the URL <a href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a> with the browser to access the tool. Once there, at the top we see the different sections of the application. Let’s go for “<em>Examples</em>“.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*J_8RsHZQNa_gcW0N.png" /></figure><p>Do you remember the Mordor and EVTX-ATTACK-SAMPLES repositories? Well, here are stored all the links to the event files of both repositories, organized by the Mitre ATT&amp;CK tactics, so it will be easier to investigate them without having to enter them in ElasticSearch.</p><p>For each example, we have a link to download the file and a link to the author’s repository, plus two different types of processing: <strong>normal processing</strong> and <strong>simple processing</strong>.</p><p>In <strong>simple processing</strong>, a simplification of the graph is performed by grouping processes with the same name, and removing some elements of the graph such as threads. This functionality can be very useful in some cases to simplify the graph, but sometimes it can be misleading, so the two options should be properly evaluated.</p><p>To show the capabilities of this section, we will use the same file loaded in previous post. We introduce in the search bar the text “<em>empire_wmic_add_user</em>“, click on the “<em>Process</em>” icon, and the application will download the event file from the repository, transform the events and create the graph, which we will see after a few seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/0*cTqmBHI9Wm4vkp2s.png" /></figure><p>Here is our first graph!</p><p>Although this file is not one of the largest, it may contain too much information to work comfortably. Clicking on “Graph Filters”, all the graph options will be displayed. Let’s take a look at them, as this is where much of the charm of the project lies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/0*bgYvuL1MgIXOBj1T.png" /></figure><h4>A. Process Area</h4><p>As seen in the image, there are three different filters in this section: by <em>integrity</em>, by <em>session </em>and by <em>process user</em>. Clicking on any of the filters will display a list of available options, taking into account the graph data.</p><h4>B. Deleting groups</h4><p>This option allows to remove entire groups of processes from the graph. To do this, select the central node of the group, i.e. the process that has generated the others, and “<em>Delete Group</em>“. The recursive delete option recursively deletes all processes created by the selected process. This option is very useful for deleting branches of the graph that are not of interest to us.</p><p>Please note that the deletion action cannot be undone, so to show again a deleted node it will be necessary to generate the graph again.</p><h4>C. Animation</h4><p>From this section it is possible to create an animation with the events of the graph. When you click on the play button, the elements of the graph will disappear, and the nodes and the arrows representing the actions will appear in order of creation. This section is very useful when the order of the actions is very relevant to the analysis, as in the case of “<em>Parent PID Spoofing</em>“.</p><h4>D. Filtering Arrows and Nodes</h4><p>From this section it is possible to hide some nodes or actions at our convenience. This option is reversible, so do not be afraid to apply it to see more clearly the events.</p><p>After deleting the nodes we are not interested in and making some filtering, it will be much easier to see only what we are interested.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/0*ie11m23dJK4fzZUP.png" /></figure><p>In the image above we see the computer “<em>HR001</em>” executing a Powershell process through a WMI command on the computer “<em>IT001</em>“, to add the user “<em>backdoor</em>“. The “<em>Action Info</em>” information below it is shown when you click on an arrow, offering information about the event it represents.</p><p>The video below shows the animation function on this small graph, so that the order of events can be better appreciated.</p><p>In the section “<em>File List</em>” and “<em>File Upload</em>” it is possible to upload our files, in EVTX format, in JSON format of Elastic events, and in CSV format. Both the JSON and CSV formats are very flexible so it is possible that it gives errors, so it may be necessary to modify the code according to our needs.</p><h3>ElasticSearch section</h3><p>The last part of Grafiki I want to show is the “<em>Elastic</em>” section. This section allows to make graphs of the events stored in our laboratory. To do this, it will be necessary:</p><ul><li>Modify the file “<em>elastic.py</em>” in the path “<em>Grafiki/grafiki/app/static/Python/src/</em>“</li><li>In line 53 and line 58 enter the IP address of HELK.</li></ul><p>Let’s see the options in this section:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/0*JKB2_JS3P5-RVKGf.png" /></figure><p>As seen in the image, the first to be selected is a timeframe, which depending on the amount of data we have in our laboratory will require more or less accuracy.</p><p>Second part are the filters, which allow to limit the data we take to the graph, being able to choose the operator <em>equal </em>or <em>not equal</em>, depending on our needs.</p><p>The filters currently implemented are:</p><ul><li><em>Name of the computer</em>, very useful when the computer to be investigated has been identified.</li><li><em>Sysmon event identifier</em>. For example, in many occasions looking at the type 1 events we can already get an idea of what is happening.</li><li><em>Source IP, destination IP and type of destination IP</em> (private or public), events related to network connection events.</li><li><em>User</em> related to the processes.</li><li><em>Process name</em>, very useful to exclude very noisy processes.</li></ul><p>An important feature that can be seen in the image is the possibility to include several possible values to our filter, separating the elements with commas. The query will be constructed using the logical “OR” operator between those elements, while the “AND” operator will be used between each of the filters.</p><p>And finally, at the bottom it is possible to select whether we want always a processing, and whether we want the events related to Powershell to be processed (beta functionality).</p><p>In the next article we will move to the action with the creation of alerts and creation of playbooks.</p><p>In the meantime, enjoy the lab and happy hunting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c618ef63f7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hunting threats without leaving home — Part III]]></title>
            <link>https://luckyluk3.medium.com/hunting-threats-without-leaving-home-part-iii-87c000e9c5a?source=rss-4268294f29eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/87c000e9c5a</guid>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[threat-hunting]]></category>
            <dc:creator><![CDATA[Luis Francisco Monge Martinez]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 16:48:19 GMT</pubDate>
            <atom:updated>2023-04-10T16:48:19.052Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hunting threats without leaving home — Part III</h3><p>Analizing the data with Kibana</p><p>Hey, hunters! How’s the hunting season going?</p><p>After what we saw in previous posts <a href="https://medium.com/@luckyluk3/hunting-threats-without-leaving-home-part-i-8bc537c80323">Intro I</a> and <a href="https://medium.com/@luckyluk3/hunting-threats-without-leaving-home-part-ii-1cd349ed2574">Intro II</a>, in this article we will continue to understand and improve our Threat Hunting lab.</p><p>We have already learned how to enter our data about real attacks and now we will learn how to exploit that data. Being able to visualize the data in a comfortable way is, along with selecting good data sources, the most important part of a laboratory. All the time we invest in an intuitive and pleasant visualization will be time saved during the analysis.</p><p>Now we are going back to the laboratory, this time we are going to learn how to handle some of the HELK functionalities that we have not seen yet. Hunting like an eagle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-7rhGvLbihCSFZtFlGbkOw.jpeg" /><figcaption>Foto de Pixabay: <a href="https://www.pexels.com/es-es/foto/halcon-marron-y-blanco-458963/">https://www.pexels.com/es-es/foto/halcon-marron-y-blanco-458963/</a></figcaption></figure><h3>The Laboratory — Data Visualization</h3><h4>Kibana Dashboards</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*jKb5KjJEkQmzbwGf.png" /></figure><p>The Kibana dashboards are the visual part offered by the HELK laboratory. From Kibana it is possible to create visualizations and dashboards visually very attractive that allow, at a glance, to know if we are facing something suspicious or not.</p><p>To do this, HELK has several dashboards that we will cover briefly. To see them, click on the icon in the right-hand side menu that says “Dashboard”.</p><h4>1. ALL-MITRE-ATTACK</h4><p>It provides a practical and easy to use visualization of the techniques, tactics, APT groups… available in Mitre ATT&amp;CK. Very useful to quickly see which techniques are attributed to a group or similar needs.</p><h4>2. MITRE-ATTACK-GROUPS</h4><p>This visualization allows the investigation of an APT group by the data about it in Mitre ATT&amp;CK . The dashboard provides a search form and shows a number of very interesting visualizations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/0*OS8Bt-hhVPCyIbdH.png" /></figure><h4>3. Global Dashboard</h4><p>This dashboard offers a quick visualization of all the existing events in the lab in the time range set; this is a very useful dashboard when you do not know what you are looking for.</p><p>For example, it allows you to see quickly if a computer is generating more events than normal, if a process is being very noisy or if more requests are being made to an IP than expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/0*8_PhM-UGACd-_Nm7.png" /></figure><h4>4. Host Investigation Dashboard</h4><p>This board is very useful when you know something has happened on a computer and more detail is necessary about the events related to that computer. The dashboard requires the name of the computer to investigate and the range of dates we are interested in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/0*igZ1muPg4uGlPkOS.png" /></figure><h4>5. Process Investigation</h4><p>As the previous dashboard allowed to investigate a computer, and in this board it is possible to investigate the actions of a specific process using its GUID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/0*548aKq1Tux3lZSby.png" /></figure><h4>6. User Investigation Dashboard</h4><p>Like the previous ones, from here it is possible to investigate the events, but in this case those related by a specific user.</p><h4>7. Sysmon Dashboard</h4><p>This board is the same as the Global Dashboard, but only with the data sent by Sysmon.</p><h4>8. Sysmon Network Dashboard</h4><p>This board allows to investigate events 3 of Sysmon, i.e. those related to network traffic. It makes possible to discover which processes on which computers are making network connections and to which countries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*yugoelgrEN0ZXF_j.png" /></figure><p>Apart from all these, HELK has many other dashboards, without forgetting that Kibana offers the possibility of creating our own in a very comfortable way.</p><p>In the next entry, we will see <strong>Grafiki</strong>, a personal project that allows a visualization of the data with graphs, and I am sure that it will be very useful. Until then, happy hunting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87c000e9c5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hunting Threats without leaving home — Part II]]></title>
            <link>https://luckyluk3.medium.com/hunting-threats-without-leaving-home-part-ii-1cd349ed2574?source=rss-4268294f29eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cd349ed2574</guid>
            <category><![CDATA[laboratory]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[threat-hunting]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[Luis Francisco Monge Martinez]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 16:41:41 GMT</pubDate>
            <atom:updated>2023-04-10T16:42:05.372Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hunting threats without leaving home — Part II</h3><p>Feeding our lab</p><h3>The data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQcNHhLNEQNgT7xUjykyew.jpeg" /><figcaption>Foto de ArtHouse Studio: <a href="https://www.pexels.com/es-es/foto/hombre-cafe-vintage-mirando-4905089/">https://www.pexels.com/es-es/foto/hombre-cafe-vintage-mirando-4905089/</a></figcaption></figure><p><a href="https://luckyluk3.medium.com/hunting-threats-without-leaving-home-part-i-8bc537c80323"><strong>In the last post we set a platform to store the data</strong></a><strong>.</strong> Now we need to feed it with some data. One way would be to install Windows virtual machines, <em>Winlogbeat </em>and <em>Sysmon</em>, but we will do that later. Now I want to talk about Mordor.</p><h3>Mordor</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/0*tIF7MfkegFCsyM-L.png" /></figure><p>This project, also maintained by <a href="https://twitter.com/Cyb3rWard0g">Roberto Rodríguez</a> and <a href="https://twitter.com/Cyb3rPandaH">José Luis Rodríguez</a>, is a repository of pre-recorded events while offensive techniques were executed on laboratory machines.</p><p>As expected, this project integrates perfectly with HELK and provides us with very interesting data to start hunting our threats. So, let’s go.</p><p>We open a new console and download the Mordor repository.</p><pre>git clone https://github.com/Cyb3rWard0g/mordor.git<br>...<br>cd mordor/datasets/small/windows</pre><p>In this folder we have all the datasets organized by Mitre ATT&amp;CK tactics. For this example we are going to use “<em>execution/empire_wmic_add_user.tar.gz</em>“.</p><pre>cd execution<br>tar -xzvf empire_wmic_add_user.tar.gz</pre><p>The decompressing will show us the name of the unpacked file. It is important to look at the date when the events were recorded, so it will be easier to find them afterwards.</p><p>Now we are going to use the tool “<em>kafkacat</em>” to insert our data into ElasticSearch through Kafka.</p><pre>kafkacat -b 192.168.129.137:9092 -t winlogbeat -P -l<br>empire_wmic_add_user_2019-05-18231333.json</pre><p>Now, in order to see the events, we open a browser tab and enter the IP address that HELK gave us at the end of Kibana install. Probably the browser will complain about the certificate; accept and continue. With regard to the password to access Kibana, we enter the one set during the installation, and the user “helk”, getting into the Kibana menu below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/0*iu_xSGewNC0KK0RR.png" /></figure><p>To check that we have our events stored, we access “<em>Discovery</em>“, with a image of a compass. Let’s see briefly what we see in that page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/0*yjoyg5sAs6fcahqp.png" /></figure><ul><li>In the consultation area (“AREA DE CONSULTA”) we create the consultations (fairly obvious).</li><li>In the time area (“AREA DE TIEMPO”) we create time filters based on absolute or relative dates, origin and end.</li><li>The filter area (“FILTROS”) allows for an easy way to filter the data.</li><li>In the index section (“INDICES”), we select the index or group of indexes we want to work on. It accepts wildcards.</li><li>In the results area (“AREA DE RESULTADOS”) we see and organize the obtained results.</li></ul><p>To start to see the data introduced, we set a relative date of 2 years ago and after refreshing (if everything went smoothly), it informs that there are 2196 results between the 6th and the 13th May 2019.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/0*tJCst8x0vsvRxniR.png" /></figure><p>We already have our data to start the hunt. I recommend to spend some time on this part to get familiar with the fields of the events, columns, filters, etc.</p><h3>EVTX-ATTACK-SAMPLES</h3><p>Another essential repository in our library is the one created by <a href="https://twitter.com/SBousseaden">Samir Bousseaden</a>, which together with Mordor are the two most complete repositories available. In this repository, Samir has been collecting Windows events of offensive techniques in “EVTX” format and has organized them by MITRE ATT&amp;CK tactics in more than 200 different files. A real feat.</p><p>To work with this repository, we do the same as before: clone it, and later we will see how to introduce it in our laboratory.</p><pre>git clone https://github.com/sbousseaden/EVTX-ATTACK-SAMPLES.git</pre><p>Since we are dealing with files in EVTX format, we need to format the data to insert it in ElasticSearch. We can make that with the “evtxtoelk” tool.</p><p>With the following commands we download the repository, install Pip and the necessary dependencies.</p><pre>git clone https://github.com/dgunter/evtxtoelk.git<br>cd evtxtoelk/ <br>sudo apt install python3-pip <br>pip3 install –r requirements.txt <br>pip3 install –upgrade requests</pre><p>Once everything installed, we need to modify the file “<em>evtxtoelk.py</em>” and add a “#” to line 98. It should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/0*KJ8uLUtpKrYOx_b5.png" /></figure><p>Save the file and we’re ready to insert the EVTX files into ElasticSearch. We need to provide two parameters to the etxtoelk file: the file we want to enter and the IP address we entered in the HELK installation.</p><pre>python3 evtxtoelk.py /home/luis/EVTX-ATTACK-SAMPLES/Defense\ Evasion/sysmon_10_1_ppid_spoofing.evtx 192.168.129.137:9200</pre><p>If everything went without errors, we got our data in ElasticSearch. However, in order to see it in Kibana we need to make one last adjustment.</p><p>Evtxtoelk creates an index in ElasticSearch called “<em>hostlogs</em>“, that can be modified executing the command with the parameter “<em>-i index_name</em>“. To be able to see the index data, go to the “<em>Management</em>” section of Kibana, the cogwheel on the left menu. Once in the management section, in the Kibana section, click on “<em>Index Patterns</em>” to access the index management page.</p><p>By default all index patterns created by HELK during the installation will show, but we have to create one. We can do that clicking on the blue button “<em>Create index patern</em>“. In the section of “<em>Index pattern</em>” we write “<em>hostlogs*</em>“; if we have set a different name in the index with evtxtoelk we have to use it here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/0*Y5Egp12jYJg0vYWI.png" /></figure><p>Click on “<em>Next step</em>” and once in the next menu, select <em>“@timestamp</em>” and click on “<em>Create index pattern</em>“.</p><p>We created our index pattern. Click on the “<em>Discovery</em>” section, the compass we know, and once there, in the index selector that should now have “<em>logs-*</em>“, we select the new created “<em>hostlogs</em>” pattern. Maybe we need to tweak with the time window so that it shows our events, but in the end we see something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/0*KnNjLgljsJRXl6mD.png" /></figure><p>So… Congratulations! We now have everything needed to start inserting attack data and begin your search and learning. In the next article we will continue talking about the advantages of HELK and install Grafiki to get more out of our events.</p><p>I hope you enjoy the lab and that the hunting season begins!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cd349ed2574" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hunting threats without leaving home — Part I]]></title>
            <link>https://luckyluk3.medium.com/hunting-threats-without-leaving-home-part-i-8bc537c80323?source=rss-4268294f29eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bc537c80323</guid>
            <category><![CDATA[laboratory]]></category>
            <category><![CDATA[threat-hunting]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Luis Francisco Monge Martinez]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 16:36:42 GMT</pubDate>
            <atom:updated>2023-04-10T17:11:05.382Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hunting threats without leaving home — Part I</h3><p>Intro</p><p>Many times, talking to friends who work in other professions, I tell them how lucky we are, those of us who work in the IT industry. We, unlike 99% of the occupations, can create realistic environments for testing, learning, practicing… and when we are done with those environments we can destroy them and the expense of material will have been zero. How lucky we are!</p><p>Those of us who are passionate about computer security are even luckier; since its inception the cybersecurity community has been characterized by its defense of information freedom, free software and collective learning, which has made us the best time in history to learn about cybersecurity.</p><p>In this case, I want to make a guide to be able to build a Threat Hunting lab from home and at zero cost (not counting the investment of our computer).</p><p>Before we get started, let’s make a brief introduction about Threat Hunting, as it is important to settle the foundations of our laboratory.</p><h3>1. What is Threat Hunting?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_dv6-W6haT7Rp0EH4_EeDg.jpeg" /><figcaption>Foto de Julia Volk de Pexels: <a href="https://www.pexels.com/es-es/foto/pajaro-negro-en-la-rama-de-un-arbol-marron-6408365/">https://www.pexels.com/es-es/foto/pajaro-negro-en-la-rama-de-un-arbol-marron-6408365/</a></figcaption></figure><p>I once heard that if you want to know what Threat Hunting is and ask three experts, you will have four different opinions. Within the contemporary world of cybersecurity, Threat Hunting is one of the most recent disciplines and that makes both companies and researchers face it in a different way.</p><p>What everyone agrees on is that it takes companies a long time to discover that they have been compromised, and the average time between a breach and the discovery of the incident is six months. Why so much time to discover an intrusion? We could be talking for hours about this, about whether antivirus systems are prepared to face modern threats, about whether system administrators are sufficiently prepared or even whether or not it should be their responsibility to defend the organization… but no.</p><p>One of the things that characterizes Threat Hunting is the change in the research paradigm.</p><p>Traditional security assumes that the organization is protected, and the job is to keep it that way by creating rules, whether it be about a hash of a file, an IP address, an access to a route, a command… most of the time to control that no one enters the organization. When crossed against the events of a system, these rules generate alerts that an analyst evaluates whether or not they are false positives.</p><p>Threat Hunting works differently. We start from the assumption that someone has used a certain technique in the organization and our job is to check by all possible means if we are right or not. We have introduced the concept of “technique”, which brings us the currently so called TTPs (Tactics, Techniques and Procedures). This is a topic that we will not go into at the moment, but of course I invite you to go to Mitre ATT&amp;CK’s page and discover this wonderful project.</p><p>As you can imagine, there are hundreds of techniques and for each one, several ways to detect them or several sources of information that we can use to detect them.</p><p>Although there are many possible approaches to Threat Hunting, in this series of articles we are going to focus on two main lines, the one based on network traffic analysis and the one based on computer event analysis. We already have some clear concepts so we are going to get down to work.</p><h3>2. The events</h3><p>Windows collects a lot of information in the form of default events and a lot of other information that we can configure. To work with them, Windows offers the tool “<em>EventVwr</em>” or “<em>Event Viewer</em>“. Let’s quickly mention the most interesting types of events from the point of view of Threat Hunting.</p><h4>Security Logs</h4><p>Perhaps one of the most important that we can analyze. In these events many actions of users, programs and services that occur on the computer are recorded. We have from events related to files to special permissions assigned to a login. <a href="https://www.ultimatewindowssecurity.com/securitylog/encyclopedia/">Here is a link to a list of events that is very useful to have close by</a>.</p><h4>Powershell</h4><p>To find these events, it will be necessary to search for them in the path “<em>Application Records/Microsoft/Windows/Powershell/Operational</em>“.</p><p>Here we can see some information, but in order to see as much information as possible for each PowerShell session we need to activate the “<em>PowerShell Transcript</em>“. This will allow us to know not only the commands executed in Powershell, but also the responses of those commands. <a href="https://www.yeahhub.com/turn-powershell-transcription-logging-windows-10/">Here is a link to a Powershell tutorial to activate it</a>.</p><h4>Sysmon</h4><p>Here is the crown jewel. <em>Sysmon </em>is a project within the <em>Sysinternals </em>suite. It is composed of a driver and a service, the driver is in responsible for monitoring the equipment waiting for certain calls to the system and when it detects them, it generates events.</p><p>Anyone could think that if we already have the events of the system itself, why generate new events? The native events of Windows are too diverse and in many cases it is very hard to work with them; however Sysmon currently offers 23 types of events, making the work much easier for the analyst.</p><p>I leave you the <a href="https://docs.microsoft.com/en-us/sysinternals/downloads/sysmon">link to the Sysmon documentation</a> where all the events are discussed.</p><h3>3. The Laboratory 🧪</h3><p>Although as we have mentioned before there are two approaches to Threat Hunting, one based on network traffic analysis and the other based on team events, we are going to focus initially on the second one and for that we are going to install the HELK project.</p><h4>HELK</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*KDM8qEsIAJvdT7jj.png" /></figure><p><a href="https://twitter.com/cyb3rward0g?lang=es">HELK is a project developed by Roberto Rodriguez</a> and based on the architecture of Elastic Seach, Logstash and Kibana, although it is much more than that, as you can see in the image.</p><p>For the installation of the laboratory we will need a Linux machine, preferably Ubuntu, and depending on the characteristics we want in our laboratory with different specifications. But first we are going to talk about what features it offers so that we can choose later.</p><h4>Kafka and KSQL</h4><p>This is an information reception system, specialized in concurrence and fault tolerance; it allows our laboratory to receive information from many systems without this being a problem. It will also serve to add information from datasets, but we will talk about that later.</p><p>KSQL is the technology that will allow Kafka’s data to be consumed.</p><h4>ELK</h4><p>Elastic Search, Logstash and Kibana. It is increasingly difficult not to build an architecture like this into a project and a growing number of free software projects are based on it.</p><ul><li><strong>ElasticSearch </strong>is a non-relational database; its greatest power lies in the indexing of large amounts of data, its distributed architecture and its API.</li><li><strong>Logstah </strong>is in charge of preparing the data to be stored in ElasticSearch: grouping, organizing, enriching… everything is possible in logstash.</li><li><strong>Kibana </strong>is the visual part of this architecture; from it we can create queries and visualizations about our data.</li></ul><h4>Elastalert</h4><p>Elastalert allows the creation of rules on the data we have in ElasticSearch and to be able to generate alerts of many types, we will talk about it more in detail.</p><h4>Spark and Jupyter</h4><p>Spark is a framework that allows to execute Jupyter playbooks and that will allow to generate playbooks with the intelligence that we take out of our investigations. We will work with it also later.</p><h3>4. Installation</h3><p>Once we know the most essential parts of the project we will talk about the different installation methods that HELK allows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*jYArGIWV6nDcPOZ0BPLF2w.png" /></figure><p>To start the installation we’ll download the Github project with Git and run the installer:</p><pre>git clone https://github.com/Cyb3rWard0g/HELK.git<br>…<br>cd HELK/docker</pre><p>The installation uses Docker containers, but we don’t have to worry about it, HELK will install it if we don’t have it. We’re going to make a change in a configuration file so we can work with Grafiki more comfortably later.</p><p>During this tutorial we are going to install the full HELK, so we will need to modify the file “<em>helk-kibana-notebook-analysis-alert-basic.yml</em>” in the “<em>HELK/docker</em>” location. On line 20, we will add the configuration so that port 9200 is open to the outside of the Docker container. It should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/0*wxgy2rPOxIJGKNbB.png" /></figure><p>Once this detail has been modified, we will proceed with the installation.</p><pre>sudo ./helk_install.sh</pre><p>The installation script will ask what installation option we want and we will choose option 4. Remember that the installation machine must have more than 8GB of RAM. Then it will ask for the IP address we want in the installation, and we will choose the default one. Then it will ask for a password to allow access to Kibana and that’s all; we will wait until the installation is finished. It will show something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/0*iYmJqrFHSkDQDJes.png" /></figure><p>Save this data in a handy place because it will be needed later.</p><p>So far, so good 😉 We already have our research panel deployed! And now that we already have a platform to store the data we have to get data… but we’ll see that in the <a href="https://medium.com/@luckyluk3/hunting-threats-without-leaving-home-part-ii-1cd349ed2574">next entry</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bc537c80323" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hunting Office Macros with Sysmon and Pandas.]]></title>
            <link>https://luckyluk3.medium.com/hunting-office-macros-with-sysmon-and-pandas-46fe0c24357e?source=rss-4268294f29eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/46fe0c24357e</guid>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[office]]></category>
            <category><![CDATA[digital-threats]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Luis Francisco Monge Martinez]]></dc:creator>
            <pubDate>Fri, 02 Dec 2022 10:45:42 GMT</pubDate>
            <atom:updated>2022-12-29T10:56:11.772Z</atom:updated>
            <content:encoded><![CDATA[<p>Using Pandas and Jupyter everywhere 🐼🪐</p><p>During these last months I have been studying the course <a href="https://www.sans.org/cyber-security-courses/defensible-security-architecture-and-engineering/">SEC530: Defensible Security Architecture and Engineering: Implementing Zero Trust for the Hybrid Enterprise</a>, during this course and certification there are different ways to implement a methodology oriented to “Zero Trust” and among the topics Office macros are mentioned.</p><p>It’s funny how when you talk about office macros, those of us in the security field get a shiver down our spine. We all know that there are multiple ways to secure a company against them, but one thing I am sure of is that, if it were up to us, we would all prefer to have macros disabled in our organization.</p><p>For better or worse, these decisions have to be very well motivated and, above all, the impact on the company has to be very well measured before any decision can be made.</p><p>To audit the use of macros there are not many options if we do not have cloud services such as O365 but we will try it.</p><p>Let’s start the adventure.</p><h4>First try, file extension.📓</h4><p>The easy approach might be to search our organization for files with macros by searching for the file extension, but it’s never that easy.</p><p>One thing that is important to know, and a lot of people don´t know, is that in order for an Office file to contain macros it must have very specific file extensions and other extensions are incompatible with them.</p><p>For many years, Microsoft wanted to identify documents containing macros with the letter “m” in the extension as docm, xlsm… and making it impossible to run macros in the new extensions containing the letter “x” at the end as docx, xlsx… but as always with Microsoft, backward compatibility did its thing here.</p><p>In the office 97–2003 document format we are allowed to store and run macros while keeping simple extensions like doc, xls… making it impossible for security analysts to know if a document can contain macros or not only using the file extension.</p><h4>Second try, Sygma rule and Sysmon 💻</h4><p>After a conversation with other professionals, they suggest me a <a href="https://github.com/NVISOsecurity/sigma-public/blob/master/rules/windows/sysmon/sysmon_susp_winword_vbadll_load.yml">Sygma rule written by Florian Roth</a>. In this rule is it possible to see that there are 3 libraries that office loads when the a file has VBA macros.</p><ul><li>‘*\VBE7.DLL*’</li><li>‘*\VBEUI.DLL*’</li><li>‘*\VBE7INTL.DLL*’</li></ul><p>Researching more I found that there is also another possible detection and it is the registry modification in HKEY_CURRENT_USER\Software\Microsoft\Office\[office_version]\Excel\Security\Trusted Documents\TrustRecords.</p><p>This looked promising if you have Sysmon or you can deploy it.</p><pre>&lt;RuleGroup name=&quot;&quot; groupRelation=&quot;or&quot;&gt;<br>  &lt;ImageLoad onmatch=&quot;include&quot;&gt;<br>    &lt;Rule name=&quot;Potential Macro file opened&quot; groupRelation=&quot;or&quot;&gt;<br>      &lt;ImageLoaded condition=&quot;end with&quot;&gt;vbeintl.dll&lt;/ImageLoaded&gt;<br>      &lt;ImageLoaded condition=&quot;end with&quot;&gt;vbe7.dll&lt;/ImageLoaded&gt;<br>      &lt;ImageLoaded condition=&quot;end with&quot;&gt;vbeui.dll&lt;/ImageLoaded&gt;<br>    &lt;/Rule&gt;<br>  &lt;/ImageLoad&gt;<br>&lt;/RuleGroup&gt;<br>&lt;RuleGroup name=&quot;&quot; groupRelation=&quot;or&quot;&gt;<br>  &lt;RegistryEvent onmatch=&quot;include&quot;&gt;<br>    &lt;TargetObject name=&quot;T1060,RunKey&quot; condition=&quot;contains&quot;&gt;Documents\TrustRecords&lt;/TargetObject&gt;<br>  &lt;/RegistryEvent&gt;<br>&lt;/RuleGroup&gt;</pre><p>It seemed like a solved case, but when you have to modify a Sysmon configuration file in an organization with thousands of machines, it’s worth double or ten times to check that everything works as expected 😊.</p><p>It occurred to me to test the Sygma rule with different office files and test what happened if these files were downloaded or not and these were the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*iulwmxgoba3Sg3Z0yScZqw.png" /><figcaption>Results.</figcaption></figure><p>It seems that our second approach is not valid neither. Although the VBE7.dll and VBEUI.dll libraries serve to identify files with locally created macros, when a file is downloaded from the internet, these libraries are loaded as well, even if the file does not contain macros.</p><p>The culprit for this behavior is the <em>Mark-of-the-Web</em> (<em>MOTW</em>) or the alternate data stream added to files when are downloaded via web browser, which causes the files to be opened in a protected view.</p><p>Since this first attempt did not work, I thought I would try to use the same approach but with a broader scope, i.e. look at all the libraries loaded by Excel in each of these executions and observe their differences.</p><h4>Third and last try, Python and Pandas 🐼 🔥</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UOazIMiURsJvEwjnO3Thcg.jpeg" /><figcaption>Foto de Erik Mclean: <a href="https://www.pexels.com/es-es/foto/ciudad-carretera-hombre-arte-4065797/">https://www.pexels.com/es-es/foto/ciudad-carretera-hombre-arte-4065797/</a></figcaption></figure><p>Anyone who has played with Procmon and the loading of libraries will know that this can be a bit tedious as each Excel run loads hundreds of libraries. To help us in this task we have our third protagonist Python with his faithful friend Jupyter 😊.</p><p>We will use Sysmon and DLL loading events to find differences between Office executions, this way we could identify differences that could indicate that an open document contained macros or not, independently of its extension.</p><p>First the Sysmon rule to monitor the libraries loaded by the Excel file during the opening of a document.</p><pre>&lt;RuleGroup name=&quot;&quot; groupRelation=&quot;or&quot;&gt;<br>  &lt;ImageLoad onmatch=&quot;include&quot;&gt;<br>    &lt;Rule name=&quot;Image Loaded by Excel&quot; groupRelation=&quot;or&quot;&gt;<br>      &lt;Image condition=&quot;end with&quot;&gt;excel.exe&lt;/Image&gt;<br>    &lt;/Rule&gt;<br>  &lt;/ImageLoad&gt;<br>&lt;/RuleGroup&gt;</pre><p>When I was thinking about tests I would like to do, I realized that compare the libraries that loaded each of the use cases was going to be very tedious so I decided to use Python and a Jupyter Notebook to be able to automate and compare results easily and because I have fun with it 😆.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Z0DIfmMH2Bv0eFTP25PvEg.jpeg" /><figcaption>Makeameme <a href="https://makeameme.org/meme/PANDAS-PANDAS-EVERYWHERE">https://makeameme.org/meme/PANDAS-PANDAS-EVERYWHERE</a></figcaption></figure><p>To parse the resulting EVTX files from Sysmon we are going to use the <a href="https://pypi.org/project/evtx/">PyEvtxParser</a> library, an old acquaintance that was very useful to me in the past when I wrote <a href="https://github.com/lucky-luk3/Grafiki">Grafiki</a>. Here you can find <a href="https://github.com/lucky-luk3/Infosec_Notebooks/blob/main/Office_loads_Macros.ipynb">this Notebook on my Github</a> among others.</p><pre>def evtx_folder_to_dataframes(directory):<br>    dataframes_list_seven = {}<br><br>    for filename in os.listdir(directory):<br>        f = os.path.join(directory, filename)<br>        if os.path.isfile(f):<br>            events_one_five = []<br>            events_seven = []<br>            a = open(f, &#39;rb&#39;)<br>            parser = PyEvtxParser(a)<br><br>            for record in parser.records_json():<br>                event = json.loads(record[&#39;data&#39;])<br>                #Image loaded<br>                if event[&quot;Event&quot;][&quot;System&quot;][&quot;EventID&quot;] == 7:<br>                    event_list = [event[&quot;Event&quot;][&quot;EventData&quot;][&quot;UtcTime&quot;],<br>                    event[&quot;Event&quot;][&quot;System&quot;][&quot;EventID&quot;],<br>                    event[&quot;Event&quot;][&quot;EventData&quot;][&quot;ImageLoaded&quot;],<br>                    event[&quot;Event&quot;][&quot;EventData&quot;][&quot;FileVersion&quot;],<br>                    event[&quot;Event&quot;][&quot;EventData&quot;][&quot;Description&quot;],<br>                    event[&quot;Event&quot;][&quot;EventData&quot;][&quot;Product&quot;],<br>                    event[&quot;Event&quot;][&quot;EventData&quot;][&quot;Company&quot;],<br>                    event[&quot;Event&quot;][&quot;EventData&quot;][&quot;OriginalFileName&quot;],<br>                    event[&quot;Event&quot;][&quot;EventData&quot;][&quot;Hashes&quot;],<br>                    event[&quot;Event&quot;][&quot;EventData&quot;][&quot;Signed&quot;],<br>                    event[&quot;Event&quot;][&quot;EventData&quot;][&quot;Signature&quot;],<br>                    event[&quot;Event&quot;][&quot;EventData&quot;][&quot;SignatureStatus&quot;]]<br>                    events_seven.append(event_list)<br>            name = filename.split(&quot;\\&quot;)[-1].split(&quot;.&quot;)[-2]<br><br>            df_7 = pd.DataFrame.from_records(events_seven,<br>                                   columns=[&#39;UtcTime&#39;,&#39;EventID&#39;, &#39;ImageLoaded&#39;, &#39;FileVersion&#39;, &#39;Description&#39;,<br>                                            &#39;Product&#39;, &#39;Company&#39;, &#39;OriginalFileName&#39;, &#39;Hashes&#39;, &#39;Signed&#39;,<br>                                           &#39;Signature&#39;, &#39;SignatureStatus&#39;])<br>            dataframes_list_seven[name] = df_7<br>            <br>    return dataframes_list_seven</pre><p>Once we have our list of events, we’ll turn to Pandas to make it easier to work with the data we have.<br>Let’s start watching how many unique libraries are loaded in each opening.</p><pre>df_count = pd.DataFrame(index=list(dataframes_list_seven.keys()), columns=[&quot;Count&quot;])<br>for e in list(dataframes_list_seven):<br>    df_count[&quot;Count&quot;][e] = dataframes_list_seven[e][&quot;ImageLoaded&quot;].nunique()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*_UHegDBYCXfROQ2Y2_x2hw.png" /><figcaption>DLL count results</figcaption></figure><p>As we can see in the image, when the document has macros or has been downloaded, the number of libraries is significantly higher.</p><p>The next question we ask ourselves is, will there be different libraries between these executions that allow us to determine that a document has macros?</p><p>To do this, what we are going to do is to make a comparison between all the measurements, thereby creating a comparative table that will allow us to detect anomalies. In the left part of the table we will have the base of our comparative, that is to say the part “Which libraries contains this execution” and in the upper part “Which does not contain this execution”.</p><p>For this we will use this simple function that allows us to make a comparative of DataFrames and we will only keep the ones that are in the first operator.</p><pre>def compare_df(df_in, df_not_in):<br>    list = df_in.merge(df_not_in.drop_duplicates(), <br>                       on=[&#39;ImageLoaded&#39;], <br>                       how=&#39;left&#39;, <br>                       indicator=True) <br>    list_min = list[list[&#39;_merge&#39;] == &#39;left_only&#39;][&quot;ImageLoaded&quot;].unique()<br>    return(list_min)<br><br>df = pd.DataFrame(index=list(dataframes_list_seven.keys()), columns=list(dataframes_list_seven.keys()))<br><br>for e in list(dataframes_list_seven.keys()):<br>    for i in list(dataframes_list_seven.keys()):<br>        list_min = compare_df(dataframes_list_seven[e], dataframes_list_seven[i])<br>        df[i][e] = len(list_min)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a-vqaseljKh3R_9FblL8mg.png" /><figcaption>Comparation result</figcaption></figure><p>The results speak for themselves and the first column allows us to draw a quick conclusion, a downloaded document without macros contains at least the same libraries as the rest of the tests 😞 with the exception of Office 1997–2003 documents with macros that contain an additional library.</p><p>At this point we can draw the conclusion that this way is not valid for detecting Office documents with macros. A great discovery that can save us from spending much more time implementing rules, analysing results and drawing conclusions on data that we believed to be reliable.</p><h4>Bonus 🎯</h4><p>As the idea with Jupyter is to generate reusable documents. We are going to implement a small menu that will help us to see in detail each of the comparisons.</p><p>Maybe in this case it is not very relevant but this notebook is easily adaptable to monitor other types of executions detecting for example differences in network connections, registry key modifications, creation of named pipes…</p><pre>def compare_events():<br>    import ipywidgets as widgets<br>    from IPython.display import display, Markdown, clear_output<br>    pd.set_option(&#39;display.max_rows&#39;, 500)<br>    output = widgets.Output()<br>    dfs = list(dataframes_list_seven.keys())<br>    columns = dataframes_list_seven[list(dataframes_list_seven.keys())[0]].columns<br>    in_widget = widgets.Dropdown(<br>                        options=dfs,<br>                        description=&#39;Events in:&#39;,<br>                        disabled=False)<br>    not_in_widget = widgets.Dropdown(<br>                        options=dfs,<br>                        description=&#39;And not in:&#39;,<br>                        disabled=False)<br>    columns = widgets.Dropdown(<br>                        options=columns,<br>                        description=&#39;Column:&#39;,<br>                        disabled=False)<br>    button = widgets.Button(description=f&#39;List&#39;)<br>    display(in_widget, not_in_widget, columns, button, output)<br><br>    def _click_function(_):<br>        with output:<br>            clear_output()<br>            list = dataframes_list_seven[in_widget.value].merge(dataframes_list_seven[not_in_widget.value].drop_duplicates(), <br>                                                          on=[&#39;ImageLoaded&#39;], <br>                                                          how=&#39;left&#39;, <br>                                                          indicator=True) <br>            list_min = list[list[&#39;_merge&#39;] == &#39;left_only&#39;][columns.value].unique()<br>            display(len(list_min))<br>            display(pd.DataFrame(list_min).style.set_properties(**{&#39;text-align&#39;: &#39;left&#39;}))<br><br>    button.on_click(_click_function)</pre><p>With this function we can generate a menu that allows us to see the difference between two of the results taking into account the selected column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*x7fYRYPAornaIQxfqwPFqQ.png" /><figcaption>Compare menu</figcaption></figure><p>I hope you liked it and that, as I did, you don’t trust my results and you dare to try it by yourselves, if you do it and the results are different, please let me know 😊</p><p>See you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46fe0c24357e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Data Science Could Make Cybersecurity Troubleshooting Easier: Firewall Logs Analysis]]></title>
            <link>https://medium.com/data-science/how-data-science-could-make-cybersecurity-troubleshooting-easier-firewall-logs-analysis-591e4832f7e6?source=rss-4268294f29eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/591e4832f7e6</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[notes-from-industry]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[incident-response]]></category>
            <dc:creator><![CDATA[Luis Francisco Monge Martinez]]></dc:creator>
            <pubDate>Thu, 19 Aug 2021 15:52:28 GMT</pubDate>
            <atom:updated>2021-08-19T21:19:09.945Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/notes-from-industry">Notes from Industry</a></h4><h4>Improving incident response ops. with data analysis techniques and tools.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5NujfDi9FxGat_-ps0XH-A.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@pixabay?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pixabay</a> from <a href="https://www.pexels.com/photo/backlit-breathing-apparatus-danger-dangerous-279979/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>Without a doubt we are in the information age, there have never been so many sources of information and in the cybersecurity sector it is no different.</p><p>When someone starts working in data analysis he constantly hears that most of the time is spent in processing, correcting and standardizing the data before working with it. This could be a trivial operation if the different manufacturers would use standardized logs, if they were consistent between their different products or even if the log format was easily processable… how nice it would be…😍</p><p>In the real world this is not the case, in incident response every customer is different and it is very common to have to fight with logs of all kinds.</p><p>One of the most useful logs in a large-scale incident are the firewall logs, which provide information on network connections to and from the outside, internal organizational traffic and in some cases even VPN access by users.</p><p>In my experience, one of the most common manufacturers I encounter is Fortinet. This company’s firewalls are very common and have a type of log that, although common, is terrifying to process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*f3rNUDk9ZwVqeYA-kIVN7w.png" /><figcaption>Fortinet logs example</figcaption></figure><p>This kind of logs is the nightmare of bash and awk lovers and for those of us who like to go further, it can be an opportunity to explore and make understand the importance of data analysis tools 😉.</p><p>In this case, the VPN traffic of a single site of a medium-sized organization will be analyzed. During one week, 14 million VPN traffic events were generated.</p><h3>First step — transformation to CSV</h3><p>Since the mission is to work from Pandas with the logs in order to obtain evidence, we need the logs in a format that Pandas can read.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddec9a0241bf3cd9ddcff8e47e8ac9dc/href">https://medium.com/media/ddec9a0241bf3cd9ddcff8e47e8ac9dc/href</a></iframe><p>This function allows us to extract the titles and fields of each line of the file as follows:</p><ul><li>Extraction of attribute groups by capturing separately the data key, the separator(s) and the data. In this way, for each line we will be able to separate what are the data and what are the keys.</li><li>Assign the same index to all values.</li><li>Since there are fields that have separators, three groups are generated. It is necessary to group the results in a single column eliminating the null results.</li><li>Generate a single row with the data, using column 0 for titles and column 1 for values.</li></ul><p>The following function can be used to iterate between the files of an entire folder and read and create a Pandas DataFrame line by line:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e95c78e7904d5a5943f49df9d7a7723c/href">https://medium.com/media/e95c78e7904d5a5943f49df9d7a7723c/href</a></iframe><p>This function does nothing special, it only creates a DataFrame in the first line of the log and adds each of the lines once processed.<br>Once it has finished with all the lines, it generates a CSV file in the indicated folder and deletes the originated DataFrame to free memory.<br>This function can be easily modified so that the DataFrame generated is maintained during the processing of all the files and at the end we have the data in memory.</p><p>These last two functions can be executed in parallel to achieve greater processing efficiency. For this, it is necessary to store them in a separate file to be able to execute the multiprocesing library correctly from Jupyter.<br>After that we can execute the following code to carry out the task in a parallelized way.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d620e360b8434f9f4b4c660e2d3c7f0/href">https://medium.com/media/9d620e360b8434f9f4b4c660e2d3c7f0/href</a></iframe><p>In order to continue, there are two main drawbacks. In the first place, the number of columns that each file has, since due to the type of logs, there are files that contain different columns and, secondly, the amount of memory necessary to process all the records. Let’s go step by step 🏃🏻.</p><h4>Adjusting columns with <strong>d6tstack</strong></h4><p>Due to the type of log formats, it is very common to find that there is a different number of columns in the files and this is not compatible with the data analysis libraries.<br>To fix this there is a library called <strong>d6tstack</strong>. <br>This library performs an analysis of the csv files and tells us which columns are present in each of the files and which are not.</p><pre>import glob<br>import d6tstack.combine_csv</pre><pre>cfg_fnames = list(glob.glob(r&#39;C:\logs_vpn_out\*.csv&#39;))<br>c = d6tstack.combine_csv.CombinerCSV(cfg_fnames)</pre><pre># check columns<br>print(&#39;all equal&#39;,c.is_all_equal())<br>print(&#39;&#39;)<br>d = c.is_column_present()</pre><p>And the output will be something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*XVY7gAbk9F_pOjFOHazTPg.png" /><figcaption>Dask columns inspection</figcaption></figure><p>To correct it, the library itself offers the possibility to rewrite the data in new files with the fixed columns.</p><pre>fnames = d6tstack.combine_csv.CombinerCSV(cfg_fnames).to_csv_align(output_dir=r&#39;C:\logs_vpn_out_fix&#39;)</pre><p>Once fixed we can move on to the next phase, reading the files.</p><h4>Fighting the need for memory 💪💻</h4><p>This is a very common problem in data analysis, we have a lot of data and not enough RAM to process it.<br>When our mission is to store standardized information on a recurring basis, we usually choose to store the information in a database such as Spark, Elastic… but in the case of incident response it is common to have to quickly analyze a type of event that it is very likely that we will never see again.</p><p>In order to deal with these situations there is Dask.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6AN-9HfEJ39LHbh-EKDtuA.png" /><figcaption><a href="https://dask.org/">https://dask.org/</a></figcaption></figure><p>This data analysis library offers us the possibility to perform queries on log files in a parallelized way using the resources of our computer. <br>In other words, it allows us to work efficiently with large amounts of data without having to load them into memory.</p><p>When you are used to work with Pandas, the process of reading files is fast, but time consuming, it is surprising that when reading files with Dask, the response is instantaneous.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*L275KtLNHzIp04o4eimhrA.png" /><figcaption>Dask DataFrame creation</figcaption></figure><p>It is important that at this point Dask has not read the files, it has divided the data by the indexes and will read them when it needs to, that is why it is so fast at this stage.<br>The <em>df </em>object is not a <em>Pandas.DataFrame</em> is a <em>Dask.DataFrame</em>, it is important not to forget it.<br>During the creation of the DataFrame it is very useful to mark the data type of each column to speed up the query and to avoid problems.</p><p>One of the most common use cases in log analysis is the search for exfiltration of information during an incident. To do this, we will perform a query with Dask to obtain a small subset of data that we can work with comfortably in memory.</p><pre>df_exf = df[[&quot;remip&quot;, &quot;tunnelid&quot;, &quot;sentbyte&quot;]].groupby([&quot;remip&quot;,&quot;tunnelid&quot;]).max().compute()</pre><p>This query took 1 minute and 28 seconds to run, this is where the big difference between Pandas and Dask lies. In Pandas this query would have been much faster, if the data would have fit in memory 😅.<br>The <strong>.compute()</strong> function allows the creation of a Pandas DataFrame with the Dask result.</p><p>In 1 minute and 28 seconds we have made a query on 14 million logs, we have made a grouping of them and we have it in a DataFrame, Dask is awesome!</p><p>The query does not make much sense if you do not know how such logs are recorded. Each time a user makes a session to another IP address over the VPN, a unique identifier called <em>tunnelid </em>is assigned. In the <em>sentbyte </em>field, the amount of information leaving the organization during that session is recorded, but instead of recording the number of bytes in each of the connections, they are reflected cumulatively, so that only the highest value of all the connections made during a session is taken into account.</p><p>To facilitate the reading of the information in bytes, I will use this code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06007ca5b9556e8fc6ca8f9620946f63/href">https://medium.com/media/06007ca5b9556e8fc6ca8f9620946f63/href</a></iframe><p>The first two IP addresses are legitimate and are not relevant for research. This would be the graph of the first 5 IP addresses to investigate.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e88ff3b3f65d3b0dcd6076dedf3dba8a/href">https://medium.com/media/e88ff3b3f65d3b0dcd6076dedf3dba8a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*509euad0QYBmr9yn5rJByQ.png" /><figcaption>Infomation sent to external IPs</figcaption></figure><p>At this point it is necessary to enrich the data we have. For this we are going to use several free services, MaxMind GeoIP, MaxMind ASN, AbuseIPDB and Dan Tor List.</p><h4>MaxMind ASN</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*1sLrddfuwqY-FChROk7NsQ.png" /><figcaption><a href="https://www.maxmind.com/en/home">https://www.maxmind.com</a></figcaption></figure><p>This service will allow us to obtain the AS of the IP addresses we need. The company MaxMind offers a database that we can download and consult offline in a very fast way.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dfeec71352b8ef4765b7da6a8484dfa/href">https://medium.com/media/4dfeec71352b8ef4765b7da6a8484dfa/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*217Xj_1nclPy_e25xoSsFw.png" /><figcaption>IP adress ASN</figcaption></figure><p>With this function we will be able to obtain the name of the company to which the IP addresses of the events belong.</p><h4>MaxMind GeoIP</h4><p>The same company offers an IP geolocation database that allows us to know the location of an IP address quite reliably.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c56bb09382e27418bbdc21d7a89352a/href">https://medium.com/media/4c56bb09382e27418bbdc21d7a89352a/href</a></iframe><p>In the same way we will be able to know the locations of the IPs of our connections.<br>On a map you can always see everything better 😏.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*Hfdx6yaqNmTmpBaFC3a6Hw.png" /><figcaption>Amount of data by country</figcaption></figure><h4>Dan Tor Node List</h4><p>It is quite common for attackers to use Tor network nodes to anonymize their communications and sometimes it can be a quick check that gives us a good lead to follow.<br>An updated list of Tor nodes can be found at the website <a href="https://www.dan.me.uk/torlist/">dan.me.uk</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70b4a8910cba109ec839d11b1e438332/href">https://medium.com/media/70b4a8910cba109ec839d11b1e438332/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*E755b1tNvDCdbHf7J3ha9w.png" /><figcaption>Tor node communications</figcaption></figure><p>Although they are not related to data exfiltration, they will be connections that will have to be checked for legitimacy.</p><h4>AbuseIPDB</h4><p>AbuseIPDB is a well-known domain and IP address reputation service. Through its API it allows us to perform 1,000 queries per day for free.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a35fe7afe1058512b184cc622d4a8e20/href">https://medium.com/media/a35fe7afe1058512b184cc622d4a8e20/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9-dTRGSzwidGvWN3IDWevg.png" /><figcaption>AbuseIPDB IP adress</figcaption></figure><p>In this case, we see multiple connections to IP addresses with a very bad reputation and which will have to be analyzed to verify their legitimacy.</p><p>At this point we are going to make a new query in order to perform new visualizations of the data to try to identify anomalies.</p><pre>df = df_dask[~df_dask[“tunnelid”].isnull()][[“remip”, “duration”, “tunnelid”,”sentbyte”]].compute()</pre><p>This query will return a subset of all the data, and through the following code we will get.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31cc788e267a012826599a568a5e86d2/href">https://medium.com/media/31cc788e267a012826599a568a5e86d2/href</a></iframe><p>Now we have 4 variables to draw graphs, number of tunnels created to a specific IP address, number of total connections made to each IP address, the sum of the duration of the connections made to each IP address and the number of bytes sent.<br>Firstly, if we make a graph relating number of connections and total duration the resulting graph will be this one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*7L2_vIsbtCcPqa8pV44q7w.png" /><figcaption>Connections VS Duration</figcaption></figure><p>In red I have highlighted the IP addresses that were used in the exfiltration of the data and that would be one of our targets.<br>Considering the data displayed, the malicious IPs have been hidden among most of the other connections, but this graph can help us to detect two types of anomalies very common in cybersecurity. <br>On the one hand, in the upper left part, IP addresses to which many connections of short duration are made will be reflected, as would be the case of Cobalt Strike beacons for example, and in the lower right part, long connections such as SSH or RDP connections will appear.</p><p>In the following graph we are going to relate the data sent with the duration of the connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*zRzLT_xK3v01ipJbKVp7RQ.png" /><figcaption>Sent data vs Duration</figcaption></figure><p>As you can see, this is the perfect graph to detect a large amount of information exfiltration. In the upper left corner we will show the IP addresses to which short connections have been made but which have sent a lot of information.<br>Finally, we will visualize the ratio between information sent and number of connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*Lm3u2Tp8lBewJM2Km3EgMw.png" /><figcaption>Sent data vs connections</figcaption></figure><p>This graph can help us to visualize both data exfiltration in few connections such as uploading files to the cloud or sending files via SSH, as well as data exfiltration in covert channels such as DNS or ICMP, since we would see many connections and a somewhat high number of information sent.<br>To finish the article, we will perform a more advanced analysis to try to detect anomalies in the connections using the four variables at the same time.</p><h4>PCA — Principal Component Analysis</h4><p>Simplifying it a lot, this Machine Learning technique will allow us to perform a reduction of dimensions without losing the uniqueness of our data.<br>We will go from having four dimensions to two, in such a way that we will be able to represent it graphically and try to visualize anomalies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1250bc01545838363e5e412e7d5dd29/href">https://medium.com/media/a1250bc01545838363e5e412e7d5dd29/href</a></iframe><p>As you can see in the code, a reduction to two dimensions is performed and then the remote IP column is added to make it easier to identify the data in the graph, the result will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*NNlpaFbZb-S6vLhxBxGt5g.png" /><figcaption>PCA results</figcaption></figure><p>And once displayed on a graph, we can identify anomalies in the connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*KiXIXDkaqRzi3W-pZfNDog.png" /><figcaption>PCA data graph</figcaption></figure><p>In this way, we could quickly identify anomalies in the connections that would give us a clue to start investigating.</p><p>Although a multitude of further analyses could be made on these data, it is time to end the article and continue in the next one. The complete notebook can be obtained at <a href="https://github.com/lucky-luk3/Infosec_Notebooks/blob/main/Forti_VPN_Logs_Analysis-Public.ipynb">this link</a>.</p><p>All in all, it is clear that data analytics is one of the keys to the future in virtually every industry, but in the case of cybersecurity it is and will be a core skill for analysts.<br>Knowing how to use the tools at our disposal will make the difference in time and results during the investigation of an incident or during monitoring.</p><p>I will continue to talk about notebooks that are useful during my daily work and I hope you find them useful.</p><p>Happy research!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=591e4832f7e6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-data-science-could-make-cybersecurity-troubleshooting-easier-firewall-logs-analysis-591e4832f7e6">How Data Science Could Make Cybersecurity Troubleshooting Easier: Firewall Logs Analysis</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hunting threats with Pandas  — $MFT Analysis]]></title>
            <link>https://medium.com/data-science/hunting-threats-with-pandas-mft-analysis-9f96a99ef27a?source=rss-4268294f29eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f96a99ef27a</guid>
            <category><![CDATA[incident-response]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[pandas]]></category>
            <dc:creator><![CDATA[Luis Francisco Monge Martinez]]></dc:creator>
            <pubDate>Thu, 12 Aug 2021 06:29:56 GMT</pubDate>
            <atom:updated>2021-08-14T16:34:29.964Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hunting threats with Pandas 🐼👊 — $MFT Analysis</h3><h4>Improving incident response with data analysis techniques and tools.</h4><p>It is really exciting to see the direction that, in my opinion, cybersecurity is taking. Incident response and even more so Threat Hunting are increasingly linked to the processing of huge amounts of information.<br>I believe this is due on the one hand to the amount of telemetry stored and/or generated by current devices and that there are more and more incidents and many are very large incidents, with many computers and even many sites of an organization involved.<br>This means that when we have to find an attacker within an organization in Threat Hunting or when we have to find the tracks of an attacker in a DFIR exercise, we have to deal with more and more information, millions of events from multiple sources, with different formats … a nightmare.</p><p>I have always argued that programming is a basic skill for any analyst in cybersecurity, if we do not have the minimum knowledge, we are doomed to always have to use third-party tools that will not always fit our needs. In this case it is no different, being able to create small scripts or programs that automate data processing will make a big difference.</p><h3>Python and Pandas to the rescue!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CiIm12IRMW8OMhWAgenQtg.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@introspectivedsgn?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Erik Mclean</a> from <a href="https://www.pexels.com/photo/man-in-black-and-white-panda-costume-standing-on-payphone-booth-during-night-time-4065800/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>While Python has the ability to surprise programmers who start with it, Pandas has blown me away!<br>Pandas is a data analysis and manipulation tool, as defined by its creators it is fast, powerful and flexible… they fall short, it’s mind-blowing. 😍<br>Although they are independent projects, it is highly recommended to “play” with Pandas using JupyterLab, well it is recommended for anything, if you have never used it, when you do, you will regret not having done it before.<br>I recommend you to install Anaconda 🐍 to work with JupyterLab, this will not end up our computer full of Python libraries that we don’t need, you have to be organized! 😄<br>To start, once Anaconda is installed, we will start JupyterLab by running this command in the Anaconda console.</p><pre>C:&gt;jupyter notebook</pre><p>Once in the Jupyter interface you will be able to create a new notebook with Pyhton 3 and start playing.</p><h3>MFT analysis 📂</h3><p>Although my intention is to make several posts talking about ways to use Pandas in the daily work of an analyst, in this case we will talk about how to work with a MFT (Master File Table) with Pandas and Python.<br>To begin with, the MFT is a very valuable asset in many security incidents as it is a database where the NTFS file system keeps track of all the files and directories created on the storage volume. The situations in which it is necessary to look at this log are legion, but in this case, our victim has suffered from ransomware.<br>The MFT is not in a comfortable format to work with and to make it easier for us I am going to use <a href="https://ericzimmerman.github.io/#!index.md">Eric Zimmerman’s MFTECmd</a> tool. 🔝<br>If the MFT is not very big we can analyze it with MS Excel, but many times the file is so big that we need something more versatile.</p><p>Initially, some variables must be declared and the MFETCmd tool must be run.</p><pre><strong>import</strong> <strong>os</strong><br><strong>from</strong> <strong>subprocess</strong> <strong>import</strong> check_output<br>mft_path = &quot;<strong>\&quot;</strong>C:<strong>\\</strong>kape<strong>\\</strong>collected<strong>\\</strong>2021-06-01T151604<strong>\\</strong>C<strong>\\</strong>$MFT<strong>\&quot;</strong>&quot;<br>mftexplorer_path = &quot;<strong>\&quot;</strong>C:<strong>\\</strong>MFTExplorer<strong>\\</strong>MFTECmd.exe<strong>\&quot;</strong>&quot;<br>output_folder = &quot;C:<strong>\\</strong>Documents<strong>\\</strong>test&quot;<br>output_filename = &quot;MyOutputFile.csv&quot;</pre><pre>command = &quot;<strong>{0}</strong> -f <strong>{1}</strong> --csv <strong>\&quot;{2}\&quot;</strong> --csvf <strong>\&quot;{3}\&quot;</strong>&quot;.format(mftexplorer_path, mft_path, output_folder, output_filename)<br>print(command)<br>output = os.popen(command).read()</pre><p>The result of this execution will be a CSV file in the set folder and that is what we need to feed our Panda. 🐼</p><pre><strong>import</strong> <strong>pandas</strong> <strong>as</strong> <strong>pd</strong> <br>pd.set_option(&#39;display.max_columns&#39;, 500)<br><br>data = pd.read_csv(output_folder + &quot;<strong>\\</strong>&quot; + output_filename)</pre><p>At this point we already have a dataframe with all the information from the MFT. To continue working comfortably with the data it is advisable to adjust the types of the fields containing dates.</p><pre>data.set_index(&quot;EntryNumber&quot;, inplace=<strong>True</strong>)<br>data[&#39;Created0x10&#39;] =  pd.to_datetime(data[&#39;Created0x10&#39;], format=&#39;%Y-%m-<strong>%d</strong> %H:%M:%S.<strong>%f</strong>&#39;)<br>data[&#39;Created0x30&#39;] =  pd.to_datetime(data[&#39;Created0x30&#39;], format=&#39;%Y-%m-<strong>%d</strong> %H:%M:%S.<strong>%f</strong>&#39;)<br>data[&#39;LastModified0x10&#39;] =  pd.to_datetime(data[&#39;LastModified0x10&#39;], format=&#39;%Y-%m-<strong>%d</strong> %H:%M:%S.<strong>%f</strong>&#39;)<br>data[&#39;LastModified0x30&#39;] =  pd.to_datetime(data[&#39;LastModified0x30&#39;], format=&#39;%Y-%m-<strong>%d</strong> %H:%M:%S.<strong>%f</strong>&#39;)<br>data[&#39;LastRecordChange0x10&#39;] =  pd.to_datetime(data[&#39;LastRecordChange0x10&#39;], format=&#39;%Y-%m-<strong>%d</strong> %H:%M:%S.<strong>%f</strong>&#39;)<br>data[&#39;LastRecordChange0x30&#39;] =  pd.to_datetime(data[&#39;LastRecordChange0x30&#39;], format=&#39;%Y-%m-<strong>%d</strong> %H:%M:%S.<strong>%f</strong>&#39;)</pre><p>The data is now ready for queries. In this case, this MFT belongs to a computer that suffered a ransomware attack, more specifically Avaddon. <br>Let’s imagine that we don’t know when the ransomware was executed and we want to know it in order to perform the investigation.<br>First of all, let’s try to see in the MFT which days are the ones in which more changes were made to files.</p><pre>dates = data[&quot;LastRecordChange0x10&quot;]<br>dates.index = dates.dt.to_period(&#39;d&#39;)<br>s = dates.groupby(level=0).size()<br>s.sort_values(ascending=<strong>False</strong>).head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*wDuUkCBCuwW--63RHhBX9w.png" /><figcaption>Days with more changes in the MFT</figcaption></figure><p>In the image above you can see how with a few commands we have extracted the dates of modification of files and after grouping the data we obtain firstly the date of installation of the operating system and secondly what apparently can be the day of the attack.<br>If we prefer to see it in a more visual way, we can generate a graph with the changes made in the last 2 months for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4iJQhzrQtaTll6DWuqW8bg.png" /><figcaption>Histogram changes in MFT by day</figcaption></figure><p>Another test we can do is to look for the most repeated files within the MFT for the last 4 months, with the intention of discovering anomalies.</p><pre>fig = px.bar(names_plot, x=&quot;FileName&quot;, &quot;title=Files with more entries&quot;)<br>Fig.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aeeyViWD82h_bZVj7Ts83A.png" /><figcaption>Files with more entries</figcaption></figure><p>The ransom notes! This ransomware creates ransom notes during its execution and modifies them with each file it encrypts. To see the information in a little more detail we will do the following.</p><pre>readme = data[data[&quot;FileName&quot;].str.contains(&quot;_readme_.txt&quot;)]<br>redme.sort_values(by=&quot;LastModified0x10&quot;, ascending=True).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*ZQq6tCMYW7dB2YrvsV5jow.png" /><figcaption>Ransom notes</figcaption></figure><p>In this case, with the appearance of the ransom notes we can know when the incident occurred but now we are going to try to find out who could have been the perpetrator only with the MFT. To do this, we are going to try to query the files with the most common extensions used by attackers in ransomware cases, but only in the 12 hours prior to the creation of the first ransom note. 🔍</p><pre>first_note = readme1.sort_values(by=&quot;LastModified0x10&quot;, ascending=<strong>True</strong>).iloc[0][&quot;LastModified0x10&quot;]<br>range_exe = first_note + pd.offsets.Hour(-12)<br>data_filtered = data[(data[&#39;Created0x10&#39;] &gt; &quot;2021-05-22&quot;) &amp; (data[&#39;Created0x10&#39;] &lt; &quot;2021-05-25&quot;)]<br>files = data_filtered[data_filtered[&quot;FileName&quot;].str.contains(&quot;\.exe|\.ps1|\.msi|\.vba&quot;, regex=<strong>True</strong>)]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*XlPvcq-huwVDdM6GmJWrdA.png" /><figcaption>Ransom executable</figcaption></figure><p>Now that we have the file we have to find out how it got to the computer, but that is something that the MFT will not be able to tell us 😄. Although we have not gone very deep, we could perform analysis on multiple MFT files, search by name patterns, compare creation and modification dates, search for files with suspicious attributes… a world of possibilities.</p><p>In future posts I will talk about more advanced cases in which Pandas can help us in our investigations as in the analysis of gigabytes of firewall logs or analysis of Windows events.<br>I hope you liked it and that you are encouraged to include Pandas and Jupyter in your arsenal of hunting tools.</p><p>You can find this notebook in <a href="https://github.com/lucky-luk3/Infosec_Notebooks/blob/main/MFT_analysis_public_v0.2.ipynb">this link</a>, enjoy!</p><p>See you in the next one and happy hunting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f96a99ef27a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/hunting-threats-with-pandas-mft-analysis-9f96a99ef27a">Hunting threats with Pandas 🐼👊 — $MFT Analysis</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hunting Cobalt Strike in Memory]]></title>
            <link>https://luckyluk3.medium.com/hunting-cobalt-strike-in-memory-1cbe820d3aaf?source=rss-4268294f29eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cbe820d3aaf</guid>
            <category><![CDATA[threat-hunting]]></category>
            <category><![CDATA[cobalt-strike]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[incident-response]]></category>
            <category><![CDATA[forensics]]></category>
            <dc:creator><![CDATA[Luis Francisco Monge Martinez]]></dc:creator>
            <pubDate>Thu, 03 Jun 2021 19:14:38 GMT</pubDate>
            <atom:updated>2021-06-03T19:14:38.415Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been meaning to get back to writing for a while now and have finally been able to carve out some time for it, so hunting season is back!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*kjyI09bMzvX_l1JS5LZ6uA.png" /><figcaption>Ref: <a href="https://unsplash.com/@spanic">https://unsplash.com/@spanic</a></figcaption></figure><p>The time has come to play with Cobalt Strike in my lab due to the number of security incidents in which it is used and how complex it is sometimes to investigate.</p><p>For those of you who don’t know about it, Cobalt Strike is an attack framework that allows anyone with $3500 to have an arsenal of really powerful offensive tools at their disposal.</p><p>It may seem like a lot of money, but for cybercriminals who have found in cybercrime a profitable business, it is not so much.</p><p>If we take a look at MITRE’s Cobalt Strike knowledge base, we will see how many advanced groups use this framework.</p><p>When faced with a challenge like this, there are many ways to deal with it and in this case, I have decided to focus this little research on detecting the Cobalt Strike agent by analyzing the memory of the compromised computer. I thought that this approach could be useful due to the large number of attacks that currently exist that avoid touching the disk during the infection process, but memory is impossible to avoid 😉</p><h3>On the attack!!</h3><p>For this example I have created an executable with Cobalt Strike in the Windows Executable mode, if you notice, without the option (S), this option would make the agent to be included in the executable. Both options have their advantages and disadvantages but in this case we will use the first one, the one that does not contain the agent and the one that will perform the download in memory of the agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*Hh4kKBOslNaT71l6sc1i1A.png" /><figcaption>Cobalt Strike Windows Executable</figcaption></figure><p>As this article is not about attack but about detection, we skip the rest of the steps for the generation of the executable 😄.</p><p>Once we have executed the binary on our victim machine, we will see a process like this. With PID 420.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*kcx5sRjNl0rYewJ5jKdigw.png" /><figcaption>Initial process</figcaption></figure><p>In order to have a sample as complete as possible, I am going to use two very useful attack techniques when it comes to evading both anti virus programs and to make manual analysis difficult for hunters like us.</p><p>These techniques are the “Parent Process ID Spoofing” and the “Process Hollowing”, in <a href="https://www.securityartwork.es/2020/11/26/threat-hunting-viii-cazando-sin-salir-de-casa-creacion-de-procesos-ii/">this article</a> I tell you more about these techniques and possible ways of detection.</p><p>To do this, I will configure the Cobal Strike session so that the following processes running from the active session, are launched as children of the process “explorer.exe” and run within a process emptied from “iexplorer.exe”.</p><p>Once everything is configured, we launch a second malicious process, but this second one is a little more difficult to find than our “bicho_malo.exe”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*Ou1Bb2cUg-TW0IMbA8S96g.png" /><figcaption>Advance malicious process</figcaption></figure><p>As you can see in the image, this process has the appearance of a legitimate Internet Explorer process and appears as a child process of Explorer, so everything leads you to believe that it is a process launched by the user and with PID 2852.</p><h3>Memory extraction💻</h3><p>For memory extraction I used “Magnet Ram Capturer”. <br>It is a free tool developed by the company Magnet and it works really well.<br>Although few sites talk about it, it is possible to run this tool from command line, very useful to perform memory captures in an automated way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*6S6a0A6fZ3uxnLLVBKz-cA.png" /><figcaption>Magnet Ram Capturer</figcaption></figure><h3>Memory analysis 🔎</h3><p>The moment of truth has arrived. Although we know what we have to find, we are going to try to learn as much as possible in the process.<br>To perform the analysis we will use Volatility, both in its version 2 and in its most modern version, version 3.<br>For the analysis we will use several Volatility plugins that will be very useful.</p><h4>Malfind — Volatility3 🐛</h4><pre>python .\vol.py -f C:\Users\user1\dump_cobalt.raw windows.malfind.Malfind | Select-String &quot;.exe&quot;</pre><p>This plugin is one of the most famous of Volatility and it is not for less. This plugin performs an automated analysis of the memory structure of the processes in search of anomalies that make them suspicious, such as, for example, when a process has a memory page marked as executable and modifiable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*00EGsTr4uplWLIWOJp7RfQ.png" /><figcaption>Volatility Malfind Result</figcaption></figure><p>As can be seen in the image, the plugin gives several false positives (which are practically always the same) but the important thing is that it is able to detect the two malicious processes that we had generated with PID 420 and 2852.</p><h4>Netscan — Volatility3 📶</h4><pre>python .\vol.py -f C:\Users\user1\dump_cobalt.raw windows.netscan.NetScan | Select-String -pattern &quot;Offset|ESTABLISHED&quot;</pre><p>On this occasion, this plugin will help us to try to detect processes that have open connections. Although this behavior can be common in many processes, it can be a good approach since the connection with the command and control console is something that sooner or later almost all malicious processes need to do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*7hu0x_ZWe2MI5qqFzZqYww.png" /><figcaption>Resultado Volatility NetScan</figcaption></figure><p>In the image we can see three “live” connections, two Microsoft IPs and a private IP which is the IP assigned to the attacking machine.<br>To check which process has established that connection, we will resort to another very useful plugin used by Yara.</p><h4>YaraScan — Volatility</h4><pre>C:\Python27\python.exe .\vol.py yarascan -Y &quot;192.168.129.131&quot; -f C:\Users\user1\dump_cobalt.raw --profile=Win10x64_19041 | select-string &quot;Owner&quot; -Context 0,2</pre><p>For this example I will use Volatility2 since version 3 does not work as well as version 2, yet. This plugin allows us to use the power of Yara to identify strings in processes, in this case I will use it to search for processes containing the suspicious IP address returned by the NetScan pugin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*Njs4kV9hxXi_aDJw48EU1Q.png" /><figcaption>YaraScan IP result</figcaption></figure><p>Analyzing the results, this plugin shows malicious processes, in which we can see parameters used by Cobalt Strike to connect to the command and control console, but there is also a false positive, “msedge.exe”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*gLrrpskjCUkYCYwCU-G42A.png" /><figcaption>YaraScan MsEdge result</figcaption></figure><p>his is because Microsoft browsers save all HTTP communications made by the computer, something a bit intrusive but very useful in forensic analysis 😃.</p><h4>YaraScan II — Volatility</h4><pre>C:\Python27\python.exe .\vol.py yarascan -y D:\rules.yar -f C:\Users\user1\dump_cobalt.raw --profile=Win10x64_19041</pre><p>Due to the power of Yara, this plugin allows us to perform multiple approaches to malicious process detection using Yara rules.<br>For this second example, I am going to use the Yara rules created by Etienne Maynier which can be found on <a href="https://github.com/Te-k/cobaltstrike/blob/master/rules.yar">his Github</a> 👏.<br>This researcher has created three Yara rules that allow to detect the Cobalt Strike agent in memory with very few false positives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*0KHRTuRM7xRMZOoFjG8bLQ.png" /><figcaption>Yara Te-k result</figcaption></figure><p>As can be seen in the image, these rules have detected the malicious process with which the “PPID Spoofing” and “Process Hollowing” techniques had been used, but not the initial process that generated the malicious binary with PID 420.<br>As the mission of this article is to detect Cobalt Strike in these two versions, we are going to try to modify the “CS_beacon” rule to detect both processes. To do this, I will use the Volaitlity3 plugin “PsList” to create a dump of the process memory.</p><pre>python .\vol.py -f C:\Users\user1\dump_cobalt.raw windows.pslist.PsList --pid 420 --dump</pre><p>This plugin allows us to see some basic information of a process, but with the option “- -dump” allows us to generate a dump of the process memory for inspection 🔎.<br>Although to create a Yara rule from a binary you can use the linux “strings” tool, this time I am going to use an essential tool in any analyst’s computer, <a href="https://www.winitor.com/">PeStudio from Winitor</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udjRa09Ue9tOhLQOk-RasQ.png" /><figcaption>Strings inPeStudio</figcaption></figure><p>If we look at the first result, there is a text string that is “\\.\pipe\MSSE-8093-server”, this is one of the signs of identity in the Cobalt Strike binaries since it fulfills one of the patterns used by the program by default.<br>Here is a link to an article written in the Cobalt Strike blog talking about the patterns in the names of the default “Named Pipes”. This information is very valuable to be able to generate a new Yara rule very useful when the attacker has not modified the configuration.</p><pre>//&quot;\\.\pipe\MSSE-&quot;<br>$p1 = {5c 5c 2e 5c 70 69 70 65 5c 4d 53 53 45 2d}<br>//&quot;\\.\pipe\status_&quot;  <br>$p2 = {5c 5c 2e 5c 70 69 70 65 5c 73 74 61 74 75 73 5f} <br>//&quot;\pipe\msagent_&quot;<br>$p3 = {5c 70 69 70 65 5c 6d 73 61 67 65 6e 74 5f}<br>//&quot;\\.\pipe\postex_&quot;  <br>$p4 = {5c 5c 2e 5c 70 69 70 65 5c 70 6f 73 74 65 78 5f}</pre><p>When these lines are added to the Yara rule created by Etienne Maynier, we get our desired result, detecting both malicious processes, with the false positive of “MsMpEng.exe” which is the Windows Defender process and which has rules very similar to these for the detection of Cobalt Strike.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*r1jshPnFDR9G29cWqrL8Wg.png" /><figcaption>Cobalt version 2 detection</figcaption></figure><p>Once we have tested the Yara rule in our team, I recommend testing it against public databases to check if they are well debugged.<br><a href="https://www.hybrid-analysis.com/">Hybrid Analysis</a> offers the possibility to launch Yara rules against its database and thus be able to see for free artifacts that have matched our rule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pfsP2XyrMAB3Et4kEG5IOg.png" /><figcaption>HybridAnalysis result</figcaption></figure><p>As you can see in the image, the rule has detected 41 files available with the free account and 1959 with the premium account. <br>Although the first results have not been detected by this sandbox during its static analysis, we can take the hash of the first result and look it up in Virus Total to make sure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i06LxOnvy5ahd4u04hoa9A.png" /><figcaption>Virus Total result</figcaption></figure><p>Indeed, when antivirus scan the behavior of this file it is detected as an agent of Cobalt Strike.<br>In future posts I will talk about the traces left by Cobalt Strike during its initial execution and during its actions such as lateral movements, elevation of privileges… <br>I hope you liked it and see you in the next one.<br>Happy hunting! 😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cbe820d3aaf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>