miércoles, 1 de octubre de 2008

setowner

Hace tiempo encontré una herramienta llamada setowner, esta herramienta establece el propietario de una carpeta o archivo a otro usuario.
Debido a que esta herramienta no proporciona el código fuente, desarrolle una herramienta similar para poder utilizarla en otros proyectos que tengo en desarrollo.

Aqui tenéis el código fuente de la aplicación.

Filaname: setowner-ng.c

#include 
#include 
#include 

/*
* setowner-ng v0.1 - Javier Olascoaga .
*
*/


int main(int argc, char *argv[])
{   
setowner ("c:\\test", "myuser");
}

int setowner (char *path, char *user) 
{
BYTE sidBuffer[100];
PSID psid=(PSID) &sidBuffer;
DWORD sidBufferSize = 100;
char szDomainName[80];
int result, peUse;
long nDomain = 80, nBufferSize, Revision;
SID_NAME_USE snu;

SECURITY_DESCRIPTOR SecDesc;

ModifyPrivilegeState(SE_RESTORE_NAME, 1);

printf ("- Changing %s owner to %s \n", path, user);

if (!LookupAccountName (NULL, user, psid, &sidBufferSize, szDomainName, &nDomain, &snu)) {
ShowError (GetLastError(), "LookupAccountName");  
return -1;            
}

if (!InitializeSecurityDescriptor (&SecDesc, SECURITY_DESCRIPTOR_REVISION)) {
ShowError (GetLastError(), "InitializeSecurityDescriptor");
return -1;                                   
}

if (!SetSecurityDescriptorOwner (&SecDesc, psid, 0)) {
ShowError (GetLastError(), "SetSecurityDescriptorOwner");
return -1;
}
if (!SetFileSecurity (path, OWNER_SECURITY_INFORMATION, &SecDesc)) {
ShowError (GetLastError(), "SetFileSecurity");
return -1;                     
}

printf ("Changed owner for %s to %s\n", path, user);

ModifyPrivilegeState(SE_RESTORE_NAME, 0);
}

int ModifyPrivilegeState (char *privilege, int enable) 
{
TOKEN_PRIVILEGES tp;
LUID luid;
HANDLE hToken;
LONG ptrPriv, res;

if (!OpenProcessToken (GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken)) 
{
ShowError (GetLastError(), "ModifyPrivilegeState");                    
return -1;     
}

if (!LookupPrivilegeValue (NULL, privilege, &luid)) {
ShowError (GetLastError(), "ModifyPrivilegeState");
return -1;                          
} 

tp.Privileges[0].Luid = luid;
tp.PrivilegeCount = 1;

if (enable) {
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
} else {
tp.Privileges[0].Attributes = 0;
}

if (!AdjustTokenPrivileges (hToken, FALSE, &tp, 0, 0, 0)) {
ShowError (GetLastError(), "ModifyPrivilegeState");
return -1;                                       
}

CloseHandle (hToken); 
}

int ShowError (int errorcode, char *func) 
{
LPVOID lpMsgBuf;

if (FormatMessage( 
FORMAT_MESSAGE_ALLOCATE_BUFFER | 
FORMAT_MESSAGE_FROM_SYSTEM | 
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
errorcode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL ))
{
printf ("[%d] %s: %s\n", errorcode, func, lpMsgBuf);
LocalFree( lpMsgBuf );
return 0;
}
printf ("[%d] %s: Unknown error\n", errorcode, func);
return 1;

}