Solved

Ntfs Permissions

Posted on 2001-08-07
10
626 Views
Last Modified: 2007-11-27
Hello, I would like to know how to change ntfs permissions using c/c++.
Exapmles will be appreciated.
0
Comment
Question by:avissar
  • 2
  • 2
  • 2
  • +4
10 Comments
 

Expert Comment

by:AAB
ID: 6358624
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
 
LVL 32

Accepted Solution

by:
jhance earned 100 total points
ID: 6359129
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
 
LVL 86

Expert Comment

by:jkr
ID: 6359359
0
 
LVL 10

Expert Comment

by:makerp
ID: 6361148
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
 

Author Comment

by:avissar
ID: 6416641
Can anybody post an example for using SetFileSecurity API ?
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 

Expert Comment

by:AAB
ID: 6416716

/******************************************************************************\
*       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
 
LVL 11

Expert Comment

by:griessh
ID: 6845363
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
 
LVL 86

Expert Comment

by:jkr
ID: 6845479
Tend to object - I mentioned "SetFileSecurity()", and posting the sample's code was a little too much...
0
 
LVL 11

Expert Comment

by:griessh
ID: 6846092
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
 
LVL 6

Expert Comment

by:Mindphaser
ID: 6997014
Force accepted

** Mindphaser - Community Support Moderator **

jkr, there will be a separate question with points for your help.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now