Пример #1
0
BOOLEAN GetInfo
(JNIEnv * jenv, PSID sid, LPSTR* ppName, LPSTR* ppDomain) 
{
	PORT_ACCESS_FROM_ENV (jenv);

	DWORD dwNameSize = 0;
	DWORD dwDomainNameSize = 0;
	SID_NAME_USE snu;
	if( !LookupAccountSid(NULL, sid, NULL, &dwNameSize, NULL, &dwDomainNameSize, &snu)) {
		if( ERROR_INSUFFICIENT_BUFFER != GetLastError() ) {
			return FALSE;
		}
	}
	*ppName = (LPSTR)hymem_allocate_memory(dwNameSize);
	if( NULL == ppName ) {
		return FALSE;
	}
	*ppDomain = (LPSTR)hymem_allocate_memory(dwDomainNameSize);
	if( NULL == ppName ) {
		DWORD err = GetLastError();
		hymem_free_memory(*ppName);
		SetLastError(err);
		return FALSE;
	}
	if( !LookupAccountSid(NULL, sid, *ppName, &dwNameSize, *ppDomain, &dwDomainNameSize, &snu)) {
		DWORD err = GetLastError();
		hymem_free_memory(*ppName);
		hymem_free_memory(*ppDomain);
		SetLastError(err);
		return FALSE;
	}

	return TRUE;
}
Пример #2
0
static bool SidToName(PSID Sid, string& Name, const string& Computer)
{
	bool Result = false;
	DWORD AccountLength=0,DomainLength=0;
	SID_NAME_USE snu;
	LookupAccountSid(Computer.data(), Sid, nullptr, &AccountLength, nullptr, &DomainLength, &snu);
	if (AccountLength && DomainLength)
	{
		wchar_t_ptr AccountName(AccountLength);
		wchar_t_ptr DomainName(DomainLength);
		if(LookupAccountSid(Computer.data(), Sid, AccountName.get(), &AccountLength, DomainName.get(), &DomainLength, &snu))
		{
			Name.assign(DomainName.get(), DomainLength).append(L"\\").append(AccountName.get(), AccountLength);
			Result = true;
		}
	}
	else
	{
		LPWSTR StrSid;
		if(ConvertSidToStringSid(Sid, &StrSid))
		{
			Name = StrSid;
			LocalFree(StrSid);
			Result = true;
		}
	}
	return Result;
}
Пример #3
0
	std::wstring userSID() const {
		if (pevlr_->UserSidOffset == 0)
			return L" ";
		PSID p = NULL; // = reinterpret_cast<const void*>(reinterpret_cast<const BYTE*>(pevlr_) + + pevlr_->UserSidOffset);
		DWORD userLen = 0;
		DWORD domainLen = 0;
		SID_NAME_USE sidName;

		LookupAccountSid(NULL, p, NULL, &userLen, NULL, &domainLen, &sidName);
		LPTSTR user = new TCHAR[userLen + 10];
		LPTSTR domain = new TCHAR[domainLen + 10];

		LookupAccountSid(NULL, p, user, &userLen, domain, &domainLen, &sidName);
		user[userLen] = 0;
		domain[domainLen] = 0;
		std::wstring ustr = user;
		std::wstring dstr = domain;
		delete[] user;
		delete[] domain;
		if (!dstr.empty())
			dstr = dstr + L"\\";
		if (ustr.empty() && dstr.empty())
			return L"missing";

		return dstr + ustr;
	}
