Would displaying PHP Exception Message be a security risk?

Viewed 1569

I want to set a custom message to be displayed to the user when I throw an error in Laravel 5.1. For example, in a controller I might have:

if(!has_access()){
    abort('401', 'please contact support to gain access to this item.');
}

Then my custom error page I would display the error with:

$exception->getMessage();

However, what if there was a SQL error or other event? Wouldn't that also set the Exception Message which I would be unknowingly outputting on my error page?

The PHP docs for getMessage() don't go into much detail about this.

How can I set a specific exception message without introducing any security risk?

3 Answers

Yes,

$e->getMessage() can potentially reveal more information about your code IF you use it in a similar way:

try {
    $executeSomethingHereForWhichYouExpectAnException();  
// Basic \Exception that reports everything  
} catch (\Exception $e) {
    $error = $e->getMessage();
}

even with 'debug' => false in app.php. For example if you have an error with your code $error would display it - basically ANY type of error (PHP,MYSQL,ETC);

However, there is a fix - to catch your CustomException messages and prevent typical error displaying if you use it in like so:

try {
    $executeSomethingHereForWhichYouExpectAnException();
// Our custom exception that throws only the messages we want
} catch (\CustomException $e) {
    // Would contain only 'my_custom_message_here'
    $error = $e->getMessage();
}

What is the difference you may ask - the difference is that instead of \Exception which is the basic error reporting, we use \CustomException class, which you throw from $executeSomethingHereForWhichYouExpectAnException() function:

executeSomethingHereForWhichYouExpectAnException(){
   if (something) {
     throw new CustomException("my_custom_message_here", 1);
   }
}

If you have more exceptions you can include them like so (as of PHP7.1):

try {
   something();
} catch(\CustomException | \SecondCustomException $e) {
  // custom exceptions
} catch(\Exception $e) {
  // basic exception containing everything
}
Related