Dev.to Security 🔐 Cybersecurity 👁 2 📖 6 min read

Your PHP stack traces may be logging card numbers. Here's a 5-minute check

I work on a payments backend, so I spend more time than I'd like thinking about what ends up in our logs. Usually the suspect is someone doing Log::info($request->all()). But there's a quieter way for a card number to ge

I work on a payments backend, so I spend more time than I'd like thinking about what ends up in our logs. Usually the suspect is someone doing Log::info($request->all()). But there's a quieter way for a card number to get there: a completely normal TypeError in a constructor.

Small disclosure first: I maintain an open-source DTO library, and at the end I show how it handles this. Everything before that is plain PHP, so it applies no matter what you use.

Reproducing it

<?php
declare(strict_types=1);

final class PaymentData
{
    public function __construct(
        public readonly int $amount,
        public readonly string $cardNumber,
    ) {}
}

function handle(array $input): PaymentData
{
    return new PaymentData($input['amount'], $input['card_number']);
}

try {
    handle(['amount' => '1500', 'card_number' => '4111111111111111']);
} catch (TypeError $e) {
    echo $e->getMessage(), "\n\n", $e->getTraceAsString(), "\n";
}

Nothing special here. amount came in as a string, which happens all the time with forms, CSV files and partner APIs. Now run it with php -n demo.php:

PaymentData::__construct(): Argument #1 ($amount) must be of type int, string given, called in demo.php on line 14

#0 demo.php(14): PaymentData->__construct('1500', '411111111111111...')
#1 demo.php(18): handle(Array)
#2 {main}

The error is about amount, but look at frame #0. All the constructor arguments are there, card number included. getTraceAsString() cuts strings to 15 chars (that's zend.exception_string_param_max_len), so you get 15 of 16 digits. Not great. And if something reads $e->getTrace() directly (some error tracking SDKs do this to show function arguments), it gets the full value:

var_dump($e->getTrace()[0]['args'][1]); // string(16) "4111111111111111"

"We have exception_ignore_args in prod, so we're fine"

Maybe. php.ini-production sets zend.exception_ignore_args = On, and then the same trace shows PaymentData->__construct() with empty parentheses. But:

  • If no php.ini is loaded, the default is Off. The official php Docker images ship php.ini-production and php.ini-development side by side, but don't load either of them. If your Dockerfile never copies one or sets the option, you're running with Off.
  • It only hides arguments. Exception messages are a different story.

So check what you actually have. And check it in the process that serves traffic, because CLI and FPM can read different ini files:

var_dump(ini_get('zend.exception_ignore_args')); // want "1"

Messages leak too

Some exceptions put the bad value right into the message. And messages get logged no matter what you set for trace arguments. Two common ones (output from PHP 8.3):

enum Currency: string { case UAH = 'UAH'; case EUR = 'EUR'; }

Currency::from('4111 1111 1111 1111');
// ValueError: "4111 1111 1111 1111" is not a valid backing value for enum Currency

new DateTimeImmutable('4111111111111111');
// DateMalformedStringException: Failed to parse time string (4111111111111111) at position 8 (1): Double date specification

Of course nobody types a card number into a currency field. But columns get shifted, a partner swaps two fields, a CSV loses a delimiter. And then the value that fails to cast is exactly the one you didn't want to see in your error tracker.

What you can do in plain PHP

1. Turn on zend.exception_ignore_args in every production image. Set it explicitly, don't rely on defaults, and check it in a smoke test after deploy. It's the cheapest fix and it covers all frames at once.

2. Use #[\SensitiveParameter] (PHP 8.2+). If you mark a parameter, PHP puts a SensitiveParameterValue object in the trace instead of the value:

final class PaymentData
{
    public function __construct(
        public readonly int $amount,
        #[\SensitiveParameter] public readonly string $cardNumber,
    ) {}
}

