Skip to content

Instantly share code, notes, and snippets.

@alexmags
alexmags / localadmins.kql
Last active February 26, 2022 08:06
Logins with local administrator access report - Defender for Endpoint
DeviceLogonEvents
| where Timestamp >= ago(30d) // last month
| where IsLocalAdmin == 1
// number of machines connected to by the account
| summarize count() by DeviceName, AccountName,LogonType // ,AdditionalFields
| sort by AccountName
// also see https://www.verboon.info/2020/09/hunting-for-local-group-membership-changes/
// https://blog.alexmags.com/tags/kql/
@alexmags
alexmags / BitlockerStatus.kql
Last active January 11, 2023 16:51
KQL Bitlocker status Defender for Endpoint
// inspired by SecGuru_OTX https://twitter.com/SecGuru_OTX/status/1402580761828593672
let TVMConfigAssessKB = DeviceTvmSecureConfigurationAssessmentKB
| where ConfigurationSubcategory == 'Bitlocker';
let timeframe = 7d;
DeviceLogonEvents
| where Timestamp >= ago(timeframe)
| where ActionType == 'LogonSuccess'
| summarize TimeGenerated = any(*) by DeviceName, DeviceId
| join (
DeviceTvmSecureConfigurationAssessment
// KQL because SharePoint Admin centre can make surprise new Conditional Access policies when you configure tenant level settings.
// Look for SharePoint ID and brackets in display name
// Create a notification action on AAD audit logs when this happens. https://blog.alexmags.com/tags/kql/
AuditLogs
| where Category == "Policy" and (Identity == 'Office 365 SharePoint Online' or TargetResources[0].displayName contains '[')
| project TimeGenerated, OperationName, TargetResources[0].displayName,Identity,InitiatedBy.user.userPrincipalName
@alexmags
alexmags / AAD Guest last login kql
Last active February 26, 2022 08:10
Report in AAD sign in logs the last time an Azure AD guest account was used
// https://blog.alexmags.com/tags/kql/
let last_sign_in_by_account =
SigninLogs
| where TimeGenerated > now(-90d)
| where ResultType == 0
// filtering out local accounts to identify guest accounts. I couldn't identify account type in log data. Maybe TimeGenerated.HomeTenantId??
| where UserPrincipalName !endswith "companyname.com" and UserPrincipalName !endswith "AlsoCompanyname.com" and UserPrincipalName !endswith "tenantname.onmicrosoft.com" and UserPrincipalName !endswith "YetAnotherVerifiedDomain.com" and UserPrincipalName !endswith "SeriouslyICouldntIdentifyAccountTypeInLogData.com"
// get last login per account
| summarize argmax(TimeGenerated, *) by UserPrincipalName;
last_sign_in_by_account
@alexmags
alexmags / set-AADRoleMembersByADSecurityGroup.ps1
Last active February 26, 2022 08:11
PowerShell to map AD security group members to Azure AD roles.
# Make code debuggable
$ErrorActionPreference = "Stop"
Set-StrictMode -Version latest
# Enable use of proxy using current credentials
$browser = New-Object System.Net.WebClient
$browser.Proxy.Credentials =[System.Net.CredentialCache]::DefaultNetworkCredentials
# Download PowerShell module if not already installed
function get-moduleIfNotInstalled ($modulename) {
@alexmags
alexmags / set-GitUserProxySettings.ps1
Last active February 26, 2021 08:30
Configure Git client to use corporate proxy and authenticate as current user
# This takes a guess at what Git config should be for proxy. Effectivly we're doing netstat.exe | find "8080"
# Lookup current user via Active Directory
[reflection.assembly]::LoadWithPartialName("System.DirectoryServices.AccountManagement") | out-null
$currentUser=[System.DirectoryServices.AccountManagement.UserPrincipal]::Current
#region Test if behind a proxy. This also generates some traffic that we'll use to determine proxy URL
try {
Write-output "Testing internet access"
$status = (Invoke-WebRequest -Uri "https://www.powershellgallery.com/api/v2" -UseBasicParsing).StatusDescription
@alexmags
alexmags / Set-GitUserConfigLocation.ps1
Created February 26, 2021 08:17
Git client puts it's config in %homedrive%%homepath%. This is usual for Windows apps and breaks when homedrive disconnected. Use %appdata%\git
# %homedrive%%homepath% is weird and breaks when homedrive disconnected. Use %appdata%
# https://git-scm.com/docs/git-config#git-config-XDGCONFIGHOMEgitconfig
$ConfigDefaultLocation="$($env:homedrive)$($env:homedrive)\.gitconfig" # breaks when network drive isn't connected
$ConfigBetterLocation="$($env:appdata)\git\config" # Standard location for app data that you want to follow user
[System.Environment]::SetEnvironmentVariable('XDG_CONFIG_HOME', "$($env:appdata)",[System.EnvironmentVariableTarget]::user)
$env:XDG_CONFIG_HOME=[System.Environment]::GetEnvironmentVariable("XDG_CONFIG_HOME","User")
# make better git data folder if not exists
New-Item -ItemType directory -Path "$($env:XDG_CONFIG_HOME)\git" -ErrorAction SilentlyContinue | out-null
@alexmags
alexmags / Set-GitUserDetails.ps1
Created February 26, 2021 08:14
Auto configure Git user name and email based on Active Directory lookup
# Auto configure Git user name and email based on Active Directory lookup
[reflection.assembly]::LoadWithPartialName("System.DirectoryServices.AccountManagement") | out-null
$currentUser=[System.DirectoryServices.AccountManagement.UserPrincipal]::Current
& git.exe config --global user.name "$($currentUser.DisplayName)"
& git.exe config --global user.email $($currentUser.EmailAddress)