0

There have been some suspect manipulations in our media library (for example, detaching and reattaching of images), such that we now have images in our library which are linked to the wrong template. So far, we have found instances of PNG images using the JPEG template.

For most browsers, this doesn't cause a problem. But we are using the X-Content-Type-Options: nosniff HTTP header and have found that one old browser that we still need to support (namely, MSIE) will then refuse to display the image since it is sent with a JPEG content-type.

Does anyone know of a way (ideally a Sitecore PowerShell script) of detecting these cases of "wrong extensions" across the entire media library? We're mostly interested in JPEG <--> PNG cases.

6

Here is an example using Sitecore PowerShell Extensions to compare the first bit with a list of known values.

$png = "89"
$gif = "47"
$bmp = "42"
$jpg = "FF"

$image = Get-Item -Path "master:" -ID "{88962785-4EE1-47F8-9CD1-028CAC9794AD}"
$media = [Sitecore.Resources.Media.MediaManager]::GetMedia([Sitecore.Data.Items.MediaItem]$image)
New-UsingBlock ($mediaStream = $media.GetStream()) {
    $bit = $mediaStream.Stream.ReadByte().ToString("X2")
    switch ($bit) {
        $png { 
            if($media.Extension -ne "png") {
                Write-Host "Mismatch for $($image.ID)"   
            }
        }
        $jpg { 
            if($media.Extension -ne "jpg") {
                Write-Host "Mismatch for $($image.ID)"   
            }
        }
        $gif { 
            if($media.Extension -ne "gif") {
                Write-Host "Mismatch for $($image.ID)"   
            }
        }
        $bmp { 
            if($media.Extension -ne "bmp") {
                Write-Host "Mismatch for $($image.ID)"   
            }
        }
        default { Write-Host "Unknown" }
    }
}

References

I used the following gist to help me figure out which headers to use when reading from the media stream. There are likely more that need to be added possibly due to compression.

  • 1
    Great use of magic numbers. Here is the link if someone wants to refer a full list. – Surya Oct 11 at 15:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.