McasExtension.psm1

$script:ModuleRoot = $PSScriptRoot
$script:ModuleVersion = (Import-PowerShellDataFile -Path "$($script:ModuleRoot)\McasExtension.psd1").ModuleVersion

# Detect whether at some level dotsourcing was enforced
$script:doDotSource = Get-PSFConfigValue -FullName McasExtension.Import.DoDotSource -Fallback $false
if ($McasExtension_dotsourcemodule) { $script:doDotSource = $true }

<#
Note on Resolve-Path:
All paths are sent through Resolve-Path/Resolve-PSFPath in order to convert them to the correct path separator.
This allows ignoring path separators throughout the import sequence, which could otherwise cause trouble depending on OS.
Resolve-Path can only be used for paths that already exist, Resolve-PSFPath can accept that the last leaf my not exist.
This is important when testing for paths.
#>


# Detect whether at some level loading individual module files, rather than the compiled module was enforced
$importIndividualFiles = Get-PSFConfigValue -FullName McasExtension.Import.IndividualFiles -Fallback $false
if ($McasExtension_importIndividualFiles) { $importIndividualFiles = $true }
if (Test-Path (Resolve-PSFPath -Path "$($script:ModuleRoot)\..\.git" -SingleItem -NewChild)) { $importIndividualFiles = $true }
if ("<was compiled>" -eq '<was not compiled>') { $importIndividualFiles = $true }
    
function Import-ModuleFile
{
    <#
        .SYNOPSIS
            Loads files into the module on module import.
         
        .DESCRIPTION
            This helper function is used during module initialization.
            It should always be dotsourced itself, in order to proper function.
             
            This provides a central location to react to files being imported, if later desired
         
        .PARAMETER Path
            The path to the file to load
         
        .EXAMPLE
            PS C:\> . Import-ModuleFile -File $function.FullName
     
            Imports the file stored in $function according to import policy
    #>

    [CmdletBinding()]
    Param (
        [string]
        $Path
    )
    
    $resolvedPath = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($Path).ProviderPath
    if ($doDotSource) { . $resolvedPath }
    else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText($resolvedPath))), $null, $null) }
}

#region Load individual files
if ($importIndividualFiles)
{
    # Execute Preimport actions
    foreach ($path in (& "$ModuleRoot\internal\scripts\preimport.ps1")) {
        . Import-ModuleFile -Path $path
    }
    
    # Import all internal functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\internal\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Import all public functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Execute Postimport actions
    foreach ($path in (& "$ModuleRoot\internal\scripts\postimport.ps1")) {
        . Import-ModuleFile -Path $path
    }
    
    # End it here, do not load compiled code below
    return
}
#endregion Load individual files

#region Load compiled code
<#
This file loads the strings documents from the respective language folders.
This allows localizing messages and errors.
Load psd1 language files for each language you wish to support.
Partial translations are acceptable - when missing a current language message,
it will fallback to English or another available language.
#>

Import-PSFLocalizedString -Path "$($script:ModuleRoot)\en-us\*.psd1" -Module 'McasExtension' -Language 'en-US'

