Ntfs Permissions

Hello, I would like to know how to change ntfs permissions using c/c++.
Exapmles will be appreciated.
avissarAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

AABCommented:
Hi..
You can use the API function NetShareSetInfo(); and NetShareGetInfo();

You can find full information in  MSDN SDK Documentation --> Win32 API --> Network Services -->  Then Click Network Managment ---> look to the Function Refrence ----> find the Share Function ...
I wanna give you example from MSDN ..

The following code sample demonstrates how to set the comment associated with a shared resource using a call to the NetShareSetInfo function.

#define UNICODE
#include <windows.h>
#include <stdio.h>
#include <lm.h>

void wmain( int argc, TCHAR *argv[ ])
{
   SHARE_INFO_1004 p;
   NET_API_STATUS res;
   DWORD parm_err = 0;

   if(argc<4)
      printf("Usage: SetInfo server share \"remark\"\n");
   else
   {
      //
      // Fill in SHARE_INFO_1004 structure member.
      //
      p.shi1004_remark=argv[3];
      //
      // Call the NetShareSetInfo function,
      //  specifying information level 1004.
      //
      res=NetShareSetInfo(argv[1], argv[2], 1004, (LPBYTE)&p, &parm_err);
      //
      // Display the result of the call.
      //
      if(res==0)
         printf("Remark set.\n");
      else
         printf("Error: %u\tparmerr=%u\n", res, parm_err);
   }
   return;
}


You can specifiy the level of information and then set by the suitable struct of information ... look also to struct SHARE_INFO_1, SHARE_INFO_2 ... etc ...
It will give the info and the types that you can modify the permission of ntfs ...
0
jhanceCommented:
This is both a simple and a difficult question.

The way to set the permissions on an NTFS file or directory is via the SetFileSecurity() API function.

The difficulty is that the entire subject of SECURITY INFORMATION and SECURITY DESCRIPTORS, which are BASIC to using this API, is quite complex and far beyond what I believe could adequately explained here.

I'd suggest you get a good book that covers Windows NT/2000 security programming.  One that I've found useful is from WROX Press and it's called "Window NT Programming" by Julian Templeman.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Amazon Web Services

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

makerpCommented:
here are some functions i wrote a while back, maybe they would help you. i have Q that i asked on this, if i remember righly jkr answered it, its under C, look at me profile

#include <windows.h>
#include <stdio.h>
#include <malloc.h>
#include <aclapi.h>

BOOL SetOwner(PSECURITY_DESCRIPTOR psdFileSD, LPTSTR  lpszFullName,  PSID psidUserSID);

PSID GetFileOwner(char *filename)
{
     PSECURITY_DESCRIPTOR pSD;
     PSID pSidOwner = NULL;
     HANDLE hFile;

     /* get a file handle */
     if((hFile = CreateFile(filename,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL)) == INVALID_HANDLE_VALUE)
     {    
          PERR("CreateFile");
          return (NULL);
     }
     /* get the owner */
     if((GetSecurityInfo(hFile,SE_FILE_OBJECT,OWNER_SECURITY_INFORMATION,&pSidOwner,NULL,NULL,NULL,&pSD)) != ERROR_SUCCESS)
     {
          PERR("GetSecurityInfo");
          return (NULL);
     }
     /* close the file handle */
     CloseHandle(hFile);
     return pSidOwner;
}

BOOL SetFileOwner(LPTSTR lpszFullName, PSID psidUserSID)
{
     UCHAR ucBuf [SZ_REL_SD_BUF];
     UCHAR ucBufAbs [SZ_ABS_SD_BUF];
     UCHAR ucBufCtrl[sizeof(PSECURITY_DESCRIPTOR_CONTROL)];
     UCHAR ucBufSidOwn[SZ_SID_OWN_BUF];
     DWORD dwSDLength = SZ_REL_SD_BUF;
     DWORD dwSidOwnLength = SZ_SID_OWN_BUF;
     DWORD dwSDLengthNeeded;
     PSECURITY_DESCRIPTOR psdSrelFileSD = (PSECURITY_DESCRIPTOR)&ucBuf;
     PSECURITY_DESCRIPTOR psdAbsFileSD = (PSECURITY_DESCRIPTOR)&ucBufAbs;
     PSECURITY_DESCRIPTOR_CONTROL psdcCtrl = (PSECURITY_DESCRIPTOR_CONTROL)&ucBufCtrl;
     PSID psidSidOwn = (PSID)&ucBufSidOwn;
     BOOL bSDSelfRelative;
     DWORD dwRevision;

     if(!GetFileSecurity(lpszFullName,(SECURITY_INFORMATION)(OWNER_SECURITY_INFORMATION),psdSrelFileSD,dwSDLength,(LPDWORD)&dwSDLengthNeeded))
     {    
          PERR("GetFileSecurity");
          return(FALSE);
     }

     if(!InitializeSecurityDescriptor(psdAbsFileSD,SECURITY_DESCRIPTOR_REVISION))
     {
          PERR("InitializeSecurityDescriptor");
          return (FALSE);
     }

     if(!GetSecurityDescriptorControl(psdSrelFileSD,psdcCtrl,&dwRevision))
     {
          PERR("GetSecurityDescriptorControl");
          return FALSE;
     }
     bSDSelfRelative = (SE_SELF_RELATIVE & *psdcCtrl);

     if(!IsValidSecurityDescriptor(psdAbsFileSD))
     {
          PERR("IsValidSecurityDescriptor said bad SD");
          return(FALSE);
     }

     if(!SetOwner(psdAbsFileSD,lpszFullName,psidUserSID))
     {
          return(FALSE);
     }

     return(TRUE);
}

