none
Take Ownership of a File

    Question

  • How would I go about taking ownership of a file in C++ (Visual Studio 2008 or C++ Builder)? I know how to do it from the cmd line, but would like to accomplich it in C++ code.

    Take Ownership for Windows 7

    Please, write me code.

    Code snippet:

    cmd.exe /c takeown /f "%windir%\system32\*.*"

    cmd.exe /c takeown /f "%windir%\*.*"

    cmd.exe /c takeown /f "%windir%\system32\ru-RU\*.*"

    cmd.exe /c takeown /f "%windir%\ru-RU\*.*"

     

    • Edited by Virtyaluk Saturday, March 13, 2010 10:24 PM
    Saturday, March 13, 2010 7:31 PM

Answers

  • Nobody will write code for you, the best you will get is advice on what direction to take.
    But first, what are you even attempting to do taking ownership of the files under the Windows directory and sub directories? The only reason I can see is for some form of malware. For a regular system it shouldn't matter what any of the permissions are for those files. Whats more, the Windows Vista/7 package system relies on these files being owned by trusted installer.

    Without a good reason, you won't find anyone to help you do such a foolish thing which can be seen as malware.
    Visit my (not very good) blog at http://c2kblog.blogspot.com/
    • Marked as answer by Wesley Yao Thursday, March 18, 2010 5:32 AM
    Saturday, March 13, 2010 8:16 PM
  • WinExec("takeown /f C:\windows\system32\imageres.dll", SW_HIDE);
    • Marked as answer by Wesley Yao Thursday, March 18, 2010 5:32 AM
    Sunday, March 14, 2010 2:24 PM
  • I agree with crescens2k  and Eric, no body will write code for you .

    But I will give you some suggestions.
    You can run  cmd line in your programme use the windows API like "ShellEexecute", "system","WinExec".

    For example, we can use "WinExec" like this:
    CString sSomeThing;
    sSomeThing.Format(_T("cmd   /C   c:\\something.bat"));   
    WinExec( sSomeThing, SW_HIDE );

    GOOD LUCK!
    • Marked as answer by Wesley Yao Thursday, March 18, 2010 5:32 AM
    Sunday, March 14, 2010 3:04 AM

