Play with Microsoft Graph PowerShell – MgGraph 101
One API and Language to rule them all. Connect PowerShell to Microsoft Graph API and take automation to the next level. A great way to work with many services and components without touching the GUI, especially for Security.
This post walks you through what MSGraph Security enables developers and IT professionals to do, along with some of the commands and resources Microsoft has released for working with PowerShell.
MSGraph in a Nutshell
The Microsoft Graph security API provides a unified interface and schema to integrate with security solutions from Microsoft and ecosystem partners. The Microsoft Graph Security API federates queries to all onboarded security providers and aggregates responses. This empowers customers to streamline security operations and better defend against increasing cyber threats. Use the Microsoft Graph Security API to build applications that:
- Consolidate and correlate security alerts from multiple sources.
- Pull and investigate all incidents and alerts from services that are part of or integrated with Microsoft 365 Defender.
- Unlock contextual data to inform investigations.
- Automate security tasks, business processes, workflows, and reporting.
- Send threat indicators to Microsoft products for customized detections.
- Invoke actions in response to new threats.
- Provide visibility into security data to enable proactive risk management.
The Microsoft Graph security API is an intermediary service or broker that provides a programmatic interface to connect multiple Microsoft Graph security providers. The Microsoft Graph Security API requests are federated to all applicable security providers. The results are aggregated and returned to the requesting application in a standard schema.
The Microsoft Graph security API provides vital features described in the following sections.
Alerts are detailed warnings about suspicious activities in a tenant that Microsoft or partner security providers have identified and flagged for action. Attacks typically employ various techniques against different entities, such as devices, users, and mailboxes. The result is alerting from multiple security providers for multiple entities in the tenant. Piecing the individual alerts together to gain insight into an attack can be challenging and time-consuming.
Alerts first pull alert data from security provider services that are either part of or integrated with Microsoft 365 Defender. Then they consume the data to return valuable clues about a completed or ongoing attack, the impacted assets, and associated evidence. In addition, they automatically correlate other alerts with the same attack techniques or the same attacker into an incident to provide a broader context of an attack.
Incidents are a collection of correlated alerts and associated data that make up the story of an attack. Incident management is part of Microsoft 365 Defender and is available in the Microsoft 365 Defender console. Microsoft 365 services and apps create alerts when they detect a suspicious or malicious event or activity. Individual alerts provide valuable clues about a completed or ongoing attack.
Legacy alerts federate calling of supported Azure and Microsoft 365 Defender security providers.
Also, there are scenarios such as Secure Score, eDiscovery, Attack simulation & training, etc.
Some use cases
Common use cases for the MgGraph PowerShell can be the following ones:
- User management: You can use the MgGraph module to manage users in your organization, such as creating new users, updating their properties, and deleting users who are no longer needed. For example, you can use the
New-MgGraph
cmdlet to create a new user with a specified set of properties, or theSet-MgGraph
cmdlet to update the properties of an existing user. - Group management: You can use the MgGraph module to manage groups in your organization, such as creating new groups, adding or removing members, and updating group properties. For example, you can use the
New-MgGraph
the cmdlet to create a new group with a specified set of properties, or theAdd-MgGraph
andRemove-MgGraph
cmdlets to manage the members of an existing group. - Resource management: You can use the MgGraph module to manage other types of resources in your organization, such as files, folders, calendars, and tasks. For example, you can use the
Get-MgGraph
the cmdlet to retrieve a list of files in a specific OneDrive folder or theSet-MgGraph
the cmdlet to update the properties of a specific calendar event. - Reporting and analysis: You can use the MgGraph module to retrieve data from Microsoft Graph for reporting and analysis purposes. For example, you can use the
Get-MgGraph
the cmdlet to retrieve a list of users and their properties, and then use PowerShell’s built-in reporting and analysis capabilities to generate charts and tables. - Automation: You can use the MgGraph module to automate routine tasks in your organization, such as creating new users or groups, updating properties, and performing bulk operations. For example, you can use PowerShell scripts that leverage the MgGraph module to automate the onboarding process for new employees or to automate the creation of distribution groups based on specific criteria.
Overall, the MgGraph PowerShell module provides a powerful and flexible way to interact with Microsoft Graph and can help you automate tasks and streamline your workflows in a variety of use cases.
Investigation Scenario
The MgGraph PowerShell module can be used for incident response investigations in several ways. Here is an example scenario:
Suppose you receive an incident report about an employee sharing sensitive company information with unauthorized external parties. You need to investigate and collect evidence to determine the extent of the breach and identify the parties involved.
- Connect to Microsoft Graph: First, you must connect to Microsoft Graph using the
Connect-MgGraph
cmdlet. You’ll be prompted to authenticate and consent to the required permissions. - Collect data: Next, you can use the
Get-MgGraph
the cmdlet to collect data relevant to the investigation. For example, you can retrieve a list of the employee’s OneDrive files and their sharing status, using a command like this:
Get-MgGraph -Resource me/drive/root/children -Select name,shared
This command retrieves all files’ names and sharing statuses in the employee’s OneDrive root folder.
- Filter and sort data: You can use the
-Filter
and-OrderBy
parameters of theGet-MgGraph
the cmdlet to filter and sort the results of your queries. For example, you can use the following command to retrieve all files that have been shared with external parties, sorted by the date they were last modified:
Get-MgGraph -Resource me/drive/root/children -Filter "shared ne null" -OrderBy lastModifiedDateTime
- Export data: Once you’ve collected the relevant data, you can export it to a file or a database for further analysis. For example, you can use the
Export-Csv
the cmdlet to export the results of your query to a CSV file, which can be imported into Excel or another tool for analysis:
Get-MgGraph -Resource me/drive/root/children -Filter "shared ne null" -OrderBy lastModifiedDateTime | Export-Csv -Path C:\temp\shared_files.csv -NoTypeInformation
This command exports the results of the previous command to a CSV file named shared_files.csv
in the C:\temp
directory.
- Follow-up actions: Once you’ve collected and analyzed the relevant data, you can take follow-up actions based on your findings. For example, you may need to revoke sharing permissions for certain files, terminate the employee’s access to company resources, or report the incident to law enforcement or regulatory authorities.
Overall, the MgGraph PowerShell module can be a powerful tool for incident response investigations, allowing you to collect and analyze data from Microsoft Graph in a flexible and efficient way.
MSGraph Security API – When & Why?
The Microsoft Graph Security API makes it easy to connect with security solutions from Microsoft and partners. It allows you to realize and enrich the value of these solutions more readily. You can connect easily with the Microsoft Graph Security API by using one of the following approaches, depending on your requirements:
- Write code
- Connect using scripts
- Drag and drop into workflows and playbooks
- Get data into reports and dashboards
- Connect using Jupyter notebooks
PowerShell Side
When using PowerShell, the MSGrapsh Security API, you need to know the principles of What it is intended for, how to connect, and the permissions.
The Microsoft Graph PowerShell SDK acts as an API wrapper for the Microsoft Graph APIs, exposing the entire API set for use in PowerShell. It contains a set of cmdlets that helps you manage identities at scale, from automating tasks to managing users in bulk using Azure AD. It will help administer every Azure AD feature with an API in Microsoft Graph.
The commands in Microsoft Graph PowerShell are autogenerated from the Microsoft Graph API schema, making it easier to get faster updates and functionality. The cmdlet reference content is also autogenerated from the API reference.
MSGraph PowerShell features
What can you do with PowerShell and MSGraph? There are many things, and if you’ve got a creative mind, this is the place for you. 😉
- Access to all Microsoft Graph APIs – Microsoft Graph PowerShell is based on Microsoft Graph API. In addition to Azure AD, the Microsoft Graph API includes APIs from other Microsoft services like SharePoint, Exchange, and Outlook. All are accessed through a single endpoint with a single access token. The Microsoft Graph PowerShell SDK provides the following benefits:
- Supports PowerShell 7 – Microsoft Graph PowerShell works with PowerShell 7 and later. It’s also compatible with Windows PowerShell 5.1.
- Cross-platform support – Microsoft Graph PowerShell works on all platforms, including Windows, macOS, and Linux.
- Supports modern authentication – Microsoft Graph PowerShell supports the MSAL, which offers more security. For example, you can use passwordless sign-in experiences.
- Supports external identities – Users from other Azure AD tenants can authenticate to services in your tenant with Microsoft Graph PowerShell.
- Least privilege – Microsoft Graph PowerShell permissions are not pre-authorized, and users must perform one-time requests for app permissions depending on their needs.
- Advanced queries – Microsoft Graph PowerShell supports rich, advanced queries via eventual consistency. For example, you can get a near-instant count of all users using advanced queries.
- Open-Source – Feature teams and the community can create great PowerShell experiences and share them with everyone.
- Receives regular updates – Microsoft Graph PowerShell commands are updated regularly to support the latest Graph API updates.
Remember that connecting to the MSGrpah API with PowerShell needs an application. You can work with the existing one or create a specific application for PowerShell.
API version – By default, the SDK uses the Microsoft Graph REST API v1.0. You can change the profile by using the Select-MgProfile command.
Authentication – The PowerShell SDK supports two types of authentication: delegated access and app-only access. Determine required permission scopes – Each API in the Microsoft Graph is protected by one or more permission scopes. The user logging in must consent to one of the required scopes for the APIs you plan to use. In this example, we’ll use the following APIs.
- List users to find the user ID of the logged-in user
- List joinedTeams to get the Teams the user is a member of.
- List channels to get the channels in a Team.
- Send a message to a Team channel.
Play with PowerShell
Let’s play with some commands to connect, display the alerts, and more. All the commands are available on my GitHub – MS-Defender-4-SecOps.
Install and import the modules
Install-Module -Name Microsoft.Graph
Select-MgProfile -Name “beta”
Import-Module Microsoft.Graph
Ensure you have the correct module installed
Get-InstalledModule “*Graph*”
Get-Module -ListAvailable Microsoft.Graph
Connect with Scope
Based on the permissions model, you need to connect to the MSGrapsh using the following scopes:
Connect-MgGraph -Scopes `
“SecurityActions.ReadWrite.All”,`
“SecurityEvents.ReadWrite.All”,`
“Policy.Read.All”,`
” Application.ReadWrite.All”,`
“User.Read.all”,`
“Application.Read.All”,`
“SecurityIncident.Read.All”,`
“SecurityIncident.ReadWrite.All”,`
“Directory.Read.All”
Once connected, you can execute the required commands.
Check Permissions – The Microsoft Graph PowerShell SDK application requires users to have domain knowledge of the semantics and syntax of Microsoft Graph API permissions used to authorize access to the API.
Find permissions related to a given application or delegated via the following command:
Find-MgGraphPermission organization | ? {$_.PermissionType -eq “Application”} | fl Name, Description
Find-MgGraphPermission application.Read | ? {$_.Consent -eq “Admin”}
Find-MgGraphPermission application.Read | fl
Find-MgGraphCommand -Uri “/users/{id}” -ApiVersion v1.0 | fl Command,Permissions
It’s time for alerts and incidents.
Once connected, you can run the relevant commands. To retrieve any existing security alerts.
Get-MgSecurityAlert | fl Title, Status, Id
Get-MgSecurityIncident | Select Id, DisplayName,Determination
Get-MgSecurityIncident | ? {$_.Status -eq “Active”}
Export results to Grid View
Get-MgSecurityAlert | `
Select-Object `
Title, `
Description, `
Category, Id | `
Out-GridView
Find specific values – The current PowerShell commands do not work as expected if you need to filter and search specific values. However, you can use the “Invoke-MgGraphRequest” command. If you are querying the graph directly, you can use this command:
Get-MgSecurityAlert | `Select-Object Title, Description, Category | Out-GridView$graphversion = “beta”$url = “https://graph.microsoft.com”$endpoint = “security/alerts”$filter = “title eq ‘Account enumeration reconnaissance'”$body = @{}$uri = “$url/$graphversion/$endpoint”$alerts = Invoke-MgGraphRequest -Uri $uri -Method GET -Body $body
Close all open alerts for Microsoft Defender for Identity with the following command, based on the AssignedTo and VendorInformation:
$alertid = Get-MgSecurityAlert | where-object {$_.AssignedTo -eq ‘Unassigned’}$params = @{Comments = @(“Case is closed”)Status = “resolved”VendorInformation = @{Provider = “Azure Advanced Threat Protection”#ProviderVersion = $nullSubProvider = “Azure Advanced Threat Protection”Vendor = “Microsoft”}}foreach ($alert in $alertid){$alert.id|Out-StringUpdate-MgSecurityAlert -AlertId ($alert).ID -BodyParameter $params}
References
What’s new in Microsoft Graph – Microsoft Graph
Use the Microsoft Graph Security API – Microsoft Graph
Microsoft Graph security API overview – Microsoft Graph