Пример #4
0
int get_account_sid(PSID pSid,char * account,size_t acclen,
		    SID_NAME_USE * peUse)
{
  DWORD dwAccountLen = 0;
  DWORD dwDomainLen = 0;
  char * szAccountName = NULL;
  char * szDomainName = NULL;
  DWORD dwRetLen = 0;
  

  LookupAccountSid(NULL,pSid,
		   szAccountName,&dwAccountLen,
		   szDomainName,&dwDomainLen,
		   peUse);


  szAccountName = (char *) malloc(dwAccountLen);

  if (szAccountName == NULL){
    SetLastError(ERROR_OUTOFMEMORY);
    return (-1);
  }

  szDomainName = (char *) malloc(dwDomainLen);

  if (szDomainName == NULL){
    free(szAccountName);
    SetLastError(ERROR_OUTOFMEMORY);
    return (-1);
  }

  if (0 == LookupAccountSid(NULL,pSid,
			    szAccountName,&dwAccountLen,
			    szDomainName,&dwDomainLen,
			    peUse)){
    if (GetLastError() == ERROR_NONE_MAPPED){
      get_textual_sid(pSid,account,acclen);
      goto free_mem;
    }
    free(szAccountName);
    free(szDomainName);
    return (-1);
  }



  if (dwDomainLen <= 1)
    _snprintf(account,acclen,"%s",szAccountName);
  else
    _snprintf(account,acclen,"%s\\%s",szDomainName,szAccountName);
  
  
 free_mem:
  free(szAccountName);
  free(szDomainName);

  return (0);
}
Пример #5
0
static void PrintUserName(PDOKAN_FILE_INFO DokanFileInfo) {
  HANDLE handle;
  UCHAR buffer[1024];
  DWORD returnLength;
  WCHAR accountName[256];
  WCHAR domainName[256];
  DWORD accountLength = sizeof(accountName) / sizeof(WCHAR);
  DWORD domainLength = sizeof(domainName) / sizeof(WCHAR);
  PTOKEN_USER tokenUser;
  SID_NAME_USE snu;

  handle = DokanOpenRequestorToken(DokanFileInfo);
  if (handle == INVALID_HANDLE_VALUE) {
    DbgPrint(L"  DokanOpenRequestorToken failed\n");
    return;
  }

  if (!GetTokenInformation(handle, TokenUser, buffer, sizeof(buffer),
                           &returnLength)) {
    DbgPrint(L"  GetTokenInformaiton failed: %d\n", GetLastError());
    CloseHandle(handle);
    return;
  }

  CloseHandle(handle);

  tokenUser = (PTOKEN_USER)buffer;
  if (!LookupAccountSid(NULL, tokenUser->User.Sid, accountName, &accountLength,
                        domainName, &domainLength, &snu)) {
    DbgPrint(L"  LookupAccountSid failed: %d\n", GetLastError());
    return;
  }

  DbgPrint(L"  AccountName: %s, DomainName: %s\n", accountName, domainName);
}
Пример #6
0
HRESULT GetProcessToken(DWORD dwProcessID, LPHANDLE token, DWORD nUserNameMax, LPWSTR szwUserName, DWORD nUserDomainMax, LPWSTR szwUserDomain) {
	HANDLE hProcess=OpenProcess(PROCESS_DUP_HANDLE|PROCESS_QUERY_INFORMATION,TRUE,dwProcessID); 
	if (!hProcess) throw std::runtime_error("OpenProcess failed");
	HRESULT retval = S_OK;
	HANDLE hToken = INVALID_HANDLE_VALUE;
	if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE | TOKEN_QUERY, &hToken)) retval = HRESULT_FROM_WIN32(GetLastError());
	else {
		BYTE buf[MAX_PATH]; DWORD dwRead = 0;
		if (!GetTokenInformation(hToken, TokenUser, buf, MAX_PATH, &dwRead)) retval = HRESULT_FROM_WIN32(GetLastError());
		else {
			TOKEN_USER *puser = reinterpret_cast<TOKEN_USER*>(buf);
			SID_NAME_USE eUse;
			if (!LookupAccountSid(NULL, puser->User.Sid, szwUserName, &nUserNameMax, szwUserDomain, &nUserDomainMax, &eUse))
				retval = HRESULT_FROM_WIN32(GetLastError());
			}
		if (FAILED(retval)) return retval;
		if (!DuplicateTokenEx(hToken, 
			TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE, 
			NULL, SecurityImpersonation, TokenPrimary,token))
			retval = HRESULT_FROM_WIN32(GetLastError());
		else  retval = S_OK;
		CloseHandle(hToken);
		}
	return retval;
}
Пример #7
0
int GetFileOwner (const char *Computer, const char *Name, char *Owner)
{
    SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION;
    SECURITY_DESCRIPTOR *sd;
    char sddata[500];
    *Owner=0;
    sd=(SECURITY_DESCRIPTOR *)sddata;

    char AnsiName[NM];
    OemToChar(Name,AnsiName);
    SetFileApisToANSI();
    DWORD Needed;
    int GetCode=GetFileSecurity(AnsiName,si,sd,sizeof(sddata),&Needed);
    SetFileApisToOEM();

    if (!GetCode || (Needed>sizeof(sddata)))
        return(FALSE);
    PSID pOwner;
    BOOL OwnerDefaulted;
    if (!GetSecurityDescriptorOwner(sd,&pOwner,&OwnerDefaulted))
        return(FALSE);
    char AccountName[200],DomainName[200];
    DWORD AccountLength=sizeof(AccountName),DomainLength=sizeof(DomainName);
    SID_NAME_USE snu;
    if (!LookupAccountSid(Computer,pOwner,AccountName,&AccountLength,DomainName,&DomainLength,&snu))
        return(FALSE);
    CharToOem(AccountName,Owner);
    return(TRUE);
}
Пример #8
0
BOOL FormatUserName(PSID sid, TCHAR *userName, size_t cchMax)
{
    BOOL success = FALSE;

    TCHAR accountName[512];
    DWORD accountNameLength = SIZEOF_ARRAY(accountName);
    TCHAR domainName[512];
    DWORD domainNameLength = SIZEOF_ARRAY(domainName);
    SID_NAME_USE eUse;
    BOOL bRet = LookupAccountSid(NULL, sid, accountName, &accountNameLength,
                                 domainName, &domainNameLength, &eUse);

    if(bRet)
    {
        StringCchPrintf(userName, cchMax, _T("%s\\%s"), domainName, accountName);
        success = TRUE;
    }
    else
    {
        LPTSTR stringSid;
        bRet = ConvertSidToStringSid(sid, &stringSid);

        if(bRet)
        {
            StringCchCopy(userName, cchMax, stringSid);

            LocalFree(stringSid);
            success = TRUE;
        }
    }

    return success;
}
Пример #9
0
CToolDumper::CSelectProcessDialog::CListElement::CListElement(PROCESSENTRY32* pProcess)
{
	//запомнить информацию
	mProcessID=pProcess->th32ProcessID;
	mParentProcessID=pProcess->th32ParentProcessID;
	_tcscpy(mszBaseName,pProcess->szExeFile);

	//получить дополнительную информацию
	HANDLE hProcess=OpenProcess(PROCESS_QUERY_INFORMATION,FALSE,mProcessID);
	//флаг успеха получения информации об учётной записи
	BOOL AccountResulted=FALSE;
	if(hProcess)
	{
		//получить полное имя файла процесса
		GetProcessImageFileName(hProcess,mszFullName,(MAX_PATH-1)*sizeof(TCHAR));
		mszFullName[MAX_PATH-1]=0;

		//получить информацию об использовании памяти процессом
		mMemoryInfoExist=GetProcessMemoryInfo(hProcess,&mMemoryInfo,sizeof(mMemoryInfo));

		//получить маркер защиты процесса
		HANDLE hProcessToken;
		if(OpenProcessToken(hProcess,TOKEN_QUERY,&hProcessToken))
		{
			//получить информацию о пользователе
			DWORD NeededSize;
			if(!GetTokenInformation(hProcessToken,TokenUser,NULL,0,&NeededSize))
			{
				TOKEN_USER* pUserInfo=(TOKEN_USER*)new BYTE[NeededSize];
				if(GetTokenInformation(hProcessToken,TokenUser,pUserInfo,NeededSize,&NeededSize))
				{
					//получить имя учётной записи, под которой работает процесс
					DWORD AccountNameLength=MAX_PATH;
					DWORD AccountDomainNameLength=MAX_PATH;
					SID_NAME_USE AccountUse;
					if(LookupAccountSid(NULL,pUserInfo->User.Sid,mszAccountName,&AccountNameLength,mszAccountDomainName,&AccountDomainNameLength,&AccountUse))
						//установить флаг результата
						AccountResulted=TRUE;
				}
				delete [] (BYTE*)pUserInfo;
			}

			CloseHandle(hProcessToken);
		}

		//закрыть описатель процесса
		CloseHandle(hProcess);
	}
	else
	{
		mszFullName[0]=0;
		mMemoryInfoExist=FALSE;
	}
	//если неудача с получением имени учётной записи, очистить строки
	if(!AccountResulted)
	{
		mszAccountName[0]=0;
		mszAccountDomainName[0]=0;
	}
}
Пример #10
0
void Helpers::GetCurrentUserAndDomain(std::wstring& strUser, std::wstring& strDomain)
{
	std::unique_ptr<void, CloseHandleHelper> hToken(nullptr);

	{
		HANDLE _hToken = nullptr;

		if ( !::OpenProcessToken(
			::GetCurrentProcess(),
			TOKEN_QUERY,
			&_hToken) )
		{
			Win32Exception::ThrowFromLastError("OpenProcessToken");
		}

		hToken.reset(_hToken);
	}

	DWORD dwReturnLength = 0;

	if ( !::GetTokenInformation(
		hToken.get(),
		TokenUser,
		nullptr,
		0,
		&dwReturnLength ) )
	{
		if( GetLastError() != ERROR_INSUFFICIENT_BUFFER )
			Win32Exception::ThrowFromLastError("GetTokenInformation");
	}

	std::unique_ptr<BYTE[]> tu(new BYTE[dwReturnLength]);

	if ( !::GetTokenInformation(
		hToken.get(),
		TokenUser,
		tu.get(),
		dwReturnLength,
		&dwReturnLength ) )
	{
			Win32Exception::ThrowFromLastError("GetTokenInformation");
	}

	wchar_t szUser[CRED_MAX_STRING_LENGTH + 1] = L"";
	wchar_t szDomain[CRED_MAX_STRING_LENGTH + 1] = L"";
	DWORD dwUserLen = static_cast<DWORD>(ARRAYSIZE(szUser));
	DWORD dwDomainLen = static_cast<DWORD>(ARRAYSIZE(szDomain));
	SID_NAME_USE snu;

	// Retrieve user name and domain name based on user's SID.
	if( !LookupAccountSid(NULL, reinterpret_cast<TOKEN_USER*>(tu.get())->User.Sid, szUser, &dwUserLen, szDomain, &dwDomainLen, &snu) )
	{
		Win32Exception::ThrowFromLastError("LookupAccountSid");
	}

	strUser = szUser;
	strDomain = szDomain;
}
Пример #11
0
CString CAppBarManager::GetCurrentUserName(LPTSTR lpstrAppName)
{   
	HANDLE hToken;   

	// 得到shell的token   
	if(!GetTokenByName(hToken, lpstrAppName))   
	{   
		return FALSE;   
	}   
	DWORD cbti = 0;   
	PTOKEN_USER ptiUser = NULL;   
	SID_NAME_USE snu;   

	// 取得所需空间大小   
	if (GetTokenInformation(hToken, TokenUser, NULL, 0, &cbti))     
	{   
		CloseHandle(hToken);   
		return FALSE;   
	}   

	// 分配空间   
	ptiUser = (PTOKEN_USER) HeapAlloc(GetProcessHeap(), 0, cbti);   
	if(!ptiUser)   
	{   
		CloseHandle(hToken);   
		return FALSE;   
	}   

	// 取得token信息   
	if (!GetTokenInformation(hToken, TokenUser, ptiUser, cbti, &cbti))   
	{   
		CloseHandle(hToken);   
		HeapFree(GetProcessHeap(), 0, ptiUser);   
		return FALSE;   
	}   

	TCHAR szUser[MAX_PATH];   
	TCHAR szDomain[MAX_PATH];   
	DWORD nUser = MAX_PATH;   
	DWORD nDomain = MAX_PATH;   

	// 根据用户的sid得到用户名和domain   
	if (!LookupAccountSid(NULL, ptiUser->User.Sid, szUser, &nUser,     
		szDomain, &nDomain, &snu))   
	{   
		CloseHandle(hToken);   
		HeapFree(GetProcessHeap(), 0, ptiUser);   
		return FALSE;   
	}   

	CloseHandle(hToken);   
	HeapFree(GetProcessHeap(), 0, ptiUser);

	CString strUserName(szUser);

	return strUserName;
}   
Пример #12
0
bool Win32::ProcessInfo::GetUserAndDomainName(CString& cszUsername, CString& cszRefDomainName)
{
   HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, m_dwProcessId);
   if (hProcess == NULL)
      return false;

   bool bRet = false;
   HANDLE hProcessToken = NULL;
   if (TRUE == OpenProcessToken(hProcess, TOKEN_QUERY, &hProcessToken))
   {
      // get length
      DWORD nLength = 0;
      GetTokenInformation(hProcessToken, TokenUser, NULL, 0, &nLength);

      std::vector<BYTE> vecData(nLength);
      TOKEN_USER* pTokenUser = (TOKEN_USER*)&vecData[0];

      if (TRUE == GetTokenInformation(hProcessToken, TokenUser, pTokenUser, nLength, &nLength))
      {
         DWORD cchName = 0, cchReferencedDomainName = 0;
         LookupAccountSid(NULL, pTokenUser->User.Sid, NULL, &cchName, NULL, &cchReferencedDomainName, NULL);

         // for some unknown reason the direct use of the output parameters don't work, so use
         // local objects here and assign later
         CString cszUsernameL, cszRefDomainNameL;
         SID_NAME_USE eUse;
         LookupAccountSid(NULL, pTokenUser->User.Sid,
            cszUsernameL.GetBuffer(cchName), &cchName,
            cszRefDomainNameL.GetBuffer(cchReferencedDomainName), &cchReferencedDomainName,
            &eUse);

         cszUsernameL.ReleaseBuffer();
         cszRefDomainNameL.ReleaseBuffer();

         cszUsername = cszUsernameL;
         cszRefDomainName = cszRefDomainNameL;
         bRet = true;
      }

      CloseHandle(hProcessToken);
   }

   return bRet;
}
Пример #13
0
/* ask a server to translate a SID into a textual representation */
static gunichar2*
GetSidName (gunichar2 *server, PSID sid, gint32 *size)
{
    gunichar2 *uniname = NULL;
    DWORD cchName = 0;
    DWORD cchDomain = 0;
    SID_NAME_USE peUse; /* out */

    LookupAccountSid (server, sid, NULL, &cchName, NULL,
                      &cchDomain, &peUse);

    if ((cchName > 0) && (cchDomain > 0)) {
        gunichar2 *user = g_malloc0 ((cchName + 1) * 2);
        gunichar2 *domain = g_malloc0 ((cchDomain + 1) * 2);

        LookupAccountSid (server, sid, user, &cchName, domain,
                          &cchDomain, &peUse);

        if (cchName > 0) {
            if (cchDomain > 0) {
                /* domain/machine name included (+ sepearator) */
                *size = cchName + cchDomain + 1;
                uniname = g_malloc0 ((*size + 1) * 2);
                memcpy (uniname, domain, cchDomain * 2);
                *(uniname + cchDomain) = '\\';
                memcpy (uniname + cchDomain + 1, user, cchName * 2);
                g_free (user);
            }
            else {
                /* no domain / machine */
                *size = cchName;
                uniname = user;
            }
        }
        else {
            /* nothing -> return NULL */
            g_free (user);
        }

        g_free (domain);
    }

    return uniname;
}
Пример #14
0
CxDlgAccountPassword::CxDlgAccountPassword(CWnd* pParent /*=NULL*/)
	: CDialog(CxDlgAccountPassword::IDD, pParent)
{
	HANDLE     hProcess, hAccessToken;
	DWORD      dwInfoBufferSize, dwDomainSize =1024;
	TCHAR      tchszUser   [1024];
	TCHAR      tchszDomain [1024];
	DWORD      dwUserNameLen = sizeof(tchszUser);
	TCHAR      InfoBuffer[1000];
	PTOKEN_USER pTokenUser = (PTOKEN_USER)InfoBuffer;
	SID_NAME_USE snu;

	//
	// Get the domain name that this user is logged on to. This could
	// also be the local machine name.
	CString strAccount = _T("");
	hProcess = GetCurrentThread();
	if (!OpenThreadToken (hProcess,TOKEN_QUERY, TRUE, &hAccessToken))
	{
		if(GetLastError() == ERROR_NO_TOKEN) 
		{
			// attempt to open the process token, since no thread token
			// exists
			BOOL bOk = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hAccessToken);
		}
	}
	if (GetTokenInformation(hAccessToken, TokenUser, InfoBuffer, 1000, &dwInfoBufferSize))
	{
		tchszDomain[0] = _T('\0');
		if (LookupAccountSid(NULL, pTokenUser->User.Sid, tchszUser, &dwUserNameLen, tchszDomain, &dwDomainSize, &snu))
		{
			if (tchszDomain[0])
			{
				//
				// Use the account name of form "DomainName\UserName"
				if (B_ACCOUNT_CURRENT_USER)
					strAccount.Format (_T("%s\\%s"), tchszDomain, tchszUser);
				else
					strAccount.Format (_T("%s\\%s"), tchszDomain, _T("ingres"));
			}
			else
			{
				strAccount = B_ACCOUNT_CURRENT_USER? tchszUser: _T("ingres");
			}
		}
	}

	//{{AFX_DATA_INIT(CxDlgAccountPassword)
	m_strAccount = _T("");
	m_strPassword = _T("");
	m_strConfirmPassword = _T("");
	//}}AFX_DATA_INIT
	m_strAccount = strAccount;
}
Пример #15
0
//author: yy2better
//email: [email protected]
//获取进程的用户名
BOOL CSecurityTool::GetProcessUser(DWORD dwProcessID, TCHAR *szUserName, DWORD nNameLen)
{
	BOOL fResult  = FALSE;
    HANDLE hProc  = NULL;
	HANDLE hToken = NULL;
	TOKEN_USER *pTokenUser = NULL;
	
	__try
	{
        // Open the process with PROCESS_QUERY_INFORMATION access
        hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, dwProcessID);
        if (hProc == NULL)
		{
			__leave;
		}
        fResult = OpenProcessToken(hProc, TOKEN_QUERY, &hToken);
        if(!fResult)  
		{
			__leave;
		}
		
		DWORD dwNeedLen = 0;		
		fResult = GetTokenInformation(hToken,TokenUser, NULL, 0, &dwNeedLen);
		if (dwNeedLen > 0)
		{
			pTokenUser = (TOKEN_USER*)new BYTE[dwNeedLen];
			fResult = GetTokenInformation(hToken,TokenUser, pTokenUser, dwNeedLen, &dwNeedLen);
			if (!fResult)
			{
				__leave;
			}
		}
		else
		{
			__leave;
		}

		SID_NAME_USE sn;
		TCHAR szDomainName[MAX_PATH];
		DWORD dwDmLen = MAX_PATH;
		fResult = LookupAccountSid(NULL, pTokenUser->User.Sid, szUserName, &nNameLen,
			szDomainName, &dwDmLen, &sn);
	}
	__finally
	{
		if (hProc)
			::CloseHandle(hProc);
		if (hToken)
			::CloseHandle(hToken);
		if (pTokenUser)
			delete[] (char*)pTokenUser;		
	}
	return fResult;
}
Пример #16
0
	SIDCacheItem(const wchar_t *Computer,PSID InitSID)
	{
		Sid=xf_malloc(GetLengthSid(InitSID));
		if(Sid)
		{
			if(CopySid(GetLengthSid(InitSID),Sid,InitSID))
			{
				DWORD AccountLength=0,DomainLength=0;
				SID_NAME_USE snu;
				LookupAccountSid(Computer,Sid,nullptr,&AccountLength,nullptr,&DomainLength,&snu);
				if (AccountLength && DomainLength)
				{
					string strAccountName,strDomainName;
					LPWSTR AccountName=strAccountName.GetBuffer(AccountLength);
					LPWSTR DomainName=strDomainName.GetBuffer(DomainLength);
					if (AccountName && DomainName)
					{
						if(LookupAccountSid(Computer,Sid,AccountName,&AccountLength,DomainName,&DomainLength,&snu))
						{
							strUserName=string(DomainName).Append(L"\\").Append(AccountName);
						}
					}
				}
				else
				{
					LPWSTR StrSid;
					if(ConvertSidToStringSid(Sid, &StrSid))
					{
						strUserName = StrSid;
						LocalFree(StrSid);
					}
				}
			}
		}

		if(strUserName.IsEmpty())
		{
			xf_free(Sid);
			Sid=nullptr;
		}
	}