function Convert-McasExAlert {
<#
    .SYNOPSIS
        Converts / Processes an alert object for greater convenience.
     
    .DESCRIPTION
        Converts / Processes an alert object for greater convenience.
        Expects the output of Get-MCASAlert or Get-McasExAlert.
     
        Resolves timestamps, flattens out the data structure and resolves files if present.
     
    .PARAMETER Alert
        The alert object to process.
     
    .EXAMPLE
        PS C:\> Get-McasExAlert -Limit '-2d' | Convert-McasExAlert
     
        Retrieve the alerts of the last two days and convert them into something readable.
#>

    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true)]
        $Alert
    )
    
    process {
        foreach ($alertObject in $Alert) {
            # $app = ($alertObject.entities | Where-Object type -eq 'service').label
            $file = ($alertObject.entities | Where-Object type -eq 'file').id
            
            $fileDetails = $null
            if ($file) { $fileDetails = Get-MCASFile -Identity $file }
            
            [pscustomobject]@{
                PSTypeName = 'Mcas.Alert'
                ID           = $alertObject._id
                Timestamp  = ConvertFrom-MCASTimestamp $alertObject.timestamp
                Title       = $alertObject.title
                PolicyName = $alertObject.Policy.Label
                PolicyType = $alertObject.Policy.PolicyType
                
                Status       = $alertObject.statusValue
                Severity   = $alertObject.severityValue
                ThreatScore = $alertObject.ThreatScore
                Url           = $alertObject.URL
                
                Proxy       = ($alertObject.Entities | Where-Object type -eq discovery_stream).Label
                Service    = ($alertObject.Entities | Where-Object type -eq service).Label
                Accounts   = ($alertObject.Entities | Where-Object type -eq account).Label
                AccountMail = ($alertObject.Entities | Where-Object type -eq account).em
                IP           = ($alertObject.Entities | Where-Object type -eq ip).Label
                Country    = ($alertObject.Entities | Where-Object type -eq country).Label
                DiscoveryService = ($alertObject.Entities | Where-Object type -eq discovery_service).Label
                DiscoveryIP = ($alertObject.Entities | Where-Object type -eq discovery_ip).Label
                DiscoveryUser = ($alertObject.Entities | Where-Object type -eq discovery_user).Label
                DiscoveryStream = ($alertObject.Entities | Where-Object type -eq discovery_stream).Label
                
                FileName   = $fileDetails.name
                FilePath   = $fileDetails.alternateLink
                FileOwner  = $fileDetails.ownerAddress
                FileCreatedDate = $(
                    if ($fileDetails.createdDate) {
                        try { ConvertFrom-MCASTimestamp $fileDetails.createdDate -ErrorAction Stop }
                        catch { $fileDetails.createdDate }
                    }
                )
                FileModifiedDate = $(
                    if ($fileDetails.modifiedDate) {
                        try { ConvertFrom-MCASTimestamp $fileDetails.modifiedDate -ErrorAction Stop }
                        catch { $fileDetails.modifiedDate }
                    }
                )
                FileStatus = $(if ($file) { $fileDetails.fileStatus[1] })
                FileAccessLevel = $(if ($file) { $fileDetails.fileAccessLevel[1] })
            }
        }
    }
}

