Advertisement
Amakesh

Untitled

Nov 14th, 2024
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function global:Set-FilePermissionsWinAPI {
  2.     param (
  3.         [string]$filePath,
  4.         [bool]$allow  # $true = full access, $false = full access - FILE_ADD_FILE
  5.     )
  6.  
  7.     # Definicje dla WinAPI
  8.     Add-Type -TypeDefinition @"
  9.    using System;
  10.    using System.Runtime.InteropServices;
  11.  
  12.    public class SafeMemoryHandle : SafeHandle
  13.    {
  14.        public SafeMemoryHandle(IntPtr handle) : base(handle, true) {}
  15.  
  16.        public override bool IsInvalid => this.handle == IntPtr.Zero;
  17.  
  18.        protected override bool ReleaseHandle()
  19.        {
  20.            return NativeMethods.LocalFree(this.handle) == IntPtr.Zero;
  21.        }
  22.    }
  23.  
  24.    public class NativeMethods {
  25.        [DllImport("advapi32.dll", SetLastError = true)]
  26.        public static extern bool InitializeSecurityDescriptor(IntPtr pSecurityDescriptor, uint dwRevision);
  27.  
  28.        [DllImport("advapi32.dll", SetLastError = true)]
  29.        public static extern bool SetSecurityDescriptorDacl(IntPtr pSecurityDescriptor, bool bDaclPresent, IntPtr pDacl, bool bDaclDefaulted);
  30.  
  31.        [DllImport("advapi32.dll", SetLastError = true)]
  32.        public static extern bool SetFileSecurity(string lpFileName, int SecurityInformation, IntPtr pSecurityDescriptor);
  33.  
  34.        [DllImport("advapi32.dll", SetLastError = true)]
  35.        public static extern bool InitializeAcl(IntPtr pAcl, uint nAclLength, uint dwAclRevision);
  36.  
  37.        [DllImport("advapi32.dll", SetLastError = true)]
  38.        public static extern bool AddAccessAllowedAce(IntPtr pAcl, uint dwAceRevision, uint AccessMask, IntPtr pSid);
  39.  
  40.        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  41.        public static extern bool ConvertStringSidToSid(string StringSid, out IntPtr Sid);
  42.  
  43.        [DllImport("kernel32.dll", SetLastError = true)]
  44.        public static extern IntPtr LocalAlloc(uint uFlags, uint uBytes);
  45.  
  46.        [DllImport("kernel32.dll", SetLastError = true)]
  47.        public static extern IntPtr LocalFree(IntPtr hMem);
  48.  
  49.        public const int DACL_SECURITY_INFORMATION = 0x00000004;
  50.        public const uint SECURITY_DESCRIPTOR_REVISION = 1;
  51.        public const uint ACL_REVISION = 2;
  52.        public const uint FULL_CONTROL = 0x1F01FF;  // Full access
  53.        public const uint LIMITED_CONTROL = 0x1F01FF - 0x0002;  // Full access without FILE_ADD_FILE
  54.    }
  55. "@
  56.  
  57. try {
  58.     # Read current permissions
  59.     $currentAcl = Get-Acl -Path $filePath
  60.     $currentPermissions = $currentAcl.Access
  61.  
  62.     # Memory allocation for ACL
  63.     $aclLength = 2048
  64.  
  65.     $aclPtr = [NativeMethods]::LocalAlloc(0, $aclLength)
  66.     if ($aclPtr -eq [IntPtr]::Zero) {
  67.         Write-Host "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - $methodName --> Memory for ACL cannot be allocated" -ForegroundColor Red
  68.        
  69.     }
  70.     $aclHandle = New-Object SafeMemoryHandle($aclPtr)
  71.     [NativeMethods]::InitializeAcl($aclHandle.DangerousGetHandle(), $aclLength, [NativeMethods]::ACL_REVISION) | Out-Null
  72.  
  73.  
  74.         # Specify the appropriate permissions
  75.         $targetPermissions = if ($allow) { [NativeMethods]::FULL_CONTROL } else { [NativeMethods]::LIMITED_CONTROL }
  76.         foreach ($perm in (Get-Acl -Path $filePath).Access) {
  77.             $sidPtr = [IntPtr]::Zero
  78.             try {
  79.                 # SID Processing
  80.                 $sid = $perm.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier])
  81.                 [NativeMethods]::ConvertStringSidToSid($sid.Value, [ref]$sidPtr) | Out-Null
  82.  
  83.                 if ($sidPtr -eq [IntPtr]::Zero) {
  84.                     throw "Conversion failed for SID: $($perm.IdentityReference)"
  85.                 }
  86.  
  87.                 # Add Permission to ACL
  88.                 if ($sid.Value -eq "S-1-5-11") {
  89.                     [NativeMethods]::AddAccessAllowedAce($aclHandle.DangerousGetHandle(), [NativeMethods]::ACL_REVISION, $targetPermissions, $sidPtr) | Out-Null
  90.                 } else {
  91.                     [NativeMethods]::AddAccessAllowedAce($aclHandle.DangerousGetHandle(), [NativeMethods]::ACL_REVISION, $perm.FileSystemRights, $sidPtr) | Out-Null
  92.                 }
  93.             }
  94.             catch {
  95.                 Write-Host "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - $methodName --> Error: $_" -ForegroundColor Red
  96.             }
  97.             finally {
  98.                 # Freeing up the memory
  99.                 if ($sidPtr -ne [IntPtr]::Zero) {
  100.                     [NativeMethods]::LocalFree($sidPtr) | Out-Null
  101.                 }
  102.             }
  103.         }
  104.  
  105.         # Initialising the pSecurityDescriptor structure
  106.         $pSecurityDescriptor = [NativeMethods]::LocalAlloc(0, 0x14)
  107.         if ($pSecurityDescriptor -eq [IntPtr]::Zero) {
  108.             Write-Host "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - $methodName --> Memory for SecurityDescriptor cannot be allocated" -ForegroundColor Red
  109.         }
  110.         $securityDescriptorHandle = New-Object SafeMemoryHandle($pSecurityDescriptor)
  111.         [NativeMethods]::InitializeSecurityDescriptor($securityDescriptorHandle.DangerousGetHandle(), [NativeMethods]::SECURITY_DESCRIPTOR_REVISION) | Out-Null
  112.         [NativeMethods]::SetSecurityDescriptorDacl($securityDescriptorHandle.DangerousGetHandle(), $true, $aclHandle.DangerousGetHandle(), $false) | Out-Null
  113.  
  114.         # Setting file permissions
  115.         if (-not [NativeMethods]::SetFileSecurity($filePath, [NativeMethods]::DACL_SECURITY_INFORMATION, $securityDescriptorHandle.DangerousGetHandle())) {
  116.             Write-Host "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - $methodName --> File permission setting error." -ForegroundColor Red
  117.         } else {
  118.             Write-Host "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - $methodName --> Permissions have been successfully updated." -ForegroundColor Green
  119.         }
  120.     }
  121.     catch {
  122.         Write-Host "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - $methodName --> Error: $_" -ForegroundColor Red
  123.     }
  124.     finally {
  125.  
  126.  
  127.         if ($aclHandle -ne $null) {
  128.             $aclHandle.Dispose()
  129.         }
  130.    
  131.         if ($securityDescriptorHandle -ne $null) {
  132.             $securityDescriptorHandle.Dispose()
  133.         }
  134.  
  135.         if ($aclPtr-ne [IntPtr]::Zero) {
  136.             [NativeMethods]::LocalFree($aclPtr) | Out-Null
  137.         }
  138.  
  139.         if ($pSecurityDescriptor-ne [IntPtr]::Zero) {
  140.             [NativeMethods]::LocalFree($pSecurityDescriptor) | Out-Null
  141.         }
  142.     }
  143. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement