Wednesday, November 18, 2026

Is This Office File RMS-Protected? Find Out with One PowerShell Script

Is This Office File RMS-Protected? Find Out with One PowerShell Script

When a user says "I can't open this PowerPoint" or "Copilot can't read this file", the first question is simple: is the file encrypted with a sensitivity label (RMS), or is it just a normal Office file?

You can answer that in seconds, without opening the file in Office, by reading its first four bytes.


How It Works

Modern Office files (.docx, .xlsx, .pptx) are ZIP packages. When a sensitivity label applies encryption, Office wraps the content inside an OLE Compound File instead. Each format has its own signature in the first bytes of the file:

First 4 bytes (hex)MeaningWhat the script does
50 4B 03 04 (PK..)Normal ZIP / Open XML package. Not encrypted.Reads label metadata and lists external links
D0 CF 11 E0OLE Compound File. For a .docx/.xlsx/.pptx this means encrypted (RMS / sensitivity label, or password protected)Pulls RMS / sign-in URLs out of the protection info
Anything elseNot a valid Office file or the file is damagedPrints the signature

Note: Older binary formats (.doc, .xls, .ppt) also start with D0 CF 11 E0, because that is their normal format. Only treat this signature as "encrypted" for the Open XML extensions.

Where label metadata is stored

For unencrypted files, the sensitivity label is still recorded in the package. Microsoft documents two places:

LocationFormatUsed by
docProps/custom.xmlCustom properties named MSIP_Label_<GUID>_<Attribute> (for example _Enabled, _Name, _SiteId, _Method)The older storage model
docMetadata/LabelInfo.xml<clbl:labelList> with <clbl:label id=... enabled=... siteId=...> elementsNewer storage, used when co-authoring for encrypted files is turned on in the tenant

Microsoft's MIP SDK FAQ says that once the new storage location is turned on, label metadata moves to LabelInfo.xml the first time the document is saved. So a script that only checks custom.xml can report "no label" on a file that does have one. The script below checks both.


The Script

Set $file to your file path and run it. The script has no param() block, so you can also run it line by line in the console or in VS Code.

# ==============================================================================
# Inspect-OfficeFileProtection.ps1
# Checks whether an Office Open XML file (.docx / .xlsx / .pptx) is encrypted
# with RMS / sensitivity label protection.
#   - Not encrypted : shows sensitivity label metadata and external links
#   - Encrypted     : shows RMS / sign-in URLs from the protection info
# ==============================================================================

# ---- Settings ----------------------------------------------------------------
# Path to the file to check
$file = "C:\Temp\Sample.pptx"

# Keywords used to filter URLs found in an encrypted file.
# Add your own tenant or RMS hostnames here if you want to match them too.
$urlFilter = "aadrm|azurerms|rms|login|microsoftonline"

# ---- Basic checks ------------------------------------------------------------
if (-not (Test-Path -LiteralPath $file)) {
    Write-Host "File not found: $file" -ForegroundColor Red
    return
}

# Read the whole file as bytes.
# Files that are open in Office may be locked; close them first if this fails.
$bytes = [System.IO.File]::ReadAllBytes($file)

# Turn the first 4 bytes into a hex string, e.g. "504B0304"
$sig = ($bytes[0..3] | ForEach-Object { $_.ToString("X2") }) -join ""
Write-Host "File      : $file"
Write-Host "Signature : $sig"

