Encrypted Malware Payloads

Recently, I was reading an article on the recently discovered hacker group dubbed the Equation Group[1], I stumbled across an interesting concept: encrypted malware payloads. Most server admins will inevitably have the experience of dealing with a comprised system, especially if you host sites running WordPress[2][3], IPB[4], vBulletin[5], Drupal[6], or a host of other systems which tend to exhibit a high number of easy to remotely exploit vulnerabilities (sometimes in the core software, more frequently in plugins). I’ve dealt with a number of compromised sites, analyzing the PHP that was injected into them.

Typically, what I’ve seen and what appears to be common, is an obfuscated payload, using base64 encoded strings and the eval() function (which executes a string as PHP code[7]). These are easy to spot (malicious PHP code normally is) and easy to de-obfuscate, determining the purpose of the code. I recently went through that process on a newly acquired client’s site, discovering that the payload was a spammy backlink page designed to improve S.E.O. for target sites by injecting links whenever the Google bot requested the page.

Continue reading Encrypted Malware Payloads

Understanding the PHP-FPM status page

PHP-FPM has a very useful feature that allows you to setup a status page to view that status of a PHP-FPM pool, configurable using the option pm.status_path. Most people who have worked with PHP-FPM have probably heard of this setting, and maybe even used it (some tools such as Munin require it for metrics). Here is a sample of the basic output:

$ curl http://localhost/server-status
pool: default
process manager: dynamic
start time: 11/Dec/2014:17:51:33 -0500
start since: 61383
accepted conn: 4682
listen queue: 0
max listen queue: 0
listen queue len: 0
idle processes: 11
active processes: 1
total processes: 12
max active processes: 2
max children reached: 0
slow requests: 3

There is also the very useful full view, which gives you per-process information for every currently running FPM process in the pool:

Continue reading Understanding the PHP-FPM status page

Long running PHP script gotcha

So I was recently answering a question on StackOverflow, and learned something quite interesting about PHP.  This particular aspect of PHP mostly affects long running scripts, such as PHP based servers or daemons.

PHP does not re-use resource ids internally, so eventually your script could run into an error with the resource ID overflows and wraps around into the negatives, which pretty much breaks everything. There was a bug report opened about it in 2009, but the issue is still present. This is a huge issue, because resources are used all over, even in not-so-apparent places. For example, most file operations use resources, as do database connections and network sockets. Some of these are obvious, as functions return a resource object (such as socket_accept). Others are not obvious, like file_get_contents, which actually uses two resources under the hood, incrementing the internal resource ID counter by two

The maximum resource id depends on your architecture (32 or 64 bit), and possibly the options used to compile PHP. On 32 bit systems, it’s almost certainly going to be 2,147,483,647. On 64 bit systems, its probably going to be 9,223,372,036,854,775,807.

While this limit is far easier to hit on 32 bit systems, it’s still possible on 64 bit systems if your script is very long running. This limit is good to be aware of when designing your application, as it’s possible to mitigate by using techniques such as forking and multiple processes.


echo gmp_init("0x41682179fbf5")."\n";// Resource id #4
echo gmp_init("0x41682179fbf5")."\n";// Resource id #5
echo gmp_init("0x41682179fbf5")."\n";// Resource id #6
echo gmp_init("0x41682179fbf5")."\n";// Resource id #9
echo gmp_init("0x41682179fbf5")."\n";// Resource id #10
echo gmp_init("0x41682179fbf5")."\n";// Resource id #11

The above code will demonstrate resource IDs incrementing if you run it locally (requires php5-gmp). You can also see file_get_contents incrementing the ID by two.

Optimizing Your PHP with Xdebug

I work with a lot of PHP applications, and part of my job is optimizing those applications to reduce server costs and maximize how many requests each server can handle. There are many ways to do this, but I’m going to talk about using a profiler, which is one of the better ways to start optimizing your code base.

You’ve probably heard people saying not to get caught up in premature optimization, maybe you’ve heard them follow up with profile your code to find the bottlenecks. A lot of people don’t know what this means, or are under the impression that profiling is quite hard to setup. However, this is certainly not true. Profiling PHP is very simple, thanks to the wonderful Xdebug extension. Before we get started setting up Xdebug, you’re going to need a program to read the profiling information files, known as cachegrind files. I personally recommend using KCacheGrind (also available on Windows), although WinCacheGrind is another good alternative. Finally, there is a very lightweight profiler called WebGrind that is web based. You should download and install one of these programs.