BOOL SetOwner(PSECURITY_DESCRIPTOR psdFileSD,LPTSTR  lpszFullName,PSID psidUserSID)
{
     if(!SetSecurityDescriptorOwner(psdFileSD,psidUserSID,FALSE))
     {
          PERR("SetSecurityDescriptorOwner");
          return(FALSE);
     }

     if(!IsValidSecurityDescriptor(psdFileSD))
     {
          PERR("IsValidSecurityDescriptor said bad SD");
          return(FALSE);
     }

     if(!SetFileSecurity(lpszFullName,(SECURITY_INFORMATION)(OWNER_SECURITY_INFORMATION),psdFileSD))
     {    
          PERR("SetFileSecurity");
          return(FALSE);
     }

     return(TRUE);
}
0
avissarAuthor Commented:
Can anybody post an example for using SetFileSecurity API ?
0
AABCommented:

/******************************************************************************\
*       This is a part of the Microsoft Source Code Samples.
*       Copyright (C) 1993-1997 Microsoft Corporation.
*       All rights reserved.
*       This source code is only intended as a supplement to
*       Microsoft Development Tools and/or WinHelp documentation.
*       See these sources for detailed information regarding the
*       Microsoft samples programs.
\******************************************************************************/

/*++

Module Name:

    Takeown.c

Abstract:

    Implements a recovery scheme to give an Administrator access to a
    file that has been denied to all.  

Environment:

    Must be run from an Administrator account in order to perform
    reliably.  

--*/
#include <windows.h>
#include <stdio.h>
#include <malloc.h>

BOOL
AssertTakeOwnership(
    HANDLE TokenHandle
    );

BOOL
GetTokenHandle(
    PHANDLE TokenHandle
    );

BOOL
VariableInitialization();




PSID AliasAdminsSid = NULL;
PSID SeWorldSid;

static SID_IDENTIFIER_AUTHORITY    SepNtAuthority = SECURITY_NT_AUTHORITY;
static SID_IDENTIFIER_AUTHORITY    SepWorldSidAuthority   = SECURITY_WORLD_SID_AUTHORITY;




void main (int argc, char *argv[])
{


    BOOL Result;
    LPSTR lpFileName;
    SECURITY_DESCRIPTOR SecurityDescriptor;
    HANDLE TokenHandle;


    //
    // We expect a file...
    //
    if (argc <= 1) {

        printf("Must specify a file name");
        return;
    }


    lpFileName = argv[1];


    Result = VariableInitialization();

    if ( !Result ) {
        printf("Out of memory\n");
        return;
    }




    Result = GetTokenHandle( &TokenHandle );

    if ( !Result ) {

        //
        // This should not happen
        //

        printf("Unable to obtain the handle to our token, exiting\n");
        return;
    }






    //
    // Attempt to put a NULL Dacl on the object
    //

    InitializeSecurityDescriptor( &SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION );


    Result = SetSecurityDescriptorDacl (
                 &SecurityDescriptor,
                 TRUE,
                 NULL,
                 FALSE
                 );



    if ( !Result ) {
        printf("SetSecurityDescriptorDacl failed, error code = %d\n", GetLastError());
        printf("Exiting\n");
        return;
    }

    Result = SetFileSecurity(
                 lpFileName,
                 DACL_SECURITY_INFORMATION,
                 &SecurityDescriptor
                 );

    if ( Result ) {

        printf("Successful, protection removed\n");
        return;
    }


    //
    // That didn't work.
    //


    //
    // Attempt to make Administrator the owner of the file.
    //


    Result = SetSecurityDescriptorOwner (
                 &SecurityDescriptor,
                 AliasAdminsSid,
                 FALSE
                 );

    if ( !Result ) {
        printf("SetSecurityDescriptorOwner failed, lasterror = %d\n", GetLastError());
        return;
    }


    Result = SetFileSecurity(
                 lpFileName,
                 OWNER_SECURITY_INFORMATION,
                 &SecurityDescriptor
                 );

    if ( !Result ) {


        //
        // That didn't work either.
        //



        //
        // Assert TakeOwnership privilege, then try again.  Note that
        // since the privilege is only enabled for the duration of
        // this process, we don't have to worry about turning it off
        // again.
        //

        Result = AssertTakeOwnership( TokenHandle );

        if ( !Result ) {
            printf("Could not enable SeTakeOwnership privilege\n");
            printf("Log on as Administrator and try again\n");
            return;
        }


        Result = SetFileSecurity(
                     lpFileName,
                     OWNER_SECURITY_INFORMATION,
                     &SecurityDescriptor
                     );

        if ( !Result ) {

            printf("Unable to assign Administrator as owner\n");
            printf("Log on as Administrator and try again\n");
            return;

        }
    }

    //
    // Try to put a benign DACL onto the file again
    //

    Result = SetFileSecurity(
                 lpFileName,
                 DACL_SECURITY_INFORMATION,
                 &SecurityDescriptor
                 );

    if ( !Result ) {

        //
        // This should not happen.
        //

        printf("SetFileSecurity unexpectedly failed, error code = %d\n", GetLastError());

    } else {

        printf("Successful, protection removed\n");
        return;
    }
}





