<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sofiane Hamlaoui on Medium]]></title>
        <description><![CDATA[Stories by Sofiane Hamlaoui on Medium]]></description>
        <link>https://medium.com/@SofianeHamlaoui?source=rss-5dda1657acd1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dTB_Vf17zmhF_Ntu6RAbUw@2x.jpeg</url>
            <title>Stories by Sofiane Hamlaoui on Medium</title>
            <link>https://medium.com/@SofianeHamlaoui?source=rss-5dda1657acd1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 03:41:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@SofianeHamlaoui/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[EU Compliance, Programmable: The API That Turns 19 EU Regulations Into JSON]]></title>
            <link>https://medium.com/@SofianeHamlaoui/eu-compliance-programmable-the-api-that-turns-19-eu-regulations-into-json-c6c8161a2034?source=rss-5dda1657acd1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6c8161a2034</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[europe]]></category>
            <category><![CDATA[cra]]></category>
            <category><![CDATA[nis2]]></category>
            <category><![CDATA[compliance]]></category>
            <dc:creator><![CDATA[Sofiane Hamlaoui]]></dc:creator>
            <pubDate>Thu, 09 Apr 2026 00:06:13 GMT</pubDate>
            <atom:updated>2026-04-09T00:37:17.599Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dWajFtuO8TVJfSAJ" /></figure><p>Here’s a number that keeps compliance officers awake at night: <strong>19</strong>.</p><p>That’s how many major <strong>EU</strong> regulations a tech company needs to juggle today. <strong>GDPR</strong>. <strong>NIS2</strong>. The <strong>AI Act</strong>. <strong>The Cyber Resilience Act</strong>. <strong>DORA</strong>. <strong>DSA</strong>. <strong>DMA</strong>. <strong>The Data Act</strong>. <strong>MiCA</strong>. <strong>CSRD</strong>. And the list keeps <strong>growing</strong>.</p><p>Each one is hundreds of pages of dense legal text, published on EUR-Lex as PDFs..</p><p>There are no APIs. No webhooks. No structured data. Just walls of text with numbered paragraphs, cross-references that loop back on themselves, and deadlines that shift when amendments pass.</p><p>If you’re a developer building anything that touches EU markets, your compliance workflow probably looks like this:</p><ol><li>Download a 340-page PDF</li><li>Ctrl+F for “incident notification”</li><li>Read 14 articles to figure out which ones actually apply to your company</li><li>Hope your legal team catches what you missed</li></ol><blockquote><em>That’s not a workflow. That’s a prayer.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7--_5K7TWdETXijex0wsLA.png" /><figcaption>EU compliance in one API Que</figcaption></figure><p>That’s the question behind <a href="https://law4devs.eu/">Law4Devs</a>, and it’s simpler than it sounds.</p><p><strong>Law4Devs</strong> processes every EU regulation PDF brought directly from <strong>EUR-Lex</strong>, gets the structure — articles, recitals, annexes, individual paragraphs and exposes it all as a clean REST API that returns JSON.</p><p>No AI summaries. No chatbot. No “here’s my interpretation of Article 33.” Just the raw legal text, structured, queryable, and filterable by stakeholder role, requirement type, and semantic tags.</p><p>The tagline is <strong>“EU Compliance, Programmable.”</strong> And unlike most taglines in this space, it actually means something.</p><p>Here’s what a real call looks like:</p><pre>curl -H &quot;X-API-Key: YOUR_API_KEY&quot; \<br>  &quot;https://api.law4devs.eu/v1/frameworks/cra/articles/15&quot;</pre><p>You get back the full article text, its paragraphs broken down individually, cross-references to related articles, semantic tags like supply-chain and vulnerability-reporting, and links to the canonical EUR-Lex source so your legal team can verify every word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ncg6e_vGz65WCh0gFIu_NQ.png" /><figcaption>CRA, in one API Call</figcaption></figure><h3>The “No AI” Positioning Is the Point</h3><p>Let me be clear about something: <strong>Law4Devs</strong> is not an AI legal assistant.</p><p>There are no LLMs generating summaries of regulations. No “<strong>AI-powered compliance insights.</strong>” No hallucinated interpretations of <em>Article 17 that sound convincing but are technically wrong.</em></p><p>The platform deliberately returns <strong>verbatim legal text from EUR-Lex</strong>, nothing more, nothing less. Every response includes a link to the official source. If your legal team questions something, they click through and read it on EUR-Lex themselves.</p><p>This matters more than you’d think.</p><p>In regulated industries, auditability isn’t a nice-to-have — it’s the whole game. An AI that summarizes a regulation is a black box. A black box doesn’t hold up in front of a regulator. Raw text with a source link does.</p><p>The <strong>irony</strong>? The most trustworthy AI-powered compliance tool is the one that doesn’t use AI at all.</p><h3>19 Frameworks, One API Key</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_6JhzFP2M7hVjnX2HAIZ0g.png" /></figure><p>That’s over <strong>2,000 articles</strong> across all frameworks, each one structured with its paragraphs, recitals, annexes, and extracted requirements — all updated daily through automated scraping of EUR-Lex.</p><p>And here’s the thing most people miss: <strong>real compliance spans multiple frameworks.</strong> A SaaS company handling EU customer data needs GDPR, NIS2, and the DSA. A fintech needs DORA, MiCA, and PSD2. A device manufacturer needs CRA, NIS2, and the RED directive.</p><p>Law4Devs lets you search across all of them simultaneously:</p><pre>from law4devs import Law4DevsClient</pre><pre>client = Law4DevsClient(api_key=&quot;...&quot;)</pre><pre>results = client.search.query(<br>    &quot;incident notification 72 hours&quot;,<br>    frameworks=[&quot;nis2&quot;, &quot;dora&quot;, &quot;cra&quot;],<br>)</pre><pre>for r in results.data:<br>    print(f&quot;{r.framework_slug.upper()} Art.{r.article_number}: {r.title}&quot;)</pre><p><strong>One query. Three frameworks. </strong>Every article that mentions 72-hour incident notification. That’s the kind of search that would take a human hours of cross-referencing.</p><h3>Stakeholder Roles: The Feature Nobody Knew They Needed</h3><p>Here’s where it gets interesting.</p><p>EU regulations don’t apply to everyone equally. They define specific roles — manufacturer, importer, distributor, authorized representative, notified body, open source steward, market surveillance authority — and assign different obligations to each.</p><p>Most compliance tools dump the entire regulation on you and say “good luck figuring out what applies.”</p><p><strong>Law4Devs</strong> extracts requirements and maps them to stakeholder roles. So if you’re an <strong>open source steward</strong>, you can filter for only the obligations that apply to that role under the CRA. If you’re a <strong>notified body</strong>, you see only what DORA expects from you.</p><pre>requirements = client.requirements.list(<br>    &quot;cra&quot;,<br>    role=&quot;manufacturer&quot;,<br>    type=&quot;obligation&quot;,<br>)</pre><p>This is genuinely useful. It turns a 300-page regulation into “here are the 47 things that actually apply to your company.”</p><p>And guess what? this is already explained to every user logged in into the <strong>Law4Devs Dashboard</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vv-rq6KpnQhda3WleZMMxg.gif" /><figcaption>Developer’s Guide</figcaption></figure><h3>The SDKs Are Actually Good</h3><p>Six official SDKs: <strong>Python, TypeScript, PHP, Java, Dart (Flutter), and Rust.</strong></p><p>All of them are open source under the MIT license. All of them support auto-pagination (so you don’t have to manually loop through pages when fetching all articles of a framework). All of them handle exponential backoff on rate limits.</p><p>The <strong>Rust SDK</strong> uses Tokio async streams. The <strong>Java SDK</strong> runs on Java 17+. The <strong>TypeScript SDK</strong> has full type inference. The P<strong>ython SDK</strong> is zero-dependency — pip install law4devs and you&#39;re done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*yzMJ9GtSRAfVz0GQlbCYDw.gif" /><figcaption>All SDKs</figcaption></figure><p>I used the Python SDK myself. It took about 90 seconds from pip install to having all GDPR articles streaming through my terminal. The auto-pagination iterator is the kind of quality-of-life feature that separates &quot;we built an SDK wrapper&quot; from &quot;we actually thought about the developer experience.&quot;</p><p><strong><em>Also, the Autocompliance CLI tool is based on the Python SDK itself…</em></strong></p><h3>Compliance Watcher: Your Personalized Compliance Dashboard (Pro)</h3><p>This is where <strong>Law4Devs</strong> goes from “useful API” to “actual compliance platform.”</p><p>The Compliance Watcher is a Pro-tier feature that turns the raw firehose of regulatory data into a <strong>personalized dashboard</strong> that shows you only what applies to your company.</p><p>Here’s how it works: you go through a guided setup where you define your profile across seven dimensions:</p><ol><li><strong>Entity type &amp; company size</strong> — Are you a software company, hardware manufacturer, financial institution, healthcare org, public administration, notified body? How many employees?</li><li><strong>Activities</strong> — What do you actually do? Develop software? Process personal data? Operate a platform? Deploy AI systems? Make radio equipment? Issue crypto assets? 20 options, multi-select.</li><li><strong>Roles</strong> — Based on your activities, the system surfaces the roles that apply to you. Manufacturer, importer, data controller, data processor, VLOP thresholds, open source steward, and more.</li><li><strong>Scope questions</strong> — Do you transfer data outside the EU? Is CSRD applicable to you?</li><li><strong>Sectors</strong> — 20 sector options from technology and healthcare to aerospace and agritech.</li><li><strong>Framework selection &amp; view mode</strong> — Pick which of the 18 frameworks matter to you, and choose between a focused view (obligations and prohibitions only) or full view (all requirement types).</li><li><strong>Your dedicated watcher URL</strong> — You get a permanent subdomain (e.g., yourcompany.law4devs.com) that becomes your compliance command center.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*Pd5dMZKghMTtmoouv0PNEA.gif" /><figcaption>Watcher config and init</figcaption></figure><p>Once configured, your Watcher dashboard shows you exactly which regulations apply, what your specific obligations are, and — critically — <strong>what’s changed</strong> since the last update. The platform uses content hashing (SHA-256) to detect when articles are modified on EUR-Lex, and surfaces those changes with a word-level diff so you can see exactly what was added, removed, or modified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*JWkflkpfn46nWcfg5BBhpg.png" /><figcaption>Compliances changes</figcaption></figure><p>No more monitoring 19 regulatory sources manually. You set your profile once, and the dashboard keeps you current.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-iZlZkNSc9HmOvkLVwm-ow.png" /><figcaption>Watcher for Pro users</figcaption></figure><h3>Auto-Compliance: CI/CD Gates &amp; Integrations (Scale)</h3><p>The Scale tier takes everything from Pro and adds what most compliance teams are still dreaming about: <strong>automated compliance checks baked into your engineering workflow.</strong></p><p><strong>CI/CD Compliance Gates</strong> — Compliance checks run in your pipeline. Gaps surface before merge, not after audit. Instead of waiting for an annual compliance review to discover you’ve drifted, your CI pipeline catches it the moment someone introduces a non-compliant change.</p><p><strong>Third-party integrations</strong> — Jira, Slack, Microsoft Teams, ServiceNow, PagerDuty, and SIEM platforms. When a regulation changes, your team knows through the tools they already use. Compliance events land in your incident management workflow, your ticketing system, your team channels. No context switching. No “did anyone check the EUR-Lex update?”</p><p><strong>Unlimited requests, 100 req/min, 100 API keys</strong> — The Scale tier removes the throttles. When compliance is automated into your pipeline, you need the rate limits to match.</p><p>This is the automation layer that turns compliance from a quarterly panic into a continuous, automated process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fYh_vQlNyU5J8iSQarVP4g.gif" /><figcaption>Auto Compliance Engine</figcaption></figure><h3>Pricing That Doesn’t Require a CFO</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y68cYm6UCp0BQNFtQdZlCQ.png" /><figcaption>Pricing</figcaption></figure><p>The Growth tier is genuinely accessible for indie developers and small teams. 10,000 requests per month is enough to build a serious internal compliance tool without breaking the bank.</p><p>The Pro tier is where the Compliance Watcher transforms raw data into a personalized compliance operation.</p><p>The Scale tier is full enterprise automation — CI/CD gates, unlimited requests, and integrations with every tool your ops team already uses.</p><h3>The European Stack Matters</h3><p>Everything runs on EU infrastructure. All data stays within the EU. The company is registered in France (SIRET 102 404 456 00018), and we’re upfront about it.</p><p><strong>In a world where most compliance tools are hosted on US servers and process EU regulatory data through American infrastructure, this is a feature, not a footnote. GDPR data residency isn’t just a checkbox — it’s a competitive advantage when your customers are EU companies who need to prove their compliance data never left the bloc.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9F3A2VxBAbI6dyf6qHZjbA.gif" /><figcaption>100% European</figcaption></figure><h3>The Bottom Line</h3><p>Compliance is usually treated as a legal problem that engineers have to deal with. Law4Devs flips that: it treats compliance as an <strong>engineering problem</strong> that legal teams can verify.</p><p>That shift matters. Because when compliance is a legal problem, you get PDFs and checklists. When it’s an engineering problem, you get APIs, SDKs, CI/CD gates, and automated monitoring.</p><p>The EU isn’t slowing down on regulation. The AI Act is already in force. The CRA deadlines are ticking. NIS2 enforcement is underway. More directives are coming. The companies that figure out how to operationalize compliance as code will have a massive advantage over the ones still Ctrl+F’ing through PDFs.</p><p>Law4Devs makes that possible. Not with AI. Not with a chatbot. With structured data, clean APIs, personalized compliance dashboards, and the engineering discipline that developers actually respect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xgzC2zJLEf2xAXWhR-lDAQ.png" /><figcaption>Law4devs.eu</figcaption></figure><p><em>Law4Devs is live at </em><a href="https://law4devs.eu/"><em>law4devs.eu</em></a><em>. The API docs are at </em><a href="https://docs.law4devs.eu/"><em>docs.law4devs.eu</em></a><em>.</em></p><p><em>Disclaimer: </em><strong><em>Law4Devs</em></strong><em> provides engineering guidance through structured regulatory data — not legal advice. Always consult qualified legal counsel for compliance decisions.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6c8161a2034" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PromptLock: The Dawn of AI-Powered Ransomware — A Deep Dive into ESET’s Groundbreaking Discovery]]></title>
            <link>https://medium.com/@SofianeHamlaoui/promptlock-the-dawn-of-ai-powered-ransomware-a-deep-dive-into-esets-groundbreaking-discovery-c7d493a5d192?source=rss-5dda1657acd1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7d493a5d192</guid>
            <dc:creator><![CDATA[Sofiane Hamlaoui]]></dc:creator>
            <pubDate>Wed, 27 Aug 2025 18:01:38 GMT</pubDate>
            <atom:updated>2025-08-27T18:01:38.660Z</atom:updated>
            <content:encoded><![CDATA[<h3>PromptLock: The Dawn of AI-Powered Ransomware — A Deep Dive into ESET’s Groundbreaking Discovery</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YBG_SvUHEHGNtzzhU6a5Ew.png" /></figure><h3><a href="https://blog.sofiane.cc/post/promptlock-the-dawn-of-ai-powered-ransomware-a-deep-dive-into-eset-s-groundbreaking-discovery#executive-summary">Executive Summary</a></h3><p>The cybersecurity landscape has reached a significant milestone with ESET‘s discovery of PromptLock, the first known AI-powered ransomware.</p><p>This groundbreaking malware leverages OpenAI’s gpt-oss:20b model through the Ollama API to dynamically generate malicious scripts, representing an unprecedented evolution in ransomware sophistication.</p><p>While currently existing as a proof-of-concept, PromptLock signals a paradigm shift in how cybercriminals may weaponize artificial intelligence for malicious purposes.</p><p>You can check my latest blog where I did write about such attacks and how imminent is this kind of attack will happen. <a href="https://blog.sofiane.cc/post/the-growing-threat-the-dark-side-of-ai-and-llms">The Growing Threat: The Dark side of AI and LLMs</a></p><p><em>Read the full article published at </em><a href="https://blog.sofiane.cc/post/promptlock-the-dawn-of-ai-powered-ransomware-a-deep-dive-into-eset-s-groundbreaking-discovery"><em>https://blog.sofiane.cc</em></a><em> on A</em>ugust 28<em>, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7d493a5d192" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Growing Threat: The Dark side of AI and LLMs]]></title>
            <link>https://medium.com/@SofianeHamlaoui/the-growing-threat-the-dark-side-of-ai-and-llms-6a5fb4aa7989?source=rss-5dda1657acd1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a5fb4aa7989</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[sofiane-hamlaoui]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Sofiane Hamlaoui]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 21:17:21 GMT</pubDate>
            <atom:updated>2025-07-08T09:39:33.430Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D-jcOfGPjqW2lcVV.png" /></figure><p>Criminal actors are increasingly leveraging artificial intelligence technologies, particularly large language models (LLMs), to enhance their malicious operations and expand their attack capabilities. These sophisticated AI systems, originally designed to benefit society, are being weaponized through multiple vectors including unrestricted models, custom-built criminal platforms, and systematic circumvention of safety mechanisms.</p><p>The proliferation of AI-powered tools has democratized access to advanced computational capabilities, with platforms like Hugging Face now hosting over 1.8 million different models. While most commercial LLMs incorporate robust safety features including alignment training and protective guardrails, cybercriminals have developed sophisticated methods to bypass these restrictions or create entirely unfiltered alternatives for illicit purposes.</p><p><em>Read the full article published at </em><a href="https://blog.sofiane.cc/post/the-growing-threat-the-dark-side-of-ai-and-llms"><em>https://blog.sofiane.cc</em></a><em> on July 3, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a5fb4aa7989" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What You Get After Running an SSH Honeypot for 30 Days]]></title>
            <link>https://medium.com/@SofianeHamlaoui/what-you-get-after-running-an-ssh-honeypot-for-30-days-74271f4f2716?source=rss-5dda1657acd1------2</link>
            <guid isPermaLink="false">https://medium.com/p/74271f4f2716</guid>
            <category><![CDATA[oinasf]]></category>
            <category><![CDATA[mips]]></category>
            <category><![CDATA[mdrfkr]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[gafgyt]]></category>
            <dc:creator><![CDATA[Sofiane Hamlaoui]]></dc:creator>
            <pubDate>Sun, 16 Jun 2024 21:32:59 GMT</pubDate>
            <atom:updated>2024-06-16T21:32:59.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*Z8CVxEyQYvr38_2_.png" /></figure><h3>What is a honeypot?</h3><p>A honeypot detects and records attacks when an attacker tries to break into a system.</p><p>The honeypot we will discuss here is an SSH honeypot.</p><h3>Environment</h3><pre>OS: Ubuntu 24.04 LTS x86_64 <br>Kernel: 6.8.0-31-generic</pre><h3>Login Attempts</h3><pre>cat X.log | grep -c &quot;login attempt&quot;<br>11599</pre><p>There were a total of 11,599 login attempts. Divided by 30 days, this means an average of 386 login attempts per day.</p><h3>Used Usernames</h3><pre>cat X.log | grep -a &quot;login attempt&quot; | awk &#39;{print $5}&#39; | awk -F &quot;&#39;&quot; &#39;{print $2}&#39; | sort | uniq -c | sort -nr | head<br>   8181 root<br>    977 345gs5662d34<br>    359 admin<br>    198 pi<br>    105 0<br>     71 ubuntu<br>     51 ubnt<br>     46 support<br>     37 user<br>     30 oracle</pre><p>As expected, there are many attacks that target customary and default usernames.</p><p>For the 345gs5662d34 user, according to the <strong>Aalborg University of Denmark Research</strong> this could be the default credential for a <strong>Polycom CX600 IP telephone</strong></p><p>Check it here :<br><a href="https://vbn.aau.dk/ws/portalfiles/portal/573748244/sweetcam_honeypot_paper_1_.pdf">SweetCam: an IP Camera Honeypot</a></p><h3>Passwords</h3><pre>cat X.log | grep -a &quot;login attempt&quot; | awk &#39;{print $5}&#39; | awk -F &quot;&#39;&quot; &#39;{print $4}&#39; | sort | uniq -c | sort -nr | head<br>    977 345gs5662d34<br>    967 3245gs5662d34<br>    246 admin<br>    239 123456<br>    208 password<br>    155 0<br>     88 root<br>     75 raspberry<br>     73 123<br>     66 raspberryraspberry993311</pre><p>Once again, the same as the default username for <strong>Polycom CX600 IP telephone</strong></p><h3>Commands executed after login</h3><pre>cat X.log | grep -a &quot;CMD&quot; | awk -F&#39;CMD: &#39; &#39;{print $2}&#39; | sort | uniq -c | sort -nr<br>   6775 echo -e &quot;\x6F\x6B&quot;<br>   1016 cd ~; chattr -ia .ssh; lockr -ia .ssh<br>   1016 cd ~ &amp;&amp; rm -rf .ssh &amp;&amp; mkdir .ssh &amp;&amp; echo &quot;ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAQEArDp4cun2lhr4KUhBGE7VvAcwdli2a8dbnrTOrbMz1+5O73fcBOx8NVbUT0bUanUV9tJ2/9p7+vD0EpZ3Tz/+0kX34uAx1RV/75GVOmNx+9EuWOnvNoaJe0QXxziIg9eLBHpgLMuakb5+BgTFB+rKJAw9u9FSTDengvS8hX1kNFS4Mjux0hJOK8rvcEmPecjdySYMb66nylAKGwCEE6WEQHmd1mUPgHwGQ0hWCwsQk13yCGPK5w6hYp5zYkFnvlC8hGmd4Ww+u97k6pfTGTUbJk14ujvcD9iUKQTTWYYjIIu5PmUux5bsZ0R4WFwdIe6+i6rBLAsPKgAySVKPRK+oRw== mdrfckr&quot;&gt;&gt;.ssh/authorized_keys &amp;&amp; chmod -R go= ~/.ssh &amp;&amp; cd ~<br>    320 uname -s -v -n -r -m<br>    112 ./oinasf; dd if=/proc/self/exe bs=22 count=1 || while read i; do echo $i; done &lt; /proc/self/exe || cat /proc/self/exe;<br>     87 uname -a<br>     29 ps | grep &#39;[Mm]iner&#39;<br>     29 ps -ef | grep &#39;[Mm]iner&#39;<br>     29 ls -la /dev/ttyGSM* /dev/ttyUSB-mod* /var/spool/sms/* /var/log/smsd.log /etc/smsd.conf* /usr/bin/qmuxd /var/qmux_connect_socket /etc/config/simman /dev/modem* /var/config/sms/*<br>     29 ifconfig<br>     29 echo Hi | cat -n<br>     29 cat /proc/cpuinfo<br>     29 /ip cloud print<br>     23 whoami<br>     23 which ls<br>     23 w<br>     23 uname -m<br>     23 uname<br>     23 top<br>     23 lscpu | grep Model<br>     23 ls -lh $(which ls)<br>     23 free -m | grep Mem | awk &#39;{print $2 ,$3, $4, $5, $6, $7}&#39;<br>     23 df -h | head -n 2 | awk &#39;FNR == 2 {print $2;}&#39;<br>     23 crontab -l<br>     23 cat /proc/cpuinfo | grep name | wc -l<br>     23 cat /proc/cpuinfo | grep name | head -n 1 | awk &#39;{print $4,$5,$6,$7,$8,$9;}&#39;<br>     23 cat /proc/cpuinfo | grep model | grep name | wc -l</pre><p>Now the interesting part starts</p><h3>The oinasf script</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JreP76H5D4PyMzlw.png" /></figure><p>The execution of a mysterious script, ./oinasf, followed by attempts to read and display the system’s executable content, indicates a probing strategy for vulnerabilities or valuable information.</p><p>The use of /ip cloud print suggests that bots target MikroTik routers to access or disrupt cloud-based services, while uname -s -m provides them with essential details about the operating system and machine architecture, valuable for crafting further actions tailored to the system’s specifics.</p><p>In conclusion, these commands represent a clear strategy to infiltrate, assess, and establish control over targeted systems.</p><p>They emphasize the bot’s preference for direct manipulation and sustained access highlighting the critical need for robust defenses against such common yet potentially devastating tactics.</p><h3>The mdrfckr crypto miner</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/0*U-G-a-YVUs8Saq3x.png" /></figure><p>This miner would simply create a cron job that would delete everything on the .ssh folder and add a single ssh key and lock other users out.</p><p>After that it would kill other miners if they exist and just have the open field.</p><p>You can check this repo of someone who already got hacked and the miner was used on his server : <a href="https://github.com/dangoldin/crypto-miner-hack/">Dump of the crypto-miner that got installed on my system — Github</a></p><h3>The MIPS malware</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IxxfMWY6D3A1inMA.png" /></figure><p>Probably another <strong>MIPS</strong> (Multiprocessor without Interlocked Pipeline Stages) architecture malware, targeting routers and IoT devices.</p><p>Here is a good read and analysis of the behaviour of a MIPS Malware :<br><a href="https://www.giac.org/paper/grem/2573/analyzing-backdoor-bot-mips-platform/124977">Analyzing a Backdoor/Bot for the MIPS Platform</a></p><h3>The Sakura.sh Script</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lGQZapCMYSe5N_jb.png" /></figure><p>This script is part of the <strong>Gafgyt Malware</strong>.</p><p><strong>Gafgyt</strong>, also known as <strong>BASHLITE</strong>, is a botnet affecting Internet of Things (IoT) devices and Linux-based systems. The malware aims to compromise and gain control of these devices, often by exploiting weak or default passwords, as well as known vulnerabilities. Gafgyt has been around since 2014 and has evolved into multiple variants, each with its own set of features and capabilities, including the ability to launch distributed denial of service (DDoS) attacks.</p><p>Here is <a href="https://securityscorecard.com/wp-content/uploads/2024/01/Report-A-Detailed-Analysis-Of-The-Gafgyt-Malware-Targeting-IoT-Devices.pdf">A Detailed Analysis of the Gafgyt Malware Targeting IoT Devices</a></p><p>© 2024 — Sofiane Hamlaooui — Making the world a better place 🌎</p><h3>🔗 Connect with me</h3><p><a href="https://twitter.com/S0fianeHamlaoui">x.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74271f4f2716" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The magic of Tailscale]]></title>
            <link>https://medium.com/@SofianeHamlaoui/the-magic-of-tailscale-d0ac4c42b085?source=rss-5dda1657acd1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0ac4c42b085</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[sofiane-hamlaoui]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[vpn]]></category>
            <category><![CDATA[tailscale]]></category>
            <dc:creator><![CDATA[Sofiane Hamlaoui]]></dc:creator>
            <pubDate>Fri, 14 Jun 2024 04:13:32 GMT</pubDate>
            <atom:updated>2024-06-14T04:13:32.831Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-rfqbwh9SaKDSmdB.png" /></figure><p>If you have multiple computers in your life including computer-adjacent things like network attached storage it’s likely you’d like to have access to each of those devices, always.</p><p>If I need to inspect a file on my Synology in my house while I’m a passenger in the car, I want to be able to do so.</p><p>The easiest way to do this is to expose the port(s) your device needs for remote access through your router/firewall.</p><p>Unfortunately, this exposes your device to the entire Internet and that’s undesirable.</p><h3>Traditional VPNs</h3><p>The easy solution to this problem is a <strong>Virtual Private Network</strong>, this means you run some sort of server inside your network that will allow devices outside the network to tunnel into the network.</p><p>Once a device is on the VPN it can access anything within that network.</p><p>Said differently, if your phone is on a VPN that is hosted in your house, then your phone can access all the devices in your house. Most corporate VPNs work this same way.</p><p>If you’ll permit some hand-waving and over-simplification, traditional VPNs tend to be a sort of funnel where there is one server running inside the network you wish to tunnel into, and all clients connect to that server. That makes setup easy, but generally, it’s sort of an all-or-none scenario, you’re either on the VPN or you’re not.</p><p>What if there was a better way?</p><h3>Tailscale</h3><p><strong>Tailscale</strong> is a VPN service that makes your devices and applications accessible anywhere in the world, securely and effortlessly. It achieves this through encrypted point-to-point connections using the open-source <strong>WireGuard</strong> protocol.</p><p>Essentially, only devices within your private network can communicate with each other</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/0*eVb5sNiaNOGEwjTG.png" /></figure><h3>Tailscale’s Approach</h3><ul><li><strong>Decentralized</strong>: Avoids centralization by connecting nodes directly.</li><li><strong>Lower Latency</strong>: Devices communicate directly, resulting in lower latency.</li><li><strong>Higher Throughput</strong>: Traffic flows directly between machines, improving efficiency.</li><li><strong>Key Exchange and Coordination</strong>: Tailscale manages the exchange of public keys and coordinates the connections between nodes.</li><li><strong>Network Traffic</strong>: Traffic typically flows directly between nodes for the shortest path and best performance.</li><li><strong>Ease of Use</strong>: Tailscale is designed to be user-friendly, requiring minimal configuration from the user.</li></ul><p>By leveraging the WireGuard protocol and a decentralized network structure, Tailscale provides a secure and efficient way to connect your devices, no matter where they are located.</p><h3>How it Works</h3><p>Tailscale is fast and reliable. Unlike traditional VPNs, which tunnel all network traffic through a central gateway server, Tailscale creates a peer-to-peer mesh network (called a tailnet):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wvFil2GD1o2wCX8p" /><figcaption><strong>The central gateway may or may not be close to users, thus resulting in higher latency. Because traffic is centralized, it can also act as a bottleneck, slowing down connections further.</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cI6GlDC104ZXEbgj" /><figcaption><strong>With Tailscale, each device is connected to the other directly, resulting in lower latency.</strong></figcaption></figure><h3>Who’s it for?</h3><p><strong>Developers</strong> can use Tailscale to publish experimental services to their team without the hassle of configuring firewall rules and network configurations.</p><p><strong>Small business owners</strong> can provide their work-from-home employees with a secure way to access sensitive resources in minutes without spending thousands of dollars on traditional VPN solutions.</p><p><strong>Enterprise leaders</strong> can reduce their security risk by drastically reducing the complexity of internal networks. By using Access Control Lists and your existing identity provider, each user has the exact level of access they need — your accountants can access the payroll system, your support team can access the bug tracker, and your developers can access servers and databases.</p><h3>Terminology and concepts</h3><h3>Access control lists</h3><p>An access control list (ACL) manages system access using rules in the tailnet policy file. You can use ACLs to filter traffic and enhance security by managing who and what can use which resources.</p><h3>CL tags</h3><p>A tag lets you assign an identity (that’s separate from human users) to devices. You can use tags in your access rules to restrict access.</p><h3>Admin console</h3><p>The admin console is the central location to view and manage your Tailscale network. You can manage nodes on your network, users and their permissions, and settings such as key expiry. The admin console also informs you if an update to the Tailscale client is available for your device. When you make changes from the admin console, the coordination server updates the changes to your tailnet immediately.</p><h3>API</h3><p>API is an acronym for application programming interface. APIs define a set of rules to interact with an application or service programmatically. The Tailscale API lets you manage your Tailscale account and tailnet.</p><h3>CLI</h3><p>CLI is an acronym for command line interface. The Tailscale CLI includes a robust set of commands with functionality that GUI applications might not have. The Tailscale CLI is installed automatically when you install Tailscale on Linux, macOS, or Windows.</p><h3>Coordination server</h3><p>A coordination server is a central server that maintains a connection to all machines in your Tailscale network. It manages encryption keys, network changes, access policy changes, and maintains a connection to all machines in your Tailscale network. The coordination server is part of the control plane, not the data plane. It avoids being a performance bottleneck by not relaying traffic between machines.</p><h3>Device</h3><p>A device is anything other than a user. It can be physical or virtual and sends, receives, or processes data on your Tailscale network.</p><h3>Device key</h3><p>A device key is a unique public and private key pair for a specific device. More than one user can use a device key, but each device can only have one device key. The combination of a specific user with a device key represents a unique node.</p><h3>Firewall</h3><p>A firewall limits what network traffic can pass between two points. Firewalls can be hardware-based or software-based. Tailscale includes a built-in firewall, defined by the domain’s access rules.</p><h3>Identity Provider</h3><p>An identity provider is a method for users to authenticate to a tailnet. Examples of identity providers include Google, Okta, and Microsoft. Tailscale is not an identity provider but relies other identity providers for authentication.</p><h3>Key expiry</h3><p>Key expiry is the end of the validity period for a cryptographic key. An expired key can no longer encrypt or decrypt data, nor authenticate a device to a Tailscale network.</p><p>Using Tailscale means you never have to manage encryption keys directly. Tailscale automatically expires keys and requires them to be regenerated at regular intervals. You can disable key expiry for long-lived devices from the admin console.</p><h3>MagicDNS</h3><p>MagicDNS automatically registers memorable hostnames for devices in your Tailscale network. It also extends and improves DNS functionality.</p><h3>NAT traversal</h3><p>NAT is an acronym for network address translation. NAT traversal is a way to connect nodes across the internet through barriers such as firewalls. Most internet devices can’t talk to each other because of firewalls and devices that do network address translation. NAT traversal works around these barriers, allowing data to traverse the network.</p><h3>Network topology</h3><p>A network topology is an arrangement of nodes in a network. It shows the connections between them. Examples of network topologies include star, bus, hub-and-spoke, mesh, and hybrid.</p><p>Traditional virtual private networks (VPNs) use a hub-and-spoke topology. Each machine communicates with another in this setup by sending all traffic through a central gateway machine. Tailscale operates as a mesh topology where each machine can talk directly to others using NAT traversal.</p><h3>Node</h3><p>A node is a combination of a user and a device.</p><h3>Peer</h3><p>A peer is another node that your node is trying to talk to. A peer might or might not be in the same domain.</p><h3>Relay</h3><p>A relay is an intermediary server that passes data between two or more nodes in a network. Tailscale uses a special type of globally distributed relay server called Designated Encrypted Relay for Packets (DERP). DERP relay servers function as a fallback to connect nodes when NAT traversal fails.</p><h3>SSO</h3><p>SSO is an acronym for single sign-on. Single sign-on lets users log in to one site using the identity of another.</p><h3>Tailnet</h3><p>A tailnet is another term for a Tailscale network, which is an interconnected collection of users, machines, and resources. The network has a control plane and a data plane that work in unison to manage access and send data between nodes.</p><p>There are personal and organization tailnets. A personal tailnet is a shared domain single-user tailnet (like gmail.com). An organization tailnet is a custom domain tailnet (like example.com),</p><h3>Tailnet policy file</h3><p>The tailnet policy file stores your Tailscale network’s access rules, along with other tailnet configuration items. It uses human JSON (HuJSON) and conforms to the Tailscale policy syntax.</p><h3>Tailscale IP address</h3><p>A Tailscale IP address is a unique IP address assigned to each machine in your Tailscale network. It’s always in the form 100.x.y.z (for example, 100.101.102.103). It stays the same even when switching between your home internet connection, cellular networks, or coffee shop Wi-Fi networks.</p><h3>Tunnel</h3><p>In networking, a tunnel is an encapsulated connection between one or more points in a network. It lets users, nodes, or resources communicate securely over a public data network.</p><h3>WireGuard</h3><p>WireGuard is the underlying cryptographic protocol that Tailscale uses.</p><p>Without forgetting modern design of the clients available on <strong>MacOS</strong>, <strong>Linux</strong>, <strong>IOS</strong>, <strong>Android</strong> &amp; <strong>Windows</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/0*Gyc7m0EpXjWVhpyV.png" /></figure><p><a href="https://twitter.com/S0fianeHamlaoui">x.com</a></p><p>© 2024 — Sofiane Hamlaooui — Making the world a better place 🌎</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0ac4c42b085" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 15 Penetration Testing Tools for Cybersecurity in 2024]]></title>
            <link>https://medium.com/@SofianeHamlaoui/top-15-penetration-testing-tools-for-cybersecurity-in-2024-4cde37b7f186?source=rss-5dda1657acd1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cde37b7f186</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[sofiane-hamlaoui]]></category>
            <category><![CDATA[hacking]]></category>
            <dc:creator><![CDATA[Sofiane Hamlaoui]]></dc:creator>
            <pubDate>Fri, 14 Jun 2024 04:03:57 GMT</pubDate>
            <atom:updated>2024-06-14T04:03:57.271Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*f2mu6Tk0DX4W-iV_2m2JdA.png" /></figure><p>To combat the growing number of sophisticated cyber threats, security professionals must stay up-to-date with the latest tools and techniques.</p><p>In this article, we will explore the top 20 penetration testing tools. These tools are indispensable for identifying, evaluating, and addressing vulnerabilities in networks and applications.</p><p>The list features a mix of open-source and commercial solutions. These state-of-the-art tools are vital for security researchers looking to protect their digital assets in today’s ever-evolving cyber landscape.</p><p>Pentesting simulates cyber attacks on an organization’s systems before cybercriminals can. By identifying vulnerabilities in a system or network, organizations get the opportunity to address vulnerabilities to prevent potential breaches. Furthermore, testing ensures companies follow regulatory requirements.</p><p>Below, we’ll look at the best penetration testing tools that you’ll want in your toolkit in 2024.</p><h3>Types of Pentesting Tools</h3><p>It’s important to differentiate pentesting tools from vulnerability scanners or scanning tools.</p><p>Scanners are automated tools used to scan a system or network for known vulnerabilities. DAST is an example of a common type of scanner. While they’re quick to deploy, they’re also limited in their ability to identify new and more complex vulnerabilities.</p><p>A penetration testing tool helps security researchers manually identify vulnerabilities. During a pentest, testers can exploit them and try to gain access to an organization’s system or network, as a cybercriminal would. As a result, pentesters can identify a wider range of vulnerabilities, both known and unknown, and provide more detailed recommendations for remediation.</p><p>Penetration testing tools fall into a wide range of categories such as:</p><ul><li>Web app, Network, Cloud, Wireless or Mobile Application Pentesting</li><li>hardware testing</li><li>social engineering</li><li>exploitation frameworks</li><li>password cracking</li></ul><p>Each tool has unique features and capabilities. Many of these tools are essential components of any pentester’s toolkit.</p><h3>Web App Pentesting Tools</h3><p>Web application penetration testing tools send various inputs to a web application to see how it responds to help uncover vulnerabilities such as SQL injection, cross-site scripting, cross-site request forgery, and authentication flaws. They can also test for vulnerabilities in web frameworks and third-party components, such as plugins or libraries.</p><ol><li><strong>Nikto2</strong></li></ol><p>Nikto2 is an open-source web server scanner. It can detect outdated software versions, insecure configuration settings, and cross-site scripting (XSS) vulnerabilities.</p><p>2. <strong>BurpSuite</strong></p><p>BurpSuite’s a popular pentesting tool. Its features include a proxy server, scanner, intruder, and repeater. This makes it a versatile tool for testing. Its proxy server allows users to intercept and modify traffic between a browser and a server. Its scanner can automatically detect and exploit vulnerabilities in web applications or APIs. BurpSuite also supports integration with tools like Metasploit and Nmap. It also comes native to Kali Linux. Read more with BurpSuite use cases.</p><h3>Network Pentesting Tools</h3><p>Network penetration testing tools analyze network configurations and services, routing protocols, and applications to find vulnerabilities in network infrastructure, devices, and protocols.</p><p>3. <strong>BurpSuite</strong></p><p>Wireshark is a popular open-source network protocol analyzer. It can be used on multiple operating systems to capture and analyze network traffic. Real-time network packet inspection and filtering capabilities facilitate focused investigation of specific network traffic.</p><h3>Cloud Pentesting Tools</h3><p>Cloud pentesting tools are designed specifically for evaluating the security posture of cloud environments. These environments are increasingly used to store sensitive data and run critical applications.</p><p>4. <strong>ScoutSuite</strong></p><p>ScoutSuite is a popular tool that scans cloud environments for vulnerabilities and misconfigurations. The tool works across AWS, Azure, and GCP. It provides a detailed analysis of cloud resources, such as virtual machines, databases, and storage buckets. It also assesses their compliance with industry-standard security best practices.</p><p>5. <strong>CloudMapper</strong></p><p>CloudMapper is an open-source cloud security tool that creates detailed visual maps of cloud infrastructure. It provides a comprehensive view of the relationships between different resources. It identifies security risks and potential attack paths. It is also capable of generating detailed reports with recommendations for addressing vulnerabilities.</p><p>6. <strong>Prowler</strong></p><p>Prowler is an open-source AWS security tool designed to audit AWS accounts for security best practices. It provides an extensive list of checks that assess compliance with industry-standard security frameworks like NIST, CIS, and PCI DSS. It also generates detailed reports of audit findings.</p><h3>Wireless Pentesting Tools</h3><p>Wireless pentesting tools, designed to identify vulnerabilities and weaknesses in wireless networks and their associated devices, help detect and exploit network security flaws, unauthorized access points, and weak encryption protocols. Read more about Cobalt’s Wireless pentesting serivces.</p><p><strong>7. Aircrack-ng</strong></p><p>Aircrack-ng provides a comprehensive suite of tools for monitoring and analyzing network traffic. It also supports cracking passwords for wifi networks that use weak encryption methods. It’s open-source and can help identify vulnerable access points, monitor network traffic, and test network security.</p><p>8. <strong>Kismet</strong></p><p>Kismet provides real-time detection and analysis of wireless network traffic, including SSIDs, MAC addresses, signal strength, and more. It helps pentesters discover and identify rogue access points, network misconfigurations, and hidden wireless networks.</p><h3>Mobile Application Pentesting Tools</h3><p>Mobile application pentesting tools analyze the security of mobile apps on various platforms, including iOS and Android. These tools often include features such as dynamic analysis, static analysis, reverse engineering, and code analysis to provide a comprehensive assessment of the mobile app’s security posture.</p><p>9. <strong>Frida</strong></p><p>Frida is a powerful tool for reverse engineering and debugging Android and iOS applications. It lets pentesters hook into function calls, intercept network traffic, and manipulate binary code to modify the behavior of the target application. It’s an ideal tool to perform in-depth analysis.</p><h3>Hardware Pentesting Tools</h3><p>Hardware pentesting tools are used to assess the security of physical devices. This includes IoT devices, hardware security modules, USB devices., ATMs, Point of Sale (POS) terminals, and others.</p><p>10. <strong>Proxmark3</strong></p><p>Proxmark3 is an open-source hardware tool used for RFID research and testing. It can read and emulate different types of RFID cards and tags, perform wireless analysis, and clone RFID devices. This tool allows pentesters to simulate various attacks, such as replay attacks and man-in-the-middle attacks, on RFID systems to assess their security posture.</p><h3>Social Engineering Pentesting Tools</h3><p>Social engineering tools are designed to simulate attacks that use human interaction to manipulate individuals into divulging sensitive information or performing specific actions. They help assess an organization’s security awareness and training programs.</p><p>11. <strong>The Social Engineer Toolkit (SET)</strong></p><p>The Social Engineer Toolkit (SET) is an open-source tool used to generate a variety of social engineering attacks like pear-phishing and credential harvesting. Additionally, it includes email spoofing, SMS spoofing, and geolocation spoofing capabilities. It can even integrate with the Metasploit Framework to allow testers to deliver payloads and exploit vulnerabilities.</p><h3>Exploitation Frameworks</h3><p>Exploitation frameworks are collections of tools that provide a range of pre-built exploits for common vulnerabilities. They often include a scripting interface for customization. Other common features such as payload generators, command shells, and post-exploitation modules make it easier for testers to gain full control of the target system.</p><p>12. <strong>SQLmap</strong></p><p>SQLmap is an open-source tool that automates the process of identifying and exploiting SQL injection vulnerabilities in web applications. It supports a variety of database management systems, including MySQL, Oracle, and PostgreSQL. While it’s largely automated, pentesters use it in combination with manual testing.</p><p>13. <strong>The Browser Exploitation Framework</strong></p><p>BeEF (The Browser Exploitation Framework) allows penetration testers to exploit client-side vulnerabilities in web browsers. BeEF hooks into a target browser and allows the tester to interact with it in rea-time. This allows testers to launch attacks like keylogging and cookie stealing. It is particularly useful for testing the effectiveness of browser-based security controls like Content Security Policy (CSP) and Same Origin Policy (SOP).</p><h3>Password Cracking Tools</h3><p>Password cracking tools are used to recover passwords by attempting to guess them through brute-force or dictionary attacks. Password cracking tools are valuable for testing the strength of an organization’s password policies. These tools can help identify vulnerabilities in password management practices.</p><p>14. <strong>John the Ripper</strong></p><p>John the Ripper is a widely-used tool for cracking passwords encrypted with popular encryption algorithms like MD5 and SHA. It can also perform dictionary attacks and to test the strength of passwords.</p><p>15. <strong>Hashcat</strong></p><p>Hashcat is a popular tool that can crack over 300 different hash types using a dictionary, brute-force, and hybrid attacks. It supports distributed cracking so multiple computers can work together to crack a password during forensic investigations.</p><p><a href="https://twitter.com/S0fianeHamlaoui">x.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cde37b7f186" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Введение в технологию eBPF]]></title>
            <link>https://medium.com/@SofianeHamlaoui/%D0%B2%D0%B2%D0%B5%D0%B4%D0%B5%D0%BD%D0%B8%D0%B5-%D0%B2-%D1%82%D0%B5%D1%85%D0%BD%D0%BE%D0%BB%D0%BE%D0%B3%D0%B8%D1%8E-ebpf-e4f99da22257?source=rss-5dda1657acd1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4f99da22257</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[sofiane-hamlaoui]]></category>
            <category><![CDATA[ebpf]]></category>
            <dc:creator><![CDATA[Sofiane Hamlaoui]]></dc:creator>
            <pubDate>Tue, 28 Jun 2022 07:56:01 GMT</pubDate>
            <atom:updated>2022-06-28T07:56:01.563Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*iWYieg6xn7JjTsas" /></figure><p>С помощью <strong>eBPF</strong> программисты могут выполнять пользовательские байт-коды в ядре без изменения ядра или загрузки модулей ядра. eBPF тесно связан с ядром. Давайте сначала представим некоторые связанные с этим основные понятия.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FpUZGgeKKfBK-W9O" /></figure><p><strong>Система Linux</strong> разделена на <strong>пространство ядра</strong> и <strong>пространство пользователя</strong>.</p><ul><li><strong>Пространство ядра</strong> является ядром операционной системы и имеет неограниченный и полный доступ ко всему оборудованию, такому как память, хранилище и процессор. Поскольку ядро обладает такими полномочиями, оно должно быть строго защищено, позволяя запускать только самый надежный код.</li><li>В <strong>пользовательском пространстве</strong> выполняются <em>неядерные процессы</em>, такие как <em>Ввод-вывод, файловые системы и т.д.</em>. Эти процессы имеют ограниченный доступ к оборудованию через <strong>системные вызовы</strong>, предоставляемые ядром. Другими словами, программы пользовательского пространства должны быть отфильтрованы в пространстве ядра.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/0*cLQZ4u0yUyjwMlJV" /></figure><p><strong>Интерфейс системного вызова</strong> может удовлетворить большинство потребностей, и разработчикам по-прежнему требуется больше гибкости при работе с новым оборудованием, файловыми системами, сетевыми протоколами и даже пользовательскими системными вызовами.</p><p>Что делать, если пользовательский код хочет получить прямой доступ к оборудованию без изменения исходного кода ядра? Можно использовать <strong>Модуль ядра Linux (LKM)</strong>. Пользовательскому пространству обычно требуется доступ к пространству ядра через системные вызовы, в то время как LKM загружается непосредственно в ядро и является частью ядра. Одной из наиболее ценных особенностей LKM является то, что он может быть загружен во время выполнения без компиляции ядра или перезагрузки компьютера.</p><p>LKM очень полезен, но также сопряжен с большим риском. Ядро и пользовательское пространство отличаются друг от друга и имеют разные соображения безопасности. Пространство ядра зарезервировано для <strong>привилегированного</strong> кода, такого как ядро операционной системы. <strong>Системные вызовы</strong> соединяют ядро и пользовательское пространство, позволяя пользовательскому пространству выполнять соответствующие операции с оборудованием. Другими словами, LKM может привести к сбою ядра. Тесная взаимосвязь между модулем и ядром приводит к резкому росту затрат на безопасность и обновление.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wVH2ZC9FMf80JI6L" /></figure><p><strong>eBPF</strong> — это новый метод доступа к <strong>службам ядра Linux и аппаратному обеспечению</strong>. Эта новая технология была использована для создания сетей, ошибок, отслеживания и брандмауэров.</p><p>Эта технология позволяет запускать изолированные программы в привилегированном контексте, таком как ядро операционной системы. Он используется для безопасного и эффективного расширения возможностей ядра без необходимости изменения исходного кода ядра или загрузки модулей ядра.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0CP44BK-QuaO1tzQ" /></figure><p><strong>eBPF</strong> программы управляются событиями и привязаны к пути кода. Путь к коду содержит определенные триггеры, называемые <strong>крючками</strong>, которые выполняют любые подключенные программы <strong>eBPF</strong> при их передаче. Некоторые примеры перехватчиков включают сетевые события, системные вызовы, записи функций и точки трассировки ядра.</p><p>При срабатывании код сначала компилируется в байт-код BPF. В свою очередь, байт-код проверяется перед его запуском, чтобы убедиться, что он не создает цикл. Этот шаг предотвращает случайную или преднамеренную компрометацию ядра Linux программой.</p><p>После того, как программа запускается на крючке, она затем выполняет вспомогательные вызовы. Эти вспомогательные вызовы представляют собой функции, которые предоставляют <strong>eBPF</strong> множество функций для доступа к памяти. Вспомогательные вызовы должны быть предварительно определены ядром, но список существующих функций <a href="https://man7.org/linux/man-pages/man7/bpf-helpers.7.html">продолжает расти</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z6A_3_ELVaNWt8Cx" /></figure><p><strong>eBPF</strong> первоначально использовался как способ повышения наблюдаемости и безопасности при фильтрации сетевых пакетов. Однако со временем это стало способом сделать реализацию пользовательского кода более безопасной, удобной и производительной.</p><p>eBPF обычно используется для <strong>отслеживания</strong> процессов в пользовательском пространстве, и здесь проявляются его преимущества. Это безопасный и полезный метод обеспечения:</p><ul><li><strong>Скорость и производительность.</strong> eBPF может перемещать обработку пакетов из пространства ядра в пространство пользователя. Аналогично, eBPF — это JIT-компилятор just-in-time (точно в срок). После компиляции байт-кода вызывается eBPF, а не новая интерпретация байт-кода для каждого метода.</li><li><strong>Низкая навязчивость.</strong> При использовании в качестве отладчика eBPF не нужно останавливать программу, чтобы наблюдать за ее состоянием.</li><li><strong>Безопасность.</strong> Программы эффективно изолированы, что означает, что исходный код ядра остается защищенным и неизменным. Этап проверки гарантирует, что ресурсы не будут перегружены программами, выполняющими бесконечные циклы.</li><li><strong>Удобство.</strong> Создание кода, который подключает функции ядра, требует меньше усилий, чем сборка и обслуживание модулей ядра.</li><li><strong>Унифицированная трассировка.</strong> eBPF предоставляет вам единую, мощную и доступную платформу для отслеживания процессов. Это повышает видимость и безопасность.</li><li><strong>Программируемость.</strong> Использование eBPF помогает увеличить многофункциональность среды без добавления дополнительных слоев. Аналогично, поскольку код выполняется непосредственно в ядре, можно хранить данные между событиями eBPF вместо того, чтобы сбрасывать их, как это делают другие трассировщики.</li><li><strong>Выразительность.</strong> eBPF является выразительным, способным выполнять функции, обычно встречающиеся только в языках высокого уровня.</li></ul><p>Поскольку <strong>eBPF</strong> — это такая новая технология, многие вещи остаются неизученными. Лучшие практики в области <strong>eBPF</strong> все еще развиваются по мере того, как технология приобретает все большее значение. Хотя определенного набора лучших практик не существует, есть несколько вещей, которые вы можете сделать, чтобы обеспечить эффективные и действенные программы.</p><p>Если вы используете eBPF для своей экосистемы, я рекомендую вам:</p><ul><li><strong>Используйте [LLVM Clang](</strong><a href="https://clang.llvm.org/"><strong>https://clang.llvm.org</strong></a><strong> /) для компиляции C в байт-код.</strong></li><li>Когда eBPF впервые появился на сцене, было необходимо закодировать и собрать программу вручную. Затем разработчики использовали ассемблер ядра для генерации байт-кода. К счастью, в этом больше нет необходимости. Clang предоставляет инфраструктуру для интерфейса и инструментария на языках Си.</li><li><strong>Используйте инструментарий BCC при написании программ BPF.</strong></li><li><a href="https://github.com/iovisor/bcc">Коллекция компиляторов BPF</a> (BCC) — это набор инструментов, который может помочь вам создавать эффективные программы отслеживания ядра и манипулирования ими. Он особенно подходит для задач, связанных с анализом производительности и управлением сетевым трафиком.</li></ul><blockquote><em>⚠️ Thanks to Simon for the translation.</em></blockquote><p>© 2022 — Sofiane Hamlaooui — Making the world a better place 🌎</p><p>Originally published at <a href="http://blog.sofiane.cc/ru">http://blog.sofiane.cc/ru</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4f99da22257" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction à la technologie eBPF]]></title>
            <link>https://medium.com/@SofianeHamlaoui/introduction-%C3%A0-la-technologie-ebpf-65f96a64f453?source=rss-5dda1657acd1------2</link>
            <guid isPermaLink="false">https://medium.com/p/65f96a64f453</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[sofiane-hamlaoui]]></category>
            <category><![CDATA[ebpf]]></category>
            <dc:creator><![CDATA[Sofiane Hamlaoui]]></dc:creator>
            <pubDate>Tue, 28 Jun 2022 07:53:52 GMT</pubDate>
            <atom:updated>2022-06-28T07:53:52.010Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*AAtOxllAb4sfVeer" /></figure><p>Avec l’ <strong>eBPF</strong>, les programmeurs peuvent exécuter des <strong>bytecodes</strong> personnalisés dans le noyau sans modifier ni charger les modules du noyau ( Kernel ). l’eBPF est étroitement lié au noyau. Introduisons d’abord quelques concepts de base connexes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YIUs9huYnR7e7p5q" /></figure><p><strong>Le système Linux</strong> est divisé en <strong>espace noyau</strong> et <strong>espace utilisateur</strong>.</p><ul><li><strong>L’espace du noyau</strong> est le cœur du système d’exploitation et dispose d’un accès illimité et complet à tout le matériel, comme la mémoire, le stockage et le processeur. Étant donné que le noyau a une telle super autorité, il est tenu d’être strictement protégé, ne permettant que le code le plus fiable de s’exécuter.</li><li>L’ <strong>espace utilisateur</strong> exécute des <em>processus non-noyau</em> — tels que <em>E/S, systèmes de fichiers, etc</em>. Ces processus ont un accès limité au matériel via des <strong>appels système</strong> exposés par le noyau. En d’autres termes, les programmes de l’espace utilisateur doivent être filtrés dans l’espace noyau.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/0*XYEHMkqyNpTCVKMC" /></figure><p>L’interface des <strong>appels système</strong> peut répondre à la plupart des besoins, et les développeurs ont encore besoin de plus de flexibilité face au nouveau matériel, aux systèmes de fichiers, aux protocoles réseau et même aux appels système personnalisés.</p><p>Que se passe-t-il si le code utilisateur veut accéder directement au matériel sans modifier le code source du noyau ? Un <strong>Linux Kernel Module (LKM)</strong> peut être utilisé. L’espace utilisateur doit généralement accéder à l’espace du noyau via des appels système, tandis que <strong>LKM</strong> est directement chargé dans le noyau et fait partie du noyau. L’une des fonctionnalités les plus précieuses de LKM est qu’il peut être chargé au moment de l’exécution sans compiler le noyau ni redémarrer la machine.</p><p><strong>LKM</strong> est très utile, mais présente également beaucoup de risques. Le noyau et l’espace utilisateur sont différents et ont des considérations de sécurité différentes. L’espace du noyau est réservé au code <strong>privilégié</strong> comme le noyau du système d’exploitation. Les <strong>appels système</strong> connectent le noyau et l’espace utilisateur, permettant à l’espace utilisateur d’effectuer les opérations appropriées sur le matériel. En d’autres termes, LKM peut planter le noyau. La relation étroite entre le module et le noyau fait monter en flèche les coûts de sécurité et de mise à niveau.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jowRND6tBi3RL2uN" /></figure><p><strong>eBPF</strong> est une nouvelle méthode d’accès aux <strong>au matériel et les services du noyau Linux</strong>. Cette nouvelle technologie a été utilisée pour le réseautage, les erreurs, le suivi et les pare-feu.</p><p>Cette technologie peut exécuter des programmes en <strong>sandbox</strong> ( <strong>isolation</strong> ) dans un contexte privilégié tel que le noyau du système d’exploitation. Il est utilisé pour étendre en toute sécurité et efficacement les capacités du noyau sans qu’il soit nécessaire de modifier le code source ou de charger des modules du noyau.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jMRVsM5C96jCMTu5" /></figure><p>Les programmes <strong>eBPF</strong> sont pilotés par des événements et attachés à un chemin de code. Le chemin du code contient des déclencheurs spécifiques appelés <strong>hooks</strong> qui exécutent tous les programmes <strong>eBPF</strong> attachés lorsqu’ils sont transmis. Certains exemples de <strong>hooks</strong> incluent les événements réseau, les appels système, les entrées de fonction et les points de trace du noyau.</p><p>Au déclenchement, le code est d’abord compilé dans le <strong>bytecode BPF</strong>. À son tour, le bytecode est vérifié avant son exécution, pour s’assurer qu’il ne crée pas de boucle. Cette étape empêche le programme de compromettre le noyau Linux accidentellement ou exprès.</p><p>Une fois qu’un programme est déclenché à un hook, il effectue ensuite des appels d’assistance. Ces appels d’assistance sont des fonctions qui équipent <strong>eBPF</strong> de nombreuses fonctionnalités pour accéder à la mémoire. Les appels d’assistance doivent être prédéfinis par le noyau, mais la liste des fonctions existantes<a href="https://man7.org/linux/man-pages/man7/bpf-helpers.7.html"><strong>continue de croître</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dLkVxpjxivjenhya" /></figure><p>l’ <strong>eBPF</strong> a été initialement utilisé pour augmenter l’ <strong>observabilité</strong> et la sécurité lors du filtrage des paquets réseau. Cependant, au fil du temps, c’est devenu un moyen de rendre l’implémentation du code fourni par l’utilisateur plus sûre, plus pratique et plus performante.</p><p>l’eBPF est généralement utilisé pour <strong>tracer</strong> les processus de l’espace utilisateur.</p><p>C’est une méthode sûre et utile pour assurer :</p><ul><li><strong>Vitesse et performances</strong> : l’eBPF peut déplacer le traitement des paquets de l’espace noyau vers l’espace utilisateur. De même, <strong>eBPF</strong> est un <strong>compilateur à la volée / Juste à temps</strong> ( <strong>JIT</strong>). Une fois le bytecode compilé, l’eBPF est invoqué plutôt qu’une nouvelle interprétation du bytecode pour chaque méthode.</li><li><strong>Faible intrusion</strong> : Lorsqu’il est utilisé comme débogueur, l’eBPF n’a pas besoin d’arrêter un programme pour observer son état.</li><li><strong>Sécurité</strong> : Les programmes sont effectivement placés dans un sandbox, ce qui signifie que le code source du noyau reste protégé et inchangé. L’étape de <strong>vérification</strong> garantit que les ressources ne sont pas saturées par des programmes qui exécutent des boucles infinies.</li><li><strong>Commodité</strong> : Créer du code qui relie les fonctions du noyau demande moins de travail que de créer et de maintenir des modules du noyau.</li><li><strong>Traçage unifié</strong> : l’eBPF vous offre un cadre unique, puissant et accessible pour les processus de traçage. Cela augmente la visibilité et la sécurité.</li><li><strong>Programmabilité</strong> : L’utilisation d’eBPF permet d’augmenter la richesse des fonctionnalités d’un environnement sans ajouter de couches supplémentaires. De même, puisque le code est exécuté directement dans le noyau, il est possible de stocker des données entre les événements eBPF au lieu de les vider comme le font d’autres traceurs.</li><li><strong>Expressivité</strong> l’eBPF est expressif, capable d’exécuter des fonctions que l’on ne trouve généralement que dans les langages de haut niveau.</li></ul><p>Étant donné que l’ <strong>eBPF</strong> est une technologie tellement nouvelle, beaucoup de choses restent inexplorées. Les meilleures pratiques concernant l’ <strong>eBPF</strong> évoluent à mesure que la technologie prend de l’importance. Bien qu’il n’existe aucun ensemble défini de meilleures pratiques, vous pouvez faire certaines choses pour garantir des programmes efficaces et efficients.</p><p>Si vous utilisez l’eBPF pour votre <strong>écosystème</strong>, je vous recommande de :</p><ul><li><strong>Utilisez </strong><a href="https://clang.llvm.org/"><strong>LLVM Clang</strong></a><strong> pour compiler le C en bytecode.</strong></li><li>Lorsque l’eBPF est entré en scène pour la première fois, il a fallu coder et assembler le programme à la main. Ensuite, les développeurs ont utilisé l’assembleur du noyau pour générer du bytecode. Heureusement, il n’est plus nécessaire de le faire. <strong>Clang</strong> fournit une infrastructure pour le frontend et les outils en langage C.</li><li><strong>Utilisez les outils BCC lors de l’écriture de programmes BPF.</strong></li><li>La <a href="https://github.com/iovisor/bcc">BPF Compiler Collection</a> (BCC) est une boîte à outils qui peut vous aider à créer des programmes efficaces de traçage et de manipulation du noyau. Il est particulièrement adapté aux tâches liées à l’analyse des performances et au contrôle du trafic réseau.</li></ul><p>© 2022 — Sofiane Hamlaooui — Making the world a better place 🌎</p><p><em>Originally published at </em><a href="http://blog.sofiane.cc/fr"><em>http://blog.sofiane.cc/fr</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65f96a64f453" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[eBPF — Understanding How It Works]]></title>
            <link>https://medium.com/@SofianeHamlaoui/ebpf-understanding-how-it-works-526a85888dfe?source=rss-5dda1657acd1------2</link>
            <guid isPermaLink="false">https://medium.com/p/526a85888dfe</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[ebpf]]></category>
            <category><![CDATA[sofiane-hamlaoui]]></category>
            <dc:creator><![CDATA[Sofiane Hamlaoui]]></dc:creator>
            <pubDate>Tue, 28 Jun 2022 07:52:10 GMT</pubDate>
            <atom:updated>2022-06-28T07:52:10.864Z</atom:updated>
            <content:encoded><![CDATA[<h3>eBPF — Understanding How It Works</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*lnu8kydmSOzX8IPB" /></figure><p>In a lot of scenarios, eBPF is not used directly but indirectly via projects like <a href="https://github.com/cilium/cilium">Cilium</a>, <a href="https://github.com/iovisor/bcc">bcc</a>, or <a href="https://github.com/iovisor/bpftrace">bpftrace</a> which provide an abstraction on top of eBPF and do not require to write programs directly but instead offer the ability to specify intent-based definitions which are then implemented with eBPF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uOqNCds3ArXFuWNn" /></figure><p>If no higher-level abstraction exists, programs need to be written directly. The Linux kernel expects eBPF programs to be loaded in the form of bytecode. While it is of course possible to write bytecode directly, the more common development practice is to leverage a compiler suite like <a href="https://llvm.org/">LLVM</a> to compile pseudo-C code into eBPF bytecode.</p><p>The eBPF infrastructure was described earlier. These capabilities are implemented collaboratively by multiple components, each with its own complexity.</p><h3>Anatomy of an eBPF Program</h3><h4>Events and Hooks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zpXEEXOCUw3ueKlP" /></figure><p>eBPF programs are triggered by events in the kernel. When some specific instructions are executed, these events will be caught at the hook. When the hook is triggered, the eBPF program is executed to capture and manipulate the data. The variety of hook positioning is one of the shining points of eBPF. For example the following:</p><ul><li>System Call: When a user space program performs a kernel function through a system call.</li><li>Function entry and exit: Intercept calls before the function exits.</li><li>Network events: When a packet is received.</li><li>kprobe and uprobe: Hook into kernel or user functions.</li></ul><h4>helper function</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nDZsUTJPRDUvj4MY" /></figure><p>Helper functions are called when the eBPF program is triggered. These special functions allow eBPF to have rich functions for accessing memory. For example Helper can perform a series of tasks:</p><ul><li>Search, update, and delete key-value pairs in the data table.</li><li>Generate pseudo-random numbers.</li><li>Collect and tag tunnel metadata.</li><li>To link the eBPF program, this function is called tail call.</li><li>Perform socket-related tasks, such as binding, obtaining cookies, and redirecting packets.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NRqjCb_tbKWC_Pgi" /></figure><p>These helper functions must be defined by the kernel, in other words, the calling ability of eBPF programs is restricted by a whitelist. The list is long and still growing.</p><h4>Maps</h4><p>To store and share data between eBPF programs and the kernel and user space, eBPF requires the use of Maps. As the name suggests, a Map is a key-value pair. Map can support a variety of data structures, and eBPF programs can send and receive data in Map through helper functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TORAOlAzi_f5eIGu" /></figure><p>The following is an incomplete list of supported map types to give an understanding of the diversity in data structures. For various map types, both a shared and a per-CPU variation is available.</p><ul><li>Hash tables, Arrays</li><li>LRU (Least Recently Used)</li><li>Ring Buffer</li><li>Stack Trace</li><li>LPM (Longest Prefix match)</li></ul><h3>Execute the eBPF program</h3><h4>Load and check</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BzKIs71BwxloTwpL" /></figure><p>All eBPF programs are executed in bytecode, so there needs to be a way to compile high-level languages into this bytecode. eBPF uses LLVM as the backend, and the frontend can intervene in any language. Because eBPF is written in C, the front end uses Clang. But before the bytecode can be hooked, it must pass a series of checks. Use Kernel Verifier to prevent programs with loops, incorrect permissions, or crashes from running in a virtual machine-like environment. If the program passes all checks, the bytecode is loaded onto the Hook using a bpf() system call.</p><h4>Verification</h4><p>The verification step ensures that the eBPF program is safe to run. It validates that the program meets several conditions, for example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vt2Kpwo9zD2A8pNp" /></figure><ul><li>The program does not crash or otherwise harm the system.</li><li>The program always runs to completion (i.e. the program does not sit in a loop forever, holding up further processing).</li></ul><h4>JIT Compilation</h4><p>The <strong>Just-in-Time (JIT)</strong> compilation step translates the generic bytecode of the program into the machine specific instruction set to optimize execution speed of the program. This makes eBPF programs run as efficiently as natively compiled kernel code or as code loaded as a kernel module.</p><h4>Required Privileges</h4><p>Unless unprivileged eBPF is enabled, all processes that intend to load eBPF programs into the Linux kernel must be running in privileged mode (root) or require the capability CAP_BPF. This means that untrusted programs cannot load eBPF programs.</p><p>If unprivileged eBPF is enabled, unprivileged processes can load certain eBPF programs subject to a reduced functionality set and with limited access to the kernel.</p><h4>Verifier</h4><p>If a process is allowed to load an eBPF program, all programs still pass through the eBPF verifier. The eBPF verifier ensures the safety of the program itself. This means, for example:</p><ul><li>Programs are validated to ensure they always run to completion, e.g. an eBPF program may never block or sit in a loop forever. eBPF programs may contain so called bounded loops but the program is only accepted if the verifier can ensure that the loop contains an exit condition which is guaranteed to become true.</li><li>Programs may not use any uninitialized variables or access memory out of bounds.</li><li>Programs must fit within the size requirements of the system. It is not possible to load arbitrarily large eBPF programs.</li><li>Program must have a finite complexity. The verifier will evaluate all possible execution paths and must be capable of completing the analysis within the limits of the configured upper complexity limit.</li></ul><h3>Summarize</h3><p>Putting the above concepts together, the eBPF program inserts hooks after passing the security check. After being triggered by an event, the program starts to execute, and uses auxiliary functions and Maps to store and operate data. Next time we’ll look at how they work together.</p><h3>Simple Usage Example</h3><p>On this example, we will use a simple eBPF program already made and functuional used that we can already find on the <strong>BPF Compiler Collection</strong>.</p><p>As I mentioned above, eBPF is used indirectly in most scenarios via projects BCC for example.</p><p>In this example we are going to use <a href="https://github.com/iovisor/bcc/blob/master/tools/tcpconnect.py">tcpconnect.py</a> that traces the kernel function performing active TCP connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/0*MYmwThpBG2G4bn67" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/0*d3YMbA0VVpCCOEls" /></figure><p>© 2022 — Sofiane Hamlaooui — Making the world a better place 🌎</p><p><em>Originally published at </em><a href="http://blog.sofiane.cc/"><em>http://blog.sofiane.cc</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=526a85888dfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[eBPF — eBPF In Action using BCC]]></title>
            <link>https://medium.com/@SofianeHamlaoui/ebpf-ebpf-in-action-using-bcc-7484c46becf?source=rss-5dda1657acd1------2</link>
            <guid isPermaLink="false">https://medium.com/p/7484c46becf</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[ebpf]]></category>
            <category><![CDATA[sofiane-hamlaoui]]></category>
            <dc:creator><![CDATA[Sofiane Hamlaoui]]></dc:creator>
            <pubDate>Tue, 28 Jun 2022 07:49:25 GMT</pubDate>
            <atom:updated>2022-06-28T07:49:25.609Z</atom:updated>
            <content:encoded><![CDATA[<h3>eBPF — eBPF In Action using BCC</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*5E0Rfw4kLny_YrFq" /></figure><p>After explaining the working of <strong>eBPF</strong> and its architecture, now we are going to try some eBPF programs to see and know what kind of operations and syscalls we can execute using it.</p><p>As already explained on the last 2 articles I wrote about eBPF, <strong>BCC</strong> is a toolkit for creating efficient <strong>kernel tracing</strong> and <strong>manipulation</strong> programs, and includes several useful tools and examples. It makes use of extended BPF ( <strong>Berkeley Packet Filters</strong>), formally known as eBPF, a new feature that was first added to Linux 3.15. Much of what BCC uses <strong>requires</strong> Linux 4.1 and above.</p><p>In general, to use these features, a Linux kernel version 4.1 or newer is required. In addition, the kernel should have been compiled with the following flags set:</p><pre>CONFIG_BPF=y CONFIG_BPF_SYSCALL=y # [optional, for tc filters] CONFIG_NET_CLS_BPF=m # [optional, for tc actions] CONFIG_NET_ACT_BPF=m CONFIG_BPF_JIT=y # [for Linux kernel versions 4.1 through 4.6] CONFIG_HAVE_BPF_JIT=y # [for Linux kernel versions 4.7 and later] CONFIG_HAVE_EBPF_JIT=y # [optional, for kprobes] CONFIG_BPF_EVENTS=y # Need kernel headers through /sys/kernel/kheaders.tar.xz CONFIG_IKHEADERS=y</pre><p>There are a few optional kernel flags needed for running bcc networking examples on vanilla kernel:</p><pre>CONFIG_NET_SCH_SFQ=m CONFIG_NET_ACT_POLICE=m CONFIG_NET_ACT_GACT=m CONFIG_DUMMY=m CONFIG_VXLAN=m</pre><blockquote><em>You can check the Kernel compile flags by copying &amp; extracting the </em><em>/proc/config.gz and checking the containing </em><em>config file</em></blockquote><p>Execute this command to check the flags on your Kernel.</p><pre>cd /tmp &amp;&amp; cp /proc/config.gz . &amp;&amp; gzip -d config.gz &amp;&amp; cat config</pre><p>You can check the whole installation process here : <a href="https://github.com/iovisor/bcc/blob/master/INSTALL.md">BCC Install</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dJP7TWm2A2JpS5bI" /></figure><blockquote><em>⚠️ : Using those scripts needs root permission to work properly</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/0*b32iZRt0YhEwG1bW" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/0*HidJ3CxMybSOb293" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/0*tQQZ7tksSI1NvtWv" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/0*153HP3cBD9CdMAkb" /></figure><pre>Those are the executed commands on my computer in loop for Polybar scipts**</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/0*IiPPWBrN9BPZhVkt" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/0*TOayuhGGJ8kc2EDs" /></figure><blockquote><em>check the whole BCC Tools Pack </em><a href="https://github.com/iovisor/bcc/tree/master/tools"><em>BCC Tools</em></a></blockquote><p>here is a picture explaining the different BCC Tracing tools / BPF programs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4fqpADPyF_WmEGc0.png" /></figure><p>So now, you do understand and know how <strong>BPF</strong>, <strong>eBPF</strong> and <strong>BPF programs</strong> work.</p><p>For better and more much scalable solutions, you will have to :</p><ol><li>Develop your own BPF programs and tools.</li><li>Use Open Source projects already working with full functional structure for each fonctionality.</li><li>Use paid products and solutions.</li></ol><p>We’ll try exploring all of this on the next articles.</p><p>© 2022 — Sofiane Hamlaooui — Making the world a better place 🌎</p><p><em>Originally published at </em><a href="http://blog.sofiane.cc/"><em>http://</em>blog.sofiane.cc</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7484c46becf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>