function Get-McasExAlert
{
<#
    .SYNOPSIS
        Search for alerts in MCAS.
     
    .DESCRIPTION
        Search for alerts in MCAS.
        Wrapper around Get-McasAlert with automatic paging.
     
    .PARAMETER Identity
        Specific event ID to search for, rather than specifying a filter condition.
     
    .PARAMETER SortBy
        How should the results be sorted (server side ordering)
     
    .PARAMETER SortDirection
        In which direction should results be sorted.
     
    .PARAMETER ResultSetSize
        This parameter is ignored.
     
    .PARAMETER Skip
        How many items should initially be skipped?
     
    .PARAMETER PeriodicWriteToFile
        Periodically writes the activities returned in JSON format to a specified file. Useful for large queries. (Example: -PeriodicWriteToFile "C:\path\to\file.txt").
     
    .PARAMETER Severity
        Limits the results by severity. Possible Values: 'High','Medium','Low'.
     
    .PARAMETER ResolutionStatus
        Limits the results to items with a specific resolution status. Possible Values: 'Open','Dismissed','Resolved'.
     
    .PARAMETER UserName
        Limits the results to items related to the specified user/users, such as 'alice@contoso.com','bob@contoso.com'.
     
    .PARAMETER AppId
        Limits the results to items related to the specified service IDs, such as 11161,11770 (for Office 365 and Google Apps, respectively).
     
    .PARAMETER AppName
        Limits the results to items related to the specified service names, such as 'Office_365' and 'Google_Apps'.
     
    .PARAMETER AppIdNot
        Limits the results to items not related to the specified service ids, such as 11161,11770 (for Office 365 and Google Apps, respectively).
     
    .PARAMETER AppNameNot
        Limits the results to items not related to the specified service names, such as 'Office_365' and 'Google_Apps'.
     
    .PARAMETER Policy
        Limits the results to items related to the specified policy ID, such as 57595d0ba6b5d8cd76d6be8c.
     
    .PARAMETER Risk
        Limits the results to items with a specific risk score. The valid range is 1-10.
     
    .PARAMETER Source
        Limits the results to items from a specific source.
     
    .PARAMETER Read
        Limits the results to read items.
     
    .PARAMETER Unread
        Limits the results to unread items.
     
    .PARAMETER Limit
        Only return alerts that happened after this timestamp.
        Supports time-relative notations, such as "-3d" to get the last 3 days.
     
    .PARAMETER Credential
        Specifies the credential object containing tenant as username (e.g. 'contoso.us.portal.cloudappsecurity.com') and the 64-character hexadecimal Oauth token as the password.
     
    .EXAMPLE
        PS C:\>Get-MCASExAlert -Identity 572caf4588011e452ec18ef0
 
        Retrieve a single alert record using the GUID.
     
    .EXAMPLE
        PS C:\> Get-MCASExAlert -ResolutionStatus Open -Severity High | Convert-McasExAlert
     
        Retrieve all severity "High" alerts that are still open, then convert them into a more accessible format.
#>

    [CmdletBinding(DefaultParameterSetName = 'filter')]
    param (
        [Parameter(Mandatory = $true, Position = 1, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'identity')]
        [string]
        $Identity,
        
        [Parameter(ParameterSetName = 'filter')]
        [string]
        $SortBy,
        
        [Parameter(ParameterSetName = 'filter')]
        [ValidateSet('Ascending','Descending')]
        [string]
        $SortDirection,
        
        [Parameter(ParameterSetName = 'filter')]
        [int]
        $ResultSetSize,
        
        [Parameter(ParameterSetName = 'filter')]
        [int]
        $Skip,
        
        [Parameter(ParameterSetName = 'filter')]
        [string]
        $PeriodicWriteToFile,
        
        [Parameter(ParameterSetName = 'filter')]
        [ValidateSet('High', 'Low', 'Medium')]
        [string[]]
        $Severity,
        
        [Parameter(ParameterSetName = 'filter')]
        [ValidateSet('Dismissed', 'Open', 'Resolved')]
        [string[]]
        $ResolutionStatus,
        
        [Parameter(ParameterSetName = 'filter')]
        [string[]]
        $UserName,
        
        [Parameter(ParameterSetName = 'filter')]
        [int[]]
        $AppId,
        
        [Parameter(ParameterSetName = 'filter')]
        [string[]]
        $AppName,
        
        [Parameter(ParameterSetName = 'filter')]
        [int[]]
        $AppIdNot,
        
        [Parameter(ParameterSetName = 'filter')]
        [string[]]
        $AppNameNot,
        
        [Parameter(ParameterSetName = 'filter')]
        [string[]]
        $Policy,
        
        [Parameter(ParameterSetName = 'filter')]
        [int[]]
        $Risk,
        
        [Parameter(ParameterSetName = 'filter')]
        [string]
        $Source,
        
        [Parameter(ParameterSetName = 'filter')]
        [switch]
        $Read,
        
        [Parameter(ParameterSetName = 'filter')]
        [switch]
        $Unread,
        
        [Parameter(ParameterSetName = 'filter')]
        [PSFDateTime]
        $Limit,
        
        [PSCredential]
        $Credential
    )
    
    begin {
        $skip = 0
        $parameters = $PSBoundParameters | ConvertTo-PSFHashtable -Exclude Identity, ResultSetSize, Skip
    }
    
    process {
        $currentParameters = $parameters
        if ($Identity) { $currentParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Credential, Identity }
        
        do {
            $alerts = Get-MCASAlert @currentParameters -ResultSetSize 100 -Skip $skip
            if (-not $alerts) { return }
            
            $last = ConvertFrom-MCASTimestamp $alerts[-1].Timestamp
            
            if ($Limit -and $last -lt $Limit) {
                $alerts | Where-Object { (ConvertFrom-MCASTimestamp $_.Timestamp) -gt $Limit }
                return
            }
            $alerts
            $skip = $skip + 100
        }
        while ($true)
    }
}