void vncExportACL::PrintSid(PSID psid)
{
    TCHAR name[256], domain[256];
    DWORD cbname = sizeof name, cbdomain = sizeof domain, rc;
    SID_NAME_USE sidUse;

    //!! next line has hardcoded server name !!
    // NULL server name is usually appropriate, though.
    if (LookupAccountSid(NULL, psid, name, &cbname, domain, &cbdomain, &sidUse))
    {
        //Todo: Check if WellKnownSID and reserve special names for them.

        /*		switch ( sidUse )
        		{
        			case SidTypeWellKnownGroup:	type = "well-known group"; break;
        			default:					type = "bad sidUse value"; break;
        		}
        */
        LPWKSTA_INFO_100 wkstainfo = NULL;
        NET_API_STATUS nStatus;
        TCHAR langroup[MAXLEN];
        TCHAR computername[MAXLEN];

        nStatus = NetWkstaGetInfo( 0 , 100 , (LPBYTE *) &wkstainfo);
        if (nStatus == NERR_Success) {
            _tcsncpy(langroup, wkstainfo->wki100_langroup, MAXLEN);
            _tcsncpy(computername, wkstainfo->wki100_computername, MAXLEN);
            langroup[MAXLEN - 1] = _T('\0');
            computername[MAXLEN - 1] = _T('\0');
            // replace computername with a dot
            if (_tcsicmp(computername, domain) == 0)
                _tcscpy(domain,_T("."));
            else if (_tcsicmp(langroup, domain) == 0)
                _tcscpy(domain, _T(".."));
        }
        else
            _tprintf(_T("NetWkstaGetInfo() returned %lu \n"), wkstainfo);

        NetApiBufferFree(wkstainfo);
        wkstainfo = NULL;

        // If domain or username contains whitespace, print enclosing quotes
        if (_tcschr(domain, _T(' ')) || _tcschr(name, _T(' ')))
            _tprintf(_T("\"%s%s%s\"\n"), domain, (domain == 0 || *domain == _T('\0'))? _T(""): _T("\\"), name);
        else
            _tprintf(_T("%s%s%s\n"), domain, (domain == 0 || *domain == _T('\0'))? _T(""): _T("\\"), name);
    }
    else
    {
        rc = GetLastError();
        _tprintf(_T("[%s] *** error %lu\n"), SidToText( psid ), rc);
    }
}
Пример #18
0
  static int __SIDToString(PSID sid, char *res, Int *sizeOfRes)
  {
      SID_NAME_USE snu;
      DWORD sizeDom = 0;
      char  sDomain[120];

      sizeDom = sizeof(sDomain);
      if (!LookupAccountSid(NULL, sid, res, sizeOfRes, sDomain, &sizeDom, &snu)) {
         res[0] = 0;
         return -1;
      }
      return 0;
  }
