EO Spam Remover : Remove & Block Malicious Emails from All Users Mailboxes

EO Spam Remover : Remove & Block Malicious Emails from All Users Mailboxes


stage direction :


As an IT technician or system and security administrator, what do you do to stop the spread of a threat?

I'll take the example of a malicious e-mail sent from an address that's "[email protected]" to all the company's employees?


  • Do you call all users one by one?
  • Do you send an e-mail to all employees warning them not to open the e-mail from "[email protected]"? What happens if they didn't read your message or your message came a little late?
  • Will you read this article and use my FREE proactive solution? If so, I encourage you to take action right away:


What is EO Spam Remover :


"EO Spam Remover" is a PowerShell program I've developed to proactively facilitate the daily tasks of IT Technicians and System and Security Admins.

"EO Spam Remover" scans all Exchange Online mailboxes and deletes all malicious e-mails originating from a specific address that may have exceeded the Office 365 anti-spam rules, thus preventing certain users from opening the malicious e-mail and stopping the spread of the threat, while at the same time working proactively.

A second feature offered by "EO Spam Remover" is to block the email address in question or block the entire domain to avoid other malicious emails from the same source.


here's a screenshot of the program :

prerequisites :

To be able to use this program you must configure same setting on Microsoft 365.

  1. Have the necessary rights to connect to Exchange Online and run commands (Exchange Online Administrator or Global Administrator).
  2. Add your Inbound Antispam Policy Name to the config.ini file , this file will be provided later or even created in the same program Directory, the program will use this to add email address or Domain to block list.
  3. Be member of "Organisation Management Group" to be able to Search and Purge Mailboxes.
  4. You must have "eDiscovery permissions".

here is some RBAC reloes related to eDiscovery permissions :

I - Assign eDiscovery permissions :

  1. Go to the compliance portal and sign in using an account that can assign permissions.
  2. In the left pane, select Roles & scopes > Permissions.
  3. On the Permissions page, under Microsoft Purview solutions, select Roles.

  • On the Role groups for Microsoft Purview solutions page, select eDiscovery Manager.
  • On the eDiscovery Manager flyout pane, do one of the following based on the eDiscovery permissions that you want to assign.

  • On the Manage eDiscovery Manager page, you can select Choose users or you can pass for the next step.

You can Assign One administrator for many Managers, in my case I have assigned my self directly on eDiscovery Administrator

  • To assign a user (or users) to the eDiscovery Administrator role group, select Choose users.

  • On the Review the role group and finish page, review the role group changes. Select Save to save the changes to the eDiscovery role groups.

For more details about eDiscovery permissions : https://learn.microsoft.com/en-us/purview/ediscovery-assign-permissions


II - Assign Organization Management Role :

  1. Go to the Exchange Online Admin Portal?and sign in using an account that can assign permissions.
  2. In the left pane, select Roles -?> Admin roles.
  3. enter "Organization" in the search box and select "Organization Management"

Select "Assigned" then select "+ Add" to add user to "Organization Management" group.

once the user has been added, it will appear in the list as follows:

You can do the steps using PowerShell :

just you need to execute this code :

# Specify the Organization Management User Email Address
$Org_Mgnt_User = "[email protected]"

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force

Import-Module ExchangeOnlineManagement

# Connect to Exchange Online
Connect-ExchangeOnline

# Add User to Organization Management Members
Add-RoleGroupMember "Organization Management" -Member $Org_Mgnt_User        


III - Add your Inbound Antispam Policy name to config.ini file :

To be able to work automatically, the program need the Antispam Poclicy Name, the program will use this to add email address or Domain to block list.

To get this information :

  • Go to Security Admin Center -> Email & Collaboration -> Policies & rules :

Select "Threat Policies"

Select "Anti Spam"

Copy the Name of your default Antispam Policy, in my case here : "Anti-spam inbound policy (Default)"

Open notepad and paste this :

AntiSpamPolicy=Anti-spam inbound policy (Default)

