This guide describes how to create and run scripts for adding save senders automatically.
Prerequisites
- To run scripts, you must have a Windows machine.
- To run scripts in the background, you must have PowerShell v7 installed.
- You must access Azure Active Directory to create an unattended authentication mechanism.
- In this guide, you are instructed to download files and create and save new files. It is recommended that you create a local directory on your system in which to place these files.
Set up app-only authentication
An initial onboarding is required for authentication using application objects. Application and service principal are used interchangeably, but an application is like a class object while a service principal is like an instance of the class. You can learn more about this at Application and service principal objects in Azure Active Directory.
Step 1: Register the application in Azure AD
Note: If you encounter problems, check the required permissions to verify that your account can create the identity.
- In your browser, access the Azure AD portal, https://portal.azure.com/.
- Login with your credentials.
-
Click App registrations.
Note: You may have to perform a search to find the App registrations service. -
On the App registrations page, click New registration.
-
On the Register an application page, configure the following settings:
-
Name: Enter something descriptive. For example, BullPhish ID.
-
Supported account types: Verify that Accounts in this organizational directory only (<YourOrganizationName> only - Single tenant) is selected.
Note:
To make the application multi-tenant for Exchange Online delegated scenarios, select the value Accounts in any organizational directory (Any Azure AD directory - Multitenant).
-
Redirect URI (optional): Do not enter any information in this section.
Note:
You can't create credentials for native applications, because you can't use that type for automated applications.
-
- Click Register. The App registrations page is displayed for the new application.
Step 2: Assign API permissions to the application
Note: The procedures in this section replace any default permissions that were automatically configured for the new app. The app doesn't need the default permissions that were replaced.
-
On the App registrations page, in the navigation menu, click Manifest.
- Copy the following code block:
"requiredResourceAccess": [
{
"resourceAppId": "00000002-0000-0ff1-ce00-000000000000",
"resourceAccess": [
{
"id": "dc50a0fb-09a3-484d-be87-e023b12c6440",
"type": "Role"
}
]
}
], - On the Manifest page, find the requiredResourceAccess entry (on line 42 through line 52, approximately).
- Paste the copied code over the requiredResourceAccess entry, replacing the resourceAppId, resourceAccess id, and resourceAccess type code.
Note: Microsoft 365 GCC High or DoD environments have access to Security & Compliance PowerShell only. For these environments, use the following values:- resourceAppId: "00000007-0000-0ff1-ce00-000000000000"
- resourceAccess id: "455e5cd2-84e8-4751-8344-5672145dfa17"
- resourceAccess type: "Role"
- Click Save.
- In the navigation menu, click API permissions.
- On the API permissions page, configure the following settings:
- API / Permissions name: Verify the value Exchange.ManageAsApp is shown.
Note: If it is not, click Add a permission > APIs my organization uses. Search for Office 365 Exchange. - Click Grant admin consent for <organization>.
- In the confirmation modal, click Yes. The Status for Exchange.ManageAsApp indicates Granted.
- API / Permissions name: Verify the value Exchange.ManageAsApp is shown.
- In the upper-right corner, click the X to close the API permissions page and return to the App registrations page.
Step 3: Generate a self-signed certificate
- On your taskbar, click the Windows icon.
-
Start typing Powershell. In the Windows Powershell pane, click Run as Administrator.
- Copy the following code and paste it into a text editor (i.e., Notepad).
Note: Some lines of code exceed the page margins because the code must remain on the same line.
# Create certificate
$mycert = New-SelfSignedCertificate -DnsName "contoso.org" -CertStoreLocation "cert:\CurrentUser\My" -NotAfter (Get-Date).AddYears(1) -KeySpec KeyExchange
# Export certificate to .pfx file
$mycert | Export-PfxCertificate -FilePath "cert location" mycert.pfx -Password (Get-Credential).password
# Export certificate to .cer file
$mycert | Export-Certificate -FilePath "cert location" mycert.cer - Delete all comment lines (i.e. # Create certificate).
- Delete empty lines between each line of code.
- Edit the following:
- New-SelfSignedCertificate -DnsName "contoso.org"
- Replace contoso.org with name of your domain. - $mycert | Export-PfxCertificate -FilePath " cert location" mycert.pfx -Password (Get-Credential).password
- Replace cert location with the path to your mycert.pfx file. - $mycert | Export-Certificate -FilePath " cert location" mycert.cer
- Replace cert location with the path to your mycert.cer file.
Example:
Here is example with the required edits:
- New-SelfSignedCertificate -DnsName "contoso.org"
- Copy the code in the editor and paste it into PowerShell.
- Press Enter.
- In the Windows PowerShell credential request modal, enter your Windows credentials and click OK.
Step 4: Attach the certificate to the Azure AD application
After you register the certificate with your application, you can use the private key (.pfx file) or the thumbprint for authentication.
- In your browser, select the App registrations - Microsoft Azure tab.
- Click the Owned applications tab.
- Select your application.
- In the navigation menu, click Certificates & secrets.
- Click the Certificates tab.
- Click Upload Certificate.
- In the Upload Certificate modal, click the folder icon.
- Navigate to the location where you saved the mycert.cer certificate.
- Select the certificate and click Open.
- Click Add.
- The certificate is listed on the Certificates tab.
- In the upper-right corner, click the X. To return to the App registrations page.
Step 5: Assign Azure AD roles to the application
There are two options for assigning Azure AD roles to your application: EDIT
- Assign Azure AD roles to the application: This method is supported in Exchange Online PowerShell and Security & Compliance PowerShell.
Note: For multi-tenant applications in Exchange Online delegated scenarios, you need to assign permissions in each customer tenant.
Assign Azure AD roles to the application
The supported Azure AD roles are indicated in the following table:
For a description of each role, see the article Azure AD built-in roles.
The Global Administrator and Exchange Administrator roles provide the required permissions for any task in Exchange Online PowerShell. For example:
- Recipient management.
- Security and protection features. For example, anti-spam, anti-malware, anti-phishing, and the associated reports.
The Security Administrator role does not have the necessary permissions for those same tasks.
The following steps are slightly different for Exchange Online PowerShell vs. Security & Compliance PowerShell. The steps for both environments are shown. To configure roles for both environments, repeat the steps in this section.
- In the navigation menu, click Roles and administrators.
- Click the here link to access the directory level.
- Find the applicable administrative role.
-
-
Exchange Online PowerShell: Search for and select the Exchange administrator role
(do not select the role's check box). -
Security & Compliance PowerShell: For example, search for and select the Compliance Administrator role (do not select the role's check box).
-
-
-
On the Assignments page, click Add assignments.
-
Exchange Online PowerShell:
-
Security & Compliance PowerShell:
-
-
In the Add assignments modal, in the Search box, start typing the name of the app you created. When it appears in the list, select it.
- Click Add.
On the Assignments page, you can see the role has been assigned to the app.
-
Exchange Online PowerShell:
-
Security & Compliance PowerShell:
-
- In the upper-right corner, click the X. To return to the Assignments page.
Note: For more information about assigning roles in Azure AD, see the article View and assign administrator roles in Azure Active Directory.
Step 6: Create the addSaveSenders_Revised.ps1 file
- Create a new text file named addSaveSenders_Revised.ps1. Make sure the file extension is .ps1. You may want to copy the file name from this step to make sure you save the text file with the correct name.
- Copy the following code:
Note: Some lines of code exceed the page margins because the code must remain on the same line.
param($ConfigPath)
$ConfigPath # includes $Configs
if (!(Get-Module -ListAvailable -Name ExchangeOnlineManagement)) {
Install-Module ExchangeOnlineManagement -Force
}
Import-Module ExchangeOnlineManagement
foreach($Config in $Configs) {
$out = 'Adding Trusted Senders for organization {0}' -f $Config.Organization
Write-Output $out
Connect-ExchangeOnline -AppId $Config.AppId -CertificateFilePath $Config.CertificateFilePath -CertificatePassword (ConvertTo-SecureString -String $Config.CertificatePassword -AsPlainText -Force) -Organization $Config.Organization
$users = Get-EXOMailbox -ResultSize unlimited
foreach($user in $users){
$out = 'Adding Trusted Senders to {0}' -f $user.UserPrincipalName
Write-Output $out
Set-MailboxJunkEmailConfiguration $user.UserPrincipalName -TrustedSendersAndDomains @{Add=$Senders}
}
Disconnect-ExchangeOnline -Confirm:$false
}
Write-Output "Finished!" - In the addSaveSenders_Revised.ps1 file, paste the code.
- Save the file.
Step 7: Create the Config.ps1 file
- Create a new text file named Config.ps1. Make sure the file extension is .ps1. You may want to copy the file name from this step to make sure you save the text file with the correct name.
- Copy the following code:
# please do not remove this line
$Configs = [System.Collections.ArrayList]::new()
$Senders="example1.com","example2.com"
# example organization 1
# AppId - id of app created in Azure AD.
# CertificateFilePath - path to generated certificate with *.pfx extension.
# CertificatePassword - password used for creating *.pfx certificate.
# Organization - Microsoft organization domain under “onmicrosoft.com”
[void]$Configs.Add(@{
AppId="000000-0000-0000-0000-000000000000";
CertificateFilePath="path/to/cert1.pfx";
CertificatePassword="1234";
Organization="org1.onmicrosoft.com";
})
# example organization 2
[void]$Configs.Add(@{
AppId="11111111-1111-1111-1111-111111111111";
CertificateFilePath="path/to/cert2.pfx";
CertificatePassword="5678";
Organization="org2.onmicrosoft.com";
}) - In the Config.ps1 file, paste the code.
- Save the file.
Step 8: Edit the Config.ps1 file
- Download the list of available sending domains that you can use in your training and phishing campaigns.
a. In BullPhish ID, in the navigation menu, select Settings > Sending Domains.
b. In the upper-right corner, click Export Sending Domains.
c. Download the Sending_Domains.csv file to the desired location. - Open the Sending_Domains.csv file.
- Copy one of the sending domains you would like to use in your campaigns. For example, bp-service-support.com (do not copy the word Verified).
- In Config.ps1, find $Senders="example1.com","example2.com"
- Replace example1.com with the sending domain you copied, bp-service-support.com in the example. Make sure it has opening and closing quotation marks.
- For the next sending domain you would like to use, copy it from the Sending_Domains.csv file. In the Config.ps1 file, replace example2.com with the sending domain you copied.
- On the same line, add the rest of the domains you would like to use. Make sure each is enclosed in quotation marks and a comma separates each domain.
- Save the file.
- In Azure, navigate to the App registrations page.
- On the Owned applications tab, find the name of your application.
- Copy the Application (client) ID number.
- In the Config.ps1 file, in the example organization 1 section, find the AppId code line.
- Replace the AppId number with the Application ID you copied. Make sure it is enclosed in quotation marks and the line ends with a semi-colon.
- Save the file.
- Complete the following information:
- CertificateFilePath="path/to/cert1.pfx";
Enter the location path where the certificate is saved
(e.g., "C:\Users\msmith\Documents\Whitelisting files\mycert.pfx";) - CertificatePassword="1234";
Enter your Windows password (e.g., "He3445jq3#";) - Organization="org1.onmicrosoft.com";
Enter the name of your organization (e.g., "devopspassly1.onmicrosoft.com";)
- CertificateFilePath="path/to/cert1.pfx";
- If you are adding another organization, go to step 18. If not, delete the # example organization 2 code block.
- Save the file.
- To add another organization, perform the main steps:
- Step 1: Register the application in Azure AD
-
Step 2: Assign API permissions to the application
-
Step 3: Generate a self-signed certificate
-
Step 4: Attach the certificate to the Azure AD application
-
Step 5: Assign Azure AD roles to the application
- In the Config.ps1 file, complete the # example organization 2 code block.
- Save the file.
Step 9: Run the scripts in PowerShell
- Copy the following code and paste it into a text file.
Note: Some lines of code exceed the page margins because the code must remain on the same line.
powershell -ExecutionPolicy unrestricted -File "\Path\To\addSaveSenders_Revised.ps1" -ConfigPath="Path\To\Config.ps1"
- Replace "\Path\To\addSaveSenders_Revised.ps1" with the location in which you saved addSaveSenders_Revised.ps1
(e.g., "C:\Users\bsmith\Documents\Documentation\addSaveSenders_Revised.ps1"). - Replace "\Path\To\Config.ps1" with location in which you saved Config.ps1 (e.g., "C:\Users\bsmith\Documents\Documentation\Config.ps1").
- Copy the edited PowerShell line of code from your text file.
- Paste it into PowerShell and press Enter.
- Follow any prompts, if presented. When done, Finished! will display.
Step 10: Create a schedule to execute scripts
- On your taskbar, click the Windows icon.
-
Start typing Task Scheduler.
- When it appears in the list, open it.
- Right-click Task Scheduler Library and select New Folder.
- Enter a folder name and click OK.
- Expand the Task Scheduler Library branch and select the folder you created.
- Select Action > Create Task.
- On the General tab:
- In the Name box, type a short descriptive name for the task. For example, PowerShell First Script.
- In the Description box, create a description for the task (optional).
- In the "Security options" section, you can configure which administrator account can run the task.
Quick Tip: The default user should be exemplary if using an account with administrative privileges. Assume you're running a Command Prompt or PowerShell command. In this case, you can select the Run whether a user is logged on or not option to prevent the command window from showing up when the task runs automatically. - Select Run with the highest privileges option if the task requires elevated privileges (optional).
- The "Configure for" settings should be left alone unless you're required to use a different compatibility option.
- Click the Triggers tab and click New.
- In the Begin the task list, select On a schedule.
- Complete the following sections:
- Settings
- Start
- Advanced settings (optional)
- Enabled is selected and should not be deselected.
- Click OK.
- Click the Actions tab and click New.
- In the Action list, select Start a program.
Note: You can still use the Send an e-mail or Display a message option, but these are deprecated features. They may not work because Microsoft is no longer maintaining them. - In the Program/script box, specify the application's path. If you don't know the path of the app, click the Browse button to find it. However, if it's a general application like PowerShell or Command Prompt, you only need to enter the file name.
- In the Add arguments box, enter the ExecutionPolicy command created in Step 9: Run the scripts in PowerShell (i.e., -ExecutionPolicy unrestricted -File "\Path\To\addSaveSenders_Revised.ps1" -ConfigPath=”Path\To\Config.ps1).
- Click OK.
- The Conditions tab includes options that along with the trigger settings, determine when the task should run. This tab is optional.
- On the Settings tab, it is recommended to set the following options:
- Run task as soon as possible after a scheduled start is missed.
- If the task fails, restart every:
- Click OK.
- To test, right-click the task name and select Run.
- Click the History tab for results.