BOOL
GetTokenHandle(
    PHANDLE TokenHandle
    )
//
// This routine will open the current process and return
// a handle to its token.
//
// These handles will be closed for us when the process
// exits.
//
{

    HANDLE ProcessHandle;
    BOOL Result;

    ProcessHandle = OpenProcess(
                        PROCESS_QUERY_INFORMATION,
                        FALSE,
                        GetCurrentProcessId()
                        );

    if ( ProcessHandle == NULL ) {

        //
        // This should not happen
        //

        return( FALSE );
    }


    Result = OpenProcessToken (
                 ProcessHandle,
                 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
                 TokenHandle
                 );

    if ( !Result ) {

        //
        // This should not happen
        //

        return( FALSE );

    }

    return( TRUE );
}


BOOL
AssertTakeOwnership(
    HANDLE TokenHandle
    )
//
// This routine turns on SeTakeOwnershipPrivilege in the current
// token.  Once that has been accomplished, we can open the file
// for WRITE_OWNER even if we are denied that access by the ACL
// on the file.

{
    LUID TakeOwnershipValue;
    BOOL Result;
    TOKEN_PRIVILEGES TokenPrivileges;


    //
    // First, find out the value of TakeOwnershipPrivilege
    //


    Result = LookupPrivilegeValue(
                 NULL,
                 "SeTakeOwnershipPrivilege",
                 &TakeOwnershipValue
                 );

    if ( !Result ) {

        //
        // This should not happen
        //

        printf("Unable to obtain value of TakeOwnership privilege\n");
        printf("Error = %d\n",GetLastError());
        printf("Exiting\n");
        return FALSE;
    }

    //
    // Set up the privilege set we will need
    //

    TokenPrivileges.PrivilegeCount = 1;
    TokenPrivileges.Privileges[0].Luid = TakeOwnershipValue;
    TokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;




    (VOID) AdjustTokenPrivileges (
                TokenHandle,
                FALSE,
                &TokenPrivileges,
                sizeof( TOKEN_PRIVILEGES ),
                NULL,
                NULL
                );

    if ( GetLastError() != NO_ERROR ) {

        return( FALSE );

    } else {

        return( TRUE );
    }

}



BOOL
VariableInitialization()

//
// Create some useful SIDs.
//

{

    BOOL Result;

    Result = AllocateAndInitializeSid(
                 &SepNtAuthority,
                 2,
                 SECURITY_BUILTIN_DOMAIN_RID,
                 DOMAIN_ALIAS_RID_ADMINS,
                 0,
                 0,
                 0,
                 0,
                 0,
                 0,
                 &AliasAdminsSid
                 );

    if ( !Result ) {
        return( FALSE );
    }


    Result = AllocateAndInitializeSid(
                 &SepWorldSidAuthority,
                 1,
                 SECURITY_WORLD_RID,
                 0,
                 0,
                 0,
                 0,
                 0,
                 0,
                 0,
                 &SeWorldSid
                 );

    if ( !Result ) {
        return( FALSE );
    }

    return( TRUE );
}
0
griesshCommented:
I think you forgot this question. I will ask Community Support to close it unless you finalize it within 7 days. Unless there is objection or further activity,  I will suggest to accept "AAB" comment(s) as an answer.

If you think your question was not answered at all, you can post a request in Community support (please include this link) to refund your points.
The link to the Community Support area is: http://www.experts-exchange.com/jsp/qList.jsp?ta=commspt

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
======
Werner
0
jkrCommented:
Tend to object - I mentioned "SetFileSecurity()", and posting the sample's code was a little too much...
0
griesshCommented:
Actually I have a "?" for my suggestion. The reason I suggested AAB was because avissar asked for an example in his/her last comment. As a rule for my suggestions I usually take the answer that answers the question completely ... first gut feeling was jhance ...

But to be honest, in reviewing YOUR comment, you had links to 2 MSKB articles ... changing ...

I will suggest to accept "jhance,jkr" comments as an answer ....

Thanks for your feedback!
======
Werner
0
MindphaserCommented:
Force accepted

** Mindphaser - Community Support Moderator **

jkr, there will be a separate question with points for your help.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.