Ejemplo n.º 1
1
PSID vncImportACL::GetSID(const TCHAR *domainaccount){
	PSID pSid = NULL;
	unsigned long ulDomLen = 0;
	unsigned long ulSidLen = 0;
	SID_NAME_USE peUse;
	TCHAR *domain = NULL;

	// Get accounts's SID
	// First call to LookupAccountName is expected to fail.
	// Sets pSid and domain size
	LookupAccountName(NULL, domainaccount, pSid, &ulSidLen,
		domain, &ulDomLen, &peUse);
	pSid = (PSID)new TCHAR[ulSidLen];
	domain = new TCHAR[ulDomLen];
	LookupAccountName(NULL, domainaccount,
		pSid, &ulSidLen, domain, &ulDomLen, &peUse);
	if (!IsValidSid(pSid)){
		_ftprintf(stderr, _T("%s: SID not valid.\n"), domainaccount);
		delete [] pSid;
				pSid = NULL;
	}
	delete [] domain;

	return pSid;
}
Ejemplo n.º 2
0
uid_t getuid()
{
    const int UNLEN = 256;
    PSID sid = NULL;
    TCHAR* domain = NULL;
    DWORD sid_size = 0;
    DWORD domain_size = 0;
    SID_NAME_USE use = SidTypeUnknown;

    TCHAR buffer[257];
    DWORD buffer_len = _countof(buffer);

    if (!GetUserName(buffer, &buffer_len)) {
        return 0;
    }

    //Called once to set the size of the sid pointer and domain  
    LookupAccountName(NULL, buffer, NULL, &sid_size, NULL, &domain_size, &use);

    //Allocate memory based on sid and domain size
    sid = (PSID)LocalAlloc(LMEM_FIXED, sid_size);
    domain = (TCHAR*)malloc(domain_size * sizeof(TCHAR));

    //Initialize sid and domain
    if (!LookupAccountName(NULL, buffer, sid, &sid_size, domain, &domain_size, &use)) {
        return 0;
    }
    if (!IsValidSid(sid)) {
        return 0;
    }
    return (uid_t)sid;
}
//------------------------------------------------------------------------------
//lecture du SID à partir d'un nom
BOOL get_sid(const char *name, SID **ppsid)
{
  SID_NAME_USE sid_use;
  DWORD sid_size = 0;
  DWORD dom_size = 0;
  char *domain;

  *ppsid = 0;
  if(LookupAccountName(0, name, 0, &sid_size, 0, &dom_size, &sid_use) == 0) {
    if(GetLastError() != ERROR_INSUFFICIENT_BUFFER)return FALSE;
  }

  *ppsid = (SID *)LocalAlloc( LMEM_FIXED, sid_size);
  domain = (char *)LocalAlloc( LMEM_FIXED, dom_size);
  if( (*ppsid == 0) || (domain == 0))
  {
    if(*ppsid)
      LocalFree((HLOCAL)*ppsid);
    if(domain)
      LocalFree((HLOCAL)domain);
    *ppsid = 0;
    return FALSE;
  }

  if(LookupAccountName(0, name, *ppsid, &sid_size, domain, &dom_size, &sid_use) == 0)
  {
    LocalFree((HLOCAL)*ppsid);
    LocalFree((HLOCAL)domain);
    *ppsid = 0;
    return FALSE;
  }

  LocalFree((HLOCAL)domain);
  return TRUE;
}
Ejemplo n.º 4
0
bool QualifyName(const TCHAR *user, LPTSTR DomName) {
	PSID pSid = NULL;
	DWORD cbSid = 0;
	DWORD cbDomName = MAXLEN;
	SID_NAME_USE sidUse;
	bool isNameQualified = false;

	__try {
		// Get Sid buffer size
		LookupAccountName(NULL, user, pSid, &cbSid, DomName, &cbDomName, &sidUse);
		if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
			__leave;
		if (!(pSid = (PSID) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbSid)))
			__leave;
		if (cbDomName > MAXLEN)
			__leave;
		// Get DomName
		if (!LookupAccountName(NULL, user, pSid, &cbSid, DomName, &cbDomName, &sidUse))
			__leave;
		isNameQualified = true;
	} __finally {
		HeapFree(GetProcessHeap(), 0, pSid);
	}

	return isNameQualified;
}
Ejemplo n.º 5
0
HRESULT COpcSecurity::GetPrincipalSID(LPCTSTR pszPrincipal, PSID *ppSid)
{
	HRESULT hr;
	LPTSTR pszRefDomain = NULL;
	DWORD dwDomainSize = 0;
	DWORD dwSidSize = 0;
	SID_NAME_USE snu;

	// Call to get size info for alloc
	LookupAccountName(NULL, pszPrincipal, *ppSid, &dwSidSize, pszRefDomain, &dwDomainSize, &snu);

	hr = GetLastError();
	if (hr != ERROR_INSUFFICIENT_BUFFER)
		return HRESULT_FROM_WIN32(hr);

	OPCTRY(pszRefDomain = new TCHAR[dwDomainSize]);
	if (pszRefDomain == NULL)
		return E_OUTOFMEMORY;

	*ppSid = (PSID) malloc(dwSidSize);
	if (*ppSid != NULL)
	{
		if (!LookupAccountName(NULL, pszPrincipal, *ppSid, &dwSidSize, pszRefDomain, &dwDomainSize, &snu))
		{
			free(*ppSid);
			*ppSid = NULL;
			delete[] pszRefDomain;
			return HRESULT_FROM_WIN32(GetLastError());
		}
		delete[] pszRefDomain;
		return S_OK;
	}
	delete[] pszRefDomain;
	return E_OUTOFMEMORY;
}
PUBLIC_FUNCTION_END

