Skip to content

Commit

Permalink
Added support for free tenants.
Browse files Browse the repository at this point in the history
  • Loading branch information
merill committed Jun 2, 2024
1 parent b029c1c commit ea5146d
Show file tree
Hide file tree
Showing 6 changed files with 226 additions and 26 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -354,3 +354,4 @@ MigrationBackup/

temp/
.DS_Store
/test
47 changes: 44 additions & 3 deletions src/Export-MsIdAzureMfaReport.ps1
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<#
.SYNOPSIS
Exports the list of users that have signed into the Azure portal, Azure CLI, or Azure PowerShell over the last 30 days by querying the sign-in logs. In [Microsoft Entra ID Free](https://learn.microsoft.com/entra/identity/monitoring-health/reference-reports-data-retention#activity-reports) tenants, sign-in log retention is limited to seven days.
Exports the list of users that have signed into the Azure portal, Azure CLI, or Azure PowerShell over the last 30 days by querying the sign-in logs.
In [Microsoft Entra ID Free](https://learn.microsoft.com/entra/identity/monitoring-health/reference-reports-data-retention#activity-reports) tenants, sign-in log retention is limited to seven days.
The report also includes each user's multi-factor authentication (MFA) registration status from Microsoft Entra.
Expand Down Expand Up @@ -50,6 +51,38 @@
Returns the results and exports them to a CSV file.
.EXAMPLE
Export-MsIdAzureMfaReport -PassThru | Export-Csv -Path .\report.csv
Returns the results and exports them to a CSV file.
.EXAMPLE
Export-MsIdAzureMfaReport .\report.xlsx -SignInsJsonPath ./signIns.json
Generates the report from the sign-ins JSON file downloaded from the Entra portal. This is required for Entra ID Free tenants.
.NOTES
### Entra ID Free tenants
If you are using an Entra ID Free tenant, additional steps are required to download the sign-in logs
Follow these steps to download the sign-in logs.
- Sign-in to the **[Entra Admin Portal](https://entra.microsoft.com)**
- From the left navigation select: **Identity** → **Monitoring & health** → **Sign-in logs**.
- Select the **Date** filter and set to **Last 7 days**
- Select **Add filters** → **Application** and type in: **Azure**
- Select **Download** → **Download JSON**
- Set the **File Name** of the first textbox to **signins** and select it's **Download** button.
- Once the file is downloaded, copy it to the folder where the export command will be run.
Re-run this command with the **-SignInsJsonPath** option.
```powershell
Export-MsIdAzureMfaReport ./report.xlsx -SignInsJsonPath ./signins.json
```
#>
function Export-MsIdAzureMfaReport {
[CmdletBinding(HelpUri = 'https://azuread.github.io/MSIdentityTools/commands/Export-MsIdAzureMfaReport')]
Expand All @@ -60,11 +93,15 @@ function Export-MsIdAzureMfaReport {
[string]
$ExcelWorkbookPath,

# Optional. Path to the sign-ins JSON file. If provided, the report will be generated from this file instead of querying the sign-ins.
[string]
$SignInsJsonPath,

# Switch to include the results in the output
[switch]
$PassThru,

# Number of days to query sign-in logs. Defaults to 30 days for premium tenants and 7 days for free tenants
# Optional. Number of days to query sign-in logs. Defaults to 30 days for premium tenants and 7 days for free tenants
[ValidateScript({
$_ -ge 0 -and $_ -le 30
},
Expand Down Expand Up @@ -105,8 +142,12 @@ function Export-MsIdAzureMfaReport {
$azureUsersMfa = $UsersMfa
}
else {
if ($null -ne $SignInsJsonPath) {
# Don't look up graph if we have the sign-ins json (usually free tenant download from portal)
$Users = Get-MsIdAzureUsers -SignInsJsonPath $SignInsJsonPath
}
# Get the users and their MFA status
if ($null -eq $Users) {
elseif ($null -eq $Users) {
# Get the users
$Users = Get-MsIdAzureUsers -Days $Days
}
Expand Down
86 changes: 81 additions & 5 deletions src/Get-MsIdAzureUsers.ps1
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
<#
.SYNOPSIS
Returns a list of users that have signed into the Azure portal, Azure CLI, or Azure PowerShell over the last 30 days by querying the sign-in logs. In [Microsoft Entra ID Free](https://learn.microsoft.com/entra/identity/monitoring-health/reference-reports-data-retention#activity-reports) tenants, sign-in log retention is limited to seven days.
Returns a list of users that have signed into the Azure portal, Azure CLI, or Azure PowerShell over the last 30 days by querying the sign-in logs.
If your tenant is a [Microsoft Entra ID Free](https://learn.microsoft.com/entra/identity/monitoring-health/reference-reports-data-retention#activity-reports), the sign-in logs need to be downloaded from
- Required permission scopes: **Directory.Read.All**, **AuditLog.Read.All**
- Required Microsoft Entra role: **Global Reader**
Expand All @@ -19,11 +21,21 @@
PS > Get-MsIdAzureUsers -Days 3
Queries the logs for the last three days and returns all the users that have signed into Azure during this period.
.EXAMPLE
PS > Get-MsIdAzureUsers -SignInsJsonPath ./signIns.json
Uses the sign-ins json file downloaded from the Microsoft Portal and returns all the users that have signed into Azure during this period.
#>

function Get-MsIdAzureUsers {
[CmdletBinding(HelpUri = 'https://azuread.github.io/MSIdentityTools/commands/Get-MsIdAzureUsers')]
param (
# Optional. Path to the sign-ins JSON file. If provided, the report will be generated from this file instead of querying the sign-ins.
[string]
$SignInsJsonPath,

# Number of days to query sign-in logs. Defaults to 30 days for premium tenants and 7 days for free tenants
[ValidateScript({
$_ -ge 0 -and $_ -le 30
Expand Down Expand Up @@ -53,7 +65,13 @@ function Get-MsIdAzureUsers {

if (!(Test-MgModulePrerequisites @('AuditLog.Read.All', 'Directory.Read.All'))) { return }

$users = GetAzureUsers $Days
if ($SignInsJsonPath) {
$users = Get-JsonFileContent -SignInsJsonPath $SignInsJsonPath
}
else {
$users = GetAzureUsers $Days
}

if ($users) {
$users.Values
}
Expand Down Expand Up @@ -164,11 +182,25 @@ function Get-MsIdAzureUsers {

$err = Get-ObjectPropertyValue $resultsJson -Property "error"
if ($err) {
$message = $err.message
if ($err.code -eq "Authentication_RequestFromUnsupportedUserRole") {
$message += " The signed-in user needs to be assigned the Microsoft Entra Global Reader role."
Write-Host "The signed-in user needs to be assigned the Microsoft Entra Global Reader role." -ForegroundColor Green
}
elseif ($err.code -eq "Authentication_RequestFromNonPremiumTenantOrB2CTenant") {
Write-Host "You are using an Entra ID Free tenant which requires additional steps to download the sign-in logs." -ForegroundColor Green
Write-Host
Write-Host "Follow these steps to download the sign-in logs." -ForegroundColor Green
Write-Host "- Sign-in to https://entra.microsoft.com" -ForegroundColor Green
Write-Host "- From the left navigation select: Identity → Monitoring & health → Sign-in logs." -ForegroundColor Green
Write-Host "- Select the 'Date' filter and set to 'Last 7 days'" -ForegroundColor Green
Write-Host "- Select 'Add filters' → 'Application' and type in: Azure" -ForegroundColor Green
Write-Host "- Select 'Download → Download JSON" -ForegroundColor Green
Write-Host "- Set the 'File Name' of the first textbox to 'signins' and select it's Download button." -ForegroundColor Green
Write-Host "- Once the file is downloaded, copy it to the folder where the export command will be run." -ForegroundColor Green
Write-Host
Write-Host "Re-run this command with the -SignInsJsonPath parameter." -ForegroundColor Green
Write-Host "E.g.> Export-MsIdAzureMfaReport ./report.xlsx -SignInsJsonPath ./signins.json" -ForegroundColor Yellow
}
Write-Error $message -ErrorAction Stop
Write-Error $err.message -ErrorAction Stop
}

$minDate = $null
Expand Down Expand Up @@ -200,6 +232,50 @@ function Get-MsIdAzureUsers {
return $allAppFilter
}

function Get-JsonFileContent ($signInsJsonPath) {
Write-Verbose "Reading sign-ins from $signInsJsonPath"
$signIns = Get-Content $signInsJsonPath -Raw | ConvertFrom-Json

$azureUsers = @{}
$count = 0

foreach ($item in $signIns) {
$count++
# Check if user exists in the dictionary and create a new object if not
[string]$userId = $item.userId
$user = $azureUsers[$userId]
if ($null -eq $user) {
$user = [pscustomobject]@{
UserId = $item.userId
UserPrincipalName = $item.userPrincipalName
UserDisplayName = $item.userDisplayName
AzureAppName = ""
AzureAppId = @($item.appId)
}
$azureUsers[$userId] = $user
}
else {
# Add the app if it doesn't already exist
if ($user.AzureAppId -notcontains $item.appId) {
$user.AzureAppId += $item.appId
}
}
}

# Update the Azure App name for each user
foreach ($user in $azureUsers.Values) {
$appNames = @()
foreach ($appId in $user.AzureAppId) {
$app = $mfaEnforcedApps | Where-Object { $_.AppId -eq $appId }
if ($app) {
$appNames += $app.DisplayName
}
}
$user.AzureAppName = $appNames -join ", "
}
return $azureUsers
}

function WriteExportProgress(
# The current step of the overal generation
[ValidateSet("Logs")]
Expand Down
72 changes: 63 additions & 9 deletions website/docs/commands/Export-MsIdAzureMfaReport.mdx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
sidebar_class_name: hidden
description: Exports the list of users that have signed into the Azure portal, Azure CLI, or Azure PowerShell over the last 30 days by querying the sign in logs.
description: Exports the list of users that have signed into the Azure portal, Azure CLI, or Azure PowerShell over the last 30 days by querying the sign-in logs.
id: Export-MsIdAzureMfaReport
title: Export-MsIdAzureMfaReport
hide_title: false
Expand All @@ -10,7 +10,7 @@ custom_edit_url: https://github.com/azuread/msidentitytools/blob/main/src/Export

## SYNOPSIS

Exports the list of users that have signed into the Azure portal, Azure CLI, or Azure PowerShell over the last 30 days by querying the sign in logs.
Exports the list of users that have signed into the Azure portal, Azure CLI, or Azure PowerShell over the last 30 days by querying the sign-in logs.
In [Microsoft Entra ID Free](https://learn.microsoft.com/entra/identity/monitoring-health/reference-reports-data-retention#activity-reports) tenants, sign-in log retention is limited to seven days.

The report also includes each user's multi-factor authentication (MFA) registration status from Microsoft Entra.
Expand All @@ -34,9 +34,9 @@ Export-MsIdAzureMfaReport .\report.xlsx
## SYNTAX

```powershell
Export-MsIdAzureMfaReport [[-ExcelWorkbookPath] <String>] [-PassThru] [-Days <Int32>] [-Users <Array>]
[-UsersMfa <Array>] [-UseAuthenticationMethodEndPoint] [-ProgressAction <ActionPreference>]
[<CommonParameters>]
Export-MsIdAzureMfaReport [[-ExcelWorkbookPath] <String>] [-SignInsJsonPath <String>] [-PassThru]
[-Days <Int32>] [-Users <Array>] [-UsersMfa <Array>] [-UseAuthenticationMethodEndPoint]
[-ProgressAction <ActionPreference>] [<CommonParameters>]
```

## DESCRIPTION
Expand All @@ -63,20 +63,19 @@ The `MFA status` is not applicable if your tenant uses a third party multi-facto
### EXAMPLE 1

```powershell
Install-Module MsIdentityTools -Scope CurrentUser
Connect-MgGraph -Scopes Directory.Read.All, AuditLog.Read.All, UserAuthenticationMethod.Read.All
Export-MsIdAzureMfaReport .\report.xlsx
```

Queries last 30 days (7 days for Free tenants) sign in logs and outputs a report of users accessing Azure and their MFA status in Excel format.
Queries last 30 days (7 days for Free tenants) sign-in logs and outputs a report of users accessing Azure and their MFA status in Excel format.

### EXAMPLE 2

```powershell
Export-MsIdAzureMfaReport .\report.xlsx -Days 3
```

Queries sign in logs for the past 3 days and outputs a report of Azure users and their MFA status in Excel format.
Queries sign-in logs for the past 3 days and outputs a report of Azure users and their MFA status in Excel format.

### EXAMPLE 3

Expand All @@ -86,6 +85,23 @@ Export-MsIdAzureMfaReport -PassThru | Export-Csv -Path .\report.csv

Returns the results and exports them to a CSV file.

### EXAMPLE 4

```powershell
Export-MsIdAzureMfaReport -PassThru | Export-Csv -Path .\report.csv
```

Returns the results and exports them to a CSV file.

### EXAMPLE 5

```powershell
Export-MsIdAzureMfaReport .\report.xlsx -SignInsJsonPath ./signIns.json
```

Generates the report from the sign-ins JSON file downloaded from the Entra portal.
This is required for Entra ID Free tenants.

## PARAMETERS

### -ExcelWorkbookPath
Expand All @@ -106,6 +122,24 @@ Accept pipeline input: False
Accept wildcard characters: False
```
### -SignInsJsonPath
Optional.
Path to the sign-ins JSON file.
If provided, the report will be generated from this file instead of querying the sign-ins.
```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -PassThru
Switch to include the results in the output
Expand All @@ -124,7 +158,8 @@ Accept wildcard characters: False
### -Days
Number of days to query sign in logs.
Optional.
Number of days to query sign-in logs.
Defaults to 30 days for premium tenants and 7 days for free tenants
```yaml
Expand Down Expand Up @@ -217,4 +252,23 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable
## NOTES
### Entra ID Free tenants
If you are using an Entra ID Free tenant, additional steps are required to download the sign-in logs
Follow these steps to download the sign-in logs.
- Sign-in to the **[Entra Admin Portal](https://entra.microsoft.com)
- From the left navigation select: **Identity** → **Monitoring & health** → **Sign-in logs**.
- Select the **Date** filter and set to **Last 7 days**
- Select **Add filters** → **Application** and type in: **Azure**
- Select **Download** → **Download JSON**
- Set the **File Name** of the first textbox to **signins' and select it's **Download** button.
- Once the file is downloaded, copy it to the folder where the export command will be run.
Re-run this command with the **-SignInsJsonPath** option.
```powershell
Export-MsIdAzureMfaReport ./report.xlsx -SignInsJsonPath ./signins.json
```

## RELATED LINKS
Loading

0 comments on commit ea5146d

Please sign in to comment.