Storing a NTFS Security Descriptor in C

Posted by Doori Bar on Stack Overflow See other posts from Stack Overflow or by Doori Bar
Published on 2010-05-11T07:21:36Z Indexed on 2010/05/11 7:24 UTC
Read the original article Hit count: 197

Filed under:
|
|

My goal is to store a NTFS Security Descriptor in its identical native state. The purpose is to restore it on-demand.

I managed to write the code for that purpose, I was wondering if anybody mind to validate a sample of it? (The for loop represents the way I store the native descriptor)

This sample only contains the flag for "OWNER", but my intention is to apply the same method for all of the security descriptor flags.

I'm just a beginner, would appreciate the heads up. Thanks, Doori Bar

#define _WIN32_WINNT 0x0501
#define WINVER 0x0501

#include <stdio.h>
#include <windows.h>
#include "accctrl.h"
#include "aclapi.h"
#include "sddl.h"

int main (void)
{
  DWORD lasterror;
  PSECURITY_DESCRIPTOR PSecurityD1, PSecurityD2;
  HANDLE hFile;
  PSID owner;
  LPTSTR ownerstr;
  BOOL ownerdefault;

  int ret = 0;
  unsigned int i;

  hFile = CreateFile("c:\\boot.ini", GENERIC_READ | ACCESS_SYSTEM_SECURITY, 
                     FILE_SHARE_READ, NULL, OPEN_EXISTING, 
                     FILE_FLAG_BACKUP_SEMANTICS, NULL);

  if (hFile == INVALID_HANDLE_VALUE) {
    fprintf(stderr,"CreateFile() failed. Error: INVALID_HANDLE_VALUE\n");
    return 1;
  }

  lasterror = GetSecurityInfo(hFile, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION
                              , &owner, NULL, NULL, NULL, &PSecurityD1);

  if (lasterror != ERROR_SUCCESS) {
    fprintf(stderr,"GetSecurityInfo() failed. Error: %lu;\n", lasterror);
    ret = 1;
    goto ret1;
  }

  ConvertSidToStringSid(owner,&ownerstr);
  printf("ownerstr of PSecurityD1: %s\n", ownerstr);

  /* The for loop represents the way I store the native descriptor */
  PSecurityD2 = malloc( GetSecurityDescriptorLength(PSecurityD1) * 
                        sizeof(unsigned char) );

  for (i=0; i < GetSecurityDescriptorLength(PSecurityD1); i++)
    ((unsigned char *) PSecurityD2)[i] = ((unsigned char *) PSecurityD1)[i];

  if (IsValidSecurityDescriptor(PSecurityD2) == 0) {
    fprintf(stderr,"IsValidSecurityDescriptor(PSecurityD2) failed.\n");
    ret = 2;
    goto ret2;
  }

  if (GetSecurityDescriptorOwner(PSecurityD2,&owner,&ownerdefault) == 0) {
    fprintf(stderr,"GetSecurityDescriptorOwner() failed.");
    ret = 2;
    goto ret2;
  }
  ConvertSidToStringSid(owner,&ownerstr);
  printf("ownerstr of PSecurityD2: %s\n", ownerstr);

  ret2:
  free(owner);
  free(ownerstr);
  free(PSecurityD1);
  free(PSecurityD2);
  ret1:
  CloseHandle(hFile);
  return ret;
}

© Stack Overflow or respective owner

Related posts about ntfs

Related posts about c