PUBLIC_FUNCTION(IsUserTheAdministrator)
{
  TCHAR * name = (TCHAR *)LocalAlloc(LPTR, string_size*sizeof(TCHAR));
  TCHAR * sidstr = NULL;
  DWORD dwName = string_size;
  PSID pSid = NULL;
  DWORD sidLen = 0;
  DWORD domLen = 0;
  TCHAR * domain = NULL;
  SID_NAME_USE use;

  if (popstring(name))
    ABORT("Missing user name plug-in parameter.");

  if ((LookupAccountName(NULL, name, 
      NULL, &sidLen, NULL, &domLen, &use) ||
      ERROR_INSUFFICIENT_BUFFER == GetLastError()) &&
      NULL != (domain = (TCHAR *)LocalAlloc(LPTR, domLen*sizeof(TCHAR))) &&
    NULL != (pSid = (PSID)LocalAlloc(LPTR, sidLen)))
  {
    if (!LookupAccountName(NULL, name, 
      pSid, &sidLen, domain, &domLen, &use))
    {
      LocalFree(pSid);
      pSid = NULL;
      ABORT_d("Couldn't lookup current user name. Error code %d: ", GetLastError());
    }

    int uid;
    if (500 == (uid = *GetSidSubAuthority(pSid, *GetSidSubAuthorityCount(pSid) - 1)))
      pushstring(_T("yes"));
    else
      pushstring(_T("no"));

    sidstr = (TCHAR *)LocalAlloc(LPTR, string_size*sizeof(TCHAR));
    ConvertSidToStringSid(pSid, &sidstr);

    int len = lstrlen(sidstr);
    TCHAR * strend = sidstr + len - 1;
    TCHAR * strstart = sidstr;
    while (*strend != '-' && len >= 0)
    {
      strend--;
      len--;
    }
    *strend = '\0';
    lstrcat(strend, _T("-500"));

    pushstring(sidstr);
  }

cleanup:
  if (NULL != sidstr)
    LocalFree(sidstr);
  LocalFree(name);
}
Ejemplo n.º 7
0
DWORD GetAccountSid(
    IN const WCHAR *accountName,
    IN const WCHAR *systemName,
    OUT SID **sid
    )
{
    SID_NAME_USE sidUsage;
    DWORD cbSid;
    DWORD cchReferencedDomainName = MAX_PATH;
    WCHAR referencedDomainName[MAX_PATH];
    DWORD status;

    if (!accountName || !sid)
        return ERROR_INVALID_PARAMETER;

    cbSid = 0;
    *sid = NULL;

    if (!LookupAccountName(
        systemName,
        accountName,
        NULL,
        &cbSid,
        referencedDomainName,
        &cchReferencedDomainName,
        &sidUsage))
    {
        status = GetLastError();
        if (ERROR_INSUFFICIENT_BUFFER != status)
        {
            return perror("LookupAccountName");
        }
    }

    *sid = LocalAlloc(LPTR, cbSid);
    if (*sid == NULL)
    {
        return perror("LocalAlloc");
    }

    if (!LookupAccountName(
        systemName,
        accountName,
        *sid,
        &cbSid,
        referencedDomainName,
        &cchReferencedDomainName,
        &sidUsage))
    {
        status = GetLastError();
        LocalFree(*sid);
        return perror2(status, "LookupAccountName");
    }

    return ERROR_SUCCESS;
}
Ejemplo n.º 8
0
/*---------------------------------------------------------------------------*\
 * NAME: GetPrincipalSID                                                     *
 * --------------------------------------------------------------------------*
 * DESCRIPTION: Creates a SID for the supplied principal.                    *
\*---------------------------------------------------------------------------*/
DWORD GetPrincipalSID (
    LPTSTR tszPrincipal,
    PSID *pSid
    )
{
    DWORD        cbSid              = 0;
    TCHAR        tszRefDomain [256] = {0};
    DWORD        cbRefDomain        = 0;
    DWORD        dwReturnValue      = ERROR_SUCCESS;
    SID_NAME_USE snu;

    cbSid = 0;
    cbRefDomain = 255;

    if(ConstructWellKnownSID(tszPrincipal, pSid)) return ERROR_SUCCESS;

    LookupAccountName (NULL,
                       tszPrincipal,
                       *pSid,
                       &cbSid,
                       tszRefDomain,
                       &cbRefDomain,
                       &snu);

    dwReturnValue = GetLastError();
    if (dwReturnValue != ERROR_INSUFFICIENT_BUFFER) goto CLEANUP;

    dwReturnValue = ERROR_SUCCESS;

    *pSid = (PSID) malloc (cbSid);
    if(!pSid)
    {
        dwReturnValue = ERROR_OUTOFMEMORY;
        goto CLEANUP;
    }

    cbRefDomain = 255;
    
    if (!LookupAccountName (NULL,
                            tszPrincipal,
                            *pSid,
                            &cbSid,
                            tszRefDomain,
                            &cbRefDomain,
                            &snu))
    {
        dwReturnValue = GetLastError();
        goto CLEANUP;
    }

CLEANUP:

    return dwReturnValue;
}
Ejemplo n.º 9
0
isc_result_t
isc_fsaccess_changeowner(const char *filename, const char *user) {
    SECURITY_DESCRIPTOR psd;
    BYTE sidBuffer[500];
    BYTE groupBuffer[500];
    PSID psid=(PSID) &sidBuffer;
    DWORD sidBufferSize = sizeof(sidBuffer);
    char domainBuffer[100];
    DWORD domainBufferSize = sizeof(domainBuffer);
    SID_NAME_USE snu;
    PSID pSidGroup = (PSID) &groupBuffer;
    DWORD groupBufferSize = sizeof(groupBuffer);


    /*
     * Determine if this is a FAT or NTFS disk and
     * call the appropriate function to set the ownership
     * FAT disks do not have ownership attributes so it's
     * a noop.
     */
    if (is_ntfs(filename) == FALSE)
        return (ISC_R_SUCCESS);

    if (!InitializeSecurityDescriptor(&psd, SECURITY_DESCRIPTOR_REVISION))
        return (ISC_R_NOPERM);

    if (!LookupAccountName(0, user, psid, &sidBufferSize, domainBuffer,
                           &domainBufferSize, &snu))
        return (ISC_R_NOPERM);

    /* Make sure administrators can get to it */
    domainBufferSize = sizeof(domainBuffer);
    if (!LookupAccountName(0, "Administrators", pSidGroup,
                           &groupBufferSize, domainBuffer, &domainBufferSize, &snu))
        return (ISC_R_NOPERM);

    if (!SetSecurityDescriptorOwner(&psd, psid, FALSE))
        return (ISC_R_NOPERM);

    if (!SetSecurityDescriptorGroup(&psd, pSidGroup, FALSE))
        return (ISC_R_NOPERM);

    if (!SetFileSecurity(filename,
                         OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION,
                         &psd))
        return (ISC_R_NOPERM);

    return (ISC_R_SUCCESS);
}
Ejemplo n.º 10
0
//
// Return the SID of specified user account
//
PSID GetUserSid(LPCTSTR szUserName)
{
	SID		*sid = 0;
	TCHAR	*dom = 0;

	DWORD	sidlen = 0;
	DWORD	domlen = 0;

	SID_NAME_USE snu;

	//
	// with no machine specified, LookupAccountName looks up user's sid in
	// following locations:
	//
	// well-known, built-in, local-machine, primary-domain, trusted-domain
	//
	while(!LookupAccountName(NULL, szUserName, sid, &sidlen, dom, &domlen, &snu))
	{
		if(sid) free(sid);
		if(dom) free(dom);

		if(GetLastError() != ERROR_INSUFFICIENT_BUFFER)
			return 0;

		sid = malloc(sidlen);
		dom = malloc(domlen);
	}

	printf("domain: %s\n", dom);

	free(dom);
	return sid;
}
Ejemplo n.º 11
0
LPTSTR CDialupass::GetLocalSid()
{
	union
	{
		SID s;
		char c[256];
	}Sid;
	DWORD sizeSid=sizeof(Sid);
	char DomainName[256];
	DWORD sizeDomainName=sizeof(DomainName);
	SID_NAME_USE peUse;
	LPSTR pSid;


	if (m_lpCurrentUser == NULL)
		return NULL;

	if(!LookupAccountName(NULL,m_lpCurrentUser,(SID*)&Sid,&sizeSid,DomainName,&sizeDomainName,&peUse))return NULL;
	if(!IsValidSid(&Sid))return NULL;


	typedef BOOL  (WINAPI *ConvertSid2StringSid)(PSID  , LPTSTR *);
	ConvertSid2StringSid proc;
	HINSTANCE	hLibrary = LoadLibrary("advapi32.dll");
	proc = (ConvertSid2StringSid) GetProcAddress(hLibrary, "ConvertSidToStringSidA");
	if(proc)   proc((SID*)&Sid.s,&pSid);
	FreeLibrary(hLibrary);
	return pSid;
}
Ejemplo n.º 12
0
	void main()
	{
		char sid[256]; // sid를 담을 변수 가변길이 이므로 충분한 크기로 버퍼를 만든다
		char domain[256];

		DWORD sid_size = 256;
		DWORD domain_size = 256;

		SID_NAME_USE use; // sid의 종류..

		// power의 sid를 구한다.
		LookupAccountName("." ,    // PC이름
						  "power", // 사용자 id
						  sid,    &sid_size,    // sid를 담을 변수,. 크기
						  domain, &domain_size,
						  &use); // sid의 종류

		cout << "Domain : " << domain << endl;
		cout << "SID 종류 : " << use << endl;

		// sid는 문자열이 아닌 이진 값이 므로 바로 출력할수는 없다.
		// 2진 sid를 문자열 sid로 변경하기. - sddl.h 가 필요..( platform sdk를 설치해야 가능)
		char* temp;
		ConvertSidToStringSid( sid, &temp);// 내부적으로 temp에 메모리할당을 해준다.

		cout << "SID : " << temp << endl;
		LocalFree( temp );
	}
