Decoding Safe URLs

I'm going to show you how to quickly get the bits you care about from URL strings.

The case study for today are the URLs you might see in Outlook that don't match the original one sent, but instead get rewritten to go through a layer of protection.

Safe Links

This URL rewriting is a side-effect of the Safe Links in Microsoft Defender for Office 365.

Safe Links scans incoming email for known malicious hyperlinks. Scanned URLs are rewritten using the Microsoft standard URL prefix: https://nam01.safelinks.protection.outlook.com. After the link is rewritten, it's analyzed for potentially malicious content.

The problem is, if you simply right-click to copy a link, you'll get the long, protected URL, which is rarely what you intended. If you click to try and grab the URL, well, you're never sure whether you landed at that specific URL, or whether you got redirected a number of times - there are always some redirects, given the design of the feature.

Decoding URLs with PowerShell

Thankfully, the target URL is encoded in the safe link, and you can easily get at it with a bit of PowerShell. We're after the url query parameter.

Add-Type -AssemblyName System.Web
$l = "https://nam06.safelinks.protection.outlook.com/?url=https%3A%2F%2foobar..."
$u = New-Object -TypeName System.Uri -ArgumentList $l
$qs = [System.Web.HttpUtility]::ParseQueryString($u.Query)
$qs["url"]

The Uri type gives you access to the various parts of the URL, but it doesn't do the work to parse each of the values in the query string. For that, we need some other types to help us out.

I'm using Add-Type to make sure that the System.Web.HttpUtility type can be accessed. It's a very interesting commandlet that I'll probably talk more about at some point.

Happy decoding!

Tags:  powershell

Home