Skip to content

Instantly share code, notes, and snippets.

@alexmags
alexmags / new-LDAPcert.ps1
Created March 23, 2024 11:15
PowerShell self-signed cert for LDAPs
# In a lab, or a AD domain with non-routable top level domain (.corp, .local etc...)
# Creating one self-signed cert usable across multiple domain controllers for encrypted LDAP
Import-Module ActiveDirectory
$addomain=get-addomain
$expirydate = (Get-Date).AddYears(1)
# Get all (currently existing) domain controllers to be subject alternative names (avoid cloud kerberos trust object)
$ArraySubjectAlternativeNames=(Get-ADComputer -SearchBase $addomain.DomainControllersContainer -filter * | where {$_.name -ne 'AzureADKerberos'}).dnshostname
$ArraySubjectAlternativeNames+="ldap.$($addomain.DNSRoot)" # useful as movable DNS alias or for network load balancer
@alexmags
alexmags / intranetSitesUsedWithIE.KQL
Last active June 7, 2022 06:03
KQL to report on sites used with Internet Explorer. Use with Defender for Endpoint Advanced Hunting https://blog.alexmags.com/posts/internet-explorer-eol-kql/
DeviceNetworkEvents
| where Timestamp > ago(7d)
| where InitiatingProcessFileName =~ 'iexplore.exe'
and RemoteUrl contains ".intranet domain here"
and RemoteUrl !contains "proxy url here"
//and RemoteUrl !contains "other thing to filter out"
// chop off http:// or https://
| extend URLwithoutProtocol=replace_string(replace_string(RemoteUrl, 'http://', ''), 'https://', '')
| extend splitURL=split(URLwithoutProtocol,'/')
| extend domain=tostring(splitURL[0])
@alexmags
alexmags / CISA_NEV_vs_DfE.kql
Last active March 7, 2022 09:50
🛡Shields up! Compare CISA Known Exploited Vulnerabilities Catalog to Microsoft Defender for Endpoint data. Use this KQL in DfE Advanced Hunting. https://docs.microsoft.com/en-us/microsoft-365/security/defender-endpoint/advanced-hunting-overview
// make a table from https://www.cisa.gov/known-exploited-vulnerabilities-catalog
let CISA_NEV = (externaldata(CveId:string,vendorProject:string,product:string,vulnerabilityName:string,dateAdded:string,shortDescription:string,requiredAction:string,dueDate:datetime)
[@"https://www.cisa.gov/sites/default/files/csv/known_exploited_vulnerabilities.csv"]
with (format="csv",ignoreFirstRecord=true));
let CISA_NEV_CveIDs= CISA_NEV | project CveId; // make a list from CVEs column
DeviceTvmSoftwareVulnerabilities
| where CveId in (CISA_NEV_CveIDs) // compare DfE devices with CVEs to CISA NEV CVEs list
| join kind = inner CISA_NEV on CveId // Join table of CVEs on devices to CISA NEV table
// format results however you like. Below shows count of devices with each CISA NEV CVE, in due date order
| summarize count() by CveId,vendorProject,product,vulnerabilityName,MicrosoftRating=VulnerabilitySeverityLevel,MicrosoftRecommendedUpdate=RecommendedSecurityUpdate, dateAdded,shortDescription,requiredAction,dueDate
@alexmags
alexmags / invoke-musak.ps1
Created February 26, 2022 09:21
Muzak for long running PowerShell scripts. Pointless
$scriptDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent # files relative to here
$musakFilePath="$scriptDir\musak.mp3" # https://www.youtube.com/watch?v=FsoIfkNQYEg
$wmplayer = New-Object System.Windows.Media.MediaPlayer
$wmplayer.Open($musakFilePath)
Start-Sleep 2 # This allows the $wmplayer time to load the audio file
$duration = $wmplayer.NaturalDuration.TimeSpan.TotalSeconds
$wmplayer.Play()
$stopwatch=[system.diagnostics.stopwatch]::StartNew()
while ($stopwatch.Elapsed.Seconds -lt $duration)
{
@alexmags
alexmags / invoke-mailboxAuditLogToCSV.ps1
Last active February 26, 2022 09:06
PowerShell to export mailbox audit logs using search-mailboxAuditLog. https://blog.alexmags.com/posts/exchange-online-email-investigation/
$StartDate='02/22/2022'
$EndDate='02/24/2022' #start of day
$MailboxOwner=someone@Companyname.com'
$mailboxAuditlogs=search-mailboxAuditLog $ MailboxOwner -StartDate $StartDate -EndDate $EndDate -LogonTypes Owner, Admin, Delegate -ShowDetails -resultsize 50000
if ($mailboxAuditlogs.count -eq 50000) {write-warning 'Results limited to 50000'}
# backtick used to split this over multiple lines. Pulling InternetMessageIds out of AggregatedRecordFoldersData JSON object
$resultTable=$mailboxAuditlogs | select MailboxOwnerUPN,LogonType,LogonUserDisplayName,Operation,ItemSubject,`
@{label='InternetMessageIds'; expression={($_.AggregatedRecordFoldersData | ConvertFrom-Json).folderitems.InternetMessageId -join ' '}},`
@alexmags
alexmags / EmailAttachmentInfo.kql
Last active February 26, 2022 09:06
KQL to track where an email attachment went. Sensitivity of file isn't recorded here unfortunately. https://blog.alexmags.com/posts/exchange-online-email-investigation/
EmailAttachmentInfo
| where SHA256 == '<File hash here>' // or you can filter by filename
| order by Timestamp asc
//| project Timestamp, SenderFromAddress, RecipientEmailAddress, FileName, FileSize, FileType, NetworkMessageId, ReportId
@alexmags
alexmags / MailItemsAccessed.kql
Last active February 26, 2022 09:07
KQL to find interactions with an email message. Note: some interactions will be Microsoft background processing, your CRM software or your backup software. https://blog.alexmags.com/posts/exchange-online-email-investigation/
CloudAppEvents
| where Timestamp > ago(3d)
| where ActionType =~ "MailItemsAccessed"
| where Application has "Exchange"
| evaluate bag_unpack(RawEventData,'Event_') // JSON in RawEventData becomes columns prefixed by Event_
// filter on Event_ mailbox owner upn if only one mailbox is of interest
| where Event_Folders has 'Internet message ID here' // get message ID from eDiscovery
// https://blog.alexmags.com/tags/kql/
@alexmags
alexmags / DeviceFileEvents.kql
Last active February 26, 2022 09:07
KQL to see who interacted with a file. Defender for Endpoint Advanced hunting. https://blog.alexmags.com/posts/exchange-online-email-investigation/
DeviceFileEvents
//| where SHA256 == 'file hash here'
| where FileName startswith "KFC secret recipe"
| order by Timestamp asc
@alexmags
alexmags / FileUploadedToCloud.KQL
Last active December 20, 2022 20:37
Defender For Endpoint KQL to report on files uploaded to cloud from Edge & Chrome by Sensitivity label. https://blog.alexmags.com/posts/kql-for-file-uploaded-to-cloud/
// https://blog.alexmags.com/tags/kql/
// lookup table for AIP label GUIDs
let AIPLabels=datatable(SensitivityGUID:string,Classification:string,SubClassification:string)
[
// AIP O365 sensitivity label GUID, parent label name, sub label name
"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "Public", "Public",
"ffffffff-gggg-hhhh-iiii-jjjjjjjjjjjj", "Internal", "Internal",
"kkkkkkkk-llll-mmmm-nnnn-oooooooooooo", "Secret", "Secret",
"pppppppp-qqqq-rrrr-ssss-tttttttttttt", "Super secret", "Super secret"
];
@alexmags
alexmags / get-ADPublishedPrintQueues.ps1
Last active October 22, 2023 23:50
PowerShell to find print servers from AD
import-module ActiveDirectory # From Remote Server Admin Tools (RSAT) Windows Desktop/server OS feature
# get print queues published in Active Directory
$printqueues=Get-AdObject -filter "objectCategory -eq 'printqueue'" -Properties *
# list the print queue server names and filter out duplicates where one server has multiple print queues
$PrintServers=$printqueues | select servername | Sort-Object -property servername -Unique
# Export to CSV file reports (calculated property printshares as semicolon delimited list) https://ss64.com/ps/select-object.html
$PrintServers | Export-Csv -NoTypeInformation -Encoding UTF8 -path $env:temp\printservers.csv