Пример #19
0
BOOL kull_m_token_getNameDomainFromSID(PSID pSid, PWSTR * pName, PWSTR * pDomain, PSID_NAME_USE pSidNameUse, LPCWSTR system)
{
	BOOL result = FALSE;
	SID_NAME_USE sidNameUse;
	PSID_NAME_USE peUse = pSidNameUse ? pSidNameUse : &sidNameUse;
	DWORD cchName = 0, cchReferencedDomainName = 0;
	
	if(!LookupAccountSid(system, pSid, NULL, &cchName, NULL, &cchReferencedDomainName, peUse) && (GetLastError() == ERROR_INSUFFICIENT_BUFFER))
	{
		if(*pName = (PWSTR) LocalAlloc(LPTR, cchName * sizeof(wchar_t)))
		{
			if(*pDomain = (PWSTR) LocalAlloc(LPTR, cchReferencedDomainName * sizeof(wchar_t)))
			{
				result = LookupAccountSid(system, pSid, *pName, &cchName, *pDomain, &cchReferencedDomainName, peUse);
				if(!result)
					*pDomain = (PWSTR) LocalFree(*pDomain);
			}
			if(!result)
				*pName = (PWSTR) LocalFree(*pName);
		}
	}
	return result;
}
Пример #20
0
/* given a access token, find the domain name of user account of the access token */
int GetDomainFromToken ( HANDLE *hAccessToken, UCHAR *domain, DWORD dwSize)
{
   UCHAR InfoBuffer[1000],username[200];
   PTOKEN_USER pTokenUser = (PTOKEN_USER)InfoBuffer;
   DWORD dwInfoBufferSize,dwAccountSize = 200, dwDomainSize = dwSize;
   SID_NAME_USE snu;

   domain[0] = '\0' ;
   GetTokenInformation(*hAccessToken,TokenUser,InfoBuffer,
						1000, &dwInfoBufferSize);

   LookupAccountSid(NULL, pTokenUser->User.Sid, (LPSTR)username,
				        &dwAccountSize,(LPSTR)domain, &dwDomainSize, &snu);
   return 0;
}
Пример #21
0
bool
GetConsoleUser(char *buffer, UINT size)
{

	HANDLE hProcess,hPToken;
	DWORD dwExplorerLogonPid=GetExplorerLogonPid();
	if (dwExplorerLogonPid==0) 
	{
		strcpy(buffer,"");
		return 0;
	}
	hProcess = OpenProcess(MAXIMUM_ALLOWED,FALSE,dwExplorerLogonPid);

   if(!::OpenProcessToken(hProcess,TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY
                                    |TOKEN_DUPLICATE|TOKEN_ASSIGN_PRIMARY|TOKEN_ADJUST_SESSIONID
                                    |TOKEN_READ|TOKEN_WRITE,&hPToken))
		{     
			   strcpy(buffer,"");
			   CloseHandle(hProcess);
			   return 0 ;
		}


   // token user
    TOKEN_USER *ptu;
	DWORD needed;
	ptu = (TOKEN_USER *) aa;//malloc( 16384 );
	if (GetTokenInformation( hPToken, TokenUser, ptu, 16384, &needed ) )
	{
		char  DomainName[64];
		memset(DomainName, 0, sizeof(DomainName));
		DWORD DomainSize;
		DomainSize =sizeof(DomainName)-1;
		SID_NAME_USE SidType;
		DWORD dwsize=size;
		LookupAccountSid(NULL, ptu->User.Sid, buffer, &dwsize, DomainName, &DomainSize, &SidType);
		//free(ptu);
		CloseHandle(hPToken);
		CloseHandle(hProcess);
		return 1;
	}
	//free(ptu);
	strcpy(buffer,"");
	CloseHandle(hPToken);
	CloseHandle(hProcess);
	return 0;
}
Пример #22
0
void Process::ownerNameDomain(){
	DWORD dwRtnCode = 0;
	BOOL bRtnBool = TRUE;
	SID_NAME_USE eUse = SidTypeUnknown;
	DWORD size = 1024;

	// Reallocate memory for the buffers.
	_ownerName = (LPTSTR)GlobalAlloc(
			  GMEM_FIXED,
			  size);

	// Check GetLastError for GlobalAlloc error condition.
	if (_ownerName == NULL)
		throw(ProcessException("GlobalAlloc error = ",GetLastError()));

	_ownerDomain = (LPTSTR)GlobalAlloc(
           GMEM_FIXED,
           size);

    // Check GetLastError for GlobalAlloc error condition.
	if (_ownerDomain == NULL)
		  throw(ProcessException("GlobalAlloc error = ", GetLastError()));

    // Second call to LookupAccountSid to get the account name.
	
    bRtnBool = LookupAccountSid(
          NULL,                   // name of local or remote computer
		  _ownerSID,              // security identifier
		  _ownerName,               // account name buffer
          (LPDWORD)&size,   // size of account name buffer 
		  _ownerDomain,             // domain name
          (LPDWORD)&size, // size of domain name buffer
          &eUse);                 // SID type

    // Check GetLastError for LookupAccountSid error condition.
    if (bRtnBool == FALSE) {
          DWORD dwErrorCode = 0;
          dwErrorCode = GetLastError();
          if (dwErrorCode == ERROR_NONE_MAPPED)
			  throw(ProcessException("Account owner not found for specified SID = ",dwErrorCode));
          else 
			  throw(ProcessException("Error in LookupAccountSid = ",dwErrorCode));
	}; 

	_ownerRID = parseRID(_ownerSID);
	return;
}
Пример #23
0
/* function 'GetProcessUsername' require 'userName' with size 'MAX_NAME' */
static int GetProcessUsername(HANDLE hProcess, char *userName)
{
	HANDLE		tok;
	TOKEN_USER	*ptu = NULL;
	DWORD		sz = 0, nlen, dlen;
	char		name[MAX_NAME], dom[MAX_NAME];
	int		iUse, res = 0;

	assert(userName);

	//clean result;
	*userName = '******';

	//open the processes token
	if (0 == OpenProcessToken(hProcess, TOKEN_QUERY, &tok))
		return res;

	// Get required buffer size and allocate the TOKEN_USER buffer
	if (0 == GetTokenInformation(tok, (TOKEN_INFORMATION_CLASS)1, (LPVOID)ptu, 0, &sz))
	{
		if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
			goto lbl_err;
		ptu = (PTOKEN_USER)zbx_malloc(ptu, sz);
	}

	// Get the token user information from the access token.
	if (0 == GetTokenInformation(tok, (TOKEN_INFORMATION_CLASS)1, (LPVOID)ptu, sz, &sz))
		goto lbl_err;

	//get the account/domain name of the SID
	nlen = sizeof(name);
	dlen = sizeof(dom);
	if (0 == LookupAccountSid(NULL, ptu->User.Sid, name, &nlen, dom, &dlen, (PSID_NAME_USE)&iUse))
		goto lbl_err;

	zbx_strlcpy(userName, name, MAX_NAME);

	res = 1;
lbl_err:
	zbx_free(ptu);

	CloseHandle(tok);

	return res;
}
Пример #24
0
static inline ProcessInfo processInfo(DWORD processId)
{
    ProcessInfo pi;
    HANDLE handle = OpenProcess(PROCESS_QUERY_INFORMATION, TOKEN_READ, processId);
    if (handle == INVALID_HANDLE_VALUE)
        return pi;
    WCHAR buffer[MAX_PATH];
    DWORD bufSize = MAX_PATH;
    if (queryFullProcessImageName(handle, 0, buffer, &bufSize))
        pi.imageName = QString::fromUtf16(reinterpret_cast<const ushort *>(buffer));

    HANDLE processTokenHandle = NULL;
    if (!OpenProcessToken(handle, TOKEN_READ, &processTokenHandle) || !processTokenHandle)
        return pi;

    DWORD size = 0;
    GetTokenInformation(processTokenHandle, TokenUser, NULL, 0, &size);

    if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
        QByteArray buf;
        buf.resize(size);
        PTOKEN_USER userToken = reinterpret_cast<PTOKEN_USER>(buf.data());
        if (userToken
            && GetTokenInformation(processTokenHandle, TokenUser, userToken, size, &size)) {
            SID_NAME_USE sidNameUse;
            TCHAR user[MAX_PATH] = { 0 };
            DWORD userNameLength = MAX_PATH;
            TCHAR domain[MAX_PATH] = { 0 };
            DWORD domainNameLength = MAX_PATH;

            if (LookupAccountSid(NULL,
                                 userToken->User.Sid,
                                 user,
                                 &userNameLength,
                                 domain,
                                 &domainNameLength,
                                 &sidNameUse))
                pi.processOwner = QString::fromUtf16(reinterpret_cast<const ushort *>(user));
        }
    }

    CloseHandle(processTokenHandle);
    CloseHandle(handle);
    return pi;
}
Пример #25
0
/* function 'zbx_get_process_username' require 'userName' with size 'MAX_NAME' */
static int	zbx_get_process_username(HANDLE hProcess, char *userName)
{
	HANDLE		tok;
	TOKEN_USER	*ptu = NULL;
	DWORD		sz = 0, nlen, dlen;
	TCHAR		name[MAX_NAME], dom[MAX_NAME];
	int		iUse, res = FAIL;

	assert(userName);

	/* clean result; */
	*userName = '******';

	/* open the processes token */
	if (0 == OpenProcessToken(hProcess, TOKEN_QUERY, &tok))
		return res;

	/* Get required buffer size and allocate the TOKEN_USER buffer */
	if (0 == GetTokenInformation(tok, (TOKEN_INFORMATION_CLASS)1, (LPVOID)ptu, 0, &sz))
	{
		if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
			goto lbl_err;
		ptu = (PTOKEN_USER)zbx_malloc(ptu, sz);
	}

	/* Get the token user information from the access token. */
	if (0 == GetTokenInformation(tok, (TOKEN_INFORMATION_CLASS)1, (LPVOID)ptu, sz, &sz))
		goto lbl_err;

	/* get the account/domain name of the SID */
	nlen = MAX_NAME;
	dlen = MAX_NAME;
	if (0 == LookupAccountSid(NULL, ptu->User.Sid, name, &nlen, dom, &dlen, (PSID_NAME_USE)&iUse))
		goto lbl_err;

	zbx_unicode_to_utf8_static(name, userName, MAX_NAME);

	res = SUCCEED;
lbl_err:
	zbx_free(ptu);

	CloseHandle(tok);

	return res;
}
Пример #26
0
APR_DECLARE(apr_status_t) apr_gid_name_get(char **groupname, apr_gid_t groupid, apr_pool_t *p)
{
#ifdef _WIN32_WCE
    *groupname = apr_pstrdup(p, "Administrators");
#else
    SID_NAME_USE type;
    char name[MAX_PATH], domain[MAX_PATH];
    DWORD cbname = sizeof(name), cbdomain = sizeof(domain);
    if (!groupid)
        return APR_EINVAL;
    if (!LookupAccountSid(NULL, groupid, name, &cbname, domain, &cbdomain, &type))
        return apr_get_os_error();
    if (type != SidTypeGroup && type != SidTypeWellKnownGroup 
                             && type != SidTypeAlias)
        return APR_EINVAL;
    *groupname = apr_pstrdup(p, name);
#endif
    return APR_SUCCESS;
}
Пример #27
0
void getservname(void)
{
	DWORD ret,i;
	HANDLE tok;
	char tmpbuf[1024], UserName[256], RefDomain[256];
	PTOKEN_USER UserToken = (PTOKEN_USER)tmpbuf;
	DWORD RetLen=1024, UserNameLen, RefDomainLen;
	SID_NAME_USE SidType;

	if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &tok))
	{
		if ((ret = GetTokenInformation(tok, TokenUser, UserToken, RetLen, &RetLen)))
		{
			UserNameLen = sizeof(UserName);
			RefDomainLen = sizeof(RefDomain);
			if ((ret = LookupAccountSid(NULL,UserToken->User.Sid,UserName,&UserNameLen,RefDomain,&RefDomainLen,&SidType)))
			{
				strcat(RefDomain,"/");
				strcat(RefDomain,UserName);
				parse_username(RefDomain);
				sfsprintf(servname, sizeof(servname),"UWIN_CS%s", RefDomain);
				sfsprintf(servdname, sizeof(servdname),"UWIN Client(%s)", RefDomain);
				strcpy(evename,RefDomain);
				strcat(evename,"event");
				for(i=0;i<strlen(servname);i++)
					if(servname[i] == '/')
						servname[i]= '#';
				{
					unsigned char *ptr;
					for(ptr=(unsigned char *)evename; *ptr ; ptr++)
						*ptr=tolower(*ptr);
				}
			}
			else
				logerr(1, "LookupAccountSid failed in getservname");
		}
		else
			logerr(1, "GetTokenInformation failed in getservname");
	}
	else
		logerr(1, "OpenProcessToken failed in getservname");
}
Пример #28
0
//This function determines the username and domain
void lookup_sid ( ACCESS_ALLOWED_ACE* pACE, char user_domain[] ) {
	char username[1024]="";
	char domain[1024]="";

	ULONG len_username = sizeof(username);
	ULONG len_domain = sizeof(domain);
	PSID pSID =(PSID)(&(pACE->SidStart));
	SID_NAME_USE sid_name_use;         

	if (!LookupAccountSid(NULL, pSID, 
		username, &len_username, domain, &len_domain, &sid_name_use)){  
		strcpy(user_domain, "unknown");
	} else {
		strcat(user_domain,domain);
		strcat(user_domain,"\\");
		strcat(user_domain,username);
	}


}
Пример #29
0
// This implementation of get_condor_username() for WinNT really 
// returns the username of the current user.  Until we finish porting
// over all the priv_state code, root=condor=user, so we may as well
// just return the identity of the current user.
const char* get_condor_username() 
{
	HANDLE hProcess = NULL;
	HANDLE hAccessToken = NULL;
	UCHAR InfoBuffer[1000];
	char szAccountName[200], szDomainName[200];
	PTOKEN_USER pTokenUser = (PTOKEN_USER)InfoBuffer;
	DWORD dwInfoBufferSize,dwAccountSize = 200, dwDomainSize = 200;
	SID_NAME_USE snu;
	int length;

	if ( CondorUserName )
		return CondorUserName;

	hProcess = GetCurrentProcess();

	OpenProcessToken(hProcess,TOKEN_READ,&hAccessToken);

	GetTokenInformation(hAccessToken,TokenUser,InfoBuffer,
		1000, &dwInfoBufferSize);

	szAccountName[0] = '\0';
	szDomainName[0] = '\0';
	LookupAccountSid(NULL, pTokenUser->User.Sid, szAccountName,
		&dwAccountSize,szDomainName, &dwDomainSize, &snu);

	length = strlen(szAccountName) + strlen(szDomainName) + 4;
	CondorUserName = (char *) malloc(length);
	if (CondorUserName == NULL) {
		EXCEPT("Out of memory. Aborting.");
	}
	sprintf(CondorUserName, "%s/%s",szDomainName,szAccountName);

	if ( hProcess )
		CloseHandle(hProcess);
	if ( hAccessToken )
		CloseHandle(hAccessToken);

	return CondorUserName;
} 
Пример #30
0
static bool x_GetAccountNameBySid(PSID sid, string* account, int* domatch = 0)
{
    _ASSERT(account);

    // Use predefined buffers for account/domain names to avoid additional
    // step to get its sizes. According to MSDN max account/domain size
    // do not exceed MAX_ACCOUNT_LEN symbols (char or wchar).

    TXChar   account_name[MAX_ACCOUNT_LEN + 2];
    TXChar   domain_name [MAX_ACCOUNT_LEN + 2];
    DWORD    account_size = sizeof(account_name)/sizeof(account_name[0]) - 1;
    DWORD    domain_size  = sizeof(domain_name)/sizeof(domain_name[0]) - 1;
    SID_NAME_USE use;

    // Always get both account & domain name, even we don't need last.
    // Because if domain name is NULL, this function can throw unhandled
    // exception in Unicode builds on some platforms.
    if ( !LookupAccountSid(NULL, sid, 
                           account_name, &account_size,
                           domain_name,  &domain_size, &use) ) {
        CNcbiError::SetFromWindowsError();
        return false;
    }

    // Save account information
    account_name[account_size] = _TX('\0');
    account->assign(_T_STDSTRING(account_name));

    if (domatch) {
        domain_name[domain_size] = _TX('\0');
        string domain(_T_STDSTRING(domain_name));
        if (*domatch != int(use)  ||  domain.empty()
            ||  NStr::EqualNocase(domain, "builtin")
            ||  NStr::FindNoCase(domain, " ") != NPOS
            /*||  x_DomainIsLocalComputer(domain_name)*/) {
            *domatch = 0;
        }
    }
    return true;
}