save notepad file with name : Config.ini in the same location of "EO Spam Remover".

IV - How the program works :

All the following steps and email addresses are fictitious addresses used for explanation and testing purposes.

assuming that I have received an e-mail from "[email protected]" containing a malicious link, there are surely other users who have received the same e-mail (IT Technicians often receive reports concerning this type of e-mail).

I run my "EO Spam Remover" program :

You should Authenticate with a configured Account (check prerequisites section).

You will be Authenticate two times (First one with Credantials, second one without).

This Authentications are for ExchangeOnline and Anti Spam Security Policy.

After seccessfull authentication tou will see this :

Next print screen is the menu :

In my case, I will choose option number 3 : ( Delete Email Address from All Users Mailboxes + Block Email-Address in Antispam Filter)

type (or copy/paste) malicious email address then Press Enter

In the next window, you'll see messages indicating the different steps and a progress bar showing the progress of the task.

after the scan is complete, you'll see the number of e-mails coming from this address, which in our case is 4.

Click on 1 to proceed with the deletion of all e-mails originating from this malicious address, or click on 0 if you wish to cancel the deletion operation.

in my case I will continue

After execution we will see, this message, that meen every thing is good ??

In my Outlook I cant see anymore "[email protected]", same thing for all company users.

Let's check Inbound Antispam Policy :

As you can see here, the malicious email address is added here :

if you type "Enter" you will be returned to the menu window to start new EO Spam removing opreation.

Here is here's the most important part of all, ???? WOW ????, it's the source code, in this code you dont need to change nothing, just copy/paste and execute, you can also download executable File from the link below.

This program can work with every Office 365 Tenant, no changes needed, keep in mind, the only changes needed is adding Default Office 365 Antispam Policy Name in the Config.ini file, who should be saved in the same directory of the script/exe file.
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force

Clear-Host

$host.ui.RawUI.WindowTitle = "Exchange-Online SPAM Remover v1.0 -- Created By : Aymen EL JAZIRI"

Write-Host
Write-Host

Write-Host "

███████╗ ██████╗     ███████╗██████╗  █████╗ ███╗   ███╗    ██████╗ ███████╗███╗   ███╗ ██████╗ ██╗   ██╗███████╗██████╗ 
██╔════╝██╔═══██╗    ██╔════╝██╔══██╗██╔══██╗████╗ ████║    ██╔══██╗██╔════╝████╗ ████║██╔═══██╗██║   ██║██╔════╝██╔══██╗
█████╗  ██║   ██║    ███████╗██████╔╝███████║██╔████╔██║    ██████╔╝█████╗  ██╔████╔██║██║   ██║██║   ██║█████╗  ██████╔╝
██╔══╝  ██║   ██║    ╚════██║██╔═══╝ ██╔══██║██║╚██╔╝██║    ██╔══██╗██╔══╝  ██║╚██╔╝██║██║   ██║╚██╗ ██╔╝██╔══╝  ██╔══██╗
███████╗╚██████╔╝    ███████║██║     ██║  ██║██║ ╚═╝ ██║    ██║  ██║███████╗██║ ╚═╝ ██║╚██████╔╝ ╚████╔╝ ███████╗██║  ██║
╚══════╝ ╚═════╝     ╚══════╝╚═╝     ╚═╝  ╚═╝╚═╝     ╚═╝    ╚═╝  ╚═╝╚══════╝╚═╝     ╚═╝ ╚═════╝   ╚═══╝  ╚══════╝╚═╝  ╚═╝
                                                                                                                         
v1.0

" -ForegroundColor Green


Write-Host
Write-Host
Write-Host
Write-Host
 
Write-Host "Press key to continue ..................." -ForegroundColor green
Write-Host
Write-Host
Write-Host

pause

Clear-Host

Write-Host
Write-Host

Import-Module ExchangeOnlineManagement

# ================================= Get Execution Directory ===========================================
function Get-ScriptDirectory 
{
    if ($psise) 
    {
        Split-Path $psise.CurrentFile.FullPath
    }
    else 
    {
        $global:PSScriptRoot
    }
}