Ejemplo n.º 13
0
bool SetOwnerInternal(LPCWSTR Object, LPCWSTR Owner)
{
	bool Result = false;

	PSID Sid = nullptr;
	//в winapi от mingw.org неправильный тип параметра.
	if(!ConvertStringSidToSid((LPWSTR)Owner, &Sid))
	{
		SID_NAME_USE Use;
		DWORD cSid=0, ReferencedDomain=0;
		LookupAccountName(nullptr, Owner, nullptr, &cSid, nullptr, &ReferencedDomain, &Use);
		if(cSid)
		{
			Sid = LocalAlloc(LMEM_FIXED, cSid);
			if(Sid)
			{
				LPWSTR ReferencedDomainName = new WCHAR[ReferencedDomain];
				if(ReferencedDomainName)
				{
					if(LookupAccountName(nullptr, Owner, Sid, &cSid, ReferencedDomainName, &ReferencedDomain, &Use))
					{
					}
					delete[] ReferencedDomainName;
				}
			}
		}
	}
	if(Sid)
	{
		Privilege TakeOwnershipPrivilege(SE_TAKE_OWNERSHIP_NAME);
		Privilege RestorePrivilege(SE_RESTORE_NAME);
		DWORD dwResult = SetNamedSecurityInfo(const_cast<LPWSTR>(Object), SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, Sid, nullptr, nullptr, nullptr);
		if(dwResult == ERROR_SUCCESS)
		{
			Result = true;
		}
		else
		{
			SetLastError(dwResult);
		}
	}
	if(Sid)
	{
		LocalFree(Sid);
	}
	return Result;
}
Ejemplo n.º 14
0
void getWindowsSID_2 (
	char	*output)
{
	char	computer_name[256];
	SID	*sid;
	SID_NAME_USE snu;
	char	*domain;
	char	*stringsid;
	unsigned long size, domainsize;

	*output = 0;

/* Get the computer name */

	size = sizeof (computer_name);
	if (! GetComputerName ((LPSTR) computer_name, &size)) return;

/* First find the size of buffers required for the SID and domain name */

	sid = 0;
	domain = 0;
	size = domainsize = 0;
	LookupAccountName(0, (LPCSTR) computer_name, sid, &size, domain, &domainsize, &snu);

/* Should have failed with ERROR_INSUFFICIENT_BUFFER */

	if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) return;

