Taking ownership of a folder and adding full permissions to a domain account in powershell?

1

1

I have a Powershell function that does part of this, but it doesn't use the domain account to take ownership and add permissions...it uses a local administrator. Is there a better way to do this in Powershell?

<#

.SYNOPSIS
    Take ownership of a folder giving the ownership to ourdomain\myuser

.DESCRIPTION
    Takes ownership of a file the way my boss said to do when deleting a user's home directory.
    Using the GUI:
    1. Right click the folder and select properties.
    2. Click the "Security" tab.
    3. Click the "Advanced" button.
    4. Next to the "Owner:" label, click "Change"
    5. Enter ourdomain\myuser
    6. Click OK, OK, OK
    7. Right click the folder and select properties.
    8. Click the "Security" tab.
    9. Click the "Advanced" button.
    10. Click "Add"
    11. Next to "Principal:" click "Select a principal"
    12. Enter ourdomain\myuser
    13. Click OK
    14. Check "Full control"
    15. Click OK, OK, OK
    16. You should now be able to manipulate or delete the folder.
.NOTES
    File Name : Microsoft.PowerShell_profile.ps1
.EXAMPLE
    Take-Ownership R:\Redirected\Users\<username>
#>
function Take-Ownership {
   param(
     [String]$Folder
   )

   # Take ownership of the folder...  
   # (though I'd prefer if I could specify a user or group instead) 
   takeown.exe /A /F $Folder

   # Obtain the current ACL for this folder.
   $CurrentACL = Get-Acl $Folder

   # Add FullControl permissions to the ACL for the user.
   Write-Host ...Adding ourdomain\myuser to $Folder -Fore Yellow
   $SystemACLPermission = "ourdomain\myuser","FullControl","ContainerInherit,ObjectInherit","None","Allow"
   $SystemAccessRule = new-object System.Security.AccessControl.FileSystemAccessRule $SystemACLPermission
   $CurrentACL.AddAccessRule($SystemAccessRule)

   #Write-Host ...Adding Infrastructure Services to $Folder -Fore Yellow
   #$AdminACLPermission = "ourdomain\myuser","FullControl","ContainerInherit,ObjectInherit"."None","Allow"
   #$SystemAccessRule = new-object System.Security.AccessControl.FilesystemAccessRule $AdminACLPermission
   #$CurrentACL.AddAccessRule($SystemAccessRule)

   # Set the ACL again.
   Set-Acl -Path $Folder -AclObject $CurrentACL
}

leeand00

Posted 2016-06-24T12:37:15.877

Reputation: 14 882

1Do I understand your question correctly, you want to take permission in another context than local Admin? If so, use more switches of takeown: takeown /s system /u domain\username /p password /f $folder /amore information in takeown /? – SimonS – 2016-06-27T11:06:40.827

Answers

1

If you're setting the owner of an object to the Administrators group, you have to be a local administrator. Otherwise, people could trivially circumvent disk quotas, since the quota accounting is based on file ownership and quotas don't affect admins.

If you are running the script as an administrator, you can set the owner of an object to any security principal, after a little fiddling around. You'll need this privilege-adjusting script from Lee Holmes, which I have edited slightly to remove extra whitespace and allow it to be run multiple times in one session:

param(    ## The privilege to adjust. This set is taken from
    ## http://msdn.microsoft.com/en-us/library/bb530716(VS.85).aspx
    [ValidateSet(
        "SeAssignPrimaryTokenPrivilege", "SeAuditPrivilege", "SeBackupPrivilege",
        "SeChangeNotifyPrivilege", "SeCreateGlobalPrivilege", "SeCreatePagefilePrivilege",
        "SeCreatePermanentPrivilege", "SeCreateSymbolicLinkPrivilege", "SeCreateTokenPrivilege",
        "SeDebugPrivilege", "SeEnableDelegationPrivilege", "SeImpersonatePrivilege", "SeIncreaseBasePriorityPrivilege",
        "SeIncreaseQuotaPrivilege", "SeIncreaseWorkingSetPrivilege", "SeLoadDriverPrivilege",
        "SeLockMemoryPrivilege", "SeMachineAccountPrivilege", "SeManageVolumePrivilege",
        "SeProfileSingleProcessPrivilege", "SeRelabelPrivilege", "SeRemoteShutdownPrivilege",
        "SeRestorePrivilege", "SeSecurityPrivilege", "SeShutdownPrivilege", "SeSyncAgentPrivilege",
        "SeSystemEnvironmentPrivilege", "SeSystemProfilePrivilege", "SeSystemtimePrivilege",
        "SeTakeOwnershipPrivilege", "SeTcbPrivilege", "SeTimeZonePrivilege", "SeTrustedCredManAccessPrivilege",
        "SeUndockPrivilege", "SeUnsolicitedInputPrivilege")]
    $Privilege,
    ## The process on which to adjust the privilege. Defaults to the current process.
    $ProcessId = $pid,
    ## Switch to disable the privilege, rather than enable it.
    [Switch] $Disable
)

## Taken from P/Invoke.NET with minor adjustments.
$definition = @'
using System;
using System.Runtime.InteropServices;
public class AdjPriv
{

    [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_ENABLED = 0x00000002;
    internal const int SE_PRIVILEGE_DISABLED = 0x00000000;
    internal const int TOKEN_QUERY = 0x00000008;
    internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;

    public static bool EnablePrivilege(long processHandle, string privilege, bool disable)
    {
        bool retVal;
        TokPriv1Luid tp;
        IntPtr hproc = new IntPtr(processHandle);
        IntPtr htok = IntPtr.Zero;
        retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
        tp.Count = 1;
        tp.Luid = 0;

        if(disable)
        {
            tp.Attr = SE_PRIVILEGE_DISABLED;
        }
        else
        {
            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;
    }
}

'@

$processHandle = (Get-Process -id $ProcessId).Handle
try { 
  Add-Type $definition 
} catch {} # Silent failure on re-registration

[AdjPriv]::EnablePrivilege($processHandle, $Privilege, $Disable)

I saved it as privs.ps1. You can then call .\privs.ps1 SeRestorePrivilege to turn on SeRestorePrivilege for your process, which allows you to set file ownership to whoever you want.

Then, instead of the takeown call, you can use that ACL object you already have:

$ownerPrincipal = New-Object System.Security.Principal.NTAccount($newOwnerName)
$CurrentACL.SetOwner($ownerPrincipal)

The new owner will be set at the same time the new ACL is applied.

Finally, you can disable the extra privilege:

.\privs.ps1 SeRestorePrivilege -Disable

Ben N

Posted 2016-06-24T12:37:15.877

Reputation: 32 973

So you're saying, that if users were able to set the owner of a file to the administrators group, or even set the owner to an administrator account, they would have the power to store as much as they want by simply by leaving their own permissions on files they previously owned and setting the owner as an admin; because quotas are calculated based on who owns the files. Well that's not a simple concept, but if you can confirm my understanding of it, I believe that I understand what you are saying. – leeand00 – 2016-06-29T21:53:46.157

1Yes, that's correct. The only special things about being a file's owner are that you always have read- and write-DAC privilege on it, and that its size counts against your quota. – Ben N – 2016-06-29T21:54:36.587