{"title":"funcptr - php","subtitle":"An engineer's technical notebook","link":[{"@attributes":{"rel":"self","type":"application\/atom+xml","href":"https:\/\/funcptr.net\/language\/php\/atom.xml"}},{"@attributes":{"rel":"alternate","type":"text\/html","href":"https:\/\/funcptr.net\/"}}],"generator":"Zola","updated":"2013-08-25T13:05:00+00:00","id":"https:\/\/funcptr.net\/language\/php\/atom.xml","entry":[{"title":"User sessions, what data should be stored where?","published":"2013-08-25T13:05:00+00:00","updated":"2013-08-25T13:05:00+00:00","author":{"name":"Delta Regeer"},"link":{"@attributes":{"rel":"alternate","type":"text\/html","href":"https:\/\/funcptr.net\/2013\/user-sessions-and-the-data-to-be-stored\/"}},"id":"https:\/\/funcptr.net\/2013\/user-sessions-and-the-data-to-be-stored\/","content":"<p><em>This article has been updated. For the old version please check\n<a rel=\"external\" href=\"https:\/\/web.archive.org\/web\/20130826031727\/http:\/\/funcptr.net\/2013\/08\/25\/user-sessions,-what-data-should-be-stored-where-\/\">Archive.org<\/a><\/em><\/p>\n<p>A couple of days ago on <a rel=\"external\" href=\"http:\/\/reddit.com\/\">reddit.com<\/a>'s <a rel=\"external\" href=\"http:\/\/reddit.com\/r\/netsec\/\">\/r\/netsec<\/a> a poster by the name\nof <a rel=\"external\" href=\"http:\/\/danweber.blogspot.com\/\">Dan Weber<\/a> posted what he believed to be an attack on PHP sessions:\n<a rel=\"external\" href=\"http:\/\/danweber.blogspot.com\/2013\/08\/hacking-php-sessions-by-running-out-of.html\">Hacking PHP sessions by running out of memory<\/a> <a rel=\"external\" href=\"http:\/\/www.reddit.com\/r\/netsec\/comments\/1k7khy\/i_know_its_not_that_hard_but_i_think_i_found_a\/\">(reddit link)<\/a>. The way\nthe \"attack\" works is as follows:<\/p>\n<ol>\n<li>Create a new session<\/li>\n<li>Assign some new data to the session, in this case a username which is used\nto signify that the user is logged in.<\/li>\n<li>Check to verify that the user should be logged in<\/li>\n<li>If the user should not be logged in, destroy the session.<\/li>\n<\/ol>\n<p>The \"attack\" would be to run the <a rel=\"external\" href=\"http:\/\/php.net\/\">PHP<\/a> script out of memory on number 3, since\nonce something is set on the session it is immediately stored, so even if the\nuser is not supposed to be logged in, they are now logged in since their\nsession says they are.<\/p>\n<p>I wouldn't necessarily call this a PHP hack, this is really just bad practice\nin terms of programming, the logic should be reversed.<\/p>\n<ol>\n<li>Create a new session<\/li>\n<li>Verify the user should be logged in<\/li>\n<li>If so, set the session data<\/li>\n<li>If the user should not be logged in, don't set the session data<\/li>\n<\/ol>\n<p>That would solve the problem at hand, and now there is no way for the user to\ntrick the PHP script into believing she is logged in when that is not the case.<\/p>\n<p>However as the discussion went on on Reddit, it became even more clear that\nthere are no good resources on what you should store in the user session, and\nwhat you shouldn't store in the user session. Some of these things may seem\nlike common knowledge, but sadly this is something every single new person to\nprogramming has to learn on their own.<\/p>\n<h2 id=\"some-assumptions\">Some assumptions<\/h2>\n<p>Let's get this out of the way, this is in no way limited to PHP, but it is the\none I will be using as an example. This can all apply to Ruby (<a rel=\"external\" href=\"http:\/\/rubyonrails.org\">Ruby on\nRails<\/a>), Python (<a rel=\"external\" href=\"http:\/\/www.pylonsproject.org\">Pyramid<\/a>) or many other frameworks.<\/p>\n<p>The basic problem is that generally writing to the session is not an atomic\ntransaction based on the page accessed, so the assumption made in this article\nis that when you write to the session it is instantly committed, and there is\nno way to roll it back upon failure. If there was, our first example listed\nwouldn't be able to occur since upon running out of memory at step 3, the\nsession would have been rolled back and cleaned up.<\/p>\n<h2 id=\"what-should-you-store-in-the-users-session\">What should you store in the users session?<\/h2>\n<p>You should only really store anything in the session that if it were made\npublic it would do very little harm.<\/p>\n<p>Really the list of items to be stored in a session are as follows:<\/p>\n<ol>\n<li>The users unique id (The ID that allows you to retrieve the users\ninformation from storage)<\/li>\n<li>Temporary state (i.e. Flash messages)<\/li>\n<li>CSRF token<\/li>\n<\/ol>\n<p>More importantly, don't store permission bits, or group memberships, or\nanything that is used to allow\/deny access to particular resources. You want to\nstore just enough information that upon a user accessing your site you are able\nto retrieve the users information from storage, and based upon that information\nfrom storage you then make decisions such as permissions\/group memberships.<\/p>\n<h3 id=\"why-is-this-important\">Why is this important?<\/h3>\n<p>One of the things that Dan Weber brought up in the Reddit post was storing the\nusers permission level and group membership in the session. If your code is\nthen relying on the session to always contain the right permission level, then\nthere is no way to expire someones access to the data.<\/p>\n<ol>\n<li>A user logs in<\/li>\n<li>A user gets various permissions, and they are set in the session<\/li>\n<li>The user has been fired from his job, and an administrator removes the\nusers permissions<\/li>\n<li>Since the user is still logged in, the users permission bits are still\nset, and he continues to have access to parts of the site\/information he\nshouldn't have access to.<\/li>\n<\/ol>\n<p>If instead on every page visit we simply pull out the users unique id and\nverify the permissions upon access, as soon as the permissions are revoked by\nthe administrator the user no longer has access to the various resources.<\/p>\n<h3 id=\"temporary-state\">Temporary state<\/h3>\n<p>There has to be an easy way to remember something from page visit to page visit\nthat isn't considered detrimental if the information gets lost. One of those\nthings is flash messages. Flash messages are generally used to provide the user\nindication that something has changed, they are shown once and then never\nagain.<\/p>\n<p>Storing these as session data makes sense. If the flash message gets set,\ngreat, if it doesn't get set, it doesn't matter. Flash messages are simply a\nnotification tool, if the user misses them it isn't important.<\/p>\n<h2 id=\"what-you-shouldn-t-store-in-the-session\">What you shouldn't store in the session<\/h2>\n<p>Definitely don't store any kind of permission bits, groups a user is a part of\nor anything that would allow the user access that they normally would not be\nable to access.<\/p>\n<p>On each page access check what permissions the user has. While it may mean a\nlittle more heavy lifting server side it provides extra security, and the means\nto enforce changes in permissions instantly.<\/p>\n<h2 id=\"good-secure-programming-practices\">Good secure programming practices<\/h2>\n<p>Keep secure programming practices in mind at all times, always consider how the\ninformation you are storing\/processing is accessed\/viewed\/administered. More\nimportantly think about the access controls that are in place, and how one\ncould expire access to a particular resource without requiring a co-operative\nclient.<\/p>\n<p>The ordering of how variables are set, and when they are set are very\nimportant.  <code>$_SESSION['isadmin'] = True<\/code> at the top of a PHP script, and then\nremoving it by checking to see if the user is actually an administrator later\non in the script is a bad idea.<\/p>\n<p>Always order your code so that if a failure does occur there is no chance that\na critical section of your code is executed by accident, or that information is\nstored in a half-verified state. This is especially important for access\ncontrol.<\/p>\n"},{"title":"Apache mod_fastcgi and PHP with PHP-FPM","published":"2010-11-14T23:37:27+00:00","updated":"2010-11-14T23:37:27+00:00","author":{"name":"Delta Regeer"},"link":{"@attributes":{"rel":"alternate","type":"text\/html","href":"https:\/\/funcptr.net\/2010\/apache-mod-fastcgi-and-php-with-php-fpm\/"}},"id":"https:\/\/funcptr.net\/2010\/apache-mod-fastcgi-and-php-with-php-fpm\/","content":"<p>Recently I did a server migration from an older server to a newer server and in\nan attempt to help stability I wanted to see if there was a better way to do\nPHP FastCGI. In my research I came across running PHP using the FastCGI server\nthat spins up a PHP on a TCP\/IP port and allows the web server to connect to\nit. However this doesn't help with spawning or keeping track of instances or\nerror recovery.<\/p>\n<p>This is where <a rel=\"external\" href=\"http:\/\/php-fpm.org\/\">PHP-FPM<\/a> comes in handy. It does all of the hard work for us,\nit spawns the processes and has a bunch of really awesome features that help\nrun PHP as various different users as required with different PHP ini files and\nmemory limits. PHP-FPM's defaults, at least from a ports install, are extremely\nsane and I don't really suggest changing them. After setting up PHP FPM I had\nto set up Apache.<\/p>\n<p><code>mod_fcgid<\/code> doesn't allow for remote connections, and as such I was unable to use\nit for what I needed it for. <code>mod_fastcgi<\/code> provides the\n<a rel=\"external\" href=\"https:\/\/web.archive.org\/web\/20101111193738\/http:\/\/www.fastcgi.com\/mod_fastcgi\/docs\/mod_fastcgi.html#FastCgiExternalServer\">FastCGIExternalServer<\/a> configuration key, which is exactly what I needed.<\/p>\n<blockquote>\n<p>\"The FastCgiExternalServer directive defines filename as an external\nFastCGI application. If filename does not begin with a slash (<code>\/<\/code>) then it is\nassumed to be relative to the <code>ServerRoot<\/code>. The filename does not have to exist\nin the local filesystem. URIs that Apache resolves to this filename will be\nhandled by this external FastCGI application.\"<\/p>\n<\/blockquote>\n<p>What this documentation does not state is that the path up to the last part of\nit has to exist in the local file system. So in my first couple of attempts I\npointed it at <code>\/usr\/local\/www\/fastcgi\/php5.fcgi<\/code> without having an actual fastcgi\ndirectory located in <code>\/usr\/local\/www\/<\/code>. There are a lot of examples that require\ncreating a new <code>FastCGIExternalServer<\/code> for each and every <code>VirtualHost<\/code> this is\nunacceptable to me, the reason they require it is because they set the\n<code>FastCGIExternalServer<\/code> path to the folder where they are going to be serving\nfiles from.<\/p>\n<p>In the end I found that after creating the <code>\/usr\/local\/www\/fastcgi<\/code> directory\n(and reading the <code>mod_fastcgi<\/code> source code) that all it does is make Apache\nbelieve a file exists in a certain directory, much like <code>Alias<\/code>, except <code>Alias<\/code>\nallows full paths to be aliased, not so here.<\/p>\n<p>The <code>AddType<\/code> and <code>Action<\/code> add custom types and what the action should be when\nsuch a type is encountered. In this case the action is to redirect the request\nto <code>\/php5.fcgi<\/code> which will handle the rest of the request. This does not require\nanother FastCGI section per <code>VirtualHost<\/code> as each PHP request will just get\nshuttled to the php handler.<\/p>\n<p>Do take note that I have specifically disallowed Apache to serve anything from\nthe <code>\/usr\/local\/www\/fastcgi\/<\/code> folder, except for a single file <code>php5.fcgi<\/code>\nwhich is our <code>FastCGIExternalServer<\/code> file.<\/p>\n<pre class=\"giallo\" style=\"color: #D6DEEB; background-color: #011627;\" ><code data-lang=\"plain\"><span class=\"giallo-l\"><span>&lt;IfModule mod_fastcgi.c&gt;<\/span><\/span>\n<span class=\"giallo-l\"><span>    Alias \/php5.fcgi \/usr\/local\/www\/fastcgi\/php5.fcgi<\/span><\/span>\n<span class=\"giallo-l\"><span>    FastCGIExternalServer \/usr\/local\/www\/fastcgi\/php5.fcgi -flush -host 127.0.0.1:9000<\/span><\/span>\n<span class=\"giallo-l\"><span>    AddType application\/x-httpd-fastphp5 .php<\/span><\/span>\n<span class=\"giallo-l\"><span>    Action application\/x-httpd-fastphp5 \/php5.fcgi<\/span><\/span>\n<span class=\"giallo-l\"><\/span>\n<span class=\"giallo-l\"><span>    &lt;Directory &quot;\/usr\/local\/www\/fastcgi\/&quot;&gt;<\/span><\/span>\n<span class=\"giallo-l\"><span>        Order deny,allow<\/span><\/span>\n<span class=\"giallo-l\"><span>        Deny from all<\/span><\/span>\n<span class=\"giallo-l\"><span>        &lt;Files &quot;php5.fcgi&quot;&gt;<\/span><\/span>\n<span class=\"giallo-l\"><span>            Order allow,deny<\/span><\/span>\n<span class=\"giallo-l\"><span>            Allow from all<\/span><\/span>\n<span class=\"giallo-l\"><span>        &lt;\/Files&gt;<\/span><\/span>\n<span class=\"giallo-l\"><span>    &lt;\/Directory&gt;<\/span><\/span>\n<span class=\"giallo-l\"><span>&lt;\/IfModule&gt;<\/span><\/span><\/code><\/pre>\n<p>Note that even-though in my <a href=\"\/2009\/moving-from-mod-fastcgi-to-mod-fcgid\/\">last post<\/a> concerning <code>mod_fastcgi<\/code> I as moving\naway from it, I am now doing the opposite, instead of <a href=\"\/2009\/moving-from-mod-fastcgi-to-mod-fcgid\/\">moving from\n<code>mod_fastcgi<\/code> to <code>mod_fcgid<\/code><\/a> I'm back to <code>mod_fastcgi<\/code>, only because\n<code>mod_fcgid<\/code> doesn't offer the same functionality.<\/p>\n<p>So far this has provided far more stability, along with PHP-FPM doing all of\nthe process management I can now use a single PHP instance that is running on a\nsingle port for the various web servers I am testing. At the moment I have both\nLighttpd and Apache using the same PHP-FPM instance. It is faster, less\nmemory is wasted and PHP-FPM is much better at process management than\n<code>mod_fastcgi<\/code> or <code>mod_fcgid<\/code>.<\/p>\n"},{"title":"FastCGI quick and dirty","published":"2006-09-13T00:19:31+00:00","updated":"2006-09-13T00:19:31+00:00","author":{"name":"Delta Regeer"},"link":{"@attributes":{"rel":"alternate","type":"text\/html","href":"https:\/\/funcptr.net\/2006\/fastcgi-quick-and-dirty\/"}},"id":"https:\/\/funcptr.net\/2006\/fastcgi-quick-and-dirty\/","content":"<p>In this quick and dirty guide for FreeBSD I will assume you have already\ncompiled and installed PHP5 with fcgi mode enabled, which can be checked by\nrunning:<\/p>\n<pre class=\"giallo\" style=\"color: #D6DEEB; background-color: #011627;\" ><code data-lang=\"shellscript\"><span class=\"giallo-l\"><span style=\"color: #82AAFF;font-style: italic;\">\/usr\/local\/bin\/php-cgi<\/span><span style=\"color: #82AAFF;\"> --version<\/span><\/span><\/code><\/pre>\n<p>I will also assume you have installed <code>mod_fastcgi<\/code> from <code>www\/mod_fastcgi<\/code>\nin the ports.<\/p>\n<p>Create the fast cgi ipc temp dir, make sure you place this somewhere it will\nkeep existing:<\/p>\n<pre class=\"giallo\" style=\"color: #D6DEEB; background-color: #011627;\" ><code data-lang=\"shellscript\"><span class=\"giallo-l\"><span style=\"color: #C5E478;font-style: italic;\">cd<\/span><span style=\"color: #ECC48D;\"> \/var\/tmp<\/span><\/span>\n<span class=\"giallo-l\"><span style=\"color: #82AAFF;font-style: italic;\">mkdir<\/span><span style=\"color: #82AAFF;\"> -p<\/span><span style=\"color: #ECC48D;\"> \/var\/tmp\/fcgi-ipc\/dynamic<\/span><\/span>\n<span class=\"giallo-l\"><span style=\"color: #82AAFF;font-style: italic;\">chmod<\/span><span style=\"color: #82AAFF;\"> -R<\/span><span style=\"color: #F78C6C;\"> 0777<\/span><span style=\"color: #ECC48D;\"> \/var\/tmp\/fcgi-ipc<\/span><\/span><\/code><\/pre>\n<p>Let's create the directory where we are going to place our PHP wrapper, this\nconfig is for server wide using the same FastCGI PHP config. This is on\npurpose, since it will allow server wide PHP usage. If you want you could then\nsplit it up into virtualhosts if one required a standalone php running for\nthat.<\/p>\n<pre class=\"giallo\" style=\"color: #D6DEEB; background-color: #011627;\" ><code data-lang=\"shellscript\"><span class=\"giallo-l\"><span style=\"color: #82AAFF;font-style: italic;\">mkdir<\/span><span style=\"color: #ECC48D;\"> \/usr\/local\/www\/fastcgi-bin\/<\/span><\/span>\n<span class=\"giallo-l\"><span style=\"color: #82AAFF;font-style: italic;\">chmod<\/span><span style=\"color: #F78C6C;\"> 755<\/span><span style=\"color: #ECC48D;\"> \/usr\/local\/www\/fastcgi-bin\/<\/span><\/span><\/code><\/pre>\n<p>Next up we create the very simple wrapper:<\/p>\n<pre class=\"giallo\" style=\"color: #D6DEEB; background-color: #011627;\" ><code data-lang=\"shellscript\"><span class=\"giallo-l\"><span style=\"color: #82AAFF;font-style: italic;\">cat<\/span><span style=\"color: #7FDBCA;\"> &lt;&lt;<\/span><span style=\"color: #D9F5DD;\"> EOF<\/span><span style=\"color: #7FDBCA;\"> &gt;<\/span><span style=\"color: #ECC48D;\"> \/usr\/local\/www\/fastcgi-bin\/php5.fcgi<\/span><\/span>\n<span class=\"giallo-l\"><span style=\"color: #ECC48D;\">#!\/bin\/sh<\/span><\/span>\n<span class=\"giallo-l\"><span style=\"color: #ECC48D;\"># To use your own php.ini, comment the next line and uncomment the following one<\/span><\/span>\n<span class=\"giallo-l\"><span style=\"color: #ECC48D;\">#PHPRC=&quot;\/usr\/local\/etc&quot;<\/span><\/span>\n<span class=\"giallo-l\"><span style=\"color: #ECC48D;\">export PHPRC<\/span><\/span>\n<span class=\"giallo-l\"><span style=\"color: #ECC48D;\">PHP_FCGI_CHILDREN=8<\/span><\/span>\n<span class=\"giallo-l\"><span style=\"color: #ECC48D;\">export PHP_FCGI_CHILDREN<\/span><\/span>\n<span class=\"giallo-l\"><span style=\"color: #ECC48D;\">exec \/usr\/local\/bin\/php-cgi<\/span><\/span>\n<span class=\"giallo-l\"><span style=\"color: #D9F5DD;\">EOF<\/span><\/span><\/code><\/pre>\n<p>Set <code>PHP_FCGI_CHILDREN<\/code> to whatever value you want, that is how many processes\nit will use. I suggest the standard which is 8, if you make it more, you use\nmore ram, you make it less Apache will have to wait if all of the PHP\nprocesses are in use.<\/p>\n<p>Next up, make it executable:<\/p>\n<pre class=\"giallo\" style=\"color: #D6DEEB; background-color: #011627;\" ><code data-lang=\"shellscript\"><span class=\"giallo-l\"><span style=\"color: #82AAFF;font-style: italic;\">chmod<\/span><span style=\"color: #ECC48D;\"> +x \/usr\/local\/www\/fastcgi-bin\/php5.fcgi<\/span><\/span><\/code><\/pre>\n<p>Last but not least, edit <code>httpd.conf<\/code> and make sure to add a comment in front\nof the <code>mod_php5<\/code> line, and uncomment the <code>mod_fastcgi<\/code> line. Then add this\nto the end of your Apache config:<\/p>\n<pre class=\"giallo\" style=\"color: #D6DEEB; background-color: #011627;\" ><code data-lang=\"plain\"><span class=\"giallo-l\"><span>&lt;IfModule mod_fastcgi.c&gt;<\/span><\/span>\n<span class=\"giallo-l\"><span>    FastCgiIpcDir \/var\/tmp\/fcgi-ipc\/<\/span><\/span>\n<span class=\"giallo-l\"><span>    FastCgiConfig  -pass-header HTTP_AUTHORIZATION<\/span><\/span>\n<span class=\"giallo-l\"><\/span>\n<span class=\"giallo-l\"><span>    AddHandler  fastcgi-script              .fcgi .fcg .fpl<\/span><\/span>\n<span class=\"giallo-l\"><\/span>\n<span class=\"giallo-l\"><span>    Action      application\/x-httpd-php5    \/fastcgi-bin\/php5.fcgi<\/span><\/span>\n<span class=\"giallo-l\"><span>    AddType     application\/x-httpd-php5    .php .php5<\/span><\/span>\n<span class=\"giallo-l\"><span>&lt;\/IfModule&gt;<\/span><\/span>\n<span class=\"giallo-l\"><\/span>\n<span class=\"giallo-l\"><span>ScriptAlias \/fastcgi-bin\/ &quot;\/usr\/local\/www\/fastcgi-bin\/&quot;<\/span><\/span>\n<span class=\"giallo-l\"><span>&lt;Location \/fastcgi-bin\/&gt;<\/span><\/span>\n<span class=\"giallo-l\"><span>    Options ExecCGI<\/span><\/span>\n<span class=\"giallo-l\"><span>    SetHandler fastcgi-script<\/span><\/span>\n<span class=\"giallo-l\"><span>    Order allow,deny<\/span><\/span>\n<span class=\"giallo-l\"><span>    Allow from all<\/span><\/span>\n<span class=\"giallo-l\"><span>&lt;\/Location&gt;<\/span><\/span><\/code><\/pre>\n<p>That's it. Restart apache and watch as the first time you access a PHP script\nFastCGI will spawn several of them, and they start serving requests. Load\nusage may seem higher, that is because unlike Apache the standalone running\nPHP's handle the jobs as they come in with whatever one is first, Apache will\ntry to put as much work in one of its preforked modules. As the PHP processes\ncome and go through FastCGI the memory usage will go up and down. Mine has\nan average of about 300 MB, which is very good compared to the 800 MB Apache\nwith <code>mod_php<\/code> would rack up.<\/p>\n"}]}