/* Allocate memory */

	sid = (SID *) malloc (size);
	domain = (char *) malloc (domainsize);

/* Get the SID */

	if (sid != NULL && domain != NULL &&
	    LookupAccountName (0, (LPCSTR) computer_name, sid, &size, domain, &domainsize, &snu) &&
	    ConvertSidToStringSid(sid, &stringsid)) {
		strcpy (output, stringsid);
		LocalFree (stringsid);
	}

/* Cleanup */

	free (sid);
	free (domain);
}
Ejemplo n.º 15
0
APR_DECLARE(apr_status_t) apr_uid_get(apr_uid_t *uid, apr_gid_t *gid,
                                      const char *username, apr_pool_t *p)
{
#ifdef _WIN32_WCE
    return APR_ENOTIMPL;
#else
    SID_NAME_USE sidtype;
    char anydomain[256];
    char *domain;
    DWORD sidlen = 0;
    DWORD domlen = sizeof(anydomain);
    DWORD rv;
    char *pos;

    if (pos = strchr(username, '/')) {
        domain = apr_pstrndup(p, username, pos - username);
        username = pos + 1;
    }
    else if (pos = strchr(username, '\\')) {
        domain = apr_pstrndup(p, username, pos - username);
        username = pos + 1;
    }
    else {
        domain = NULL;
    }
    /* Get nothing on the first pass ... need to size the sid buffer 
     */
    rv = LookupAccountName(domain, username, domain, &sidlen, 
                           anydomain, &domlen, &sidtype);
    if (sidlen) {
        /* Give it back on the second pass
         */
        *uid = apr_palloc(p, sidlen);
        domlen = sizeof(anydomain);
        rv = LookupAccountName(domain, username, *uid, &sidlen, 
                               anydomain, &domlen, &sidtype);
    }
    if (!sidlen || !rv) {
        return apr_get_os_error();
    }
    /* There doesn't seem to be a simple way to retrieve the primary group sid
     */
    *gid = NULL;
    return APR_SUCCESS;
#endif
}
Ejemplo n.º 16
0
DWORD GetPrincipalSID (
    LPTSTR Principal,
    PSID *Sid)
{
    DWORD sidSize;
    TCHAR refDomain [256];
    DWORD refDomainSize;
    DWORD returnValue;
    SID_NAME_USE snu;

    sidSize = 0;
    refDomainSize = 255;

    LookupAccountName(
        NULL,
        Principal,
        *Sid,
        &sidSize,
        refDomain,
        &refDomainSize,
        &snu);

    returnValue = GetLastError();
    if (returnValue != ERROR_INSUFFICIENT_BUFFER)
    {
        return returnValue;
    }

    *Sid = (PSID) malloc (sidSize);
    refDomainSize = 255;

    if (!LookupAccountName (
            NULL,
            Principal,
            *Sid,
            &sidSize,
            refDomain,
            &refDomainSize,
            &snu))
    {
        return GetLastError();
    }

    return ERROR_SUCCESS;
}
Ejemplo n.º 17
0
BOOL
GetAccountSid(LPTSTR SystemName, LPTSTR AccountName, PSID *Sid) {
	LPTSTR ReferencedDomain = NULL;
	DWORD cbSid = 128;    /* initial allocation attempt */
	DWORD cbReferencedDomain = 16; /* initial allocation size */
	SID_NAME_USE peUse;
	BOOL bSuccess = FALSE; /* assume this function will fail */

	__try {
		/*
		 * initial memory allocations
		 */
		if ((*Sid = HeapAlloc(GetProcessHeap(), 0, cbSid)) == NULL)
			__leave;

		if ((ReferencedDomain = (LPTSTR) HeapAlloc(GetProcessHeap(), 0,
				       cbReferencedDomain)) == NULL) __leave;

		/*
		 * Obtain the SID of the specified account on the specified system.
		 */
		while (!LookupAccountName(SystemName, AccountName, *Sid, &cbSid,
					  ReferencedDomain, &cbReferencedDomain,
					  &peUse))
		{
			if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
				/* reallocate memory */
				if ((*Sid = HeapReAlloc(GetProcessHeap(), 0,
					*Sid, cbSid)) == NULL) __leave;

				if ((ReferencedDomain= (LPTSTR) HeapReAlloc(
					GetProcessHeap(), 0, ReferencedDomain,
					cbReferencedDomain)) == NULL)
				__leave;
			}
			else
				__leave;
		}
		bSuccess = TRUE;
	} /* finally */
	__finally {

		/* Cleanup and indicate failure, if appropriate. */

		HeapFree(GetProcessHeap(), 0, ReferencedDomain);

		if (!bSuccess) {
			if (*Sid != NULL) {
				HeapFree(GetProcessHeap(), 0, *Sid);
				*Sid = NULL;
			}
		}

	}

	return (bSuccess);
}
Ejemplo n.º 18
0
static PSID x_GetAccountSidByName(const string& account, SID_NAME_USE type = (SID_NAME_USE)0)
{
    PSID         sid         = NULL;
    DWORD        sid_size    = 0;
    TXChar*      domain      = NULL;
    DWORD        domain_size = 0;
    SID_NAME_USE use;

    TXString name(_T_XSTRING(account));

    // First call to LookupAccountName() to get the buffer sizes
    if ( !LookupAccountName(NULL, name.c_str(), sid, &sid_size, domain, &domain_size, &use) 
          &&  GetLastError() != ERROR_INSUFFICIENT_BUFFER ) {
        CNcbiError::SetFromWindowsError();
        return NULL;
    }
    try {
        // Allocate buffers
        sid    = (PSID) LocalAlloc(LMEM_FIXED, sid_size);
        domain = (TXChar*) malloc(domain_size * sizeof(TXChar));
        if ( !sid  ||  !domain ) {
            throw(0);
        }
        // Second call to get the actual account info
        if ( !LookupAccountName(NULL, name.c_str(), sid, &sid_size, domain, &domain_size, &use) ) {
            CNcbiError::SetFromWindowsError();
            throw(0);
        }
        // Check type of account
        if (type  &&  type != use ) {
            CNcbiError::Set(CNcbiError::eUnknown);
            throw(0);
        }
    }
    catch (int) {
        LocalFree(sid);
        sid = NULL;
    }
    // Clean up
    if ( domain ) free(domain);

    return sid;
}
Ejemplo n.º 19
0
void GetSid(PSID sid, LPDWORD pSidSize, LPCWSTR accountName)
{
    SID_NAME_USE use;
    WCHAR referencedDomainName[1024];
    DWORD cchReferencedDomainName = sizeof(referencedDomainName) / sizeof(WCHAR);
    if (!LookupAccountName(NULL, accountName, sid, pSidSize, referencedDomainName, &cchReferencedDomainName, &use))
    {
        Win32Exception::ThrowFromLastError();
    }
}
Ejemplo n.º 20
0
bool SetOwnerInternal(const string& Object, const string& Owner)
{
	bool Result = false;

	PSID Sid = nullptr;
	SCOPE_EXIT { LocalFree(Sid); };

	if(!ConvertStringSidToSid(Owner.data(), &Sid))
	{
		SID_NAME_USE Use;
		DWORD cSid=0, ReferencedDomain=0;
		LookupAccountName(nullptr, Owner.data(), nullptr, &cSid, nullptr, &ReferencedDomain, &Use);
		if(cSid)
		{
			Sid = LocalAlloc(LMEM_FIXED, cSid);
			if(Sid)
			{
				std::vector<wchar_t> ReferencedDomainName(ReferencedDomain);
				if(LookupAccountName(nullptr, Owner.data(), Sid, &cSid, ReferencedDomainName.data(), &ReferencedDomain, &Use))
				{
					;
				}
			}
		}
	}
	if(Sid)
	{
		SCOPED_ACTION(Privilege)(SE_TAKE_OWNERSHIP_NAME);
		SCOPED_ACTION(Privilege)(SE_RESTORE_NAME);
		DWORD dwResult = SetNamedSecurityInfo(const_cast<LPWSTR>(Object.data()), SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION, Sid, nullptr, nullptr, nullptr);
		if(dwResult == ERROR_SUCCESS)
		{
			Result = true;
		}
		else
		{
			SetLastError(dwResult);
		}
	}
	return Result;
}
/**
 * Does not closeHandle on the session handle, nor does it perform UnloadUserProfile
 * on the profile handle. The profile handle cannot be unloaded, that would unload
 * the registry keys that we just got the root to. These cleanup flaws are probably acceptable
 * for the Polarizer, which runs for a few minutes before shutting down.
 **/
