invictus-ir/Microsoft-Extractor-Suite

[Bug] - Get-ActivityLogs - Null error returned for subscriptions with no logs

Closed this issue · 6 comments

Issue
When using Get-ActivityLogs on a tenancy with multiple subscriptions, the initial check for $areYouConnected fails on the default subscription, as there are no activity logs in that subscription.

This also occurs during acqusition on these invalid subscriptions

Get-AzActivityLog : Exception type: ErrorResponseException, Message: Null/Empty, Code: Null, Status code:BadRequest,
Reason phrase: Bad Request
At C:\Microsoft-Extractor-Suite-main\Scripts\Get-AzureActivityLogs.ps1:166 char:21
+ ... ntResults = Get-AzActivityLog -StartTime $start -EndTime $end -MaxRec ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Get-AzActivityLog], PSInvalidOperationException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Insights.Events.GetAzureRmLogCommand

Expected Behavior
Get-AzActivity Log runs through each of the subscriptions in the tenancy to check for authentication and / the presence of logs.

Where this null is returned, move to the next subscription and check there before erroring the whole script.

Where a valid subscription is identified, store the valid subscription id in an array for acqusition

If no subscriptions are valid, return [WARNING] and break.

Possible Solution

Firstly, we should change the test for areYouConnected

	try {
		$areYouConnected = Get-AzSubscription -ErrorAction stop -WarningAction silentlyContinue
	}
	catch {
		write-logFile -Message "[WARNING] You must call Connect-AzureAZ before running this script" -Color "Red"
		break
	}
	

Next we should try to catch this specific error for [Microsoft.Azure.Commands.Insights.Events.GetAzureRmLogCommand] and gracefully handle it. Its been a while since I have coded this, but I have used this documentation previously for error handling on certain errors

  1. https://www.sharepointdiary.com/2021/07/powershell-try-catch-exception-handling.html
  2. https://www.gngrninja.com/script-ninja/2016/6/5/powershell-getting-started-part-11-error-handling

The error type is

$error[1] | Get-Member


   TypeName: System.Management.Automation.ActionPreferenceStopException

Name                        MemberType Definition
----                        ---------- ----------
Equals                      Method     bool Equals(System.Object obj), bool _Exception.Equals(System.Object obj)
GetBaseException            Method     System.Exception GetBaseException(), System.Exception _Exception.GetBaseExcep...
GetHashCode                 Method     int GetHashCode(), int _Exception.GetHashCode()
GetObjectData               Method     void GetObjectData(System.Runtime.Serialization.SerializationInfo info, Syste...
GetType                     Method     type GetType(), type _Exception.GetType()
ToString                    Method     string ToString(), string _Exception.ToString()
Data                        Property   System.Collections.IDictionary Data {get;}
ErrorRecord                 Property   System.Management.Automation.ErrorRecord ErrorRecord {get;}
HelpLink                    Property   string HelpLink {get;set;}
HResult                     Property   int HResult {get;set;}
InnerException              Property   System.Exception InnerException {get;}
Message                     Property   string Message {get;}
Source                      Property   string Source {get;set;}
StackTrace                  Property   string StackTrace {get;}
TargetSite                  Property   System.Reflection.MethodBase TargetSite {get;}
WasThrownFromThrowStatement Property   bool WasThrownFromThrowStatement {get;set;}

So we should be able to use this to handle the error gracefully

	try {
		foreach ($sub in $Subscription) {	
			$name = $sub.Name
			$iD = $sub.Id
			
			Set-AzContext -Subscription $iD | Out-Null

			[array]$validSub = Get-AzSubscription Get-AzActivityLog -ErrorAction stop -WarningAction silentlyContinue
		}
	}
	catch [System.Management.Automation.ActionPreferenceStopException] {
		write-logFile -Message "[WARNING] $sub contains no or null logs! moving on" -Color "Red"
	}
	catch {
		write-logFile -Message "[ERROR] another error has occured $($error) please check the azure documentaion for further troubleshooting" -Color "Red"
		return
	}
       

Support

Unfortunatley i don't have capacity to code this one at the moment, but hopefully the above helps as a jumping off point unless i find some extra time soon.

Great catch! We're on it and will incorporate a fix in our upcoming update. We're aiming to roll this out by the end of the week.

Hi, the update is live. The error shouldn't happen anymore, let me know if it works as expected. If so, I will close the issue.

Thanks Joey,

Ive had a look through the code and it looks good, I'll confirm later today in a test case to be sure.

Just did a test and that works a treat, I'd still reccomend doing a try catch so you make sure your catching the right error long term though 😊.

Will try to add one in the next update!

Hi, hope you are doing well! I just added the Try/Catch part as requested :).