All replies

  • Nobody will write code for you, the best you will get is advice on what direction to take.
    But first, what are you even attempting to do taking ownership of the files under the Windows directory and sub directories? The only reason I can see is for some form of malware. For a regular system it shouldn't matter what any of the permissions are for those files. Whats more, the Windows Vista/7 package system relies on these files being owned by trusted installer.

    Without a good reason, you won't find anyone to help you do such a foolish thing which can be seen as malware.
    Visit my (not very good) blog at http://c2kblog.blogspot.com/
    • Marked as answer by Wesley Yao Thursday, March 18, 2010 5:32 AM
    Saturday, March 13, 2010 8:16 PM
  • Nobody will write code for you, the best you will get is advice on what direction to take.
    But first, what are you even attempting to do taking ownership of the files under the Windows directory and sub directories? The only reason I can see is for some form of malware. For a regular system it shouldn't matter what any of the permissions are for those files. Whats more, the Windows Vista/7 package system relies on these files being owned by trusted installer.

    Without a good reason, you won't find anyone to help you do such a foolish thing which can be seen as malware.
    Visit my (not very good) blog at http://c2kblog.blogspot.com/

    tnx but u don’t help me!!

    But i wont help.

    I wont create Resources Patcher for Windows 7 & I mast write program for patching a files for which it is necessary to become the ownership
    please, help me write code in C++

    Saturday, March 13, 2010 10:30 PM
  • I don't think it is right to ask people to write the code for you.

    I can give you some pointers.  You can find out the Win32 APIs that takeown.exe uses if you run dumpbin /imports takeown.exe in a Visual Studio Command Prompt.  I think most of the APIs you are looking for are in ADVAPI32.dll.
    Sunday, March 14, 2010 2:12 AM
  • I agree with crescens2k  and Eric, no body will write code for you .

    But I will give you some suggestions.
    You can run  cmd line in your programme use the windows API like "ShellEexecute", "system","WinExec".

    For example, we can use "WinExec" like this:
    CString sSomeThing;
    sSomeThing.Format(_T("cmd   /C   c:\\something.bat"));   
    WinExec( sSomeThing, SW_HIDE );

    GOOD LUCK!
    • Marked as answer by Wesley Yao Thursday, March 18, 2010 5:32 AM
    Sunday, March 14, 2010 3:04 AM
  • crescens2k,
    Eric Haddan ,
    bob.shao,
    sorry for my egoism
    But I very badly understand programming through that I ask to help me with a code writing.

    Here the scenario of a command line for my program, I need to translate it in C++


    ----------------------------------code--------------------------------------------------
    @echo off
    color 2a
    set is=C:\is
    cmd.exe /c takeown /f "C:\windows\system32\imageres.dll"
    copy %windir%\system32\imageres.dll %is%\backup
    copy %windir%\system32\imageres.dll %is%\new
    ren %windir%\system32\imageres.dll imageres.dll.backup
    %is%\patch\Patch_imageres.exe  -force -guiless -auto -quiet -nobackup -dir %is%\new
    move /y %is%\new\*.* %windir%\system32
    icacls "%windir%\system32\imageres.sll" /grant Администраторы:F
    pause
    end
    -------------------------------------end code---------------------------------------------

    More precisely I need to translate only one line (take ownership of a file), and with the rest I somehow itself will understand


    ----------------------------------------code------------------------------------------------
    cmd.exe /c takeown /f "C:\windows\system32\imageres.dll"
    ----------------------------------------end code--------------------------------------------

    or


    ----------------------------------------code-----------------------------------------------
    cmd.exe /c takeown /f "%windir%\sytem32\*.*"
    -----------------------------------------end code------------------------------------------









    please, help me write code...





    Sunday, March 14, 2010 1:46 PM
  • WinExec("takeown /f C:\windows\system32\imageres.dll", SW_HIDE);
    • Marked as answer by Wesley Yao Thursday, March 18, 2010 5:32 AM
    Sunday, March 14, 2010 2:24 PM
  • >WinExec("takeown /f C:\windows\system32\imageres.dll", SW_HIDE);

    Those backslashes will have to be doubled:

    WinExec("takeown /f C:\\windows\\system32\\imageres.dll", SW_HIDE);

    - Wayne
    Sunday, March 14, 2010 8:30 PM
  • Good catch Wayne! ;)
    Sunday, March 14, 2010 8:50 PM
  • WinExec("takeown /f C:\windows\system32\imageres.dll", SW_HIDE);

    end for all files in folder is:

    WinExec("takeown /f C:\windows\system32\*.*", SW_HIDE);

    no like this

    WinExec("cmd.exe /c takeown /f C:\windows\system32\imageres.dll", SW_HIDE);

    or

    WinExec("cmd.exe /c takeown /f %windir%\system32\*.*);

    ??

    Sunday, March 14, 2010 9:43 PM
  • I'm not sure what you are trying to do, but I think it's a very bad idea if you start taking ownership of system files like kernel32.dll, ntdll.dll, and ntosktrnl.exe.  I believe Windows has a list of files it won't let you replace, so to do a general takeown in the system directory probably will not work anyways.
    Sunday, March 14, 2010 10:45 PM
  • No, it can work and could damage the system badly. The user executing the program need to be VERY clear about what the program is going to do, should have the same warning severity level as SHFormatDrive.

    The following is signature, not part of post
    Please mark the post answered your question as the answer, and mark other helpful posts as helpful.
    Visual C++ MVP
    Tuesday, March 16, 2010 12:39 AM
  • Thats why I refused to give help initially.

    Everything in System32/SysWow64 has read and execute permissions. That is always enough for applications.

    Even if you want to create a resource patcher for Windows, there are just some files that you do not touch. Doing a take ownership on everything will break things, and as I said earlier, is foolish. The only way people would even think about helping you is if you change your design.

    1. Only change permissions on the files you need to modify.

    2. Change them back to the original settings as soon as you are finished.

    This is as close to the best design as you can get because any modifications of Windows system files is a bad idea.


    Visit my (not very good) blog at http://c2kblog.blogspot.com/
    Friday, March 19, 2010 2:37 PM
  • Really you guys are fu8king idiots! Logged in just to say that. It's ridiculous I own my computer and can't get the permissions to delete what I want
    Saturday, May 29, 2010 6:10 AM
  • Hey.. This is the solution.
    From http://www.emmet-gray.com/Articles/ChangeOwner.htm

    Imports System
    Imports System.Diagnostics
    Imports System.Runtime.InteropServices

    Module SetPrivilegs
        <StructLayout(LayoutKind.Sequential, Pack:=4)> _
        Private Structure LUID_AND_ATTRIBUTES
            Dim Luid As Long
            Dim Attributes As Integer
        End Structure

        <StructLayout(LayoutKind.Sequential, Pack:=4)> _
        Private Structure TOKEN_PRIVILEGES
            Dim PrivilegeCount As Integer
            Dim Privilege1 As LUID_AND_ATTRIBUTES
            Dim Privilege2 As LUID_AND_ATTRIBUTES
        End Structure

        <DllImport("advapi32.dll")> _
        Private Function OpenProcessToken _
            (ByVal ProcessHandle As IntPtr, _
             ByVal DesiredAccess As Integer, _
             ByRef TokenHandle As IntPtr) _
            As Boolean
        End Function

        <DllImport("advapi32.dll")> _
        Private Function LookupPrivilegeValue _
            (ByVal lpSystemName As String, _
             ByVal lpName As String, _
             ByRef lpLuid As Long) _
             As Boolean
        End Function

        <DllImport("advapi32.dll")> _
        Private Function AdjustTokenPrivileges _
            (ByVal TokenHandle As IntPtr, _
             ByVal DisableAllPrivileges As Boolean, _
             ByRef NewState As TOKEN_PRIVILEGES, _
             ByVal BufferLength As Integer, _
             ByVal PreviousState As IntPtr, _
             ByVal ReturnLength As IntPtr) _
             As Boolean
        End Function

        Const TOKEN_QUERY As Integer = &H8
        Const TOKEN_ADJUST_PRIVILEGES As Integer = &H20
        Const SE_TAKE_OWNERSHIP_NAME As String = "SeTakeOwnershipPrivilege"
        Const SE_RESTORE_NAME As String = "SeRestorePrivilege"
        Const SE_PRIVILEGE_ENABLED As Integer = &H2
        Private Const SE_FILE_OBJECT As Integer = 1&
        Private Const OWNER_SECURITY_INFORMATION As Integer = &H1

        Private Const NAME_SIZE As Integer = 64
        Private Const SID_SIZE As Integer = 32

        'DWORD SetNamedSecurityInfo(
        '  LPTSTR pObjectName,
        '  SE_OBJECT_TYPE ObjectType,
        '  SECURITY_INFORMATION SecurityInfo,
        '  PSID psidOwner,
        '  PSID psidGroup,
        '  PACL pDacl,
        '  PACL pSacl
        ');
        Declare Auto Function SetNamedSecurityInfo Lib "AdvAPI32.DLL" ( _
        ByVal pObjectName As String, _
        ByVal ObjectType As Integer, _
        ByVal SecurityInfo As Integer, _
        ByVal psidOwner As IntPtr, _
        ByVal psidGroup As IntPtr, _
        ByVal pDacl As IntPtr, _
        ByVal pSacl As IntPtr) As Integer

        'BOOL LookupAccountName(
        '  LPCTSTR lpSystemName,
        '  LPCTSTR lpAccountName,
        '  PSID Sid,
        '  LPDWORD cbSid,
        '  LPTSTR ReferencedDomainName,
        '  LPDWORD cchReferencedDomainName,
        '  PSID_NAME_USE peUse
        ');
        Declare Auto Function LookupAccountName Lib "advapi32.dll" ( _
        ByVal lpSystemName As String, _
        ByVal lpAccountName As String, _
        ByVal Sid As IntPtr, _
        ByRef cbSid As Integer, _
        ByVal lpReferencedDomainName As String, _
        ByRef cchReferencedDomainName As Integer, _
        ByRef peUse As IntPtr) As Boolean

        Public Declare Function LocalFree Lib "kernel32" ( _
        ByVal hMem As IntPtr) As Integer

        Public Function SetPrivileges() As Boolean
            Dim hProc, hToken As IntPtr
            Dim luid_TakeOwnership, luid_Restore As Long
            Dim tp As New TOKEN_PRIVILEGES

            ' get the current process's token
            hProc = Process.GetCurrentProcess().Handle
            hToken = IntPtr.Zero
            If Not OpenProcessToken(hProc, TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY, hToken) Then
                Return False
            End If

            ' get the LUIDs for the  privileges (provided they already exists)
            luid_TakeOwnership = 0
            If Not LookupPrivilegeValue(Nothing, SE_TAKE_OWNERSHIP_NAME, luid_TakeOwnership) Then
                Return False
            End If
            luid_Restore = 0
            If Not LookupPrivilegeValue(Nothing, SE_RESTORE_NAME, luid_Restore) Then
                Return False
            End If

            tp.PrivilegeCount = 2
            tp.Privilege1.Luid = luid_TakeOwnership
            tp.Privilege1.Attributes = SE_PRIVILEGE_ENABLED
            tp.Privilege2.Luid = luid_Restore
            tp.Privilege2.Attributes = SE_PRIVILEGE_ENABLED

            ' enable the privileges
            If Not AdjustTokenPrivileges(hToken, False, tp, 0, IntPtr.Zero, IntPtr.Zero) Then
                Return False
            End If

            Return True
        End Function

        Sub ChangeOwner(ByRef strPath As String, ByVal strUserName As String)
            Dim pNewOwner, deUse As IntPtr
            Dim Win32Error As Win32Exception
            Dim domain_name As String
            Dim ret, sid_len, domain_len As Integer

            ' Series of quick sanity checks before we proceed...

            ' Do we have the required Privilege?
            If SetPrivileges() = False Then
                Throw New Exception("Required privilege not held by the user")
            End If

            ' Does the file even exist?
            If File.Exists(strPath) = False Then
                If Directory.Exists(strPath) = False Then
                    Throw New Exception("File or Directory not found")
                End If
            End If

            ' Convert the name to a valid SID
            sid_len = SID_SIZE
            pNewOwner = Marshal.AllocHGlobal(sid_len)
            domain_len = NAME_SIZE
            domain_name = Space(domain_len)
            If LookupAccountName(Nothing, strUserName, pNewOwner, sid_len, domain_name, domain_len, deUse) = False Then
                ret = Marshal.GetLastWin32Error()
                Win32Error = New Win32Exception(ret)
                Throw New Exception(Win32Error.Message)
            End If

            ' write the new Owner
            ret = SetNamedSecurityInfo(strPath, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, pNewOwner, Nothing, Nothing, Nothing)
            If ret <> 0 Then
                Win32Error = New Win32Exception(ret)
                Throw New Exception(Win32Error.Message)
            End If

            ' clean up and go home
            Marshal.FreeHGlobal(pNewOwner)
        End Sub
    End Module

    Friday, October 08, 2010 7:18 AM