$ExecPath = Get-ScriptDirectory

# ================================== Load Ini Config File ===============================================

# Load Ini File and convert it to 
$AntiSpamPolicy = ""
try
{
    $Config = Get-Content ($ExecPath +'\Config.ini') | Select -First 1 | ConvertFrom-StringData
    
    # Sepecify your Office 365 Antispam Policy Name
    $AntiSpamPolicy = $Config['AntiSpamPolicy']
}
catch
{
    Write-Host "Error while Loading Config Ini File" -ForegroundColor Red
}


# ================================== Function to validate Email Address =================================

function ValidateEmail
{
    param([string]$EmailAddress)
? ? $EmailAddress -match "^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"
}

# ================================== Function to Read Email Address =================================

function ReadEmail
{
    do
    {
        $Email = Read-Host "Please Entrer Email Address to Delete/Block"
    }Until(ValidateEmail($Email))
    return $Email
}

# ================================== Function To Connect to Exchange Online  ==============================

function ConnectToExchage
{
    try
    {
        # Connect To Exchange On line : 
	    Connect-IPPSSession  
        Connect-ExchangeOnline

        if(Get-ConnectionInformation | Where-Object {$_.Name -match 'ExchangeOnline*' -and $_.state -eq 'Connected'})
        {
            Write-Host "Successfully Connected to Office 365" -ForegroundColor Green
        }
    }
    catch
    {
        # Error Message
		Write-Host "$_.Exception.Message" -ForegroundColor Red
    }    

}

# ================================== Function To Search and delete Email address  ==============================

function SearchDeleteEmail()
{
    param([string]$SenderToBlock)

    Write-Host "Email Address to Block is : $SenderToBlock"
    Write-Host
    Write-Host "Create compliance ..................OK"

    # Name for compliance with DATE / TIME
    $ComplaianceName = "Compaliance " + (Get-Date -Format "dd/MM/yyyy HH:mm")

    Write-Host "Create Job Search ..................OK"
    # Create Job Search by sender 
    $Query = 'from:' + $SenderToBlock
    New-ComplianceSearch -Name $ComplaianceName -ExchangeLocation All -ContentMatchQuery $Query 

    Write-Host "Start Job Search ..................OK"
    # Start Job Search 
    Start-ComplianceSearch -Identity $ComplaianceName

    # Follow task Progress Completed Or NOT
    Write-Host "Follow Job Progress ...............OK"
    Write-Host
    Write-Host
    Start-Sleep 5
    Get-ComplianceSearch -Identity $ComplaianceName
    Write-Host "Progress." -NoNewline
    do
    {
        $comp = Get-ComplianceSearch -Identity $ComplaianceName
        Write-Host ".." -NoNewline
        if($($comp.Status) -eq 'Completed')
        {
            Write-Host 
            $comp
            break
        }
        Start-Sleep 5
    
    }Until( $($comp.Status) -eq 'Completed')
    
    Write-Host
    # Show All task details
    Write-Host "Show Job Details ..................OK"
    $recup = Get-ComplianceSearch -Identity $ComplaianceName | Select-Object Name, RunBy, Status, JobStartTime, JobEndTime , Errors , Items , Size | Format-List
    $recup
    
    do
    {
        $Exec = Read-Host "Do you want to continue ? Press 1 for Yes , Press 0 For No"

    }Until( ( $Exec -eq '0') -OR ($Exec -eq '1') )

    if($Exec -eq '1')
    {
        try
        {
            # Soft-delete messages
            New-ComplianceSearchAction -SearchName $ComplaianceName -Purge -PurgeType SoftDelete -Force -Confirm:$false
            Write-Host "$($recup.Items) Emails Deleted from Users Mailboxes" -ForegroundColor Green
        }
        catch
        {
            Write-Host "Error While Deleting Email Address from Users Mailbox " -ForegroundColor Red
        }
    }

}


