Prevent Subdomain Takeover in Laravel – Security Guide & Fixes

Understanding Subdomain Takeover in Laravel

Subdomain takeover is a security vulnerability that occurs when a subdomain points to an external service (e.g., GitHub Pages, AWS, Heroku) that is no longer in use. Attackers can claim the abandoned service and take control of the subdomain, potentially hosting malicious content.

Prevent Subdomain Takeover in Laravel – Security Guide & Fixes

In Laravel applications, developers often use subdomains for multi-tenancy, API endpoints, or user-generated content. If not managed properly, these subdomains can become vulnerable to takeover.

How Does Subdomain Takeover Happen?

  1. Dangling DNS Records – A subdomain is still pointing to an external service that no longer hosts content.
  2. Claiming the Service – Attackers check if the service is available and take control of it.
  3. Exploiting the Subdomain – The attacker uploads malicious content or uses it for phishing and scams.

Checking for Vulnerable Subdomains

To prevent subdomain takeover, start by scanning your website for vulnerable subdomains. Use our Free Website Security Scanner to analyze DNS records and detect security risks.

Screenshot of the free tools webpage where you can access security assessment tools.
Screenshot of the free tools webpage where you can access security assessment tools.

Securing Your Laravel Application Against Subdomain Takeover

1. Regularly Audit DNS Records

Run the following command to check DNS records for any abandoned services:

dig CNAME vulnerable.example.com

If it points to an inactive third-party service, update or remove the record immediately.


2. Remove Unused Subdomains

If you have a subdomain that is no longer in use, remove it from your DNS records to prevent takeover.

# Delete subdomain record in Linux
sudo nano /etc/nginx/sites-available/example.com
# Remove the subdomain entry

3. Validate Subdomain Ownership in Laravel

Use Laravel middleware to verify subdomains before routing requests:

// app/Http/Middleware/VerifySubdomain.php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class VerifySubdomain
{
    public function handle(Request $request, Closure $next)
    {
        $allowedSubdomains = ['user1', 'user2']; // List of valid subdomains
        $subdomain = explode('.', $request->getHost())[0];

        if (!in_array($subdomain, $allowedSubdomains)) {
            abort(403, "Unauthorized subdomain access");
        }

        return $next($request);
    }
}

Register the middleware in app/Http/Kernel.php:

protected $routeMiddleware = [
    'verify.subdomain' => \App\Http\Middleware\VerifySubdomain::class,
];

Then, apply it to routes in routes/web.php:

Route::group(['middleware' => 'verify.subdomain'], function () {
    Route::get('/', function () {
        return "Welcome to the secure subdomain!";
    });
});


4. Set Up Proper Security Headers

Implement security headers in Laravel to prevent domain hijacking:

use Illuminate\Support\Facades\Response;

Route::get('/', function () {
    return Response::make("Secure Laravel App")
        ->header("X-Frame-Options", "DENY")
        ->header("Content-Security-Policy", "default-src 'self'")
        ->header("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
});


5. Monitor DNS Changes Automatically

Use Laravel’s scheduled tasks feature to regularly monitor DNS records and detect unauthorized changes.

Create a new command:

php artisan make:command CheckDNSRecords

Modify app/Console/Commands/CheckDNSRecords.php:

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;

class CheckDNSRecords extends Command
{
    protected $signature = 'check:dns';
    protected $description = 'Monitor DNS records for subdomain security';

    public function handle()
    {
        $domain = "example.com";
        $dnsRecords = dns_get_record($domain, DNS_CNAME);

        if (empty($dnsRecords)) {
            $this->info("No CNAME records found. Subdomain is safe.");
        } else {
            $this->warn("Potential risk detected! Check your DNS settings.");
        }
    }
}

Schedule it in app/Console/Kernel.php:

protected function schedule(Schedule $schedule)
{
    $schedule->command('check:dns')->daily();
}


6. Regularly Assess Website Security

Use automated security tools like our Website Security Checker to monitor and assess vulnerabilities.

An Example of a vulnerability assessment report generated with our free tool, providing insights into possible vulnerabilities.
An Example of a vulnerability assessment report generated with our free tool, providing insights into possible vulnerabilities.

Final Thoughts

Subdomain takeover can lead to serious security risks, including phishing, malware distribution, and data breaches. Laravel developers should regularly audit DNS records, validate subdomain ownership, and use security tools to protect their applications.

For more cybersecurity insights and Laravel security tips, visit our Pentest Testing Blog.

By following these best practices and leveraging security automation to check Website Vulnerability, you can safeguard your Laravel application from subdomain takeover threats. 🚀

Comments

Popular posts from this blog

Fix Sensitive Data Exposure in Symfony Apps

Fix Security Misconfiguration Issues in Symfony

Prevent Remote Code Execution (RCE) Vulnerabilities in Symfony