Capturing Phishing Email Using Custom Middleware in ASP.Net Core Web API

1. Create Custom Middleware

Create a custom middleware that will intercept incoming HTTP requests and inspect the email content for potential phishing indicators. Middleware in ASP.NET Core can be used to perform custom processing on incoming requests and outgoing responses.

2. Define Phishing Indicators

Define a set of phishing indicators or patterns that you want to check for in the email content. Phishing indicators can include specific keywords, suspicious URLs, known phishing email templates, etc.

3. Implement the Phishing Detection Logic

In your custom middleware, implement the logic to check for the defined phishing indicators in the email content. This can be done by inspecting the request payload or any relevant data that contains the email content.

4. Respond to Phishing Detection

If your middleware detects any phishing indicators in the email content, you can take appropriate actions such as logging the event, blocking the request, returning an error response, or forwarding the email to a designated security team for further analysis.

5. Register Custom Middleware in Startup.cs

In the Startup.cs file of your ASP.NET Core Web API project, register your custom middleware in the request pipeline. The order in which middleware is registered is essential, so make sure to place it at an appropriate position in the pipeline.

ASP.NET Core Web API. For this example, we'll use a simplified approach based on keyword matching, as discussed earlier. Remember that this is just a basic example for demonstration purposes and should not be considered a comprehensive phishing detection solution.

Step 1. Create a new ASP.NET Core Web API project using Visual Studio or the .NET CLI

dotnet new webapi -n PhishingDetectionAPI
cd PhishingDetectionAPI

Step 2. Add a new class named PhishingDetectionMiddleware.cs in the root folder of the project:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
Author SardarMudassar Ali Khan
public class PhishingDetectionMiddleware
{
    private readonly RequestDelegate _next;
    private readonly List<string> _phishingKeywords;

    public PhishingDetectionMiddleware(RequestDelegate next)
    {
        _next = next;
        
        _phishingKeywords = new List<string>
        {
            "bank account",
            "password reset",
            "verify your account",
            "urgent",
            "confidential",
            "suspicious login",
        };
       // Here We can implement the Dynamic List of From any data Source
    }

    public async Task InvokeAsync(HttpContext context)
    {
        string emailContent = await GetEmailContentFromBody(context.Request);

        bool isPhishing = IsPhishingEmail(emailContent);

        if (isPhishing)
        {
            await HandlePhishingDetection(context);
        }
        else
        {
            await _next(context);
        }
    }

    private async Task<string> GetEmailContentFromBody(HttpRequest request)
    {
        using (var reader = new StreamReader(request.Body, Encoding.UTF8, true, 1024, true))
        {
            string requestBody = await reader.ReadToEndAsync();

            int contentStartIndex = requestBody.IndexOf("\"content\":");
            if (contentStartIndex >= 0)
            {
                int contentEndIndex = requestBody.IndexOf(",", contentStartIndex);
                if (contentEndIndex >= 0)
                {
                    string contentValue = requestBody.Substring(contentStartIndex + 
                  "\"content\":".Length, contentEndIndex - contentStartIndex - 
                  "\"content\":".Length);
                    return contentValue.Trim('\"', ' ', '\t', '\n', '\r');
                }
            }
        }

        return null;
    }

    private bool IsPhishingEmail(string emailContent)
    {

        if (string.IsNullOrEmpty(emailContent))
        {
            return false;
        }

        emailContent = emailContent.ToLower();
         insensitive matching.

        foreach (var keyword in _phishingKeywords)
        {
            if (emailContent.Contains(keyword))
            {
                return true; 
            }
        }

        return false;
    }

    private async Task HandlePhishingDetection(HttpContext context)
    {
        context.Response.StatusCode = StatusCodes.Status400BadRequest;
        await context.Response.WriteAsync("Phishing email detected. Please refrain from suspicious 
        activities.");
    }
}

Step 3. In Startup.cs, add the registration for the custom middleware in the Configure method.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace PhishingDetectionAPI
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            // Add your custom phishing detection middleware to the pipeline.
            app.UseMiddleware<PhishingDetectionMiddleware>();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

Step 4. Run the project after completing the above logic 

Run using Visual Studio or using given below CLI command 

Run the Web API:

ASP.NET Core Web API with the phishing detection middleware is up and running. When a request is made to your API with email content that matches any of the phishing keywords, it will respond with a 400 Bad Request and a custom message indicating that a phishing email was detected. You can modify the HandlePhishingDetection method to include additional actions such as logging, reporting, or blocking as per your requirements.


Similar Articles