Disabling the Scripting.FileSystemObject ComObject (When you get the 0x8002801c error)


While working with a customer to automate the hardening process (STIG: Security Technical Implementation Guide) for IIS servers, we ran into a problem (error 0x8002801c) when we tried to run the following command in order to disable (unregister) the Scripting.FileSystemObject ComObject

C:\Windows\System32\regsvr32.exe /u scrrun.dll

The 0x8002801c error translates to TYPE_E_REGISTRYACCESS. Using Sysinternal’s Process Monitor (aka procmon), we found that it was failing because of missing permissions to the following registry keys:

HKEY_CLASSES_ROOT\TypeLib\{420B2830-E718-11CF-893D-00A0C9054228}\1.0\0\win32
HKEY_CLASSES_ROOT\Scripting.FileSystemObject\CLSID

Note that adding permissions to the first key only (as suggested in Finding V-13700 @ stigviewer.com) is not enough. The command would run without errors, the validation would pass (thinking that FSO is disabled) but you could still create and use FSO objects.

So for automating the whole process, we needed to take ownership on the registry keys, add permissions to the keys, and then run the command to unregister the DLL.

This results in the following code:

#region Helper functions
function Set-Ownership {
[CmdletBinding(SupportsShouldProcess = $false)]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$Path,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()] [ValidatePattern('(\w+)\\(\w+)')]
[string]$Identity,
[Parameter(Mandatory = $false)]
[switch]$AddFullControl,
[Parameter(Mandatory = $false)]
[switch]$Recurse
)
begin {
$tokenManipulate = @'
using System;
using System.Runtime.InteropServices;
public class TokenManipulate {
[DllImport("kernel32.dll", ExactSpelling = true)]
internal static extern IntPtr GetCurrentProcess();
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);
[DllImport("advapi32.dll", SetLastError = true)]
internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct TokPriv1Luid {
public int Count;
public long Luid;
public int Attr;
}
internal const int SE_PRIVILEGE_DISABLED = 0x00000000;
internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
internal const int TOKEN_QUERY = 0x00000008;
internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
public static bool AddPrivilege(string privilege) {
bool retVal;
TokPriv1Luid tp;
IntPtr hproc = GetCurrentProcess();
IntPtr htok = IntPtr.Zero;
retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
tp.Count = 1;
tp.Luid = 0;
tp.Attr = SE_PRIVILEGE_ENABLED;
retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
return retVal;
}
public static bool RemovePrivilege(string privilege) {
bool retVal;
TokPriv1Luid tp;
IntPtr hproc = GetCurrentProcess();
IntPtr htok = IntPtr.Zero;
retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
tp.Count = 1;
tp.Luid = 0;
tp.Attr = SE_PRIVILEGE_DISABLED;
retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
return retVal;
}
}
'@
}
Process {
Add-Type -TypeDefinition $TokenManipulate
[void][TokenManipulate]::AddPrivilege('SeTakeOwnershipPrivilege')
[void][TokenManipulate]::AddPrivilege('SeRestorePrivilege')
$item = Get-Item -Path $Path -ErrorAction SilentlyContinue
if(-not $item) {
Write-Warning ("'{0}' not found" -f $Path)
return
}
$owner = New-Object System.Security.Principal.NTAccount -ArgumentList ($Identity -split '\\')
if ($item.PSIsContainer) {
switch ($item.PSProvider.Name) {
'FileSystem' {
$acl = New-Object -TypeName System.Security.AccessControl.DirectorySecurity
}
'Registry' {
$acl = New-Object -TypeName System.Security.AccessControl.RegistrySecurity
switch (($item.Name -split '\\')[0]) {
'HKEY_CLASSES_ROOT' { $rootKey = [Microsoft.Win32.Registry]::ClassesRoot; break }
'HKEY_LOCAL_MACHINE' { $rootKey = [Microsoft.Win32.Registry]::LocalMachine; break }
'HKEY_CURRENT_USER' { $rootKey = [Microsoft.Win32.Registry]::CurrentUser; break }
'HKEY_USERS' { $rootKey = [Microsoft.Win32.Registry]::Users; break }
'HKEY_CURRENT_CONFIG' { $rootKey = [Microsoft.Win32.Registry]::CurrentConfig; break }
}
$key = $item.Name -replace "$rootKey\\"
$item = $rootKey.OpenSubKey($Key, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,
[System.Security.AccessControl.RegistryRights]::TakeOwnership)
}
}
Write-Verbose "Setting ownership for $($owner.Value) on $Path"
$acl.SetOwner($owner)
$item.SetAccessControl($acl)
if($AddFullControl) {
$ace = New-Object -TypeName System.Security.AccessControl.RegistryAccessRule -ArgumentList @(
$owner, [System.Security.AccessControl.RegistryRights]::FullControl,
[System.Security.AccessControl.InheritanceFlags]::None,
[System.Security.AccessControl.PropagationFlags]::None,
[System.Security.AccessControl.AccessControlType]::Allow
)
Write-Verbose "Setting FullControl permissions for $($owner.Value) on $Path"
$acl.AddAccessRule($ace)
$item.SetAccessControl($acl)
}
if ($item.PSProvider.Name -eq 'Registry') { $item.Close() }
if ($Recurse.IsPresent) {
if ($item.PSProvider.Name -eq 'Registry') {
$items = @(Get-ChildItem -Path $Path -Recurse -Force | Where-Object { $_.PSIsContainer })
}
else {
$items = @(Get-ChildItem -Path $Path -Recurse -Force)
}
for ($i = 0; $i -lt $items.Count; $i++) {
switch ($item.PSProvider.Name) {
'FileSystem' {
$item = Get-Item $items[$i].FullName
if ($item.PSIsContainer) { $acl = New-Object -TypeName System.Security.AccessControl.DirectorySecurity }
else { $acl = New-Object -TypeName System.Security.AccessControl.FileSecurity }
}
'Registry' {
$item = Get-Item $items[$i].PSPath
$acl = New-Object -TypeName System.Security.AccessControl.RegistrySecurity
switch ($item.Name.Split('\')[0]) {
'HKEY_CLASSES_ROOT' { $rootKey = [Microsoft.Win32.Registry]::ClassesRoot; break }
'HKEY_LOCAL_MACHINE' { $rootKey = [Microsoft.Win32.Registry]::LocalMachine; break }
'HKEY_CURRENT_USER' { $rootKey = [Microsoft.Win32.Registry]::CurrentUser; break }
'HKEY_USERS' { $rootKey = [Microsoft.Win32.Registry]::Users; break }
'HKEY_CURRENT_CONFIG' { $rootKey = [Microsoft.Win32.Registry]::CurrentConfig; break }
}
$Key = $item.Name.Replace(($item.Name.Split('\')[0] + '\'), '')
$item = $rootKey.OpenSubKey($Key, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,
[System.Security.AccessControl.RegistryRights]::TakeOwnership)
}
}
$acl.SetOwner($owner)
Write-Verbose "Setting ownership for $($owner.Value) on $($item.Name)"
$item.SetAccessControl($acl)
if ($item.PSProvider.Name -eq 'Registry') { $item.Close() }
}
}
}
else {
if ($Recurse.IsPresent) { Write-Warning 'Object specified is neither a folder nor a registry key. Recursion is not possible.' }
switch ($item.PSProvider.Name) {
'FileSystem' { $acl = New-Object -TypeName System.Security.AccessControl.FileSecurity }
'Registry' { Write-Error 'You cannot set ownership on a registry value' }
default { Write-Error "Unknown provider: $($item.PSProvider.Name)" }
}
$acl.SetOwner($owner)
Write-Verbose "Setting ownership for $($owner.Value) on $Path"
$item.SetAccessControl($acl)
}
}
}
#endregion
#region Test FileSystemObject ComObject (Should work)
(New-Object -ComObject Scripting.FileSystemObject).Drives
#endregion
#region Set ownership and add permissions to the relevant registry keys
$regPaths = @(
'Registry::HKEY_CLASSES_ROOT\TypeLib\{420B2830-E718-11CF-893D-00A0C9054228}\1.0\0\win32'
'Registry::HKEY_CLASSES_ROOT\TypeLib\{420B2830-E718-11CF-893D-00A0C9054228}\1.0\0\win64'
'Registry::HKEY_CLASSES_ROOT\TypeLib\{420B2830-E718-11CF-893D-00A0C9054228}\1.0\0'
'Registry::HKEY_CLASSES_ROOT\TypeLib\{420B2830-E718-11CF-893D-00A0C9054228}\1.0\FLAGS'
'Registry::HKEY_CLASSES_ROOT\TypeLib\{420B2830-E718-11CF-893D-00A0C9054228}\1.0\HELPDIR'
'Registry::HKEY_CLASSES_ROOT\TypeLib\{420B2830-E718-11CF-893D-00A0C9054228}\1.0'
'Registry::HKEY_CLASSES_ROOT\TypeLib\{420B2830-E718-11CF-893D-00A0C9054228}'
)
foreach($regPath in $regPaths) {
Set-Ownership -Path $regPath -Identity 'BUILTIN\Administrators' -AddFullControl -Recurse -Verbose
}
#endregion
#region unregister the FileSystemObject scrrun dll
C:\Windows\System32\regsvr32.exe scrrun.dll /u /s
#endregion
#region Test FileSystemObject ComObject (Should fail)
(New-Object -ComObject Scripting.FileSystemObject).Drives
#endregion

HTH,
Martin.

Adding extended properties as NoteProperties


Continuing my post on Filtering files by their metadata (extended properties), and a question raised by Ankor in the comments section, I decided to quickly wrap up a new function (based on the one in the post) that simply adds the specified extended properties as new note properties to the object in the pipeline. As we would be reading only the required extended properties it would run much faster, and we could simply filter those objects later using the Where-Object (or with any other comparison statement).

The functions’ code is:

function Add-ExtendedAttribute {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true)]
[Alias(FullName, PSPath)]
[string[]]$Path,
[Parameter(Mandatory = $true)]
[ValidateRange(0,287)]
[int[]]$ExtendedAttributeId
)
begin {
$oShell = New-Object -ComObject Shell.Application
}
process {
$Path | ForEach-Object {
if (Test-Path -Path $_ -PathType Leaf) {
$FileItem = Get-Item -Path $_
$oFolder = $oShell.Namespace($FileItem.DirectoryName)
$oItem = $oFolder.ParseName($FileItem.Name)
$ExtendedAttributeId | ForEach-Object {
$ExtPropName = $oFolder.GetDetailsOf($oFolder.Items, $_)
$ExtValName = $oFolder.GetDetailsOf($oItem, $_)
$params = @{
InputObject = $FileItem
MemberType = NoteProperty
Name = $ExtPropName
Value = $ExtValName
}
$FileItem = Add-Member @params -PassThru
}
}
$FileItem
}
}
end {
$oShell = $null
}
}