Before continuing, a small note about callgrind/cachegrind files. Callgrind is a tool included with Valgrind, a C/C++ analysis tool. A lot of different profilers support this format, so the information about interpreting the results below are language agnostic.

Continue reading Optimizing Your PHP with Xdebug

PayPal IPN/PDT Libraries

A long time ago, I wrote a few PHP scripts to help me work with PayPal IPN & PDT requests. I’ve been using them in my projects ever since, but they’ve been in desperate need of an update. Recently I was refactoring a client’s website, and decided to rewrite my PayPal scripts while I was at it.

The new scripts are namespaced, and much cleaner. They are available over on GitHub at brandonwamboldt/paypal-tools. These scripts don’t do much on their own, but are meant to be integrated with your own code base.

Here is a real world example of how I am using the code in my WordPress payments module (which I hope to release on GitHub as well).

$ipn = new \PayPal\IpnRequest();
$ipn->process(function($data) {
  parse_str(urldecode($data['custom']), $custom);

  // Check to see if we should handle it
  if (!isset($custom['wpipn'])) {

  // Parent?
  if (isset($data['parent_txn_id'])) {
    $parent = Transaction::find_one_by('transaction_id', $data['parent_txn_id']);

  // Does it already exist in our system (from PDT most likely)
  $transaction     = Transaction::find_one_by('transaction_id', $data['txn_id']);
  $new_transaction = false;

  if (!$transaction) {
    $new_transaction = true;
    $transaction     = new Transaction;

  // Create a transaction
  $transaction->set_parent_id($parent ? $parent->primary_key() : 0);
  $transaction->set_effective_date(new DateTime($custom['effective']));
  $transaction->set_sandbox(isset($data['test_ipn']) ? $data['test_ipn'] : 0);
  $transaction->set_payment_date(new DateTime($data['payment_date']));

  // If the transaction is a refund, void, etc, we need to reverse the
  // action being performed, so switch previous/next values
  if ($transaction->is_unsuccessful()) {

  // If the transaction is incomplete, we shouldn't do anything.
  if ($transaction->is_incomplete()) {

  // Save

  // Plugin hook
  if ($new_transaction) {
    do_action('payments:transaction:processed', $custom['action'], $transaction);


WordPress Must-Use Plugins

At this point in time, WordPress remains the easiest-to-use “CMS” available to us, so I end up developing quite a few sites with it. Somehow, there is this great feature I’ve never heard of until a few weeks back, so I thought I’d share with the class.

WordPress has this feature called “Must Use Plugins“, aka mu-plugins. They go in the directory /wp-content/mu-plugins/ which does not exist by default. WordPress will load every .php file in that top level directory, before regular plugins. In my efforts to write less crappy code on WordPress, this directory has proved invaluable. However, rarely do you want a bunch of .php files in that directory. Normally, you’d want a system more like the regular plugin directory where each plugin can be a file OR a directory.

I wrote up a little proxy loader script that accomplishes this. Just save as /wp-content/mu-plugins/proxy-loader.php or something, and it will load either /wp-content/mu-plugins/<plugin-name>/<plugin-name>.php OR /wp-content/mu-plugins/<plugin-name>/plugin.php if those files exist. The plugin is available via GitHub.

Use Layouts & Sub Templates

For the context of this article, I’ll be using Zend Framework 1 for usage examples (Why am I using Zend Framework 1 you ask? Because this post is based on an email I sent to my coworkers the other day who use Zend Framework 1). However, all major frameworks support something like this (Symfony2, Zend Framework 2, Laravel, Ruby on Rails, Django, etc).


Layouts let you abstract the HTML code that is re-used on every page to a single (or several) re-usable template files. Using a layout system allows you to write cleaner, more DRY code. In Zend, layouts are located in the /application/layouts/scripts folder, and use the .phtml extension much like views. Generally, a layout will contain the HTML head/foot, and any parts of the page that may appear in every page (Top navigation for instance). Example of a Zend layout:

<!DOCTYPE html>

    <title>Some Title</title>

    <?php echo $this->layout()->content ?>


The part in the body will print out the contents of your regular view. That way, you only need to include the unique parts of a page in the view.

To select a layout in your controller, call the following code:


This will use the layout file /application/layouts/scripts/admin.phtml.

Passing Variables To Your Layout

A common requirement is to pass unique variables to your layout, for example, the page title. This is easily accomplished. In your controller, use the following syntax to assign variables:

$this->_helper->layout->__set('title', 'My Page Title');

In your layout template, use the following syntax to access variables:

<?php echo Zend_Layout::getMvcInstance()->title ?>

Rendering Partial Templates

Commonly, you’ll have some code that is re-used in multiple places but is not something you can place in a layout. A great example of this would be a widget that appears on several pages but not all of them. For situations like this, you can use the render() function.

render() can be used in layouts or regular views. It will render the contents of a given .phtml template and return it. Here’s an example of its use:

<?php echo $this->render('widgets/products.phtml') ?>

The render() function loads a template relative to /application/views/scripts when used in a regular view, and /application/layouts/scripts when used in a layout.

Variables available in the current template are available in the rendered template as well.

The Partial Function

Also of note is the partial() function. It behaves almost exactly like render(), except you pass it the variables in can use instead of it using the current scope. This is good if you’re iterating over an array (like an array of products) and want to render each one as a template. Example:

foreach ($products as $product) {
    echo $this->partial('partials/product_row.phtml', $product);


While the examples used here are specific to Zend Framework 1, the concepts are applicable to most modern frameworks and templating systems (Including Twig).

Writing nicer console scripts

Recently I working on a web application for a client over at my new company, Spark Creek. The particular component I was building was an import script, runnable via the command line. It was written in PHP, as a bundle for Symfony. At first, I built the script to output progress like “Matched 50 URLs on page: 1”. It would output a newline for every page. This produced a lot of output for a simple console script, and wasn’t very nice. What I wanted to do was match certain utilities like wget, which have a progress indicator that changes dynamically. I looked and couldn’t find how to do it, but with a little research I was able to recreate the effect.

The \x08 hex character code is the ASCII backspace character. If you write it to the console, it deletes a character. With PHP, I kept track of the line length, and every iteration of the loop, I would use str_repeat to send however many backspace characters I needed to erase the current line. Then I would write a new line for the current progress of the loop. This created a very smooth progress indicator.

Here’s a barebones version as a proof of concept:

$lastLineSize = 0;

for ($i = 0; $i <= 50; $i++) {
    echo str_repeat("\x08", $lastLineSize);
    echo "Iteration {$i} of 50";
    $lastLineSize = strlen("Iteration {$i} of 50");

echo " - Done\n";

and the resulting console output after the script is complete looks like this:

[[email protected] /home/brandon] > php test.php
Iteration 50 of 50 - Done
[[email protected] /home/brandon] >

Run the script for yourself to see what it looks like. Basically, the script counts from iteration 0 to 50, all on one line. It makes for very fancy console scripts 🙂

Symfony: Using the current user object with a form

Recently I’ve been working with Symfony, a powerful and popular PHP framework. I’ve been running into my fair share of problems with the framework, a lot of which stems from lack of content/documentation for Symfony 2.x, so I’ve decided to start writing some blog posts about it.

For the application I’ve been developing (For one of my clients over at Spark Creek), I’ve had to create an edit profile page. Using Symfony’s form builder, I created my own form class but wanted to use the current user object instead of creating a dummy model. The problem I was running into was that whenever I tried changing my email address to one already in use, it would show me an error but it would switch by user account to the user with the email address I entered.

After a bit of research, I discovered that the current user object was being re-saved to the session, and since forms bind data to the entity/model even if it’s invalid, the new email was getting saved. Not to the database, just to the session. A bit more research lead me to a simple fix, if the form validation failed, call refresh() from the Doctrine entity manager. This function restores an entity to it’s original state (From the database). Continue reading Symfony: Using the current user object with a form

I just released util.php

I just released my latest project, util.php to GitHub. Util.php is a single file that you can include in any of your projects without worrying about conflicts, since it’s entirely contained within the class util. The project includes dozens of functions (Over 40 right now) that most developers either need or use very frequently. It’s especially useful for small one-off projects that don’t warrant a framework that would normally include these methods.

It includes an extremely powerful alternative to print_r/var_dump that can be executed on variables of any type, and will show you the variable’s type, size, contents and more depending on the type of variable. It supports displaying arrays and objects, and includes some JavaScript that allows you to expand/collapse nested array elements within the variable. Here’s a screenshot of the function, util::var_dump( $var ):

util::var_dump() in action

The library also includes functions like array_pluck, array_first, array_last, get_var/post_var/request_var/etc (Retrieves a value from the superglobals but lets you specify a default if they aren’t set). If you’re interested in a complete list of the functions, take a look at the documentation I wrote.

The project includes a suite of unit tests as well. Please check it out, and feel free to submit issue reports, pull requests or fork it. I’ve already received 20 issue reports, had 15 forks and have 70+ watchers on GitHub!