# ================================== Connect To Exchange Online  ==============================


write-host "Start Connection to Microsoft Exchange Online" -ForegroundColor Green

ConnectToExchage

if(!(Get-ConnectionInformation | Where-Object {$_.Name -match 'ExchangeOnline*' -and $_.state -eq 'Connected'}))
{
    Write-Host "Error While Connecting to Office 365" -ForegroundColor Red
    exit
}


write-host
write-host
write-host
Start-Sleep 6

# ================================== Get  ==============================



$menu = @"


_______________________________________________________________________________
██▓????Exchange-Online SPAM Remover v1.0 -- Created By : Aymen EL JAZIRI????▓██ 
______________________________________________________________________________

__________________________________ Select Option _______________________________

    1) Delete Email Address from All Users Mailboxes                          
    2) Delete Email Address from All Users Mailboxes + Block Domain in Antispam Filter         
    3) Delete Email Address from All Users Mailboxes + Block Email-Address in Antispam Filter              

_______________________________________________________________________________
    x) Close the Program
_______________________________________________________________________________

"@


# ================================== Get  ==============================


do
{
    cmd /c color 71
    Clear-Host
    [Console]::WriteLine($menu)

    $Selection = Read-Host("  Enter your choice ")
    Clear-Host
    Switch($Selection)
    {
        1 {
            Write-Host "`n`n Delete Email Address from All Users Mailboxes   : " -ForegroundColor Green
            Write-Host
            Write-Host
            [string]$Email = ReadEmail
            SearchDeleteEmail -SenderToBlock $Email
            pause
        }

        2 {
            Write-Host "`n`n Delete Email Address from All Users Mailboxes + Block Domain in Antispam Filter   : " -ForegroundColor Green
            Write-Host
            Write-Host
            [string]$Email = ReadEmail
            SearchDeleteEmail -SenderToBlock $Email
            # Block Domain Address In Anti Spam Policy
            $Domain = $Email.Split("@")[1]
            Set-HostedContentFilterPolicy -Identity $AntiSpamPolicy -BlockedSenders @{Add=$Domain}
            Write-Host "Domain $Domain Blocked in Antispam Filter : $AntiSpamPolicy" -ForegroundColor Green
            pause
        }

        3 {
            Write-Host "`n`n Delete Email Address from All Users Mailboxes + Block Email Address in Antispam Filter   : " -ForegroundColor Green
            Write-Host
            Write-Host
            [string]$Email = ReadEmail
            SearchDeleteEmail  -SenderToBlock $Email
            # Block Email Address In Anti Spam Policy
            Set-HostedContentFilterPolicy -Identity $AntiSpamPolicy -BlockedSenders @{Add=$Email}
            Write-Host "Email Address $Email Blocked in Antispam Filter : $AntiSpamPolicy" -ForegroundColor Green
            pause
        }

    }
}Until($Selection -eq 'x')

# Disconnect from Office 365
#Disconnect-ExchangeOnline -Confirm:$false
        

You can also download the EXE version and send it to your Level 1/2/3 technician.

https://drive.google.com/file/d/1bsn-25d5sglJLO-L8GKTbZkLzBZVqq-M/view?usp=sharing

Enjoy the Tool ??.

Dont forget to share and follow.


Aymen EL JAZIRI

System Administrator

Soumaya Beddey

biologiste , technicienne de laboratoire, contr?le/assurance qualité, microbiologie,R&D, physico-chimique

7 个月

Keep going ??

Taking proactive steps is key. Stay on top of the latest security measures to protect your organization. ??

Michael Crane

Senior Cloud Solutions Architect (Security)

7 个月
Renae Pagel

Triage Security Engineer 2

7 个月

Nice but this wontt stop an email and user clicking. You can just use office admin to pull emails, etc., and use a product like proofpoint. But otherwise, cool tool.

Fran?ois Michael Dain

Service Delivery Manager and Architect M365

7 个月

要查看或添加评论,请登录

社区洞察

其他会员也浏览了