コード例 #1
0
LRESULT CProgressDlg::OnProgressUpdateUI(WPARAM wParam, LPARAM lParam)
{
	if (wParam == MSG_PROGRESSDLG_START)
	{
		m_BufStart = 0;
		m_Animate.Play(0, INT_MAX, INT_MAX);
		DialogEnableWindow(IDCANCEL, TRUE);
		if (m_pTaskbarList)
		{
			m_pTaskbarList->SetProgressState(m_hWnd, TBPF_NORMAL);
			m_pTaskbarList->SetProgressValue(m_hWnd, 0, 100);
		}
	}
	if (wParam == MSG_PROGRESSDLG_END || wParam == MSG_PROGRESSDLG_FAILED)
	{
		CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": got message: %d\n", wParam);
		ULONGLONG tickSpent = GetTickCount64() - m_startTick;
		CString strEndTime = CLoglistUtils::FormatDateAndTime(CTime::GetCurrentTime(), DATE_SHORTDATE, true, false);

		if (m_bBufferAll)
		{
			m_Databuf.m_critSec.Lock();
			m_Databuf.push_back(0);
			m_Log.SetWindowText(Convert2UnionCode(reinterpret_cast<char*>(m_Databuf.data())));
			m_Databuf.m_critSec.Unlock();
		}
		m_BufStart = 0;
		m_Databuf.m_critSec.Lock();
		this->m_Databuf.clear();
		m_Databuf.m_critSec.Unlock();

		m_bDone = true;
		m_Animate.Stop();
		m_Progress.SetPos(100);
		this->DialogEnableWindow(IDOK, TRUE);

		m_GitStatus = static_cast<DWORD>(lParam);
		if (m_GitCmd.IsEmpty() && m_GitCmdList.empty())
			m_GitStatus = DWORD(-1);

		// detect crashes of perl when performing git svn actions
		if (m_GitStatus == 0 && m_GitCmd.Find(L" svn ") > 1)
		{
			CString log;
			m_Log.GetWindowText(log);
			if (log.GetLength() > 18 && log.Mid(log.GetLength() - 18) == L"perl.exe.stackdump")
				m_GitStatus = DWORD(-1);
		}

		if (m_PostExecCallback)
		{
			CString extraMsg;
			m_PostExecCallback(m_GitStatus, extraMsg);
			if (!extraMsg.IsEmpty())
			{
				int start = m_Log.GetTextLength();
				m_Log.SetSel(start, start);
				m_Log.ReplaceSel(extraMsg);
			}
		}
		{
			CString text;
			m_Log.GetWindowText(text);
			text.Remove('\r');
			CAppUtils::StyleURLs(text, &m_Log);
		}
		if (this->m_GitStatus)
		{
			if (m_pTaskbarList)
			{
				m_pTaskbarList->SetProgressState(m_hWnd, TBPF_ERROR);
				m_pTaskbarList->SetProgressValue(m_hWnd, 100, 100);
			}
			CString log;
			log.Format(IDS_PROC_PROGRESS_GITUNCLEANEXIT, m_GitStatus);
			CString err;
			if (CRegDWORD(L"Software\\TortoiseGit\\ShowGitexeTimings", TRUE))
				err.Format(L"\r\n\r\n%s (%I64u ms @ %s)\r\n", static_cast<LPCTSTR>(log), tickSpent, static_cast<LPCTSTR>(strEndTime));
			else
				err.Format(L"\r\n\r\n%s\r\n", static_cast<LPCTSTR>(log));
			if (!m_GitCmd.IsEmpty() || !m_GitCmdList.empty())
				InsertColorText(this->m_Log, err, RGB(255, 0, 0));
			if (CRegDWORD(L"Software\\TortoiseGit\\NoSounds", FALSE) == FALSE)
				PlaySound(reinterpret_cast<LPCTSTR>(SND_ALIAS_SYSTEMEXCLAMATION), nullptr, SND_ALIAS_ID | SND_ASYNC);
		}
		else {
			if (m_pTaskbarList)
				m_pTaskbarList->SetProgressState(m_hWnd, TBPF_NOPROGRESS);
			CString temp;
			temp.LoadString(IDS_SUCCESS);
			CString log;
			if (CRegDWORD(L"Software\\TortoiseGit\\ShowGitexeTimings", TRUE))
				log.Format(L"\r\n%s (%I64u ms @ %s)\r\n", static_cast<LPCTSTR>(temp), tickSpent, static_cast<LPCTSTR>(strEndTime));
			else
				log.Format(L"\r\n%s\r\n", static_cast<LPCTSTR>(temp));
			InsertColorText(this->m_Log, log, RGB(0, 0, 255));
			this->DialogEnableWindow(IDCANCEL, FALSE);
		}

		m_Log.PostMessage(WM_VSCROLL, SB_BOTTOM, 0);

		if (wParam == MSG_PROGRESSDLG_END)
		{
			if (m_PostCmdCallback) // new handling method using callback
			{
				m_PostCmdCallback(m_GitStatus, m_PostCmdList);

				if (!m_PostCmdList.empty())
				{
					int i = 0;
					for (const auto& entry : m_PostCmdList)
					{
						++i;
						m_ctrlPostCmd.AddEntry(entry.label, entry.icon);
						TCHAR accellerator = CStringUtils::GetAccellerator(entry.label);
						if (accellerator == L'\0')
							continue;
						++m_accellerators[accellerator].cnt;
						if (m_accellerators[accellerator].cnt > 1)
							m_accellerators[accellerator].id = -1;
						else
							m_accellerators[accellerator].id = i - 1;
					}

					if (m_accellerators.size())
					{
						auto lpaccelNew = static_cast<LPACCEL>(LocalAlloc(LPTR, m_accellerators.size() * sizeof(ACCEL)));
						SCOPE_EXIT { LocalFree(lpaccelNew); };
						i = 0;
						for (auto& entry : m_accellerators)
						{
							lpaccelNew[i].cmd = static_cast<WORD>(WM_USER + 1 + entry.second.id);
							lpaccelNew[i].fVirt = FVIRTKEY | FALT;
							lpaccelNew[i].key = entry.first;
							entry.second.wmid = lpaccelNew[i].cmd;
							++i;
						}
						m_hAccel = CreateAcceleratorTable(lpaccelNew, static_cast<int>(m_accellerators.size()));
					}
					GetDlgItem(IDC_PROGRESS_BUTTON1)->ShowWindow(SW_SHOW);
				}
			}
コード例 #2
0
ファイル: PSCryptor.cpp プロジェクト: dannyyiu/ps-color-test
BOOL CreatePrivateExponentOneKey(LPTSTR szProvider, 
                                 DWORD dwProvType,
                                 LPTSTR szContainer,
                                 DWORD dwKeySpec,
                                 HCRYPTPROV *hProv, 
                                 HCRYPTKEY *hPrivateKey)
{
   BOOL fReturn = FALSE;
   BOOL fResult;
   int n;
   LPBYTE keyblob = NULL;
   DWORD dwkeyblob;
   DWORD dwBitLen;
   BYTE *ptr;

   __try
   {
      *hProv = 0;
      *hPrivateKey = 0;

      if ((dwKeySpec != AT_KEYEXCHANGE) && (dwKeySpec != AT_SIGNATURE))  __leave;

      // Try to create new container
      fResult = CryptAcquireContext(hProv, szContainer, szProvider, 
                                    dwProvType, CRYPT_NEWKEYSET);
      if (!fResult)
      {
         // If the container exists, open it
         if (GetLastError() == NTE_EXISTS)
         {
            fResult = CryptAcquireContext(hProv, szContainer, szProvider, dwProvType, 0);
            if (!fResult)
            {
               // No good, leave
               __leave;
            }
         }
         else
         {
            // No good, leave
            __leave;
         }
      }

      // Generate the private key
      fResult = CryptGenKey(*hProv, dwKeySpec, CRYPT_EXPORTABLE, hPrivateKey);
      if (!fResult) __leave;

      // Export the private key, we'll convert it to a private
      // exponent of one key
      fResult = CryptExportKey(*hPrivateKey, 0, PRIVATEKEYBLOB, 0, NULL, &dwkeyblob);
      if (!fResult) __leave;      

      keyblob = (LPBYTE)LocalAlloc(LPTR, dwkeyblob);
      if (!keyblob) __leave;

      fResult = CryptExportKey(*hPrivateKey, 0, PRIVATEKEYBLOB, 0, keyblob, &dwkeyblob);
      if (!fResult) __leave;


      CryptDestroyKey(*hPrivateKey);
      *hPrivateKey = 0;

      // Get the bit length of the key
      memcpy(&dwBitLen, &keyblob[12], 4);      

      // Modify the Exponent in Key BLOB format
      // Key BLOB format is documented in SDK

      // Convert pubexp in rsapubkey to 1
      ptr = &keyblob[16];
      for (n = 0; n < 4; n++)
      {
         if (n == 0) ptr[n] = 1;
         else ptr[n] = 0;
      }

      // Skip pubexp
      ptr += 4;
      // Skip modulus, prime1, prime2
      ptr += (dwBitLen/8);
      ptr += (dwBitLen/16);
      ptr += (dwBitLen/16);

      // Convert exponent1 to 1
      for (n = 0; n < (dwBitLen/16); n++)
      {
         if (n == 0) ptr[n] = 1;
         else ptr[n] = 0;
      }

      // Skip exponent1
      ptr += (dwBitLen/16);

      // Convert exponent2 to 1
      for (n = 0; n < (dwBitLen/16); n++)
      {
         if (n == 0) ptr[n] = 1;
         else ptr[n] = 0;
      }

      // Skip exponent2, coefficient
      ptr += (dwBitLen/16);
      ptr += (dwBitLen/16);

      // Convert privateExponent to 1
      for (n = 0; n < (dwBitLen/8); n++)
      {
         if (n == 0) ptr[n] = 1;
         else ptr[n] = 0;
      }
      
      // Import the exponent-of-one private key.      
      if (!CryptImportKey(*hProv, keyblob, dwkeyblob, 0, 0, hPrivateKey))
      {                 
         __leave;
      }

      fReturn = TRUE;
   }
   __finally
   {
      if (keyblob) LocalFree(keyblob);

      if (!fReturn)
      {
         if (*hPrivateKey) CryptDestroyKey(*hPrivateKey);
         if (*hProv) CryptReleaseContext(*hProv, 0);
      }
   }

   return fReturn;
}
コード例 #3
0
ファイル: osverify.cpp プロジェクト: JanD1943/ndas4windows
BOOL WINAPI
IsUserAdmin(VOID)
/*++

Routine Description:

This routine returns TRUE if the caller's process is a
member of the Administrators local group.

Caller is NOT expected to be impersonating anyone and IS
expected to be able to open their own process and process
token.

Arguments:

None.

Return Value:

TRUE - Caller has Administrators local group.

FALSE - Caller does not have Administrators local group.

--*/

{
	HANDLE Token;
	DWORD BytesRequired;
	PTOKEN_GROUPS Groups;
	BOOL b;
	DWORD i;
	SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
	PSID AdministratorsGroup;

	//
	// Open the process token.
	//
	if(!OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY,&Token)) {
		return(GetLastError() == ERROR_CALL_NOT_IMPLEMENTED);
	}

	b = FALSE;
	Groups = NULL;

	//
	// Get group information.
	//
	if(!GetTokenInformation(Token,TokenGroups,NULL,0,&BytesRequired)
		&& (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
		&& (Groups = (PTOKEN_GROUPS)LocalAlloc(LPTR,BytesRequired))
		&& GetTokenInformation(Token,TokenGroups,Groups,BytesRequired,&BytesRequired)) 
	{

		b = AllocateAndInitializeSid(
			&NtAuthority,
			2,
			SECURITY_BUILTIN_DOMAIN_RID,
			DOMAIN_ALIAS_RID_ADMINS,
			0, 0, 0, 0, 0, 0,
			&AdministratorsGroup
			);

		if(b) {

			//
			// See if the user has the administrator group.
			//
			b = FALSE;
			for(i=0; i<Groups->GroupCount; i++) {
				if(EqualSid(Groups->Groups[i].Sid,AdministratorsGroup)) {
					b = TRUE;
					break;
				}
			}

			FreeSid(AdministratorsGroup);
		}
	}

	//
	// Clean up and return.
	//

	if(Groups) {
		LocalFree((HLOCAL)Groups);
	}

	CloseHandle(Token);

	return(b);
}
コード例 #4
0
ファイル: filever.c プロジェクト: mingpen/OpenNT
/* VerpQueryValue
 * Given a pointer to a branch of a version info tree and the name of a
 * sub-branch (as in "sub\subsub\subsubsub\..."), this fills in a pointer
 * to the specified value and a word for its length.  Returns TRUE on success,
 * FALSE on failure.
 *
 * Note that a subblock name may start with a '\\', but it will be ignored.
 * To get the value of the current block, use lpSubBlock=""
 */
BOOL
APIENTRY
VerpQueryValue(
        const LPVOID pb,
        LPVOID lpSubBlockX,    // can be ansi or unicode
        INT    nIndex,
        LPVOID *lplpKey,
        LPVOID *lplpBuffer,
        PUINT puLen,
        BOOL    bUnicodeNeeded
        )
{
  ANSI_STRING AnsiString;
  UNICODE_STRING UnicodeString;
  LPWSTR lpSubBlockOrg;
  LPWSTR lpSubBlock;
  NTSTATUS Status;

  VERBLOCK *pBlock = (PVOID)pb;
  LPWSTR lpStart, lpEndBlock, lpEndSubBlock;
  WCHAR cTemp, cEndBlock;
  DWORD dwHeadLen, dwTotBlockLen;
  BOOL bLastSpec;
  INT nCmp;
  BOOL bString;

  *puLen = 0;

  /*
   * Major hack: wType is 0 for win32 versions, but holds 56 ('V')
   * for win16.
   */

  if (((VERHEAD*)pb)->wType)
     return VerpQueryValue16(pb,
                             lpSubBlockX,
                             nIndex,
                             lplpKey,
                             lplpBuffer,
                             puLen,
                             bUnicodeNeeded);

  /*
   * If doesnt need unicode, then we must thunk the input parameter
   * to unicode.
   */

  if (!bUnicodeNeeded) {

     RtlInitAnsiString(&AnsiString, (LPSTR)lpSubBlockX);
     Status = RtlAnsiStringToUnicodeString(&UnicodeString, &AnsiString, TRUE);

     if (!NT_SUCCESS(Status)) {
        SetLastError(Status);
        return FALSE;
     }
     lpSubBlock = UnicodeString.Buffer;

  } else {
     lpSubBlockOrg = (LPWSTR)LocalAlloc(LPTR,(lstrlen(lpSubBlockX)+1)*sizeof(WCHAR));
     if (lpSubBlockOrg == NULL ) {
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        return FALSE;
     }
     lstrcpy(lpSubBlockOrg,lpSubBlockX);
     lpSubBlock = lpSubBlockOrg;
  }



  /* Ensure that the total length is less than 32K but greater than the
   * size of a block header; we will assume that the size of pBlock is at
   * least the value of this first int.
   * Put a '\0' at the end of the block so that none of the wcslen's will
   * go past then end of the block.  We will replace it before returning.
   */
  if ((int)pBlock->wTotLen < sizeof(VERBLOCK))
      goto Fail;

  lpEndBlock = (LPWSTR)((LPSTR)pBlock + pBlock->wTotLen - sizeof(WCHAR));
  cEndBlock = *lpEndBlock;
  *lpEndBlock = 0;
  bString = FALSE;
  bLastSpec = FALSE;

#define NOTDONE() (*lpSubBlock || nIndex != -1)

  while (NOTDONE()) {
      //
      // Ignore leading '\\'s
      //
      while (*lpSubBlock == TEXT('\\'))
          ++lpSubBlock;

      if (NOTDONE()) {
          /* Make sure we still have some of the block left to play with
           */
          dwTotBlockLen = (LPSTR)lpEndBlock - (LPSTR)pBlock + sizeof(WCHAR);
          if ((int)dwTotBlockLen < sizeof(VERBLOCK) ||
              pBlock->wTotLen > (WORD)dwTotBlockLen)
              goto NotFound;

          /* Calculate the length of the "header" (the two length WORDs plus
           * the data type flag plus the identifying string) and skip
           * past the value.
           */
          dwHeadLen = DWORDUP(sizeof(VERBLOCK) - sizeof(WCHAR) +
                             (wcslen(pBlock->szKey) + 1) * sizeof(WCHAR)) +
                     DWORDUP(pBlock->wValLen);
          if (dwHeadLen > pBlock->wTotLen)
              goto NotFound;
          lpEndSubBlock = (LPWSTR)((LPSTR)pBlock + pBlock->wTotLen);
          pBlock = (VERBLOCK*)((LPSTR)pBlock+dwHeadLen);

          /* Look for the first sub-block name and terminate it
           */
          for (lpStart=lpSubBlock; *lpSubBlock && *lpSubBlock!=TEXT('\\');
             lpSubBlock++)
             /* find next '\\' */ ;
          cTemp = *lpSubBlock;
          *lpSubBlock = 0;

          /* Continue while there are sub-blocks left
           * pBlock->wTotLen should always be a valid pointer here because
           * we have validated dwHeadLen above, and we validated the previous
           * value of pBlock->wTotLen before using it
           */
          nCmp = 1;
          while ((int)pBlock->wTotLen > sizeof(VERBLOCK) &&
                 (int)pBlock->wTotLen <= (LPSTR)lpEndSubBlock-(LPSTR)pBlock) {

              //
              // Index functionality: if we are at the end of the path
              // (cTemp == 0 set below) and nIndex is NOT -1 (index search)
              // then break on nIndex zero.  Else do normal wscicmp.
              //
              if (bLastSpec && nIndex != -1) {

                  if (!nIndex) {

                      if (lplpKey) {
                          *lplpKey = pBlock->szKey;
                      }
                      nCmp=0;

                      //
                      // Index found, set nInde to -1
                      // so that we exit this loop
                      //
                      nIndex = -1;
                      break;
                  }

                  nIndex--;

              } else {

                  //
                  // Check if the sub-block name is what we are looking for
                  //

                  if (!(nCmp=_wcsicmp(lpStart, pBlock->szKey)))
                      break;
              }

              /* Skip to the next sub-block
               */
              pBlock=(VERBLOCK*)((LPSTR)pBlock+DWORDUP(pBlock->wTotLen));
          }

          /* Restore the char NULLed above and return failure if the sub-block
           * was not found
           */
          *lpSubBlock = cTemp;
          if (nCmp)
              goto NotFound;
        }
        bLastSpec = !cTemp;
    }

#undef NOTDONE

  /* Fill in the appropriate buffers and return success
   */

   *puLen = pBlock->wValLen;

  /* Add code to handle the case of a null value.
   *
   * If zero-len, then return the pointer to the null terminator
   * of the key.  Remember that this is thunked in the ansi case.
   *
   * We can't just look at pBlock->wValLen.  Check if it really is
   * zero-len by seeing if the end of the key string is the end of the
   * block (i.e., the val string is outside of the current block).
   */

  lpStart = (LPWSTR)((LPSTR)pBlock+DWORDUP((sizeof(VERBLOCK)-sizeof(WCHAR))+
         (wcslen(pBlock->szKey)+1)*sizeof(WCHAR)));

  *lplpBuffer = lpStart < (LPWSTR)((LPBYTE)pBlock+pBlock->wTotLen) ?
      lpStart :
      (LPWSTR)(pBlock->szKey+wcslen(pBlock->szKey));

  bString = pBlock->wType;

  *lpEndBlock = cEndBlock;

  /*
   * Must free string we allocated above
   */

  if (!bUnicodeNeeded) {
     RtlFreeUnicodeString(&UnicodeString);
  } else {
     LocalFree(lpSubBlockOrg);
  }

  /*----------------------------------------------------------------------
   * thunk the results
   *
   * Must always thunk key, sometimes (if bString true) value
   *----------------------------------------------------------------------*/

  if (!bUnicodeNeeded) {

     if (bString && *puLen != 0) {
         int cb;

         //
         // Must multiply length by two
         //
         UnicodeString.Length = UnicodeString.MaximumLength = (SHORT)(*puLen * 2);
         UnicodeString.Buffer = *lplpBuffer;

         //
         // Do the string conversion in the second half of the buffer
         // Assumes wTotLen is first filed in VERHEAD
         //

         // cb = offset in buffer to beginning of string
         cb = (PBYTE)*lplpBuffer - (PBYTE)pb;

         AnsiString.Buffer = (PBYTE)pb + DWORDUP(*((WORD*)pb)) + (DWORD)(cb)/2;

         // cb = number of bytes till end of buffer
         cb = (int)(DWORDUP(*((WORD*)pb))) - cb;

         // No need to add space for Zero terminator since it is already
         // accounted for in *puLen.
         AnsiString.MaximumLength = (SHORT)min(*puLen, (cb / sizeof(WCHAR)));
         RtlUnicodeStringToAnsiString(&AnsiString, &UnicodeString, FALSE);

         *lplpBuffer = AnsiString.Buffer;

     }

     if (lplpKey) {

         //
         // Thunk the key
         //
         dwHeadLen = wcslen(*lplpKey);
         UnicodeString.Length = UnicodeString.MaximumLength = (SHORT)(dwHeadLen * sizeof(WCHAR));
         UnicodeString.Buffer = *lplpKey;

         AnsiString.Buffer = (PBYTE)pb + DWORDUP(*((WORD*)pb)) +
            (DWORD)((PBYTE)*lplpKey - (PBYTE)pb)/2;

         AnsiString.MaximumLength = (SHORT)(dwHeadLen + 1);
         RtlUnicodeStringToAnsiString(&AnsiString, &UnicodeString, FALSE);

         *lplpKey = AnsiString.Buffer;
     }
  }

  return(TRUE);


NotFound:
  /* Restore the char we NULLed above
   */
  *lpEndBlock = cEndBlock;

Fail:

  if (!bUnicodeNeeded) {

     RtlFreeUnicodeString(&UnicodeString);
  } else {
     LocalFree(lpSubBlockOrg);
  }

  return(FALSE);
}
コード例 #5
0
//  the main function 
void __cdecl main(int argc, char *argv[])

{

    DNS_STATUS status;               // return value of  DnsModifyRecordsInSet() function.
    PDNS_RECORD pmyDnsRecord = NULL; //pointer to DNS_RECORD structure
    PIP4_ARRAY pSrvList = NULL;      //pinter to IP4_ARRAY structure
    LPTSTR pOwnerName = NULL, pNameData = NULL;  //owner name and the data for CNAME resource record
    char HostipAddress[BUFFER_LEN];         //Ip address required to add host record
    char DnsServIp[BUFFER_LEN];             //DNS server ip address

    memset(HostipAddress, 0, sizeof(HostipAddress) );
    memset(DnsServIp, 0, sizeof(DnsServIp) );


    //Allocate memory for DNS_RECORD structure.

    pmyDnsRecord = (PDNS_RECORD) LocalAlloc( LPTR, sizeof( DNS_RECORD ) );

    if (!pmyDnsRecord) {
        printf("Memory allocaltion failed\n");
        exit(1);
    }

    if (argc > 8) {

        for (int i = 1; i < argc ; i++) {

            if ( (argv[i][0] == '-') || (argv[i][0] == '/') ) {

                switch (tolower(argv[i][1])) {
                
                case 'n':
                    pOwnerName = argv[++i];
                    pmyDnsRecord->pName = pOwnerName; //copy the Owner name information 
                    break;

                case 't':
                    if (!_stricmp(argv[i+1], "A") )
                        pmyDnsRecord->wType = DNS_TYPE_A; //add host records
                    else if (!_stricmp(argv[i+1], "CNAME") )
                        pmyDnsRecord->wType = DNS_TYPE_CNAME; //add CNAME records
                    else
                        Usage(argv[0]);
                    i++;
                    break;

                case 'l':
                    pmyDnsRecord->dwTtl = atoi(argv[++i]); // time to live value in seconds
                    break;
                case 'd':
                    if (pmyDnsRecord->wType == DNS_TYPE_A) {
                        pmyDnsRecord->wDataLength = sizeof(DNS_A_DATA); //data structure for A records
                        strncpy_s(HostipAddress, _countof(HostipAddress), argv[++i], _TRUNCATE);
                        HostipAddress[sizeof(HostipAddress)-1] = '\0';
                        pmyDnsRecord->Data.A.IpAddress = inet_addr(HostipAddress); //convert string to proper address
                        if ( pmyDnsRecord->Data.A.IpAddress == INADDR_NONE ) {
                            printf("Invalid IP address in A record data \n");
                            Usage(argv[0]);
                        }
                        break;
                    }
                    else {
                        pmyDnsRecord->wDataLength = sizeof(DNS_PTR_DATA); //data structure for CNAME records
                        pNameData = argv[++i];
                        pmyDnsRecord->Data.Cname.pNameHost = pNameData;
                        break;
                    }
                case 's':
                    // Allocate memory for IP4_ARRAY structure
                    pSrvList = (PIP4_ARRAY) LocalAlloc(LPTR,sizeof(IP4_ARRAY));
                    if (!pSrvList) {
                        printf("Memory allocation failed \n");
                        exit(1);
                    }
                    if (argv[++i]) {
                        strncpy_s(DnsServIp, _countof(DnsServIp), argv[i], _TRUNCATE);
                        DnsServIp[sizeof(DnsServIp)-1] = '\0';
                        pSrvList->AddrCount = 1;
                        pSrvList->AddrArray[0] = inet_addr(DnsServIp); //DNS server IP address
                        if ( pSrvList->AddrArray[0] == INADDR_NONE ) {
                            printf("Invalid DNS server IP address\n");
                            Usage(argv[0]);
                        }
                        break; 
                    }

                default:
                    Usage(argv[0]);
                    break;
                }
            }
            else
                Usage(argv[0]);


        }   

    }
    else {
        Usage(argv[0]);
    }



    // Calling function DNSModifyRecordsInSet_A to add Host or CNAME records    

    status = DnsModifyRecordsInSet_A(pmyDnsRecord,                     //pointer to DNS_RECORD
                                     NULL,                      
                                     DNS_UPDATE_SECURITY_USE_DEFAULT,  //do not attempt secure dynamic updates
                                     NULL,                             //use default credentials
                                     pSrvList,                         //contains DNS server IP address
                                     NULL);                            //reserved for future use

    if (status) {
        if (pmyDnsRecord->wType == DNS_TYPE_A)
            printf("Failed to add the host record for %s and the error is %d \n", pOwnerName, status);
        else
            printf("Failed to add the Cname record for %s and the error is %d \n", pOwnerName, status);
    }
    else {
        if (pmyDnsRecord->wType == DNS_TYPE_A)
            printf("Successfully added the host record for %s \n", pOwnerName);
        else
            printf("Successfully added the Cname record for %s \n", pOwnerName);
    }           


    LocalFree(pmyDnsRecord); // Free the memory allocated for DNS_RECORD structure
    LocalFree(pSrvList);     // Free the memory allocated for IP4_ARRAY structure


}
コード例 #6
0
ファイル: global.c プロジェクト: mingpen/OpenNT
BOOL
MissypGlobalInitialize(
    IN  PSECMGR_CONTROL             SecMgrControl
    )

/*++
Routine Description:

    This function is called to initialize the global variables.
    This is done during DLL initialization.  As such, this routine
    also does some degree of sanity checking of revision levels.


Arguments

    SecMgrControl - Points to a Security Manager control block
        for use by the smedly.  This block will not change once
        smedly has returned, and therefore, it may be referenced
        directly in the future (rather than having to copy it).


Return Values:

    TRUE - The call completed successfully.

    FALSE - Something went wrong.  GetLastError() contains
        details on the exact cause of the error.  Possible
        values include:

                ERROR_UNKNOWN_REVISION

--*/
{
    NTSTATUS
        NtStatus;

    ULONG
        Index,
        AreaIndex;

    BOOLEAN
        IgnoreBoolean;

    SID_IDENTIFIER_AUTHORITY
        WorldSidAuthority = SECURITY_WORLD_SID_AUTHORITY,
        NtAuthority = SECURITY_NT_AUTHORITY;

    //
    // Check the major revision level.  If it isn't the same as
    // our revision, then we don't support it.
    //

    if (SecMgrControl->Revision.Major != SECMGR_REVISION_MAJOR_1) {
        SetLastError( ERROR_UNKNOWN_REVISION );
        return(FALSE);
    }

    //
    // Save a pointer to the security manager control.
    // Also save a pointer to the security manager's dispatch table
    // to make calling them easier and faster.
    //

    MissypSecMgrControl = SecMgrControl;
    MissypSecMgr = MissypSecMgrControl->Api;


    //
    // Save a copy of the security manager's hInstance for quick reference
    //

    MissypSecMgrhInstance = SecMgrControl->hInstance;

    //
    // Get the product type
    //
    
    IgnoreBoolean = RtlGetNtProductType( &MissypProductType );
    ASSERT(IgnoreBoolean == TRUE);



    //
    // Initialize the sids
    //


    NtStatus = RtlAllocateAndInitializeSid(
                   &WorldSidAuthority,
                   1,
                   SECURITY_WORLD_RID,
                   0, 0, 0, 0, 0, 0, 0,
                   &MissypWorldSid
                   );
    if (!NT_SUCCESS(NtStatus)) {
        KdPrint(("SecMgr: Failed to initialize world sid, status = 0x%lx", NtStatus));
        return(FALSE);
    }


    NtStatus = RtlAllocateAndInitializeSid(
                   &NtAuthority,
                   2,
                   SECURITY_BUILTIN_DOMAIN_RID,
                   DOMAIN_ALIAS_RID_ACCOUNT_OPS,
                   0, 0, 0, 0, 0, 0,
                   &MissypAccountOpsSid
                   );
    if (!NT_SUCCESS(NtStatus)) {
        KdPrint(("SecMgr: Failed to initialize admin AcountOps sid, status = 0x%lx", NtStatus));
        return(FALSE);
    }

    NtStatus = RtlAllocateAndInitializeSid(
                   &NtAuthority,
                   2,
                   SECURITY_BUILTIN_DOMAIN_RID,
                   DOMAIN_ALIAS_RID_SYSTEM_OPS,
                   0, 0, 0, 0, 0, 0,
                   &MissypServerOpsSid
                   );
    if (!NT_SUCCESS(NtStatus)) {
        KdPrint(("SecMgr: Failed to initialize admin ServerOps sid, status = 0x%lx", NtStatus));
        return(FALSE);
    }

    NtStatus = RtlAllocateAndInitializeSid(
                   &NtAuthority,
                   2,
                   SECURITY_BUILTIN_DOMAIN_RID,
                   DOMAIN_ALIAS_RID_PRINT_OPS,
                   0, 0, 0, 0, 0, 0,
                   &MissypPrintOpsSid
                   );
    if (!NT_SUCCESS(NtStatus)) {
        KdPrint(("SecMgr: Failed to initialize admin PrintOps sid, status = 0x%lx", NtStatus));
        return(FALSE);
    }

    NtStatus = RtlAllocateAndInitializeSid(
                   &NtAuthority,
                   2,
                   SECURITY_BUILTIN_DOMAIN_RID,
                   DOMAIN_ALIAS_RID_BACKUP_OPS,
                   0, 0, 0, 0, 0, 0,
                   &MissypBackupOpsSid
                   );
    if (!NT_SUCCESS(NtStatus)) {
        KdPrint(("SecMgr: Failed to initialize admin BackupOps sid, status = 0x%lx", NtStatus));
        return(FALSE);
    }

    NtStatus = RtlAllocateAndInitializeSid(
                   &NtAuthority,
                   2,
                   SECURITY_BUILTIN_DOMAIN_RID,
                   DOMAIN_ALIAS_RID_ADMINS,
                   0, 0, 0, 0, 0, 0,
                   &MissypAdminsSid
                   );
    if (!NT_SUCCESS(NtStatus)) {
        KdPrint(("SecMgr: Failed to initialize admin alias sid, status = 0x%lx", NtStatus));
        return(FALSE);
    }


    //
    // Group the sids by type
    //

    Index=0;
    MissypAnyoneSids.Sid[Index++] = MissypWorldSid;
    MissypAnyoneSids.Accounts = Index;
    ASSERT(Index < MISSYP_MAX_WELL_KNOWN_ACCOUNTS);

    Index=0;
    MissypOperatorSids.Sid[Index++] = MissypAccountOpsSid;
    MissypOperatorSids.Sid[Index++] = MissypBackupOpsSid;
    MissypOperatorSids.Sid[Index++] = MissypPrintOpsSid;
    MissypOperatorSids.Sid[Index++] = MissypServerOpsSid;
    MissypOperatorSids.Accounts = Index;
    ASSERT(Index < MISSYP_MAX_WELL_KNOWN_ACCOUNTS);

    Index=0;
    MissypOpersAndAdminsSids.Sid[Index++] = MissypAccountOpsSid;
    MissypOpersAndAdminsSids.Sid[Index++] = MissypBackupOpsSid;
    MissypOpersAndAdminsSids.Sid[Index++] = MissypPrintOpsSid;
    MissypOpersAndAdminsSids.Sid[Index++] = MissypServerOpsSid;
    MissypOpersAndAdminsSids.Sid[Index++] = MissypAdminsSid;
    MissypOpersAndAdminsSids.Accounts = Index;
    ASSERT(Index < MISSYP_MAX_WELL_KNOWN_ACCOUNTS);

    Index=0;
    MissypAdminsSids.Sid[Index++] = MissypAdminsSid;
    MissypAdminsSids.Accounts = Index;
    ASSERT(Index < MISSYP_MAX_WELL_KNOWN_ACCOUNTS);


    //
    // Initialize our smedly control block with no areas in it.
    // The area/item information will be added by the initialization
    // routine of each area.
    //

    //
    // Revision
    //

    MissypControl.Revision.Major = SECMGR_REVISION_MAJOR_1;
    MissypControl.Revision.Minor = SECMGR_REVISION_MINOR_0;

    MissypControl.Api = (PSECMGR_SMEDLY_DISPATCH_TABLE)
                         LocalAlloc( LPTR, sizeof(SECMGR_SMEDLY_DISPATCH_TABLE) );
    if (MissypControl.Api == NULL) {
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        return(FALSE);
    }


    //
    // Dispatch table
    //

    MissypControl.Api->InvokeArea           = MissyInvokeArea;
    MissypControl.Api->InvokeItem           = MissyInvokeItem;
    MissypControl.Api->NewSecurityLevel     = MissyNewSecurityLevel;
    MissypControl.Api->ReportFileChange     = MissyReportFileChange;
    MissypControl.Api->GenerateProfile      = MissyGenerateProfile;
    MissypControl.Api->ApplyProfile         = MissyApplyProfile;


    //
    // control flags
    //

    MissypControl.Flags = 0;        // Don't support reporting or profiles yet


    //
    // build up the control structure for the areas we support
    //

    MissypControl.AreaCount = MISSYP_AREA_COUNT;
    MissypControl.Areas = (PSECMGR_AREA_DESCRIPTOR)
                           LocalAlloc( LPTR, MissypControl.AreaCount * sizeof(SECMGR_AREA_DESCRIPTOR));
    
    if (MissypControl.Areas == NULL) {
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        return(FALSE);
    }

    //
    // System Access area
    //

    AreaIndex = 0;
    if (!MissypSysAccInitialize( AreaIndex )) {
        return(FALSE);
    }

    //
    // Auditing area
    //

    AreaIndex++;
    if (!MissypAuditInitialize( AreaIndex )) {
        return(FALSE);
    }

    //
    // File System area
    //

    AreaIndex++;
    if (!MissypFileSysInitialize( AreaIndex )) {
        return(FALSE);
    }


    //
    // Configuration area
    //

    AreaIndex++;
    if (!MissypConfigInitialize( AreaIndex )) {
        return(FALSE);
    }

    ASSERT(AreaIndex < MISSYP_AREA_COUNT);



}
コード例 #7
0
ファイル: gethna.c プロジェクト: Akasurde/krb5
WINAPI
rgethostbyaddr(const char *addr, int len, int type)
{
    DNS_STATUS status;
    struct hostent* host;
#ifdef DEBUG
    char debstr[80];
#endif

    PDNS_RECORD pDnsRecord;
    DNS_FREE_TYPE freetype ;
    char qbuf[BUFSIZ];

    if (type != AF_INET)
        return ((struct hostent *) NULL);

    wsprintf(qbuf, "%u.%u.%u.%u.in-addr.arpa",
         ((unsigned)addr[3] & 0xff),
         ((unsigned)addr[2] & 0xff),
         ((unsigned)addr[1] & 0xff),
         ((unsigned)addr[0] & 0xff));


    freetype =  DnsFreeRecordListDeep;


    status = DnsQuery_A(qbuf,                 //pointer to OwnerName
                        DNS_TYPE_PTR,         //Type of the record to be queried
                        DNS_QUERY_STANDARD,
                        NULL,                   //contains DNS server IP address
                        &pDnsRecord,                //Resource record comprising the response
                        NULL);                     //reserved for future use

    if (status) {
#ifdef DEBUG
        if (_res.options & RES_DEBUG)
        {
            wsprintf(debstr, "res_query failed\n");
            OutputDebugString(debstr);
        }
#endif

        return  NULL;
    }

    host = (struct hostent*)(TlsGetValue(dwGhaIndex));
    if (host == NULL) {
	LPVOID lpvData = (LPVOID) LocalAlloc(LPTR, sizeof(struct hostent));
	if (lpvData != NULL) {
	    TlsSetValue(dwGhaIndex, lpvData);
	    host = (struct hostent*)lpvData;
	} else
	    return NULL;
    }

    if (host->h_name == NULL)
	host->h_name = LocalAlloc(LPTR, DNS_MAX_LABEL_BUFFER_LENGTH);
    if (host->h_aliases == NULL)
	host->h_aliases = LocalAlloc(LPTR, 1*sizeof(LPSTR));
    if (host->h_addr_list == NULL)
    {
	host->h_addr_list = LocalAlloc(LPTR, 2*sizeof(LPSTR));
	host->h_addr_list[0] = LocalAlloc(LPTR, DNS_MAX_LABEL_BUFFER_LENGTH);
    }

    strcpy(host->h_name, pDnsRecord->Data.Ptr.pNameHost);
    host->h_addrtype = type;
    host->h_length = len;
    host->h_aliases[0] = NULL;
    memcpy(host->h_addr_list[0], addr, sizeof(unsigned long));
    host->h_addr_list[1] = NULL;
    DnsRecordListFree(pDnsRecord, freetype);

    return host;

}
コード例 #8
0
ファイル: debugger.cpp プロジェクト: jrfonseca/drmingw
BOOL ObtainSeDebugPrivilege(void)
{
    HANDLE hToken;
    PTOKEN_PRIVILEGES NewPrivileges;
    BYTE OldPriv[1024];
    PBYTE pbOldPriv;
    ULONG cbNeeded;
    BOOLEAN fRc;
    LUID LuidPrivilege;

    // Make sure we have access to adjust and to get the old token privileges
    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
    {
        OutputDebug("OpenProcessToken failed with 0x%08lx\n", GetLastError());

        return FALSE;
    }

    cbNeeded = 0;

    // Initialize the privilege adjustment structure
    LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &LuidPrivilege );

    NewPrivileges = (PTOKEN_PRIVILEGES) LocalAlloc(
        LMEM_ZEROINIT,
        sizeof(TOKEN_PRIVILEGES) + (1 - ANYSIZE_ARRAY)*sizeof(LUID_AND_ATTRIBUTES)
    );
    if(NewPrivileges == NULL) {
        return FALSE;
    }

    NewPrivileges->PrivilegeCount = 1;
    NewPrivileges->Privileges[0].Luid = LuidPrivilege;
    NewPrivileges->Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    // Enable the privilege
    pbOldPriv = OldPriv;
    fRc = AdjustTokenPrivileges(
        hToken,
        FALSE,
        NewPrivileges,
        1024,
        (PTOKEN_PRIVILEGES)pbOldPriv,
        &cbNeeded
    );

    if (!fRc) {

        // If the stack was too small to hold the privileges
        // then allocate off the heap
        if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {

            pbOldPriv = (PBYTE)LocalAlloc(LMEM_FIXED, cbNeeded);
            if (pbOldPriv == NULL) {
                return FALSE;
            }

            fRc = AdjustTokenPrivileges(
                hToken,
                FALSE,
                NewPrivileges,
                cbNeeded,
                (PTOKEN_PRIVILEGES)pbOldPriv,
                &cbNeeded
            );
        }
    }
    return fRc;
}
コード例 #9
0
ファイル: stub.c プロジェクト: elia/ocra
void *SzAlloc(void *p, size_t size) { p = p; return LocalAlloc(LMEM_FIXED, size); }
コード例 #10
0
ファイル: kuhl_m_crypto.c プロジェクト: GreenDamTan/mimikatz
NTSTATUS kuhl_m_crypto_l_certificates(int argc, wchar_t * argv[])
{
	HCERTSTORE hCertificateStore;
	PCCERT_CONTEXT pCertContext;
	DWORD i, j, dwSizeNeeded, keySpec;
	wchar_t *certName;
	PCRYPT_KEY_PROV_INFO pBuffer;
	HCRYPTPROV_OR_NCRYPT_KEY_HANDLE monProv;
	HCRYPTKEY maCle;
	BOOL keyToFree;

	PCWCHAR szSystemStore, szStore;
	DWORD dwSystemStore = 0;

	BOOL export = kull_m_string_args_byName(argc, argv, L"export", NULL, NULL);

	kull_m_string_args_byName(argc, argv, L"systemstore", &szSystemStore, L"CURRENT_USER"/*kuhl_m_crypto_system_stores[0].name*/);
	dwSystemStore = kull_m_crypto_system_store_to_dword(szSystemStore);
	kull_m_string_args_byName(argc, argv, L"store", &szStore, L"My");

	kprintf(L" * System Store  : \'%s\' (0x%08x)\n"
			L" * Store         : \'%s\'\n\n",
			szSystemStore, dwSystemStore,
			szStore);

	if(hCertificateStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, (HCRYPTPROV_LEGACY) NULL, dwSystemStore | CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG, szStore))
	{
		for (i = 0, pCertContext = CertEnumCertificatesInStore(hCertificateStore, NULL); pCertContext != NULL; pCertContext = CertEnumCertificatesInStore(hCertificateStore, pCertContext), i++)
		{
			for(j = 0; j < ARRAYSIZE(nameSrc); j++)
			{
				dwSizeNeeded = CertGetNameString(pCertContext, nameSrc[j], 0, NULL, NULL, 0);
				if(dwSizeNeeded > 0)
				{
					if(certName = (wchar_t *) LocalAlloc(LPTR, dwSizeNeeded * sizeof(wchar_t)))
					{
						if(CertGetNameString(pCertContext, nameSrc[j], 0, NULL, certName, dwSizeNeeded) == dwSizeNeeded)
						{
							kprintf(L"%2u. %s\n", i, certName);

							dwSizeNeeded = 0;
							if(CertGetCertificateContextProperty(pCertContext, CERT_KEY_PROV_INFO_PROP_ID, NULL, &dwSizeNeeded))
							{
								if(pBuffer = (PCRYPT_KEY_PROV_INFO) LocalAlloc(LPTR, dwSizeNeeded))
								{
									if(CertGetCertificateContextProperty(pCertContext, CERT_KEY_PROV_INFO_PROP_ID, pBuffer, &dwSizeNeeded))
									{
										kprintf(
											L"\tKey Container  : %s\n"
											L"\tProvider       : %s\n",
											(pBuffer->pwszContainerName ? pBuffer->pwszContainerName : L"(null)"),
											(pBuffer->pwszProvName ? pBuffer->pwszProvName : L"(null)"));
										
										if(CryptAcquireCertificatePrivateKey(pCertContext, CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG /* CRYPT_ACQUIRE_SILENT_FLAG NULL */, NULL, &monProv, &keySpec, &keyToFree))
										{
											kprintf(L"\tType           : %s (0x%08x)\n", kull_m_crypto_keytype_to_str(keySpec), keySpec);

											if(keySpec != CERT_NCRYPT_KEY_SPEC)
											{
												if(CryptGetUserKey(monProv, keySpec, &maCle))
												{
													kuhl_m_crypto_printKeyInfos(0, maCle);
													CryptDestroyKey(maCle);
												}
												else PRINT_ERROR_AUTO(L"CryptGetUserKey");

												if(keyToFree)
													CryptReleaseContext(monProv, 0);
											}
											else if(kuhl_m_crypto_hNCrypt)
											{
												kuhl_m_crypto_printKeyInfos(monProv, 0);
												if(keyToFree)
													K_NCryptFreeObject(monProv);
											}
											else PRINT_ERROR(L"keySpec == CERT_NCRYPT_KEY_SPEC without CNG Handle ?\n");

										} else PRINT_ERROR_AUTO(L"CryptAcquireCertificatePrivateKey");
									} else PRINT_ERROR_AUTO(L"CertGetCertificateContextProperty");
								}
								LocalFree(pBuffer);
								if(!export)
									kprintf(L"\n");
							}

							if(export)
								kuhl_m_crypto_exportCert(pCertContext, (BOOL) dwSizeNeeded, szSystemStore, szStore, i, certName);

						} else PRINT_ERROR_AUTO(L"CertGetNameString");
						LocalFree(certName);
					}
					break;
				} else PRINT_ERROR_AUTO(L"CertGetNameString (for len)");	
			}
コード例 #11
0
static
PBITMAPINFO CreateBitmapInfoStruct(HBITMAP hBmp)
{
    BITMAP bmp;
    PBITMAPINFO pbmi;
    WORD    cClrBits;

    // Retrieve the bitmap color format, width, and height.
    if (!GetObject(hBmp, sizeof(BITMAP), (LPSTR)&bmp))
        errhandler("GetObject");

    // Convert the color format to a count of bits.
    cClrBits = (WORD)(bmp.bmPlanes * bmp.bmBitsPixel);
    if (cClrBits == 1)
        cClrBits = 1;
    else if (cClrBits <= 4)
        cClrBits = 4;
    else if (cClrBits <= 8)
        cClrBits = 8;
    else if (cClrBits <= 16)
        cClrBits = 16;
    else if (cClrBits <= 24)
        cClrBits = 24;
    else cClrBits = 32;

    // Allocate memory for the BITMAPINFO structure. (This structure
    // contains a BITMAPINFOHEADER structure and an array of RGBQUAD
    // data structures.)

    if (cClrBits < 24)
        pbmi = (PBITMAPINFO)LocalAlloc(LPTR,
        sizeof(BITMAPINFOHEADER)+
        sizeof(RGBQUAD)* (1 << cClrBits));

    // There is no RGBQUAD array for these formats: 24-bit-per-pixel or 32-bit-per-pixel

    else
        pbmi = (PBITMAPINFO)LocalAlloc(LPTR,
        sizeof(BITMAPINFOHEADER));

    // Initialize the fields in the BITMAPINFO structure.

    pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    pbmi->bmiHeader.biWidth = bmp.bmWidth;
    pbmi->bmiHeader.biHeight = bmp.bmHeight;
    pbmi->bmiHeader.biPlanes = bmp.bmPlanes;
    pbmi->bmiHeader.biBitCount = bmp.bmBitsPixel;
    if (cClrBits < 24)
        pbmi->bmiHeader.biClrUsed = (1 << cClrBits);

    // If the bitmap is not compressed, set the BI_RGB flag.
    pbmi->bmiHeader.biCompression = BI_RGB;

    // Compute the number of bytes in the array of color
    // indices and store the result in biSizeImage.
    // The width must be DWORD aligned unless the bitmap is RLE
    // compressed.
    pbmi->bmiHeader.biSizeImage = ((pbmi->bmiHeader.biWidth * cClrBits + 31) & ~31) / 8
        * pbmi->bmiHeader.biHeight;
    // Set biClrImportant to 0, indicating that all of the
    // device colors are important.
    pbmi->bmiHeader.biClrImportant = 0;

    return pbmi;
}
コード例 #12
0
ファイル: kull_m_registry.c プロジェクト: 2005wind/mimikatz
BOOL kull_m_registry_RegEnumValue(IN PKULL_M_REGISTRY_HANDLE hRegistry, IN HKEY hKey, IN DWORD dwIndex, OUT LPWSTR lpValueName, IN OUT LPDWORD lpcchValueName, IN LPDWORD lpReserved, OUT OPTIONAL LPDWORD lpType, OUT OPTIONAL LPBYTE lpData, OUT OPTIONAL LPDWORD lpcbData)
{
	BOOL status = FALSE;
	DWORD dwErrCode, szBuffer;
	wchar_t * buffer;
	PKULL_M_REGISTRY_HIVE_KEY_NAMED pKn;
	PKULL_M_REGISTRY_HIVE_VALUE_LIST pVl;
	PKULL_M_REGISTRY_HIVE_VALUE_KEY pVk;
	PVOID dataLoc;

	switch(hRegistry->type)
	{
	case KULL_M_REGISTRY_TYPE_OWN:
		dwErrCode = RegEnumValue(hKey, dwIndex, lpValueName, lpcchValueName, lpReserved, lpType, lpData, lpcbData);
		if(!(status = (dwErrCode == ERROR_SUCCESS)))
			SetLastError(dwErrCode);
		break;
	case KULL_M_REGISTRY_TYPE_HIVE:
		pKn = hKey ? (PKULL_M_REGISTRY_HIVE_KEY_NAMED) hKey : hRegistry->pHandleHive->pRootNamedKey;
		if(pKn->tag == 'kn')
		{
			if(pKn->nbValues && (dwIndex < pKn->nbValues) && (pKn->offsetValues != -1))
			{
				pVl = (PKULL_M_REGISTRY_HIVE_VALUE_LIST) (hRegistry->pHandleHive->pStartOf + pKn->offsetValues);
				pVk = (PKULL_M_REGISTRY_HIVE_VALUE_KEY) (hRegistry->pHandleHive->pStartOf + pVl->offsetValue[dwIndex]);
				if((pVk->tag == 'kv') && lpValueName && lpcchValueName)
				{
					if(pVk->szValueName)
					{
						if(pVk->flags & KULL_M_REGISTRY_HIVE_VALUE_KEY_FLAG_ASCII_NAME)
						{
							szBuffer = pVk->szValueName + 1;
							buffer = kull_m_string_qad_ansi_c_to_unicode((char *) pVk->valueName, pVk->szValueName);
						}
						else
						{
							szBuffer = pVk->szValueName / sizeof(wchar_t) + 1;
							if(buffer = (wchar_t *) LocalAlloc(LPTR, pVk->szValueName + sizeof(wchar_t)))
								RtlCopyMemory(buffer, pVk->valueName, pVk->szValueName);
						}

						if(buffer)
						{
							if(status = (*lpcchValueName >= szBuffer))
							{
								RtlCopyMemory(lpValueName, buffer, szBuffer * sizeof(wchar_t));
								*lpcchValueName = szBuffer - 1;
							}
							LocalFree(buffer);
						}
					}
					else if(!pVk->szValueName)
					{
						lpValueName = NULL;
						*lpcchValueName = 0;
					}

					if(status)
					{
						szBuffer = pVk->szData & ~0x80000000;
						if(lpType)
							*lpType = pVk->typeData;

						if(lpcbData)
						{
							if(lpData)
							{
								if(status = (*lpcbData >= szBuffer))
								{
									dataLoc = (pVk->szData & 0x80000000) ? &pVk->offsetData : (PVOID) &(((PKULL_M_REGISTRY_HIVE_BIN_CELL) (hRegistry->pHandleHive->pStartOf + pVk->offsetData))->data);
									RtlCopyMemory(lpData, dataLoc , szBuffer);
								}
							}
							*lpcbData = szBuffer;
						}
					}
				}
			}
		}
		break;
	default:
		break;
	}
	return status;
}
コード例 #13
0
ファイル: kull_m_registry.c プロジェクト: 2005wind/mimikatz
BOOL kull_m_registry_RegQueryValueEx(IN PKULL_M_REGISTRY_HANDLE hRegistry, IN HKEY hKey, IN OPTIONAL LPCWSTR lpValueName, IN LPDWORD lpReserved, OUT OPTIONAL LPDWORD lpType, OUT OPTIONAL LPBYTE lpData, IN OUT OPTIONAL LPDWORD lpcbData)
{
	BOOL status = FALSE;
	DWORD dwErrCode, i, szData;
	PKULL_M_REGISTRY_HIVE_KEY_NAMED pKn;
	PKULL_M_REGISTRY_HIVE_VALUE_LIST pVl;
	PKULL_M_REGISTRY_HIVE_VALUE_KEY pVk, pFvk = NULL;
	wchar_t * buffer;
	PVOID dataLoc;

	switch(hRegistry->type)
	{
		case KULL_M_REGISTRY_TYPE_OWN:
			dwErrCode = RegQueryValueEx(hKey, lpValueName, lpReserved, lpType, lpData, lpcbData);
			if(!(status = (dwErrCode == ERROR_SUCCESS)))
				SetLastError(dwErrCode);
			break;
		case KULL_M_REGISTRY_TYPE_HIVE:
			pKn = hKey ? (PKULL_M_REGISTRY_HIVE_KEY_NAMED) hKey : hRegistry->pHandleHive->pRootNamedKey;
			if(pKn->tag == 'kn')
			{
				if(pKn->nbValues && (pKn->offsetValues != -1))
				{
					pVl = (PKULL_M_REGISTRY_HIVE_VALUE_LIST) (hRegistry->pHandleHive->pStartOf + pKn->offsetValues);
					for(i = 0 ; i < pKn->nbValues && !pFvk; i++)
					{
						pVk = (PKULL_M_REGISTRY_HIVE_VALUE_KEY) (hRegistry->pHandleHive->pStartOf + pVl->offsetValue[i]);
						if(pVk->tag == 'kv')
						{
							if(lpValueName)
							{
								if(pVk->szValueName)
								{
									if(pVk->flags & KULL_M_REGISTRY_HIVE_VALUE_KEY_FLAG_ASCII_NAME)
										buffer = kull_m_string_qad_ansi_c_to_unicode((char *) pVk->valueName, pVk->szValueName);
									else if(buffer = (wchar_t *) LocalAlloc(LPTR, pVk->szValueName + sizeof(wchar_t)))
										RtlCopyMemory(buffer, pVk->valueName, pVk->szValueName);

									if(buffer)
									{
										if(_wcsicmp(lpValueName, buffer) == 0)
											pFvk = pVk;
										LocalFree(buffer);
									}
								}
							}
							else if(!pVk->szValueName)
								pFvk = pVk;

							if(status = (pFvk != NULL))
							{
								szData = pFvk->szData & ~0x80000000;
								if(lpType)
									*lpType = pFvk->typeData;
								
								if(lpcbData)
								{
									if(lpData)
									{
										if(status = (*lpcbData >= szData))
										{
											dataLoc = (pFvk->szData & 0x80000000) ? &pFvk->offsetData : (PVOID) &(((PKULL_M_REGISTRY_HIVE_BIN_CELL) (hRegistry->pHandleHive->pStartOf + pFvk->offsetData))->data);
											RtlCopyMemory(lpData, dataLoc , szData);
										}
									}
									*lpcbData = szData;
								}
							}
						}
					}
				}
			}
			break;
		default:
			break;
	}
	return status;
}
コード例 #14
0
ファイル: pentagram.cpp プロジェクト: amichaelt/pentagram
 PCHAR*
 CommandLineToArgvA(
     PCHAR CmdLine,
     int* _argc
     )
 {
     PCHAR* argv;
     PCHAR  _argv;
     ULONG   len;
     ULONG   argc;
     CHAR   a;
     ULONG   i, j;

     BOOLEAN  in_QM;
     BOOLEAN  in_TEXT;
     BOOLEAN  in_SPACE;

     len = strlen(CmdLine);
     i = ((len+2)/2)*sizeof(PVOID) + sizeof(PVOID);

	 argv = (PCHAR*)LocalAlloc(LMEM_FIXED, i + (len+2)*sizeof(CHAR));

     _argv = (PCHAR)(((PUCHAR)argv)+i);

     argc = 0;
     argv[argc] = _argv;
     in_QM = FALSE;
     in_TEXT = FALSE;
     in_SPACE = TRUE;
     i = 0;
     j = 0;

     while( a = CmdLine[i] ) {
         if(in_QM) {
             if(a == '\"') {
                 in_QM = FALSE;
             } else {
                 _argv[j] = a;
                 j++;
             }
         } else {
             switch(a) {
             case '\"':
                 in_QM = TRUE;
                 in_TEXT = TRUE;
                 if(in_SPACE) {
                     argv[argc] = _argv+j;
                     argc++;
                 }
                 in_SPACE = FALSE;
                 break;
             case ' ':
             case '\t':
             case '\n':
             case '\r':
                 if(in_TEXT) {
                     _argv[j] = '\0';
                     j++;
                 }
                 in_TEXT = FALSE;
                 in_SPACE = TRUE;
                 break;
             default:
                 in_TEXT = TRUE;
                 if(in_SPACE) {
                     argv[argc] = _argv+j;
                     argc++;
                 }
                 _argv[j] = a;
                 j++;
                 in_SPACE = FALSE;
                 break;
             }
         }
         i++;
     }
     _argv[j] = '\0';
     argv[argc] = NULL;

     (*_argc) = argc;
     return argv;
 }
コード例 #15
0
/*
 * @implemented
 */
BOOL
WINAPI
EnumProcesses(DWORD *lpidProcess,
              DWORD cb,
              LPDWORD lpcbNeeded)
{
    NTSTATUS Status;
    DWORD Size = MAXSHORT, Count;
    PSYSTEM_PROCESS_INFORMATION ProcInfo;
    PSYSTEM_PROCESS_INFORMATION ProcInfoArray;

    /* First of all, query all the processes */
    do
    {
        ProcInfoArray = LocalAlloc(LMEM_FIXED, Size);
        if (ProcInfoArray == NULL)
        {
            return FALSE;
        }

        Status = NtQuerySystemInformation(SystemProcessInformation, ProcInfoArray, Size, NULL);
        if (Status == STATUS_INFO_LENGTH_MISMATCH)
        {
            LocalFree(ProcInfoArray);
            Size += MAXSHORT;
            continue;
        }

        break;
    }
    while (TRUE);

    if (!NT_SUCCESS(Status))
    {
        LocalFree(ProcInfoArray);
        SetLastError(RtlNtStatusToDosError(Status));
        return FALSE;
    }

    /* Then, loop to output data */
    Count = 0;
    ProcInfo = ProcInfoArray;

    _SEH2_TRY
    {
        do
        {
            /* It may sound weird, but actually MS only updated Count on
             * successful write. So, it cannot measure the amount of space needed!
             * This is really tricky.
             */
            if (Count < cb / sizeof(DWORD))
            {
                lpidProcess[Count] = (DWORD)ProcInfo->UniqueProcessId;
                Count++;
            }

            if (ProcInfo->NextEntryOffset == 0)
            {
                break;
            }

            ProcInfo = (PSYSTEM_PROCESS_INFORMATION)((ULONG_PTR)ProcInfo + ProcInfo->NextEntryOffset);
        }
        while (TRUE);

        *lpcbNeeded = Count * sizeof(DWORD);
    }
    _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
    {
        SetLastError(RtlNtStatusToDosError(_SEH2_GetExceptionCode()));
        LocalFree(ProcInfoArray);
        _SEH2_YIELD(return FALSE);
    }
    _SEH2_END;

    LocalFree(ProcInfoArray);
    return TRUE;
}
コード例 #16
0
ファイル: Anti_U_Folder_Hider.cpp プロジェクト: cpylua/wsuite
BOOL ScanUDisk(IN LPCTSTR lpUDisk,IN BOOL bDelSuspicious)
{
	size_t dwLen = 0;
	size_t dwDirNameLen = 0;

	LPTSTR lpSearchDisk = NULL;		//The U Disk to search
	LPTSTR lpDirName = NULL;		//Full file path
	LPTSTR lpFileName = NULL;		//File with the same name as a directory, but has a ".exe" type extension

	HANDLE hFind = INVALID_HANDLE_VALUE;
	WIN32_FIND_DATA FindFileData;

	//Build the search string
	StringCchLength(lpUDisk,20/*set this to 4 later*/,&dwLen);
	lpSearchDisk = (LPTSTR)LocalAlloc(LPTR,(dwLen+2) * sizeof(TCHAR));
	StringCchPrintf(lpSearchDisk,dwLen+3,TEXT("%s%s"),lpUDisk,TEXT("*"));

	hFind = FindFirstFile(lpSearchDisk, &FindFileData);
	if (hFind != INVALID_HANDLE_VALUE)
	{
		do
		{
			if ( IsDotsDirectory(FindFileData.cFileName) )
				continue;

			//construct the directory or file full path
			StringCchLength(FindFileData.cFileName,MAX_PATH,&dwDirNameLen);	//get the directory name length
			dwDirNameLen += dwLen + 2;
			lpDirName = (LPTSTR)LocalAlloc(LPTR,dwDirNameLen * sizeof(TCHAR));	
			StringCchPrintf(lpDirName,LocalSize((HLOCAL)lpDirName),TEXT("%s%s"),lpUDisk,FindFileData.cFileName);
			
			//construct the full suspicious file path
			lpFileName = (LPTSTR)LocalAlloc(LPTR,(dwDirNameLen + 4) * sizeof(TCHAR));
			StringCchPrintf(lpFileName,LocalSize((HLOCAL)lpFileName),TEXT("%s.exe"),lpDirName);

			if ( (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY )
			{
				//it's a directory
				SetFileAttributes(lpDirName,FindFileData.dwFileAttributes & ~FILE_ATTRIBUTE_HIDDEN & ~FILE_ATTRIBUTE_SYSTEM);
				
				if( bDelSuspicious )
				{
					//delete suspicious file
					DelSuspiciousFile(lpFileName,FindFileData.dwFileAttributes);
				}
			}
			else		//it's a file
			{	
				if( bDelSuspicious )
				{
					//delete "autorun.inf"
					if( !_tcsicmp(FindFileData.cFileName,TEXT("autorun.inf")) )
						DelSuspiciousFile(lpDirName,FILE_ATTRIBUTE_NORMAL);
						
					//delete other malicious files
					if( IsFileMalicious(FindFileData.cFileName) )
					{						
						DelSuspiciousFile(lpDirName,FindFileData.dwFileAttributes);
					}
				}
			}

		} while (FindNextFile(hFind, &FindFileData));
	}
	FindClose(hFind);
	hFind = NULL;

	LocalFree((HLOCAL)lpDirName);
	LocalFree((HLOCAL)lpSearchDisk);
	lpSearchDisk = NULL;
	lpDirName = NULL;	
	
	return TRUE;
}
コード例 #17
0
ファイル: kuhl_m_dpapi_creds.c プロジェクト: 0x0mar/mimikatz
NTSTATUS kuhl_m_dpapi_vault(int argc, wchar_t * argv[])
{
	PCWSTR inFilePolicy, inFileCred;
	PVOID filePolicy, fileCred, out;
	DWORD szFilePolicy, szFileCred, szOut, len, i, mode = CRYPT_MODE_CBC;
	BYTE aes128[AES_128_KEY_SIZE], aes256[AES_256_KEY_SIZE];
	PKULL_M_CRED_VAULT_POLICY vaultPolicy;
	PKULL_M_CRED_VAULT_CREDENTIAL vaultCredential;
	PKULL_M_CRED_VAULT_CREDENTIAL_ATTRIBUTE attribute;
	PKULL_M_CRED_VAULT_CLEAR clear;
	PVOID buffer;
	BOOL isAttr;
	HCRYPTPROV hProv;
	HCRYPTKEY hKey;
	
	if(kull_m_string_args_byName(argc, argv, L"cred", &inFileCred, NULL))
	{
		if(kull_m_file_readData(inFileCred, (PBYTE *) &fileCred, &szFileCred))
		{
			if(vaultCredential = kull_m_cred_vault_credential_create(fileCred))
			{
				kull_m_cred_vault_credential_descr(0, vaultCredential);

				if(kull_m_string_args_byName(argc, argv, L"policy", &inFilePolicy, NULL))
				{
					if(kull_m_file_readData(inFilePolicy, (PBYTE *) &filePolicy, &szFilePolicy))
					{
						if(vaultPolicy = kull_m_cred_vault_policy_create(filePolicy))
						{
							kull_m_cred_vault_policy_descr(0, vaultPolicy);
							if(kuhl_m_dpapi_unprotect_raw_or_blob(vaultPolicy->key->KeyBlob, vaultPolicy->key->dwKeyBlob, NULL, argc, argv, NULL, 0, &out, &szOut, L"Decrypting Policy Keys:\n"))
							{
								if(kull_m_cred_vault_policy_key(out, szOut, aes128, aes256))
								{
									kprintf(L"  AES128 key: "); kull_m_string_wprintf_hex(aes128, AES_128_KEY_SIZE, 0); kprintf(L"\n");
									kprintf(L"  AES256 key: "); kull_m_string_wprintf_hex(aes256, AES_256_KEY_SIZE, 0); kprintf(L"\n\n");
									
									if(CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT))
									{
										for(i = 0; i < vaultCredential->__cbElements; i++)
										{
											if(attribute = vaultCredential->attributes[i])
											{
												kprintf(L"  > Attribute %u : ", attribute->id);
												if(attribute->data && (len = attribute->szData))
												{
													if(buffer = LocalAlloc(LPTR, len))
													{
														RtlCopyMemory(buffer, attribute->data, len);
														if(kuhl_m_dpapi_vault_key_type(attribute, hProv, aes128, aes256, &hKey, &isAttr))
														{
															if(CryptDecrypt(hKey, 0, TRUE, 0, (PBYTE) buffer, &len))
															{
																if(isAttr)
																{
																	kull_m_string_wprintf_hex(buffer, len, 0);
																}
																else
																{
																	kprintf(L"\n");
																	if(!attribute->id || (attribute->id == 100))
																	{
																		if(clear = kull_m_cred_vault_clear_create(buffer))
																		{
																			kull_m_cred_vault_clear_descr(1, clear);
																			kull_m_cred_vault_clear_delete(clear);
																		}
																	}
																	else kull_m_string_wprintf_hex(buffer, len, 1 | (16 << 16));
																	kprintf(L"\n");
																}
															}
															else PRINT_ERROR_AUTO(L"CryptDecrypt");
														}
														LocalFree(buffer);
													}
												}
												kprintf(L"\n");
											}
										}
										CryptReleaseContext(hProv, 0);
									}
								}
								LocalFree(out);
							}
							kull_m_cred_vault_policy_delete(vaultPolicy);
						}
						LocalFree(filePolicy);
					}
					else PRINT_ERROR_AUTO(L"kull_m_file_readData (policy)");
				}
				kull_m_cred_vault_credential_delete(vaultCredential);
			}
			LocalFree(fileCred);
		}
		else PRINT_ERROR_AUTO(L"kull_m_file_readData (cred)");
	}
	else PRINT_ERROR(L"Input Cred file needed (/cred:file)\n");
				
	return STATUS_SUCCESS;
}
コード例 #18
0
/* 
    pContext [in]: Pointer to a string containing the registry path to the active key 
    for the stream interface driver

    lpvBusContext [in]: Potentially process-mapped pointer passed as the fourth parameter to ActivateDeviceEx. 
    If this driver was loaded through legacy mechanisms, then lpvBusContext is zero.    
*/
extern "C" DWORD BKL_Init(
  LPCTSTR pContext, 
  LPCVOID lpvBusContext
)
{   
    DWORD dwStatus, dwSize, dwType;
    HKEY hkDevice = NULL;
    BKL_MDD_INFO *pBKLinfo = NULL;

    UNREFERENCED_PARAMETER(lpvBusContext);
   
    if (IsDVIMode())
        return 0;
    
    DEBUGMSG(ZONE_BACKLIGHT, (TEXT("+BKL_Init() context %s.\r\n"), pContext));


    g_pBacklight = GetBacklightObject();
    if (g_pBacklight == NULL)
    {
        goto error;
    }

    // Allocate enough storage for this instance of our backlight
    pBKLinfo = (BKL_MDD_INFO *)LocalAlloc(LPTR, sizeof(BKL_MDD_INFO));
    if (pBKLinfo == NULL)
    {
        DEBUGMSG(ZONE_ERROR, (L"ERROR: BKL_Init: "
            L"Failed allocate BKL_MDD_INFO device structure\r\n" ));
        goto error;
    }

    // get device name from registry
    dwStatus = RegOpenKeyEx(HKEY_LOCAL_MACHINE, pContext, 0, 0, &hkDevice);
    if(dwStatus != ERROR_SUCCESS) 
    {
        DEBUGMSG(ZONE_ERROR, (TEXT("BLK_Init: OpenDeviceKey failed with %u\r\n"), dwStatus));
        goto error;
    }
    dwSize = sizeof(pBKLinfo->szName);
    dwStatus = RegQueryValueEx(hkDevice, DEVLOAD_DEVNAME_VALNAME, NULL, &dwType, (LPBYTE)pBKLinfo->szName, &dwSize);
    if(dwStatus != ERROR_SUCCESS)
    {
        DEBUGMSG(ZONE_ERROR, (TEXT("BLK_Init: RegQueryValueEx failed with %u\r\n"), dwStatus));
        goto error;

    }
    RegCloseKey(hkDevice);
    hkDevice = NULL;

    // create exit event to be set by deinit:
    pBKLinfo->hExitEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
    if(NULL == pBKLinfo->hExitEvent)
    {
        DEBUGMSG(ZONE_ERROR, (TEXT("BLK_Init: OpenDeviceKey failed with %u\r\n"), dwStatus));
        goto error;
    }

    pBKLinfo->hCoreDll = LoadLibrary(TEXT("coredll.dll"));
    if (NULL != pBKLinfo->hCoreDll) 
    {
        pBKLinfo->pfnGetSystemPowerStatusEx2 = (PFN_GetSystemPowerStatusEx2)
            GetProcAddress(pBKLinfo->hCoreDll, TEXT("GetSystemPowerStatusEx2"));
        if (!pBKLinfo->pfnGetSystemPowerStatusEx2) 
        {
            DEBUGMSG(ZONE_WARN,  (TEXT("GetProcAddress failed for GetSystemPowerStatusEx2. Assuming always on AC power.\r\n")));
        }
    }

//MYS     pBKLinfo->dwPddContext = BacklightInit(pContext, lpvBusContext, &(pBKLinfo->dwCurState));
    if (g_pBacklight->Initialize(pContext) == FALSE)
        {
        DEBUGMSG(ZONE_ERROR, (L"ERROR: BKL_Init: "
            L"Failed to initialize backlight object\r\n"
            ));
        goto error;
        }
    
    // if there are no user settings for this, we act as if they are selected:
    pBKLinfo->fBatteryTapOn = TRUE;
    pBKLinfo->fExternalTapOn = TRUE;

    // in case there is no setting for this:
    pBKLinfo->dwBattTimeout = 0;
    pBKLinfo->dwACTimeout = 0;

    pBKLinfo->dwCurState = D0;
    g_pBacklight->SetPowerState(pBKLinfo->dwCurState);
 
    //create thread to wait for reg / power source changes:
    pBKLinfo->hBklThread = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)fnBackLightThread, pBKLinfo, 0, NULL);
    if(NULL == pBKLinfo->hBklThread)
    {
        DEBUGMSG(ZONE_ERROR, (TEXT("BLK_Init: OpenDeviceKey failed with %u\r\n"), dwStatus));
        goto error;
    }

    DEBUGMSG(ZONE_BACKLIGHT, (TEXT("-BKL_Init().\r\n")));

    return (DWORD) pBKLinfo;

error:
    if(hkDevice)
    {
        RegCloseKey(hkDevice);
    }

    FreeContext(pBKLinfo);    

    return 0;

}
コード例 #19
0
ファイル: gethna.c プロジェクト: Akasurde/krb5
WINAPI
rgethostbyname(char *name)
{
    struct hostent* host;
    DNS_STATUS status;
    const char *cp;
    char queryname[DNS_MAX_NAME_BUFFER_LENGTH ];
#ifdef DEBUG
    char debstr[80];
#endif
    char** domain;
    struct in_addr host_addr;

    host = (struct hostent*)(TlsGetValue(dwGhnIndex));
    if (host == NULL) {
	LPVOID lpvData = (LPVOID) LocalAlloc(LPTR, sizeof(struct hostent));
	if (lpvData != NULL) {
	    TlsSetValue(dwGhnIndex, lpvData);
	    host = (struct hostent*)lpvData;
	} else
	    return NULL;
    }

    if (host->h_name == NULL)
	host->h_name = LocalAlloc(LPTR, DNS_MAX_LABEL_BUFFER_LENGTH);
    if (host->h_aliases == NULL)
	host->h_aliases = LocalAlloc(LPTR, 1*sizeof(LPSTR));
    if (host->h_addr_list == NULL)
    {
	host->h_addr_list = LocalAlloc(LPTR, 2*sizeof(LPSTR));
	host->h_addr_list[0] = LocalAlloc(LPTR, DNS_MAX_LABEL_BUFFER_LENGTH);
    }


    /*
     * disallow names consisting only of digits/dots, unless
     * they end in a dot.
     */
    if (isdigit(name[0])) {
        for (cp = name;; ++cp) {
            if (!*cp) {
                if (*--cp == '.')
                    break;
                /*
                 * All-numeric, no dot at the end.
                 * Fake up a hostent as if we'd actually
                 * done a lookup.
                 */
                if (!inet_aton(name, &host_addr)) {
                    return((struct hostent *) NULL);
                }
                strcpy(host->h_name, name);
                host->h_aliases[0] = NULL;
                host->h_addrtype = AF_INET;
                host->h_length = sizeof(u_long);
                memcpy(host->h_addr_list[0], &host_addr, sizeof(host_addr));
				host->h_addr_list[1] = NULL;
                return (host);
            }
            if (!isdigit(*cp) && *cp != '.')
                break;
        }
    }

    strcpy(queryname, name);

    if ((_res.options & RES_INIT) == 0 && res_init() == -1)
        return NULL;
    if (strchr(name, '.') == NULL)
    {
	if (_res.options & RES_DEFNAMES)
	{
	    for (domain = _res.dnsrch; *domain; domain++) {
		strcpy(queryname, name);
		strcat(queryname, ".");
		strcat(queryname, *domain);
		status = doquery(queryname, host);
		if (status == 0)
		    break;
	    }
	}
    }
    else {
	status = doquery(queryname, host);
    }

    if (status) {
#ifdef DEBUG
	if (_res.options & RES_DEBUG)
	{
	    wsprintf(debstr, "res_query failed\n");
	    OutputDebugString(debstr);
	}
#endif
        return  NULL;
    }
    return host;
}
コード例 #20
0
ファイル: hspi.c プロジェクト: blackfa1con/openembed
PSPI_PUBLIC_CONTEXT HSP_Init(PVOID Context) 
{
	LPTSTR          				ActivePath = (LPTSTR) Context; // HKLM\Drivers\Active\xx
	PSPI_PUBLIC_CONTEXT		pPublicSpi = NULL;
	BOOL            				bResult = TRUE;
	DWORD           			dwHwIntr=0;

	RETAILMSG(1,(TEXT("++HSP_Init Function\r\n")));
	RETAILMSG(1,(TEXT("Active Path : %s\n"), ActivePath));

	if ( !(pPublicSpi = (PSPI_PUBLIC_CONTEXT)LocalAlloc( LPTR, sizeof(SPI_PUBLIC_CONTEXT) )) )
	{
		RETAILMSG(1,(TEXT("Can't not allocate for SPI Context\n")));
		return NULL;
	}


    if(!HW_Init(pPublicSpi)) 
    {
    	RETAILMSG(1,(TEXT("HW_Init is failed\n")));
    	return NULL;
    } else {
    	RETAILMSG(1,(TEXT("HW_Init is completed\n")));
    }
    
	do 
	{
		InitializeCriticalSection(&(pPublicSpi->CsRxAccess));
		InitializeCriticalSection(&(pPublicSpi->CsTxAccess));

		//Rx Thread
		pPublicSpi->hRxEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
		
		pPublicSpi->hRxThread = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)ThreadForRx, (LPVOID)pPublicSpi, 0, (LPDWORD)&pPublicSpi->dwRxThreadId);
		if (pPublicSpi->hRxThread == NULL)
		{
			RETAILMSG(1,(TEXT("SPI Rx Thread creation error!!!\n")));
			bResult = FALSE;
			break;
		}
		
		pPublicSpi->hRxDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);		
		pPublicSpi->hRxIntrDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
		
		//Tx Thread
		pPublicSpi->hTxEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
		
		pPublicSpi->hTxThread = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)ThreadForTx, (LPVOID)pPublicSpi, 0, (LPDWORD)&pPublicSpi->dwTxThreadId);
		if (pPublicSpi->hTxThread == NULL)
		{
			RETAILMSG(1,(TEXT("SPI Dma Thread creation error!!!\n")));
			bResult = FALSE;
			break;
		}
		
		pPublicSpi->hTxDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);		
		pPublicSpi->hTxIntrDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
		
		//Spi ISR
		pPublicSpi->dwSpiSysIntr = SYSINTR_NOP;
		dwHwIntr = IRQ_SPI1;		//HS-SPI

		pPublicSpi->hSpiEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
		
		if (!KernelIoControl(IOCTL_HAL_REQUEST_SYSINTR, &dwHwIntr, sizeof(DWORD), &pPublicSpi->dwSpiSysIntr, sizeof(DWORD), NULL))
		{
			RETAILMSG(1,(TEXT("Failed to request the SPI sysintr.\n")));
			pPublicSpi->dwSpiSysIntr = SYSINTR_UNDEFINED;
			bResult = FALSE;
			break;
		}

		if (!InterruptInitialize(pPublicSpi->dwSpiSysIntr, pPublicSpi->hSpiEvent, NULL, 0))
		{
			RETAILMSG(1,(TEXT("SPI Interrupt Initialization failed!!!\n")));
			bResult = FALSE;
			break;
		}

		pPublicSpi->hSpiThread = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)ThreadForSpi, (LPVOID)pPublicSpi, 0, (LPDWORD)&pPublicSpi->dwSpiThreadId);
		if (pPublicSpi->hSpiThread == NULL)
		{
			RETAILMSG(1,(TEXT("SPI ISR Thread creation error!!!\n")));
			bResult = FALSE;
			break;
		}
		
		
		//Rx DMA Done ISR
		pPublicSpi->dwRxDmaDoneSysIntr = SYSINTR_NOP;	
		dwHwIntr = IRQ_DMA3;	

		pPublicSpi->hRxDmaDoneDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
		pPublicSpi->hRxDmaDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);


		if (!KernelIoControl(IOCTL_HAL_REQUEST_SYSINTR, &dwHwIntr, sizeof(DWORD), &pPublicSpi->dwRxDmaDoneSysIntr, sizeof(DWORD), NULL))
		{
			RETAILMSG(1,(TEXT("Failed to request the SPI_DMA sysintr.\n")));
			pPublicSpi->dwRxDmaDoneSysIntr = SYSINTR_UNDEFINED;
			bResult = FALSE;
			break;
		}

		if (!InterruptInitialize(pPublicSpi->dwRxDmaDoneSysIntr, pPublicSpi->hRxDmaDoneEvent, NULL, 0))
		{
			RETAILMSG(1,(TEXT("DMA Interrupt Initialization failed!!!\n")));
			bResult = FALSE;
			break;
		}

		pPublicSpi->hRxDmaDoneThread = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)ThreadForRxDmaDone, (LPVOID)pPublicSpi, 0, (LPDWORD)&pPublicSpi->dwRxDmaDoneThreadId);
		if (pPublicSpi->hRxDmaDoneThread == NULL)
		{
			RETAILMSG(1,(TEXT("SPI Dma Thread creation error!!!\n")));
			bResult = FALSE;
			break;
		}
		
		//Tx DMA Done ISR
		pPublicSpi->dwTxDmaDoneSysIntr = SYSINTR_NOP;
		dwHwIntr = IRQ_DMA4;		
		
		pPublicSpi->hTxDmaDoneDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
		pPublicSpi->hTxDmaDoneEvent = CreateEvent(NULL, FALSE, FALSE, NULL);


		if (!KernelIoControl(IOCTL_HAL_REQUEST_SYSINTR, &dwHwIntr, sizeof(DWORD), &pPublicSpi->dwTxDmaDoneSysIntr, sizeof(DWORD), NULL))
		{
			RETAILMSG(1,(TEXT("Failed to request the SPI_DMA sysintr.\n")));
			pPublicSpi->dwTxDmaDoneSysIntr = SYSINTR_UNDEFINED;
			bResult = FALSE;
			break;
		}

		if (!InterruptInitialize(pPublicSpi->dwTxDmaDoneSysIntr, pPublicSpi->hTxDmaDoneEvent, NULL, 0))
		{
			RETAILMSG(1,(TEXT("DMA Interrupt Initialization failed!!!\n")));
			bResult = FALSE;
			break;
		}

		pPublicSpi->hTxDmaDoneThread = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)ThreadForTxDmaDone, (LPVOID)pPublicSpi, 0, (LPDWORD)&pPublicSpi->dwTxDmaDoneThreadId);
		if (pPublicSpi->hTxDmaDoneThread == NULL)
		{
			RETAILMSG(1,(TEXT("SPI Dma Thread creation error!!!\n")));
			bResult = FALSE;
			break;
		}
	} while (0);
	
	
	if(bResult) return pPublicSpi;
	else 		return NULL;
}
コード例 #21
0
ファイル: filever.c プロジェクト: mingpen/OpenNT
BOOL
VerpQueryValue16(
        const LPVOID pb,
        LPVOID lpSubBlockX,
        INT    nIndex,
        LPVOID *lplpKey,
        LPVOID *lplpBuffer,
        PUINT puLen,
        BOOL    bUnicodeNeeded
        )
{
   ANSI_STRING AnsiString;
   UNICODE_STRING UnicodeString;
   LPSTR lpSubBlock;
   LPSTR lpSubBlockOrg;
   NTSTATUS Status;

   VERBLOCK16 *pBlock = (VERBLOCK16*)pb;
   LPSTR lpStart, lpEndBlock, lpEndSubBlock;
   CHAR cTemp, cEndBlock;
   BOOL bLastSpec;
   DWORD dwHeadLen, dwTotBlockLen;
   INT  nCmp;

   BOOL bThunkNeeded;

  /*
   * If needs unicode, then we must thunk the input parameter
   * to ansi.  If it's ansi already, we make a copy so we can
   * modify it.
   */

   if (bUnicodeNeeded) {

      //
      // Thunk is not needed if lpSubBlockX == \VarFileInfo\Translation
      // or if lpSubBlockX == \
      //
      bThunkNeeded = (BOOL)((*(LPTSTR)lpSubBlockX != 0) &&
                            (lstrcmp(lpSubBlockX, TEXT("\\")) != 0) &&
                            (lstrcmpi(lpSubBlockX, szTrans) != 0));

      RtlInitUnicodeString(&UnicodeString, lpSubBlockX);
      Status = RtlUnicodeStringToAnsiString(&AnsiString, &UnicodeString, TRUE);

      if (!NT_SUCCESS(Status)) {
         SetLastError(Status);
         return FALSE;
      }
      lpSubBlock = AnsiString.Buffer;

   } else {
     lpSubBlockOrg = (LPSTR)LocalAlloc(LPTR,(lstrlenA(lpSubBlockX)+1)*sizeof(CHAR));
     if (lpSubBlockOrg == NULL ) {
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        return FALSE;
     }
     lstrcpyA(lpSubBlockOrg,lpSubBlockX);
     lpSubBlock = lpSubBlockOrg;
   }

   *puLen = 0;

  /* Ensure that the total length is less than 32K but greater than the
   * size of a block header; we will assume that the size of pBlock is at
   * least the value of this first INT.
   */
  if ((INT)pBlock->wTotLen < sizeof(VERBLOCK16))
      goto Fail;

  /*
   * Put a '\0' at the end of the block so that none of the lstrlen's will
   * go past then end of the block.  We will replace it before returning.
   */
  lpEndBlock = ((LPSTR)pBlock) + pBlock->wTotLen - 1;
  cEndBlock = *lpEndBlock;
  *lpEndBlock = '\0';

  bLastSpec = FALSE;

#define NOTDONE() (*lpSubBlock || nIndex != -1)

  while (NOTDONE()) {
      //
      // Ignore leading '\\'s
      //
      while (*lpSubBlock == '\\')
          ++lpSubBlock;

      if (NOTDONE()) {
          /* Make sure we still have some of the block left to play with
           */
          dwTotBlockLen = lpEndBlock - ((LPSTR)pBlock) + 1;
          if ((INT)dwTotBlockLen<sizeof(VERBLOCK16) ||
             pBlock->wTotLen>dwTotBlockLen)

             goto NotFound;

          /* Calculate the length of the "header" (the two length WORDs plus
           * the identifying string) and skip past the value
           */

          dwHeadLen = sizeof(WORD)*2 + DWORDUP(lstrlenA(pBlock->szKey)+1)
                     + DWORDUP(pBlock->wValLen);

          if (dwHeadLen > pBlock->wTotLen)
              goto NotFound;
          lpEndSubBlock = ((LPSTR)pBlock) + pBlock->wTotLen;
          pBlock = (VERBLOCK16 FAR *)((LPSTR)pBlock+dwHeadLen);

          /* Look for the first sub-block name and terminate it
           */
          for (lpStart=lpSubBlock; *lpSubBlock && *lpSubBlock!='\\';
             lpSubBlock=CharNextA(lpSubBlock))
             /* find next '\\' */ ;
          cTemp = *lpSubBlock;
          *lpSubBlock = '\0';

          /* Continue while there are sub-blocks left
           * pBlock->wTotLen should always be a valid pointer here because
           * we have validated dwHeadLen above, and we validated the previous
           * value of pBlock->wTotLen before using it
           */

          nCmp = 1;
          while ((INT)pBlock->wTotLen>sizeof(VERBLOCK16) &&
             (INT)(lpEndSubBlock-((LPSTR)pBlock))>=(INT)pBlock->wTotLen) {

              //
              // Index functionality: if we are at the end of the path
              // (cTemp == 0 set below) and nIndex is NOT -1 (index search)
              // then break on nIndex zero.  Else do normal wscicmp.
              //
              if (bLastSpec && nIndex != -1) {

                  if (!nIndex) {

                      if (lplpKey) {
                          *lplpKey = pBlock->szKey;
                      }
                      nCmp=0;

                      //
                      // Index found, set nInde to -1
                      // so that we exit this loop
                      //
                      nIndex = -1;
                      break;
                  }

                  nIndex--;

              } else {

                  //
                  // Check if the sub-block name is what we are looking for
                  //

                  if (!(nCmp=lstrcmpiA(lpStart, pBlock->szKey)))
                      break;
              }

              /* Skip to the next sub-block
               */
              pBlock=(VERBLOCK16 FAR *)((LPSTR)pBlock+DWORDUP(pBlock->wTotLen));
          }

          /* Restore the char NULLed above and return failure if the sub-block
           * was not found
           */
          *lpSubBlock = cTemp;
          if (nCmp)
              goto NotFound;
        }
        bLastSpec = !cTemp;
    }

  /* Fill in the appropriate buffers and return success
   */
  *puLen = pBlock->wValLen;

  *lplpBuffer = (LPSTR)pBlock + 4 + DWORDUP(lstrlenA(pBlock->szKey) + 1);

  //
  // Shouldn't need zero-length value check since win31 compatible.
  //

  *lpEndBlock = cEndBlock;

  /*
   * Must free string we allocated above
   */

  if (bUnicodeNeeded) {
     RtlFreeAnsiString(&AnsiString);
  } else {
     LocalFree(lpSubBlockOrg);
  }


  /*----------------------------------------------------------------------
   * thunk the results
   *
   * Must always thunk key, always ??? value
   *
   * We have no way of knowing if the resource info is binary or strings
   * Version stuff is usually string info, so thunk.
   *
   * The best we can do is assume that everything is a string UNLESS
   * we are looking at \VarFileInfo\Translation or at \.
   *
   * This is acceptable because the documenation of VerQueryValue
   * indicates that this is used only for strings (except these cases.)
   *----------------------------------------------------------------------*/

  if (bUnicodeNeeded) {

      //
      // Do thunk only if we aren't looking for \VarFileInfo\Translation or \
      //
      if (bThunkNeeded) {

         AnsiString.Length = AnsiString.MaximumLength = (SHORT)*puLen;
         AnsiString.Buffer = *lplpBuffer;

         //
         // Do the string conversion in the second half of the buffer
         // Assumes wTotLen is first filed in VERHEAD
         //
         UnicodeString.Buffer = (LPWSTR)((PBYTE)pb + DWORDUP(*((WORD*)pb)) +
             (DWORD)((PBYTE)*lplpBuffer - (PBYTE)pb)*2);

         UnicodeString.MaximumLength = (SHORT)((*puLen+1) * sizeof(WCHAR));
         RtlAnsiStringToUnicodeString(&UnicodeString, &AnsiString, FALSE);

         *lplpBuffer = UnicodeString.Buffer;
      }

      if (lplpKey) {

         //
         // Thunk the key
         //

         dwHeadLen = lstrlenA(*lplpKey);
         AnsiString.Length = AnsiString.MaximumLength = (SHORT)dwHeadLen;
         AnsiString.Buffer = *lplpKey;

         UnicodeString.Buffer = (LPWSTR) ((PBYTE)pb + DWORDUP(*((WORD*)pb)) +
            (DWORD)((PBYTE)*lplpKey - (PBYTE)pb)*2);

         UnicodeString.MaximumLength = (SHORT)((dwHeadLen+1) * sizeof(WCHAR));
         RtlAnsiStringToUnicodeString(&UnicodeString, &AnsiString, FALSE);

         *lplpKey = UnicodeString.Buffer;
     }
  }

  return(TRUE);



NotFound:

  /* Restore the char we NULLed above
   */
  *lpEndBlock = cEndBlock;

Fail:

  if (bUnicodeNeeded) {
     RtlFreeAnsiString(&AnsiString);
  } else {
     LocalFree(lpSubBlockOrg);
  }

  return(FALSE);
}
コード例 #22
0
BOOL SignVerifyFile(HCRYPTPROV hProv,
                    HCRYPTKEY hPubKey,
                    DWORD dwKeySpec,
                    ALG_ID HashAlgId,
                    LPTSTR szFileToSign,
                    LPTSTR szSigFile,
                    BOOL fSign)
{
   HCRYPTHASH hHash = NULL;
   HANDLE hDataFile = INVALID_HANDLE_VALUE;
   HANDLE hSigFile = INVALID_HANDLE_VALUE;   
   LPBYTE pbSignature = NULL;
   DWORD dwSignature;         
   BYTE pbBuffer[BUFFER_SIZE];
   DWORD dwBytesRead, dwBytesWritten;
   BOOL fResult;
   BOOL fFinished = FALSE; 
   BOOL fReturn = FALSE;

   __try
   {  
      // Open Data file
      hDataFile = CreateFile(szFileToSign, 
                             GENERIC_READ, 
                             0, 
                             NULL, 
                             OPEN_EXISTING, 
                             FILE_ATTRIBUTE_NORMAL, 
                             NULL);
      if (hDataFile == INVALID_HANDLE_VALUE)
      {
         MyPrintf(_T("CreateFile failed with %d\n"), GetLastError());
         __leave;
      }

      // Open/Create signature file
      hSigFile = CreateFile(szSigFile, 
                            GENERIC_READ|GENERIC_WRITE, 
                            0, 
                            NULL, 
                            OPEN_ALWAYS, 
                            FILE_ATTRIBUTE_NORMAL, 
                            NULL);
      if (hSigFile == INVALID_HANDLE_VALUE)
      {
         MyPrintf(_T("CreateFile failed with %d\n"), GetLastError());
         __leave;
      }

      // Create Hash
      fResult = CryptCreateHash(hProv, HashAlgId, 0, 0, &hHash);
      if (!fResult)
      {
         MyPrintf(_T("CryptCreateHash failed with %x\n"), GetLastError());
         __leave;
      }

      // Loop through file and hash file contents
      do
      {
         dwBytesRead = 0;

         fResult = ReadFile(hDataFile, pbBuffer, BUFFER_SIZE, &dwBytesRead, NULL);

         if (dwBytesRead == 0) break;

         if (!fResult)
         {
            MyPrintf(_T("ReadFile failed with %d\n"), GetLastError());
            __leave;
         }

         fFinished = (dwBytesRead < BUFFER_SIZE);

         fResult = CryptHashData(hHash, pbBuffer, dwBytesRead, 0);
         if (!fResult)
         {
            MyPrintf(_T("CryptHashData failed with %x\n"), GetLastError());
            __leave;
         }

      } while (fFinished == FALSE);

      if (fSign)
      {
         // Get Signature size
         fResult = CryptSignHash(hHash, dwKeySpec, NULL, 0, NULL, &dwSignature);
         if (!fResult)
         {
            MyPrintf(_T("CryptSignHash failed with %x\n"), GetLastError());
            __leave;
         }

         // Allocate signature bytes
         pbSignature = (LPBYTE)LocalAlloc(LPTR, dwSignature);
         if (!pbSignature)
         {
            MyPrintf(_T("LocalAlloc failed with %d\n"), GetLastError());
            __leave;
         }

         // Sign and get back signature
         fResult = CryptSignHash(hHash, dwKeySpec, NULL, 0, pbSignature, &dwSignature);
         if (!fResult)
         {
            MyPrintf(_T("CryptSignHash failed with %x\n"), GetLastError());
            __leave;
         }

         // Write signature to file
         fResult = WriteFile(hSigFile, pbSignature, dwSignature, &dwBytesWritten, NULL);
         if (!fResult)
         {
            MyPrintf(_T("WriteFile failed with %d\n"), GetLastError());
            __leave;
         }
      }
      else
      {
         // Get size of signature file
         dwSignature = GetFileSize(hSigFile, NULL);
         if (dwSignature == INVALID_FILE_SIZE)
         {
            MyPrintf(_T("GetFileSize failed with %d\n"), GetLastError());
            __leave;
         }

         // Allocate signature bytes
         pbSignature = (LPBYTE)LocalAlloc(LPTR, dwSignature);
         if (!pbSignature)
         {
            MyPrintf(_T("LocalAlloc failed with %d\n"), GetLastError());
            __leave;
         }

         // Read Signature
         fResult = ReadFile(hSigFile, pbSignature, dwSignature, &dwBytesRead, NULL);
         if (!fResult)
         {
            MyPrintf(_T("ReadFile failed with %d\n"), GetLastError());
            __leave;
         }

         // Verify Signature
         fResult = CryptVerifySignature(hHash, pbSignature, dwSignature, hPubKey, NULL, 0);
         if (!fResult)
         {
            MyPrintf(_T("CryptVerifySignature failed with %x\n"), GetLastError());
            __leave;
         }
      }

      fReturn = TRUE;
   }
   __finally
   {
      // Clean up
      if (hHash != NULL) CryptDestroyHash(hHash);      
      if (hDataFile != INVALID_HANDLE_VALUE) CloseHandle(hDataFile);
      if (hSigFile != INVALID_HANDLE_VALUE) CloseHandle(hSigFile);
      CheckAndLocalFree(pbSignature);
   }

   return fReturn;
}
コード例 #23
0
ファイル: TextObject.cpp プロジェクト: identity0815/os45
LPTSTR ASSISTANT::Text::GetTtfName()
{   
   static _TCHAR tszTtfName[512];


   HKEY hKeyMachine; 
   LONG regErr = RegOpenKeyEx (HKEY_LOCAL_MACHINE, 
                     _T("Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts"), NULL,KEY_READ,&hKeyMachine); 
	if ( regErr != ERROR_SUCCESS )
   {
      LONG regErr = RegOpenKeyEx (HKEY_LOCAL_MACHINE, 
                        _T("Software\\Microsoft\\Windows\\CurrentVersion\\Fonts"), NULL,KEY_READ,&hKeyMachine); 
      if ( regErr != ERROR_SUCCESS )
      {
         return NULL;
      }
	}

   DWORD subValues;
   regErr = RegQueryInfoKey(hKeyMachine, NULL, NULL, NULL, NULL, NULL, NULL, &subValues, NULL, NULL, NULL, NULL);
   if ( regErr != ERROR_SUCCESS )
   {
      return NULL;
   }

   HRESULT hr = ::CoInitialize(NULL);

   HDC hdc = ::CreateCompatibleDC(NULL);

   DWORD dwType;
   _TCHAR tszEntryName[512];
   _TCHAR tszEntryValue[512];
   
   HFONT font = CreateFontIndirect(&m_logFont);
   UINT cbData;       
   LPOUTLINETEXTMETRIC lpoltm;     
   SelectObject(hdc, font);
   cbData = GetOutlineTextMetrics (hdc, 0, NULL);
   DeleteObject(font);
   _TCHAR tszFontFace[512];
   if (cbData == 0) 
   {
      _tcscpy(tszFontFace, m_logFont.lfFaceName);
   }
   else
   {
      lpoltm = (LPOUTLINETEXTMETRIC)LocalAlloc (LPTR, cbData);
      GetOutlineTextMetrics (hdc, cbData, lpoltm);  
      _tcscpy(tszFontFace, (_TCHAR *)((DWORD) lpoltm + lpoltm->otmpFaceName));
   }

   bool bFoundFontInfo = false;
   for (int i = 0; i < subValues && !bFoundFontInfo; i++) 
   {       
      unsigned long entryNameLength = 512 * sizeof _TCHAR;
      unsigned long entryValueLength = 512 * sizeof _TCHAR;
      if (RegEnumValue(hKeyMachine, i, tszEntryName, &entryNameLength, 
         NULL, &dwType, (unsigned char *)tszEntryValue, &entryValueLength) != ERROR_SUCCESS)
      {
         continue;
      }
      
      _TCHAR tszFaceName[512];
      _tcscpy(tszFaceName, tszEntryName);
      _TCHAR *p = _tcsrchr(tszFaceName, '(');
      if (p != NULL)
         *p = '\0';

	  if (tszFaceName[_tcslen(tszFaceName) - 1] == _T(' '))
		  tszFaceName[_tcslen(tszFaceName) - 1] = _T('\0');

      if (_tcscmp(tszFontFace, tszFaceName) == 0)
      {
         bFoundFontInfo = true;
         UINT nStringLength = _tcslen(tszEntryValue);
         _tcscpy(tszTtfName, tszEntryValue);
         tszTtfName[nStringLength] = '\0';
      }

   }

   ::DeleteDC(hdc);
   ::CoUninitialize();

   RegCloseKey(hKeyMachine);

   if (bFoundFontInfo)
      return tszTtfName;
   else
      return NULL;

}
コード例 #24
0
PTCHAR CDevice::GetDevicePath( IN  LPGUID InterfaceGuid )
{
    HDEVINFO HardwareDeviceInfo;
    SP_DEVICE_INTERFACE_DATA DeviceInterfaceData;
    PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData = NULL;
    ULONG Length, RequiredLength = 0;
    BOOL bResult;

    HardwareDeviceInfo = SetupDiGetClassDevs(
                             InterfaceGuid,
                             NULL,
                             NULL,
                             (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE)
                             );

    if (HardwareDeviceInfo == INVALID_HANDLE_VALUE)
    {
        printf("Cannot get class devices.\n");
        return NULL;
    }

    DeviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);

    bResult = SetupDiEnumDeviceInterfaces(HardwareDeviceInfo,
                             0,
                             InterfaceGuid,
                             0,
                             &DeviceInterfaceData
                             );

    if (bResult == FALSE) {
        printf("Cannot get enumerate device interfaces.\n");
        SetupDiDestroyDeviceInfoList(HardwareDeviceInfo);
        return NULL;
    }

    SetupDiGetDeviceInterfaceDetail(
        HardwareDeviceInfo,
        &DeviceInterfaceData,
        NULL,
        0,
        &RequiredLength,
        NULL
        );

    DeviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA) LocalAlloc(LMEM_FIXED, RequiredLength);

    if (DeviceInterfaceDetailData == NULL)
    {
        printf("Cannot allocate memory.\n");
        SetupDiDestroyDeviceInfoList(HardwareDeviceInfo);
        return NULL;
    }

    DeviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);

    Length = RequiredLength;

    bResult = SetupDiGetDeviceInterfaceDetail(
                             HardwareDeviceInfo,
                             &DeviceInterfaceData,
                             DeviceInterfaceDetailData,
                             Length,
                             &RequiredLength,
                             NULL
                             );

    if (bResult == FALSE)
    {
        printf("Cannot get device interface details.\n");
        SetupDiDestroyDeviceInfoList(HardwareDeviceInfo);
        LocalFree(DeviceInterfaceDetailData);
        return NULL;
    }

    return DeviceInterfaceDetailData->DevicePath;
}
コード例 #25
0
ファイル: PSCryptor.cpp プロジェクト: dannyyiu/ps-color-test
BOOL ImportPlainSessionBlob(HCRYPTPROV hProv,
                            HCRYPTKEY hPrivateKey,
                            ALG_ID dwAlgId,
                            LPBYTE pbKeyMaterial ,
                            DWORD dwKeyMaterial ,
                            HCRYPTKEY *hSessionKey)
{
   BOOL fResult;   
   BOOL fReturn = FALSE;
   BOOL fFound = FALSE;
   LPBYTE pbSessionBlob = NULL;
   DWORD dwSessionBlob, dwSize, n;
   DWORD dwPublicKeySize;
   DWORD dwProvSessionKeySize;
   ALG_ID dwPrivKeyAlg;
   LPBYTE pbPtr; 
   DWORD dwFlags = CRYPT_FIRST;
   PROV_ENUMALGS_EX ProvEnum;
   HCRYPTKEY hTempKey = 0;

   __try
   {
      // Double check to see if this provider supports this algorithm
      // and key size
      do
      {        
         dwSize = sizeof(ProvEnum);
         fResult = CryptGetProvParam(hProv, PP_ENUMALGS_EX, (LPBYTE)&ProvEnum,
                                     &dwSize, dwFlags);
         if (!fResult) break;

         dwFlags = 0;

         if (ProvEnum.aiAlgid == dwAlgId) fFound = TRUE;
                                     
      } while (!fFound);

      if (!fFound) __leave;

      // We have to get the key size(including padding)
      // from an HCRYPTKEY handle.  PP_ENUMALGS_EX contains
      // the key size without the padding so we can't use it.
      fResult = CryptGenKey(hProv, dwAlgId, 0, &hTempKey);
      if (!fResult) __leave;
      
      dwSize = sizeof(DWORD);
      fResult = CryptGetKeyParam(hTempKey, KP_KEYLEN, (LPBYTE)&dwProvSessionKeySize,
                                 &dwSize, 0);
      if (!fResult) __leave;      
      CryptDestroyKey(hTempKey);
      hTempKey = 0;

      // Our key is too big, leave
      if ((dwKeyMaterial * 8) > dwProvSessionKeySize) __leave;

      // Get private key's algorithm
      dwSize = sizeof(ALG_ID);
      fResult = CryptGetKeyParam(hPrivateKey, KP_ALGID, (LPBYTE)&dwPrivKeyAlg, &dwSize, 0);
      if (!fResult) __leave;

      // Get private key's length in bits
      dwSize = sizeof(DWORD);
      fResult = CryptGetKeyParam(hPrivateKey, KP_KEYLEN, (LPBYTE)&dwPublicKeySize, &dwSize, 0);
      if (!fResult) __leave;

      // calculate Simple blob's length
      dwSessionBlob = (dwPublicKeySize/8) + sizeof(ALG_ID) + sizeof(BLOBHEADER);

      // allocate simple blob buffer
      pbSessionBlob = (LPBYTE)LocalAlloc(LPTR, dwSessionBlob);
      if (!pbSessionBlob) __leave;

      pbPtr = pbSessionBlob;

      // SIMPLEBLOB Format is documented in SDK
      // Copy header to buffer
      ((BLOBHEADER *)pbPtr)->bType = SIMPLEBLOB;
      ((BLOBHEADER *)pbPtr)->bVersion = 2;
      ((BLOBHEADER *)pbPtr)->reserved = 0;
      ((BLOBHEADER *)pbPtr)->aiKeyAlg = dwAlgId;
      pbPtr += sizeof(BLOBHEADER);

      // Copy private key algorithm to buffer
      *((DWORD *)pbPtr) = dwPrivKeyAlg;
      pbPtr += sizeof(ALG_ID);

      // Place the key material in reverse order
      for (n = 0; n < dwKeyMaterial; n++)
      {
         pbPtr[n] = pbKeyMaterial[dwKeyMaterial-n-1];
      }
     
      // 3 is for the first reserved byte after the key material + the 2 reserved bytes at the end.
      dwSize = dwSessionBlob - (sizeof(ALG_ID) + sizeof(BLOBHEADER) + dwKeyMaterial + 3);
      pbPtr += (dwKeyMaterial+1);

      // Generate random data for the rest of the buffer
      // (except that last two bytes)
      fResult = CryptGenRandom(hProv, dwSize, pbPtr);
      if (!fResult) __leave;

      for (n = 0; n < dwSize; n++)
      {
         if (pbPtr[n] == 0) pbPtr[n] = 1;
      }

      pbSessionBlob[dwSessionBlob - 2] = 2;

      fResult = CryptImportKey(hProv, pbSessionBlob , dwSessionBlob, 
                               hPrivateKey, CRYPT_EXPORTABLE, hSessionKey);
      if (!fResult) __leave;

      fReturn = TRUE;           
   }
   __finally
   {
      if (hTempKey) CryptDestroyKey(hTempKey);
      if (pbSessionBlob) LocalFree(pbSessionBlob);
   }
   
   return fReturn;
}
コード例 #26
0
/*
 * @implemented
 */