# ==============================================================================
# CASE 1: "PK.." = normal ZIP package = NOT encrypted
# ==============================================================================
if ($sig -eq "504B0304") {
    Write-Host "`nNot encrypted (normal ZIP package). Checking labels and external links..." -ForegroundColor Green

    # Load the .NET ZIP classes and open the file read-only
    Add-Type -AssemblyName System.IO.Compression.FileSystem
    $zip = [System.IO.Compression.ZipFile]::OpenRead($file)

    try {
        # Small helper: read a ZIP entry as text and close the stream afterwards
        function Read-ZipEntryText($entry) {
            $reader = New-Object System.IO.StreamReader($entry.Open())
            try {
                return $reader.ReadToEnd()
            } finally {
                $reader.Dispose()
            }
        }

        # ---- 1a. Label metadata in docProps/custom.xml (older storage) -------
        Write-Host "`n[custom.xml] MSIP_Label_* custom properties" -ForegroundColor Cyan
        $custom = $zip.Entries | Where-Object { $_.FullName -eq "docProps/custom.xml" }

        if ($custom) {
            $xml = Read-ZipEntryText $custom

            # Each label property looks like:
            #   <property ... name="MSIP_Label_<GUID>_Name"><vt:lpwstr>General</vt:lpwstr></property>
            $labelProps = [regex]::Matches($xml, 'name="(MSIP_Label_[^"]+)"[^>]*>\s*<vt:lpwstr>([^<]*)')

            if ($labelProps.Count -gt 0) {
                $labelProps | ForEach-Object {
                    "  {0} = {1}" -f $_.Groups[1].Value, $_.Groups[2].Value
                }
            } else {
                Write-Host "  custom.xml exists but has no MSIP_Label_* properties."
            }
        } else {
            Write-Host "  No docProps/custom.xml in this file."
        }

        # ---- 1b. Label metadata in docMetadata/LabelInfo.xml (newer storage) --
        Write-Host "`n[LabelInfo.xml] Sensitivity label information part" -ForegroundColor Cyan
        $labelInfo = $zip.Entries | Where-Object { $_.FullName -eq "docMetadata/LabelInfo.xml" }

        if ($labelInfo) {
            $labelXml = Read-ZipEntryText $labelInfo

            # Each label looks like:
            #   <clbl:label id="{GUID}" enabled="1" method="Standard" siteId="{GUID}" removed="0" />
            $labels = [regex]::Matches($labelXml, '<clbl:label\s+([^>]*?)/?>')

            if ($labels.Count -gt 0) {
                foreach ($label in $labels) {
                    # Turn the attributes into "name=value" pairs
                    $attrs = [regex]::Matches($label.Groups[1].Value, '(\w+)="([^"]*)"') |
                        ForEach-Object { "{0}={1}" -f $_.Groups[1].Value, $_.Groups[2].Value }
                    Write-Host ("  Label: " + ($attrs -join "; "))
                }
            } else {
                Write-Host "  LabelInfo.xml exists but has no label entries."
            }
        } else {
            Write-Host "  No docMetadata/LabelInfo.xml in this file."
        }

        # ---- 1c. External links in any .rels file -----------------------------
        # Relationship files (.rels) list links to images, templates, linked data,
        # etc. TargetMode="External" means the file points to something outside
        # itself (a URL or a network path).
        Write-Host "`n[.rels] External links" -ForegroundColor Cyan
        $foundLinks = 0

        foreach ($relEntry in ($zip.Entries | Where-Object { $_.FullName -like "*.rels" })) {
            # Save the entry name in a variable. Inside the inner ForEach-Object,
            # $_ is the regex match, not the ZIP entry.
            $relName = $relEntry.FullName
            $rels    = Read-ZipEntryText $relEntry

            # Match each <Relationship ... /> element, then check its attributes.
            # This works whatever order Target and TargetMode appear in.
            [regex]::Matches($rels, '<Relationship\s[^>]*>') | ForEach-Object {
                $rel = $_.Value
                if ($rel -match 'TargetMode="External"' -and $rel -match 'Target="([^"]+)"') {
                    "  EXTERNAL LINK in {0}: {1}" -f $relName, $Matches[1]
                    $foundLinks++
                }
            }
        }

        if ($foundLinks -eq 0) {
            Write-Host "  No external links found."
        }
    } finally {
        # Always release the file handle, even if something above fails
        $zip.Dispose()
    }

# ==============================================================================
# CASE 2: D0CF11E0 = OLE Compound File = ENCRYPTED Open XML file
# ==============================================================================
} elseif ($sig -eq "D0CF11E0") {
    Write-Host "`nFile is ENCRYPTED (RMS / sensitivity label protection, or password protected)." -ForegroundColor Yellow

    # The RMS publishing license inside the file is stored as UTF-16 text,
    # so decode the bytes as Unicode and search for URLs.
    # This is a quick heuristic, not a full parser of the compound file.
    $text = [System.Text.Encoding]::Unicode.GetString($bytes)

    $urls = [regex]::Matches($text, 'https?://[A-Za-z0-9\.\-/_:]+') |
        ForEach-Object { $_.Value } |
        Sort-Object -Unique |
        Where-Object { $_ -match $urlFilter }

    if ($urls) {
        Write-Host "`nRMS / sign-in URLs found in the protection info:" -ForegroundColor Cyan
        $urls | ForEach-Object { "  $_" }
    } else {
        # No RMS URLs usually means a plain password, not a sensitivity label
        Write-Host "`nNo RMS URLs found. The file may be password protected instead of label protected."
    }

# ==============================================================================
# CASE 3: Anything else
# ==============================================================================
} else {
    Write-Host "`nUnknown file signature: $sig (not a valid Office file, or the file is damaged)" -ForegroundColor Red
}

Example Output

Unencrypted file with a label:

File      : C:\Temp\Sample.pptx
Signature : 504B0304

Not encrypted (normal ZIP package). Checking labels and external links...

[custom.xml] MSIP_Label_* custom properties
  No docProps/custom.xml in this file.

[LabelInfo.xml] Sensitivity label information part
  Label: id={00000000-0000-0000-0000-000000000000}; enabled=1; method=Standard; siteId={11111111-1111-1111-1111-111111111111}; removed=0

[.rels] External links
  No external links found.

Encrypted file:

File      : C:\Temp\Sample.pptx
Signature : D0CF11E0

File is ENCRYPTED (RMS / sensitivity label protection, or password protected).

RMS / sign-in URLs found in the protection info:
  https://<tenant-id>.rms.<region>.aadrm.com/_wmcs/licensing

Reading the Results

ResultWhat it usually meansNext step
Not encrypted, no label metadataUnlabeled fileNothing to fix for protection
Not encrypted, label shows enabled=1 / _Enabled = trueA label without encryption (for example General or Internal)Content is readable by any app or service that can open the file
Encrypted, RMS URLs foundA sensitivity label that applies encryptionThe reader needs usage rights from the label. Check the label's encryption settings in the Microsoft Purview portal
Encrypted, no RMS URLsA password set in Office (File > Info > Protect)The owner must remove the password
External links foundThe file points to outside content (linked data, remote templates, web images)Check that the targets are expected and reachable

Tips

  • Close the file in Office first. ReadAllBytes can fail if Office is holding a lock on the file.
  • Run it on many files. Wrap the script in Get-ChildItem -Path "C:\Temp" -Include *.docx,*.xlsx,*.pptx -Recurse | ForEach-Object { $file = $_.FullName; ... } to scan a whole folder.
  • The encrypted-file check is a heuristic. It pulls URLs out of the raw bytes. To see the actual label name and rights on an encrypted file, use Get-FileStatus from the Purview Information Protection PowerShell module.

References

No comments:

Post a Comment

Featured Post

Is This Office File RMS-Protected? Find Out with One PowerShell Script

Is This Office File RMS-Protected? Find Out with One PowerShell Script When a user says "I can't open this PowerPoint" or ...

Popular posts