And you can use it:


# Rating: 19
dir -Path G:MusicaMSpecial | Add-ExtendedAttribute -ExtendedAttributeId 19 |
    Where-Object { $_.Rating -eq ‘2 Stars’ } | Copy-Item -Destination G:Temp

Or:


# Genre: 16
dir -Path G:MusicaMSpecial | Add-ExtendedAttribute -ExtendedAttributeId 16 |
    Where-Object { $_.Genre -eq ‘Rock’ } | Copy-Item -Destination G:Temp

Thank you Ankor for raising the question

HTH,
Martin.

Filtering files by their metadata (extended properties)


When you run Get-ChildItem or any of its’ aliases, you’ll get back an array of objects, usually System.IO.FileInfo and System.IO.DirectoryInfo (if you have directories too).

The properties displayed are Mode, LastWritetime, Length and Name. Of course there are other properties in the returned objects, but these are the ones that get displayed by default (more on what gets displayed by default and why, in a future post).

You can use the Format-* or the Select-Object cmdlets to output the other properties and their values, or run Get-ChildItem | Get-Member -MemberType Properties to list all the properties in the PowerShell object.

PS C:> Get-ChildItem | Get-Member -MemberType Properties
 
 
   TypeName: System.IO.FileInfo
 
Name              MemberType     Definition                                                                      
—-              ———-     ———-                                                                      
Mode              CodeProperty   System.String Mode{get=Mode;}                                                   
PSChildName       NoteProperty   System.String PSChildName=myFile.txt                                                 
PSDrive           NoteProperty   System.Management.Automation.PSDriveInfo PSDrive=C                              
PSIsContainer     NoteProperty   System.Boolean PSIsContainer=False                                              
PSParentPath      NoteProperty   System.String PSParentPath=Microsoft.PowerShell.CoreFileSystem::C:            
PSPath            NoteProperty   System.String PSPath=Microsoft.PowerShell.CoreFileSystem::C:myFile.txt             
PSProvider        NoteProperty   System.Management.Automation.ProviderInfo PSProvider=Microsoft.PowerShell.Core…
Attributes        Property       System.IO.FileAttributes Attributes {get;set;}                                  
CreationTime      Property       datetime CreationTime {get;set;}                                                
CreationTimeUtc   Property       datetime CreationTimeUtc {get;set;}                                             
Directory         Property       System.IO.DirectoryInfo Directory {get;}                                        
DirectoryName     Property       string DirectoryName {get;}                                                     
Exists            Property       bool Exists {get;}                                                              
Extension         Property       string Extension {get;}                                                         
FullName          Property       string FullName {get;}                                                          
IsReadOnly        Property       bool IsReadOnly {get;set;}                                                      
LastAccessTime    Property       datetime LastAccessTime {get;set;}                                              
LastAccessTimeUtc Property       datetime LastAccessTimeUtc {get;set;}                                           
LastWriteTime     Property       datetime LastWriteTime {get;set;}                                               
LastWriteTimeUtc  Property       datetime LastWriteTimeUtc {get;set;}                                            
Length            Property       long Length {get;}                                                              
Name              Property       string Name {get;}                                                              
BaseName          ScriptProperty System.Object BaseName {get=if ($this.Extension.Length -gt 0){$this.Name.Remov…
VersionInfo       ScriptProperty System.Object VersionInfo {get=[System.Diagnostics.FileVersionInfo]::GetVersio…

 

But when you use the Windows explorer in details view, you can see that the files contain a lot of other properties (such as Publisher, Rating, Bit rate, Genre, etc. for music files and Camera model, Date taken, Dimensions, Exposure time, etc. for pictures), these are called extended properties.

If you want to list these extended properties in PowerShell, or filter the files in a folder by a value on one of those properties you will have to use the Shell.Application ComObject.

For this purpose exactly, I wrote my own version of the Get-FileMetaData function (based on Ed Wilson’s version described in http://blogs.technet.com/b/heyscriptingguy/archive/2014/02/06/use-powershell-to-find-metadata-from-photograph-files.aspx):

function Get-FileMetaData {

 
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true,
                   ValueFromPipeline = $true,
                   ValueFromPipelineByPropertyName = $true)]
        [Alias(‘FullName’, ‘PSPath’)]
        [string[]]$Path
    )
 
    begin {
        $oShell = New-Object -ComObject Shell.Application
    }
 
    process {
        $Path | ForEach-Object {
 
            if (Test-Path -Path $_ -PathType Leaf) {
 
                $FileItem = Get-Item -Path $_
 
                $oFolder = $oShell.Namespace($FileItem.DirectoryName)
                $oItem = $oFolder.ParseName($FileItem.Name)
 
                $props = @{}
 
                0..287 | ForEach-Object {
                    $ExtPropName = $oFolder.GetDetailsOf($oFolder.Items, $_)
                    $ExtValName = $oFolder.GetDetailsOf($oItem, $_)
               
                    if (-not $props.ContainsKey($ExtPropName) -and
                            ($ExtPropName -ne )) {
                                $props.Add($ExtPropName, $ExtValName)
                    }
 
                }
 
                New-Object PSObject -Property $props
            }
        }
 
    }
 
    end {
        $oShell = $null
    }
}
 

And you can use it, for example:

dir -Path C:Pictures | Get-FileMetaData | Where-Object { $_.‘Camera maker’ -eq ‘NIKON’ }

or:

dir -Path C:Music -Recurse | Get-FileMetaData | Where-Object { $_.Genre -in @(‘Rock’,‘Pop’) } | Select-Object Path, Genre, ‘Bit rate’

 

 

Thanks to Israel Gofman for the PowerShell challenge.

HTH,

Martin.