RegKey getUserRegistryRoot(std::wstring accountName, std::wstring password) {
    HANDLE session;
	if (!LogonUser(accountName.c_str(), NULL, password.c_str(),
				LOGON32_LOGON_INTERACTIVE,
				LOGON32_PROVIDER_DEFAULT,
				&session)) {
        DWORD error = GetLastError();
        printf("LogonUser() failed: %d", error);
        logtools.log(L"LogonUser() failed", error);
        return RegKey::INVALID;
	}
    // Load the pet account's registry hive.
    wchar_t account[128] = {};
    wcsncat(account, accountName.c_str(), 128);
	PROFILEINFO profile = { sizeof(PROFILEINFO), 0, account };
	if (!LoadUserProfile(session, &profile)) {
        printf("LoadUserProfile() failed: %d", GetLastError());
        logtools.log(L"LoadUserProfile() failed", GetLastError());
        return RegKey::INVALID;
	}
    // now the pet hive is loaded, compute the SID so I
    // can get a name for the key that I can use to make a RegKey
    // Can't use the session handle I just got back because it
    // can't be converted to a regkey, either get the name or 
    // give up on using our regkey abstraction.
    BYTE sid[10000];
    DWORD sidSize = 10000;
    DWORD domainSize = 1000;
    wchar_t domain[1000];
    SID_NAME_USE peUse;
    BOOL lookupWorked = LookupAccountName(NULL,accountName.c_str(), sid, 
        &sidSize, domain, &domainSize, &peUse);
    if (lookupWorked) {

        LPTSTR sidNameChars;
        BOOL converted = ConvertSidToStringSidW(sid, &sidNameChars);
        if (converted) {
            std::wstring sidName = sidNameChars;
            RegKey key = RegKey::HKU.open(sidName);
            LocalFree(sidNameChars);
            return key;
        } else {
            logtools.log(L"convert sid to string failed", GetLastError());
            return RegKey::INVALID;
        }
    } else {
        int err = GetLastError();
        logtools.log(L"lookupAccountName failed", err);
        return RegKey::INVALID;
    }
    
    return RegKey::INVALID;
}
Ejemplo n.º 22
0
  static int __stringToSID(char *account, PSID *res, Int *sizeOfRes)
  {
      SID_NAME_USE snu;
      DWORD sizeDom = 0;
      char  sDomain[120];

      sizeDom = sizeof(sDomain);
      if (!LookupAccountName(NULL, account, res, sizeOfRes, sDomain, &sizeDom, &snu)) {
         return -1;
      }
      return 0;
  }