BOOL
WINAPI
EnumDeviceDrivers(LPVOID *lpImageBase,
                  DWORD cb,
                  LPDWORD lpcbNeeded)
{
    NTSTATUS Status;
    DWORD NewSize, Count;
    PRTL_PROCESS_MODULES Information;
    /* By default, to prevent too many reallocations, we already make room for 4 modules */
    DWORD Size = sizeof(RTL_PROCESS_MODULES) + 3 * sizeof(RTL_PROCESS_MODULE_INFORMATION);

    do
    {
        /* Allocate a buffer to hold modules information */
        Information = LocalAlloc(LMEM_FIXED, Size);
        if (!Information)
        {
            SetLastError(ERROR_NO_SYSTEM_RESOURCES);
            return FALSE;
        }

        /* Query information */
        Status = NtQuerySystemInformation(SystemModuleInformation, Information, Size, &Count);
        /* In case of an error */
        if (!NT_SUCCESS(Status))
        {
            /* Save the amount of output modules */
            NewSize = Information->NumberOfModules;
            /* And free buffer */
            LocalFree(Information);

            /* If it was not a length mismatch (ie, buffer too small), just leave */
            if (Status != STATUS_INFO_LENGTH_MISMATCH)
            {
                SetLastError(RtlNtStatusToDosError(Status));
                return FALSE;
            }

            /* Compute new size length */
            ASSERT(Size >= sizeof(RTL_PROCESS_MODULES));
            NewSize *= sizeof(RTL_PROCESS_MODULE_INFORMATION);
            NewSize += sizeof(ULONG);
            ASSERT(NewSize >= sizeof(RTL_PROCESS_MODULES));
            /* Check whether it is really bigger - otherwise, leave */
            if (NewSize < Size)
            {
                ASSERT(NewSize > Size);
                SetLastError(RtlNtStatusToDosError(STATUS_INFO_LENGTH_MISMATCH));
                return FALSE;
            }

            /* Loop again with that new buffer */
            Size = NewSize;
            continue;
        }

        /* End of allocation loop */
        break;
    } while (TRUE);

    _SEH2_TRY
    {
        for (Count = 0; Count < Information->NumberOfModules && Count < cb / sizeof(LPVOID); ++Count)
        {
            lpImageBase[Count] = Information->Modules[Count].ImageBase;
        }

        *lpcbNeeded = Information->NumberOfModules * sizeof(LPVOID);
    }
    _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
    {
        SetLastError(RtlNtStatusToDosError(_SEH2_GetExceptionCode()));
        _SEH2_YIELD(return FALSE);
    }
    _SEH2_END;

    return TRUE;
}
コード例 #27
0
ファイル: batch.c プロジェクト: aragaer/wine
void WCMD_batch (WCHAR *file, WCHAR *command, int called, WCHAR *startLabel, HANDLE pgmHandle) {

  HANDLE h = INVALID_HANDLE_VALUE;
  BATCH_CONTEXT *prev_context;

  if (startLabel == NULL) {
    h = CreateFileW (file, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
                     NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if (h == INVALID_HANDLE_VALUE) {
      SetLastError (ERROR_FILE_NOT_FOUND);
      WCMD_print_error ();
      return;
    }
  } else {
    DuplicateHandle(GetCurrentProcess(), pgmHandle,
                    GetCurrentProcess(), &h,
                    0, FALSE, DUPLICATE_SAME_ACCESS);
  }

/*
 *	Create a context structure for this batch file.
 */

  prev_context = context;
  context = LocalAlloc (LMEM_FIXED, sizeof (BATCH_CONTEXT));
  context -> h = h;
  context->batchfileW = WCMD_strdupW(file);
  context -> command = command;
  memset(context -> shift_count, 0x00, sizeof(context -> shift_count));
  context -> prev_context = prev_context;
  context -> skip_rest = FALSE;

  /* If processing a call :label, 'goto' the label in question */
  if (startLabel) {
    strcpyW(param1, startLabel);
    WCMD_goto(NULL);
  }

/*
 * 	Work through the file line by line. Specific batch commands are processed here,
 * 	the rest are handled by the main command processor.
 */

  while (context -> skip_rest == FALSE) {
      CMD_LIST *toExecute = NULL;         /* Commands left to be executed */
      if (WCMD_ReadAndParseLine(NULL, &toExecute, h) == NULL)
        break;
      WCMD_process_commands(toExecute, FALSE, NULL, NULL);
      WCMD_free_commands(toExecute);
      toExecute = NULL;
  }
  CloseHandle (h);

/*
 *	If invoked by a CALL, we return to the context of our caller. Otherwise return
 *	to the caller's caller.
 */

  HeapFree(GetProcessHeap(), 0, context->batchfileW);
  LocalFree (context);
  if ((prev_context != NULL) && (!called)) {
    prev_context -> skip_rest = TRUE;
    context = prev_context;
  }
  context = prev_context;
}
コード例 #28
0
/*
 * @implemented
 */
static BOOL NTAPI
FindDeviceDriver(IN PVOID ImageBase,
                 OUT PRTL_PROCESS_MODULE_INFORMATION MatchingModule)
{
    NTSTATUS Status;
    DWORD NewSize, Count;
    PRTL_PROCESS_MODULES Information;
    RTL_PROCESS_MODULE_INFORMATION Module;
    /* By default, to prevent too many reallocations, we already make room for 4 modules */
    DWORD Size = sizeof(RTL_PROCESS_MODULES) + 3 * sizeof(RTL_PROCESS_MODULE_INFORMATION);

    do
    {
        /* Allocate a buffer to hold modules information */
        Information = LocalAlloc(LMEM_FIXED, Size);
        if (!Information)
        {
            SetLastError(ERROR_NO_SYSTEM_RESOURCES);
            return FALSE;
        }

        /* Query information */
        Status = NtQuerySystemInformation(SystemModuleInformation, Information, Size, &Count);
        /* In case of an error */
        if (!NT_SUCCESS(Status))
        {
            /* Save the amount of output modules */
            NewSize = Information->NumberOfModules;
            /* And free buffer */
            LocalFree(Information);

            /* If it was not a length mismatch (ie, buffer too small), just leave */
            if (Status != STATUS_INFO_LENGTH_MISMATCH)
            {
                SetLastError(RtlNtStatusToDosError(Status));
                return FALSE;
            }

            /* Compute new size length */
            ASSERT(Size >= sizeof(RTL_PROCESS_MODULES));
            NewSize *= sizeof(RTL_PROCESS_MODULE_INFORMATION);
            NewSize += sizeof(ULONG);
            ASSERT(NewSize >= sizeof(RTL_PROCESS_MODULES));
            /* Check whether it is really bigger - otherwise, leave */
            if (NewSize < Size)
            {
                ASSERT(NewSize > Size);
                SetLastError(RtlNtStatusToDosError(STATUS_INFO_LENGTH_MISMATCH));
                return FALSE;
            }

            /* Loop again with that new buffer */
            Size = NewSize;
            continue;
        }

        /* No modules returned? Leave */
        if (Information->NumberOfModules == 0)
        {
            break;
        }

        /* Try to find which module matches the base address given */
        for (Count = 0; Count < Information->NumberOfModules; ++Count)
        {
            Module = Information->Modules[Count];
            if (Module.ImageBase == ImageBase)
            {
                /* Copy the matching module and leave */
                memcpy(MatchingModule, &Module, sizeof(Module));
                LocalFree(Information);
                return TRUE;
            }
        }

        /* If we arrive here, it means we were not able to find matching base address */
        break;
    } while (TRUE);

    /* Release and leave */
    LocalFree(Information);
    SetLastError(ERROR_INVALID_HANDLE);

    return FALSE;
}
コード例 #29
0
ファイル: resman.c プロジェクト: RareHare/reactos
/*
 * @unimplemented
 */
AUTHZAPI
BOOL
WINAPI
AuthzInitializeResourceManager(IN DWORD flags,
                               IN PFN_AUTHZ_DYNAMIC_ACCESS_CHECK pfnAccessCheck  OPTIONAL,
                               IN PFN_AUTHZ_COMPUTE_DYNAMIC_GROUPS pfnComputeDynamicGroups  OPTIONAL,
                               IN PFN_AUTHZ_FREE_DYNAMIC_GROUPS pfnFreeDynamicGroups  OPTIONAL,
                               IN PCWSTR ResourceManagerName  OPTIONAL,
                               IN PAUTHZ_RESOURCE_MANAGER_HANDLE pAuthzResourceManager)
{
    BOOL Ret = FALSE;

    if (pAuthzResourceManager != NULL &&
        !(flags & ~(AUTHZ_RM_FLAG_NO_AUDIT | AUTHZ_RM_FLAG_INITIALIZE_UNDER_IMPERSONATION)))
    {
        PAUTHZ_RESMAN ResMan;
        SIZE_T RequiredSize = sizeof(AUTHZ_RESMAN);

        if (ResourceManagerName != NULL)
        {
            RequiredSize += wcslen(ResourceManagerName) * sizeof(WCHAR);
        }

        ResMan = (PAUTHZ_RESMAN)LocalAlloc(LMEM_FIXED,
                                           RequiredSize);
        if (ResMan != NULL)
        {
            /* initialize the resource manager structure */
#if DBG
            ResMan->Tag = RESMAN_TAG;
#endif

            ResMan->flags = flags;
            ResMan->UserSid = NULL;

            if (ResourceManagerName != NULL)
            {
                wcscpy(ResMan->ResourceManagerName,
                       ResourceManagerName);
            }
            else
                ResMan->ResourceManagerName[0] = UNICODE_NULL;

            ResMan->pfnAccessCheck = pfnAccessCheck;
            ResMan->pfnComputeDynamicGroups = pfnComputeDynamicGroups;
            ResMan->pfnFreeDynamicGroups = pfnFreeDynamicGroups;

            if (!(flags & AUTHZ_RM_FLAG_NO_AUDIT))
            {
                /* FIXME - initialize auditing */
                DPRINT1("Auditing not implemented!\n");
            }

            if (flags & AUTHZ_RM_FLAG_INITIALIZE_UNDER_IMPERSONATION)
            {
                Ret = AuthzpInitUnderImpersonation(ResMan);
            }
            else
            {
                Ret = AuthzpInitSelf(ResMan);
            }

            if (Ret)
            {
                /* finally return the handle */
                *pAuthzResourceManager = (AUTHZ_RESOURCE_MANAGER_HANDLE)ResMan;
            }
            else
            {
                DPRINT1("Querying the token failed!\n");
                LocalFree((HLOCAL)ResMan);
            }
        }
    }
    else
        SetLastError(ERROR_INVALID_PARAMETER);

    return Ret;
}
コード例 #30
0
ファイル: crypt.c プロジェクト: AmesianX/RosWine
static void test_set_provider_ex(void)
{
	DWORD result;
	DWORD notNull = 5;
        LPSTR curProvName = NULL;
        DWORD curlen;
	
	/* results */
	LPSTR pszProvName = NULL;
	DWORD cbProvName;
	
	if(!pCryptGetDefaultProviderA || !pCryptSetProviderExA)
	{
	    win_skip("CryptGetDefaultProviderA and/or CryptSetProviderExA are not available\n");
	    return;
	}

        /* store the current one */
        pCryptGetDefaultProviderA(PROV_RSA_FULL, NULL, CRYPT_MACHINE_DEFAULT, NULL, &curlen);
        if (!(curProvName = LocalAlloc(LMEM_ZEROINIT, curlen)))
            return;
        result = pCryptGetDefaultProviderA(PROV_RSA_FULL, NULL, CRYPT_MACHINE_DEFAULT, curProvName, &curlen);
        ok(result, "%d\n", GetLastError());

	/* check pdwReserved for NULL */
	result = pCryptSetProviderExA(MS_DEF_PROV, PROV_RSA_FULL, &notNull, CRYPT_MACHINE_DEFAULT);
	ok(!result && GetLastError()==ERROR_INVALID_PARAMETER, "expected %i, got %d\n",
		ERROR_INVALID_PARAMETER, GetLastError());

	/* remove the default provider and then set it to MS_DEF_PROV/PROV_RSA_FULL */
        SetLastError(0xdeadbeef);
	result = pCryptSetProviderExA(MS_DEF_PROV, PROV_RSA_FULL, NULL, CRYPT_MACHINE_DEFAULT | CRYPT_DELETE_DEFAULT);
	if (!result)
	{
                ok( GetLastError() == ERROR_ACCESS_DENIED || broken(GetLastError() == ERROR_INVALID_PARAMETER),
                    "wrong error %u\n", GetLastError() );
		skip("Not enough rights to remove the default provider\n");
                LocalFree(curProvName);
		return;
	}

	result = pCryptSetProviderExA(MS_DEF_PROV, PROV_RSA_FULL, NULL, CRYPT_MACHINE_DEFAULT);
	ok(result, "%d\n", GetLastError());
	
	/* call CryptGetDefaultProvider to see if they match */
	result = pCryptGetDefaultProviderA(PROV_RSA_FULL, NULL, CRYPT_MACHINE_DEFAULT, NULL, &cbProvName);
	ok(result, "%d\n", GetLastError());
	if (!(pszProvName = LocalAlloc(LMEM_ZEROINIT, cbProvName)))
		goto reset;

	result = pCryptGetDefaultProviderA(PROV_RSA_FULL, NULL, CRYPT_MACHINE_DEFAULT, pszProvName, &cbProvName);
	ok(result && !strcmp(MS_DEF_PROV, pszProvName), "expected %s, got %s\n", MS_DEF_PROV, pszProvName);
	ok(result && cbProvName==(strlen(MS_DEF_PROV) + 1), "expected %i, got %d\n", (lstrlenA(MS_DEF_PROV) + 1), cbProvName);

	LocalFree(pszProvName);

reset:
        /* Set the provider back to it's original */
        result = pCryptSetProviderExA(curProvName, PROV_RSA_FULL, NULL, CRYPT_MACHINE_DEFAULT);
        ok(result, "%d\n", GetLastError());
        LocalFree(curProvName);
}