Query Details
//Detect when a service principal is added to Azure AD after working hours or on weekends //Data connector required for this query - Azure Active Directory - Audit Logs let Saturday = time(6.00:00:00); let Sunday = time(0.00:00:00); AuditLogs | where TimeGenerated > ago(7d) // extend LocalTime to your time zone | extend LocalTime=TimeGenerated + 5h // Change hours of the day to suit your company, i.e this would find activations between 6pm and 6am | where dayofweek(LocalTime) in (Saturday, Sunday) or hourofday(LocalTime) !between (6 .. 18) | where OperationName == "Add service principal" //Exclude service principals created by managed identities (if you have automation tasks running this may trigger), but you can remove the exclusion if required | where parse_json(tostring(InitiatedBy.app)).displayName != "Managed Service Identity" | extend Actor = tostring(parse_json(tostring(InitiatedBy.user)).userPrincipalName) | extend AppId = tostring(AdditionalDetails[1].value) | extend ['Actor IP Address'] = tostring(parse_json(tostring(InitiatedBy.user)).ipAddress) | project LocalTime, Actor, ['Actor IP Address'], AppId
This query is used to detect when a service principal is added to Azure AD outside of working hours or on weekends. It requires the Azure Active Directory - Audit Logs data connector. The query filters the audit logs for the past 7 days and converts the timestamp to the local time zone. It then checks if the activity occurred on a Saturday, Sunday, or outside of the specified working hours. It further filters for the specific operation of adding a service principal and excludes service principals created by managed identities. The query extracts the actor's user principal name, IP address, and the application ID associated with the service principal. The results are then projected to include the local time, actor information, and application ID.

Matt Zorich
Released: June 17, 2022
Tables
Keywords
Operators