function handle(#[\SensitiveParameter] array $input): PaymentData { /* ... */ }
#0 demo.php(14): PaymentData->__construct('1500', Object(SensitiveParameterValue))
#1 demo.php(18): handle(Object(SensitiveParameterValue))

The problem is you need it on every parameter of every function the raw payload goes through: controller helper, mapper, factory. Forget one and that frame leaks again. And it doesn't help with messages at all.

3. Don't put values into exception messages. Where you turn input into objects, catch the exception and throw a new one with just the field name, like Invalid value for field 'currency'. And don't pass the original as previous. Most loggers print the whole chain, messages included.

4. Watch dumps and serialization. __debugInfo() changes what var_dump() and print_r() show, but not var_export() or serialize(). And serialize() writes the full value wherever the result goes, like a queued job payload in Redis or in the jobs table, or a cache entry. If an object should never leave the process, __serialize() is the place to scrub it, or just throw there.

What I did in my library

Simple Data Objects builds the constructor call itself, so it can do most of this for you:

  • The raw payload is marked #[\SensitiveParameter] in from(), in the generated hydrator and in the internal helpers that touch it.
  • If the constructor throws, the library rewrites the trace before rethrowing. Every argument in the DTO's __construct frame becomes a SensitiveParameterValue, marked or not. Here's the main part from src/Support/Redactor.php:
foreach ($trace as $i => $frame) {
    if (($frame['function'] ?? null) === '__construct'
        && isset($frame['class'], $frame['args'])
        && is_a($class, (string) $frame['class'], true)) {
        $trace[$i]['args'] = array_map(
            static fn (mixed $arg): \SensitiveParameterValue => $arg instanceof \SensitiveParameterValue ? $arg : new \SensitiveParameterValue($arg),
            (array) $frame['args'],
        );
    }
}

Yes, it writes to the private trace property of Exception and Error through reflection, for every exception in the previous chain. It's a hack, and I'd be happy if PHP didn't need it. But it only runs when something has already failed.

  • Messages the library builds go through a card number mask, just as a safety net. Any run of 13 to 19 digits (spaces and dashes are fine) keeps only the last four. So "4111 1111 1111 1111" is not a valid backing value turns into "**** **** **** 1111" is not a valid backing value.
  • If a property has #[Sensitive] and its cast fails, you get a generic error without the original message. Add the HasSensitiveFields trait and var_dump() shows [redacted], while serialize() throws instead of writing the value out:
use StdOut\SimpleDataObjects\BaseData;
use StdOut\SimpleDataObjects\Attributes\Sensitive;
use StdOut\SimpleDataObjects\Concerns\HasSensitiveFields;

final class PaymentData extends BaseData
{
    use HasSensitiveFields;

    public function __construct(
        public readonly int $amount,
        #[Sensitive]
        public readonly string $cardNumber,
    ) {}
}

It's not magic though. The mask only catches things that look like card numbers, not CVVs, IBANs, tokens or passwords. #[Sensitive] and the trait are opt-in. And if you log $request->all() yourself, no library will save you. This closes the accidental paths, nothing more.

And a nice bonus on top of all this: the library is fast and easy on resources. Each DTO class gets its hydrator and serializer compiled once, so there's no reflection work on every call, and lazyCollection() keeps memory flat on large imports. I'm leaving numbers out on purpose, because this post is about logs. If you're curious, the benchmark repo lets you measure it on your own payloads.

The library is std-out/simple-data-objects (PHP 8.4+, MIT).

Quick checklist

  • ini_get('zend.exception_ignore_args') returns "1" in FPM or your workers, not only in CLI.
  • Your Dockerfile copies php.ini-production or sets the option itself.
  • Functions and constructors that get raw card data or credentials use #[\SensitiveParameter].
  • Boundary code throws with field names, not values, and doesn't chain the original exception.
  • Objects with secrets have __debugInfo() and scrub or block __serialize().
  • Grep a day of logs for runs of 13 to 19 digits. Crude, but even one real hit is worth a ticket.

What did I miss? If you've caught sensitive data leaking into logs somewhere unexpected, I'd really like to hear where.

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.