static char * ParseSid(TCHAR * trustee)
{
  PSID pSid = NULL;
  TCHAR * strend = trustee + lstrlen(trustee) - 1;

  if ('(' == *trustee && ')' == *strend)
  {
    *strend = '\0'; 
    ++trustee;

    //pSid = GetBinarySid(trustee);
    if (!ConvertStringSidToSid(trustee, &pSid))
      pSid = NULL;
  }
  else
  {
    DWORD sidLen = 0;
    DWORD domLen = 0;
    TCHAR * domain = NULL;
    SID_NAME_USE use;

    if ((LookupAccountName(NULL, trustee, 
       NULL, &sidLen, NULL, &domLen, &use) ||
       ERROR_INSUFFICIENT_BUFFER == GetLastError()) &&
        NULL != (domain = (TCHAR *)LocalAlloc(LPTR, domLen*sizeof(TCHAR))) &&
      NULL != (pSid = (PSID)LocalAlloc(LPTR, sidLen)))
    {
      if (!LookupAccountName(NULL, trustee, 
        pSid, &sidLen, domain, &domLen, &use))
      {
        LocalFree(pSid);
        pSid = NULL;
      }
    }

    LocalFree(domain);
  }

  return (char *)pSid;
}
Ejemplo n.º 24
0
MIKTEXINTERNALFUNC(bool) ReportMiKTeXEvent(unsigned short eventType, unsigned long eventId, ...)
{
#if ! REPORT_EVENTS
  UNUSED_ALWAYS(eventType);
  UNUSED_ALWAYS(eventId);
  return false;
#else
  vector<const char *> vecStrings;
  va_list marker;
  va_start(marker, eventId);
  for (const char * lpsz = va_arg(marker, const char *);
  lpsz != nullptr;
    lpsz = va_arg(marker, const char *))
  {
    vecStrings.push_back(lpsz);
  }
  va_end(marker);

  HANDLE hEventSource = RegisterEventSource(0, SOURCE);
  if (hEventSource == nullptr)
  {
    return false;
  }

  PSID pSid = 0;
  size_t bufSize = 8192;
  AutoMemoryPointer pBuf(malloc(bufSize));
  if (pBuf.Get() == nullptr)
  {
    OUT_OF_MEMORY("malloc");
  }
  char szAccountName[BufferSizes::MaxPath];
  unsigned long n = BufferSizes::MaxPath;
  if (GetUserName(szAccountName, &n))
  {
    unsigned long sidSize = static_cast<unsigned long>(bufSize);
    pSid = reinterpret_cast<PSID>(pBuf.Get());
    char szDomainName[BufferSizes::MaxPath];
    unsigned long domainNameSize = BufferSizes::MaxPath;
    SID_NAME_USE use;
    if (!LookupAccountName(0, szAccountName, pSid, &sidSize, szDomainName, &domainNameSize, &use))
    {
      pSid = 0;
    }
  }
  BOOL done =
    ReportEvent(hEventSource, eventType, 0, eventId, pSid, static_cast<unsigned short>(vecStrings.size()), 0, &vecStrings[0], 0);
  DeregisterEventSource(hEventSource);

  return done ? true : false;
#endif
}
Ejemplo n.º 25
0
BOOL kull_m_token_getSidDomainFromName(PCWSTR pName, PSID * pSid, PWSTR * pDomain, PSID_NAME_USE pSidNameUse, LPCWSTR system)
{
	BOOL result = FALSE;
	SID_NAME_USE sidNameUse;
	PSID_NAME_USE peUse = pSidNameUse ? pSidNameUse : &sidNameUse;
	DWORD cbSid = 0, cchReferencedDomainName = 0;
	
	if(!LookupAccountName(system, pName, NULL, &cbSid, NULL, &cchReferencedDomainName, peUse) && (GetLastError() == ERROR_INSUFFICIENT_BUFFER))
	{
		if(*pSid = (PSID) LocalAlloc(LPTR, cbSid * sizeof(wchar_t)))
		{
			if(*pDomain = (PWSTR) LocalAlloc(LPTR, cchReferencedDomainName * sizeof(wchar_t)))
			{
				result = LookupAccountName(system, pName, *pSid, &cbSid, *pDomain, &cchReferencedDomainName, peUse);
				if(!result)
					*pDomain = (PWSTR) LocalFree(*pDomain);
			}
			if(!result)
				*pSid = (PSID) LocalFree(*pSid);
		}
	}
	return result;
}
Ejemplo n.º 26
0
PSID convert_jsstring_to_sid(JSContext * cx, JSString * curMemberString, DWORD * errorCode)
{
	PSID curMember;
	if(!ConvertStringSidToSid((LPWSTR)JS_GetStringChars(curMemberString), &curMember))
	{
		DWORD sidSize = 0, cbDomain;
		SID_NAME_USE peUse;
		*errorCode = GetLastError();
		JS_YieldRequest(cx);
		if(!LookupAccountName(NULL, (LPWSTR)JS_GetStringChars(curMemberString), NULL, &sidSize, NULL, &cbDomain, &peUse) && GetLastError() != ERROR_INSUFFICIENT_BUFFER)
		{
			*errorCode = GetLastError();
			return NULL;
		}
		curMember = (PSID)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sidSize);
		JS_YieldRequest(cx);
		LPTSTR domainName = (LPTSTR)HeapAlloc(GetProcessHeap(), 0, cbDomain * sizeof(TCHAR));
		if(!LookupAccountName(NULL, (LPWSTR)JS_GetStringChars(curMemberString), curMember, &sidSize, domainName, &cbDomain, &peUse))
		{
			*errorCode = GetLastError();
			HeapFree(GetProcessHeap(), 0, curMember);
			HeapFree(GetProcessHeap(), 0, domainName);
			return NULL;
		}
		HeapFree(GetProcessHeap(), 0, domainName);
		*errorCode = ERROR_SUCCESS;
	}
	else
	{
		DWORD sidSize = GetLengthSid(curMember);
		PSID retMember = (PSID)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sidSize);
		CopySid(sidSize, retMember, curMember);
		LocalFree(curMember);
		curMember = retMember;
	}
	return curMember;
}
//------------------------------------------------------------------------------
//local function part !!!
//------------------------------------------------------------------------------
void GetSIDFromUser(char *user, char* rid, char *sid, unsigned int max_size)
{
  BYTE BSid[MAX_PATH];
  PSID psid       = (PSID)BSid;
  DWORD sid_size  = MAX_PATH;
  SID_NAME_USE TypeSid;

  char domain[MAX_PATH];
  DWORD domain_size = MAX_PATH;

  if(LookupAccountName(NULL,(LPCTSTR)user,psid,(LPDWORD)&sid_size,(LPTSTR)domain,(LPDWORD)&domain_size,(PSID_NAME_USE)&TypeSid))
  {
    if (IsValidSid(psid))SidtoUser(psid, user, rid, sid, max_size);
  }
}
Ejemplo n.º 28
0
PSID name_to_PSID(char *name)
{
	SID_NAME_USE snu;
	char	*sidbuf, domainname[512];
	DWORD	sidlen, dnamelen;

	sidlen = 512;
	sidbuf = (char*)calloc(1, sidlen);
	dnamelen = sizeof(domainname);
	if ( FALSE==LookupAccountName(NULL, name, sidbuf, &sidlen,
		domainname, &dnamelen, &snu) ) {
			free(sidbuf);
			return	NULL;
		}
		return	(PSID) sidbuf;
}
Ejemplo n.º 29
0
int LSAUserCommand::executeCommand(LSA_HANDLE handle) {    
  CString accountName = CreateFormatted(L"%s", mySettings->getUserName());

  const DWORD sz = 2044;
  PSID sid = (PSID)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sz + 1);  
  TCHAR foundDomain[sz+1];
  DWORD psz = sz;
  DWORD pdz = sz;
  SID_NAME_USE use = SidTypeUser;

  LOG.LogDebug(L"Call LookupAccountName");
  if (0 == LookupAccountName(NULL, accountName, sid, &psz, foundDomain, &pdz, &use)) {
    LOG.LogErrorFormat(L"Failed to LookupAccountName. %s", LOG.GetLastError());
    return 1;
  }

  foundDomain[pdz] = L'\0';
  LOG.LogDebugFormat(L"LSA Policy opened: Domain %s", foundDomain);
  return executeCommand(handle, sid);
}
Ejemplo n.º 30
0
static int
iwin32_get_sid (const char *name, PSID *ext_sid)
{
  char domain [BUFFER_SIZE];
  DWORD domain_size = BUFFER_SIZE;
  DWORD sid_size    = BUFFER_SIZE;
  SID *sid;
  SID_NAME_USE account_type;

  assert (name    != NULL);
  assert (ext_sid != NULL);

  sid = malloc (sid_size);
  if (!sid) return 0;

  if (!LookupAccountName (NULL, name, sid, &sid_size,
    domain, &domain_size, &account_type)) return 0;

  *ext_sid = sid;
  return 1;
}