Search code examples
phpsecurityloggingphp-7credentials

How to hide only sensitive arguments in PHP's debug_backtrace?


Consider the following code. In the event that an exception occurs, the trace (which will be logged and stored in a database) will include the sensitive password data. How can sensitive data in cases like this, while allowing other non-sensitive arguments, be hidden?

<?php
$user = 'john';
$pass = 'secret';

function auth($user, $pass) {
    // authentication logic
}

function login($user, $pass) {
    throw new Exception('Unexpected error');

    // various logic
    auth($user, $pass);
    // various logic
}

try {
    login($user, $pass);
} catch (Throwable $e) {
    send_to_log($e->getTrace()); // This reveals the password "secret"
}

Solution

  • Starting from the PHP version 8.2 (Dec 2022) there is a feature named "Redacting parameters in back traces". This will hide the parameter from any stack trace in your PHP application.

    Here is an example from that RFC:

    <?php
     
    function test(
        $foo,
        #[\SensitiveParameter] $bar,
        $baz
    ) {
        throw new \Exception('Error');
    }
     
    test('foo', 'bar', 'baz');
     
    /*
    Fatal error: Uncaught Exception: Error in test.php:8
    Stack trace:
    #0 test.php(11): test('foo', Object(SensitiveParameterValue), 'baz')
    #1 {main}
      thrown in test.php on line 8
    */
    

    Note that for some built-in functions (such as PDO and mysqli database password parameter for example), this annotation is already in effect.