function Get-McasExMalwareFileActivity
{
<#
    .SYNOPSIS
        Search MCAS for FileMalwareDetected activities.
     
    .DESCRIPTION
        Search MCAS for FileMalwareDetected activities.
     
    .PARAMETER Limit
        How far to look into the past.
        Defaults to one day.
     
    .EXAMPLE
        PS C:\> Get-McasExMalwareFileActivity
     
        Get all detected malware in file activities in the last day
#>

    [CmdletBinding()]
    Param (
        [Parameter(ParameterSetName = 'filter')]
        [PSFDateTime]
        $Limit = '-1d'
    )
    
    begin {
        #region Utility Functions
        function ConvertFrom-Activity {
            [CmdletBinding()]
            param (
                [parameter(ValueFromPipeline = $true)]
                $ActivityObject
            )
            process {
                [PSCustomObject]@{
                    ID = $ActivityObject._id
                    File = @($ActivityObject.mainInfo.EventObjects).Where{ $_.objType -eq 0 }.name
                    ServiceType = @($ActivityObject.mainInfo.EventObjects).Where{ $_.objType -eq 1 }.serviceObjectType
                    App = $ActivityObject.appName
                    Created = ConvertFrom-MCASTimestamp -Timestamp $ActivityObject.Created
                    Timestamp = ConvertFrom-MCASTimestamp -Timestamp $ActivityObject.Timestamp
                    TenantId = $ActivityObject.aadTenantId
                    EventTypeValue = $ActivityObject.eventTypeValue
                    EventTypeName = $ActivityObject.eventTypeName
                    EventCategory = $ActivityObject.description_metadata.event_category
                    Confidence = $ActivityObject.confidenceLevel
                    Severity = $ActivityObject.Severity
                    MatchingRules = $ActivityObject.matchingRules
                    Description = $ActivityObject.description
                    
                    OrganizationId = $ActivityObject.rawDataJson.OrganizationId
                    CreationTime = $ActivityObject.rawDataJson.CreationTime
                    CorrelationId = $ActivityObject.rawDataJson.CorrelationId
                    RecordType = $ActivityObject.rawDataJson.RecordType
                    Operation = $ActivityObject.rawDataJson.Operation
                    UserType = $ActivityObject.rawDataJson.UserType
                    Workload = $ActivityObject.rawDataJson.Workload
                    ClientIP = $ActivityObject.rawDataJson.ClientIP
                    UserAgent = $ActivityObject.rawDataJson.UserAgent
                    UserKey = $ActivityObject.rawDataJson.UserKey
                    Version = $ActivityObject.rawDataJson.Version
                    ItemType = $ActivityObject.rawDataJson.ItemType
                    SourceFileExtension = $ActivityObject.rawDataJson.SourceFileExtension
                    ObjectId = $ActivityObject.rawDataJson.ObjectId
                    UserId = $ActivityObject.rawDataJson.UserId
                    ListItemUniqueId = $ActivityObject.rawDataJson.ListItemUniqueId
                    SourceRelativeUrl = $ActivityObject.rawDataJson.SourceRelativeUrl
                    EventSource = $ActivityObject.rawDataJson.EventSource
                    SourceFileName = $ActivityObject.rawDataJson.SourceFileName
                    FileId = $ActivityObject.rawDataJson.Id
                    SiteUrl = $ActivityObject.rawDataJson.SiteUrl
                    WebId = $ActivityObject.rawDataJson.WebId
                    ListId = $ActivityObject.rawDataJson.ListId
                    Site = $ActivityObject.rawDataJson.Site
                    VirusVendor = $ActivityObject.rawDataJson.VirusVendor
                    VirusInfo = $ActivityObject.rawDataJson.VirusInfo
                    
                    RawObject = $ActivityObject
                }
            }
        }
        #endregion Utility Functions
        
        $eventTypes = @(
            '20892:EVENT_O365_SP_FILE_MALWARE_DETECTED:FileMalwareDetected'
            '15600:EVENT_O365_ONEDRIVE_FILE_MALWARE_DETECTED:FileMalwareDetected'
        )
    }
    process{
        $skip = 0
        do {
            $activities = Get-MCASActivity -EventTypeName $eventTypes -ResultSetSize 100 -Skip $skip -DateAfter $Limit
            if (-not $activities) { return }
            $activities | ConvertFrom-Activity
            if (@($activities).Count -lt 100) { return }
            $skip = $skip + 100
        }
        while ($true)
    }
}

<#
This is an example configuration file
 
By default, it is enough to have a single one of them,
however if you have enough configuration settings to justify having multiple copies of it,
feel totally free to split them into multiple files.
#>


<#
# Example Configuration
Set-PSFConfig -Module 'McasExtension' -Name 'Example.Setting' -Value 10 -Initialize -Validation 'integer' -Handler { } -Description "Example configuration setting. Your module can then use the setting using 'Get-PSFConfigValue'"
#>


Set-PSFConfig -Module 'McasExtension' -Name 'Import.DoDotSource' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be dotsourced on import. By default, the files of this module are read as string value and invoked, which is faster but worse on debugging."
Set-PSFConfig -Module 'McasExtension' -Name 'Import.IndividualFiles' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be imported individually. During the module build, all module code is compiled into few files, which are imported instead by default. Loading the compiled versions is faster, using the individual files is easier for debugging and testing out adjustments."

<#
Stored scriptblocks are available in [PsfValidateScript()] attributes.
This makes it easier to centrally provide the same scriptblock multiple times,
without having to maintain it in separate locations.
 
It also prevents lengthy validation scriptblocks from making your parameter block
hard to read.
 
Set-PSFScriptblock -Name 'McasExtension.ScriptBlockName' -Scriptblock {
     
}
#>


<#
# Example:
Register-PSFTeppScriptblock -Name "McasExtension.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' }
#>


<#
# Example:
Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name McasExtension.alcohol
#>


New-PSFLicense -Product 'McasExtension' -Manufacturer 'Friedrich Weinmann' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2021-03-31") -Text @"
Copyright (c) 2021 Friedrich Weinmann
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"@

#endregion Load compiled code