Understanding and Managing Mark of the Web in .NET

 
 
  • Gérald Barré

#What is Mark of the Web?

Mark of the Web (MOTW) is a Windows security feature that protects users from potentially unsafe files downloaded from the internet. When you download a file, Windows automatically adds a special metadata tag indicating the file originated from an untrusted source and may contain harmful content.

Windows components such as Microsoft Edge and Windows Explorer use MOTW to determine how to handle files. When you try to open a file with MOTW, Windows displays a warning message or prompts you to confirm before opening it.

#Why Check MOTW in Your Application?

Checking MOTW before processing files can help protect your application from security vulnerabilities. By verifying a file's origin, you can prevent executing malicious code or opening files that could compromise the user's system.

#How MOTW Works Internally

MOTW is implemented as an alternate data stream (ADS) attached to the file. The ADS contains information about the file's origin, including the URL it was downloaded from and its security zone (Internet, Local Intranet, Trusted Sites, etc.).

You can inspect the Zone.Identifier ADS to check the MOTW. Here's what the content looks like:

INI
[ZoneTransfer]
ZoneId=3
ReferrerUrl=https://example.com/

The ZoneId field indicates the security zone of the file according to the URLZONE enumeration:

  • 0 - Local Machine
  • 1 - Intranet
  • 2 - Trusted Sites
  • 3 - Internet
  • 4 - Untrusted

While you could read the ADS directly, it's better to use the IInternetSecurityManager interface to reliably retrieve the zone of a URL or file.

#Working with MOTW in .NET

To add, read, or remove MOTW from files in your .NET applications, you can use the Meziantou.Framework.Win32.MarkOfTheWeb library.

First, install the package:

Shell
dotnet add package Meziantou.Framework.Win32.MarkOfTheWeb

Then use the following methods to manage MOTW:

C#
using Meziantou.Framework.Win32;

var path = @"C:\path\to\your\file.txt";

// Set the Mark of the Web to indicate the file came from the internet
MarkOfTheWeb.SetFileZone(path, UrlZone.Internet);

// Get the zone of the file
var zone = MarkOfTheWeb.GetFileZone(path);

// Get the content of the Mark of the Web ADS
var adsContent = MarkOfTheWeb.GetFileZoneContent(path);

// Remove the Mark of the Web
MarkOfTheWeb.RemoveFileZone(path);

// Check if the file is marked as coming from the internet or untrusted
bool isUntrusted = MarkOfTheWeb.IsUntrusted(path);

#Additional resources

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?