Esempio n. 1
0
void CAgentCtl::ProcessInstruction(const CInstruction& instruction)
{
	USES_CONVERSION;

	if (lstrcmpi(instruction.szCommand, _T("Speak")) == 0)
		SpeakText(CComBSTR(instruction.szText));
	else if (lstrcmpi(instruction.szCommand, _T("Play")) == 0)
		m_pCharacter->Play((BSTR)CComBSTR(instruction.szText), &m_nRequestID);
	else if (lstrcmpi(instruction.szCommand, _T("Hide")) == 0)
		m_pCharacter->Hide(FALSE, &m_nRequestID);
	else if (lstrcmpi(instruction.szCommand, _T("Show")) == 0)
		m_pCharacter->Show(FALSE, &m_nRequestID);
	else if (lstrcmpi(instruction.szCommand, _T("MoveTo")) == 0)
	{
		short x, y;
#ifdef _UNICODE
		wscanf_s(instruction.szText, _T("%d, %d"), &x, &y);
#else
		sscanf_s(instruction.szText, _T("%d, %d"), &x, &y);
#endif
		m_pCharacter->MoveTo(x, y, (100-m_nSpeed)*10+100, &m_nRequestID);
	}
	else if (lstrcmpi(instruction.szCommand, _T("GestureAt")) == 0)
	{
		short x, y;
#ifdef _UNICODE
		wscanf_s(instruction.szText, _T("%d, %d"), &x, &y);
#else
		sscanf_s(instruction.szText, _T("%d, %d"), &x, &y);
#endif
		m_pCharacter->GestureAt(x, y, &m_nRequestID);
	}
}
int _tmain(int argc, _TCHAR* argv[])
{
	TCHAR szBuf[200];
	wscanf_s(L"%ls", szBuf, _countof(szBuf));
	
	HANDLE hFileRes = CreateFile(szBuf, GENERIC_WRITE | GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hFileRes == INVALID_HANDLE_VALUE)
	{
		printf("打开文件出错\n");
	}

	DWORD dwFileSize = GetFileSize(hFileRes, NULL);
	HANDLE hFileMap = CreateFileMapping(hFileRes, NULL, PAGE_READWRITE, 0, dwFileSize + sizeof(char), NULL);
	if (hFileMap == NULL)
	{
		printf("创建文件映射对象失败\n");
	}

	PVOID pvFile = MapViewOfFile(hFileMap, FILE_MAP_WRITE, 0, 0, 0);
	if (pvFile == NULL)
	{
		printf("映射文件失败\n");
	}

	PSTR psFile = (PSTR)pvFile;
	psFile[dwFileSize / sizeof(char)] = 0;
	_strrev(psFile);

	SetFilePointer(hFileRes, dwFileSize, NULL, FILE_BEGIN);
	SetEndOfFile(hFileRes);
	UnmapViewOfFile(pvFile);
	CloseHandle(hFileRes);
	CloseHandle(hFileMap);
	return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
/// ProgramaPrincipal.
/// Propósito: Método principal. Na Orientação a Objetos substitui a função main()<br>
/// Entradas: Nenhuma<br>
/// Saídas: Inteiro com o código de retorno do programa<br>
///
///////////////////////////////////////////////////////////////////////////////////////////////////
int PRINCIPAL::ProgramaPrincipal(){
	bool			 em_loop = true;
	int				 opcao_menu = -1;
	LONG			 lLastError = ERROR_SUCCESS;
	TCHAR			 nomePortaSerial[5]=_T("COM5");

	menu.BoasVindas();
	if(!logs.Inicio()) return 1;								// Se houve falha nos logs, fecha programa

	// Tenta abrir a porta serial ----------------------------------------------------------------------------
	#if defined DefPortaPersonalizada							// Porta padrão COM5 ou porta personalizada
		cout << "Digite o número da porta: ";				    // Pede pro usuário digitar o nome da porta
		wscanf_s(_T("COM%s"), &nomePortaSerial);				// Recebe e formata porta digitada COMx
	#endif														
																//
	lLastError = serial.Open(nomePortaSerial, 0, 0, false);		// Abre a porta serial
	if(!serial.VerificaSeAbriu(lLastError, nomePortaSerial))	// Verifica se abriu a porta serial
		return ERROR_SERIAL_NO_DEVICE;							// Se não abriu, termina o programa
	// -------------------------------------------------------------------------------------------------------

	// Configura a porta serial para 9600bps, 8 bits, sem paridade, 1 stop bit -------------------------------
    lLastError = serial.Setup(CSerial::EBaud9600,CSerial::EData8,CSerial::EParNone,CSerial::EStop1);
	if(!serial.VerificaSeConfigurou(lLastError))				// Verifica se configurou corretamente
		return lLastError;										// Se não configurou, termina o programa
																//
	serial.MostraConectado();									// Se aqui chegou, está conectado à serial
	// -------------------------------------------------------------------------------------------------------
	
	// Conecta com o banco de dados --------------------------------------------------------------------------
	Cmysql.Conecta();											// Tenta conectar ao banco de dados
	if(!Cmysql.MostraConcetado()){								// Mostra status (conectado ou não)
		system("pause");											//
		return 1;
	}else system("pause");
	// -------------------------------------------------------------------------------------------------------

	// Menu principal ----------------------------------------------------------------------------------------
	while(true){
		system("cls");
		while(opcao_menu==-1) opcao_menu = menu.Principal();	// Chama o menu principal
		switch(opcao_menu){										// Trata os casos
			case 0: return 0; break;							// 0: termina o programa
			case 1: I8051.ControleDeAcesso(); break;			// 1: controle de acesso
			case 2: I8051.CadastroCartao(); break;				// 2: cadastro de cartão
			case 3: menu.InserirCreditos(&Cmysql); break;		// 3: inserir créditos
			case 4: Cmysql.PegaTodos(); system("PAUSE"); break;	// 4: lista todos os cartões
			case 5: Cmysql.RemoveItem(); system("PAUSE"); break;// 5: remove cartão
			default: break;										// default: nada
		}
		opcao_menu = -1;
	}
	// -------------------------------------------------------------------------------------------------------

    serial.Close();
    return 0;
}
VOID ChooseAddress()
{
	printf("输入想要复制的地址\n");
	wscanf_s(L"%ls", szBuf, _countof(szBuf));
	WFile = CreateFile(szBuf, GENERIC_WRITE, 0, NULL, CREATE_NEW, 0, NULL);
	if (RFile == INVALID_HANDLE_VALUE)
	{
		printf("设置失败\n");
	}
	return;
}
VOID ChooseFile()
{
	printf("输入你想要复制的文件的绝对路径(不支持超过4G的文件)\n");
	wscanf_s(L"%ls", szBuf, _countof(szBuf));
	RFile = CreateFile(szBuf, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
	if (RFile == INVALID_HANDLE_VALUE)
	{
		printf("打开文件失败\n");
		return;
	}
	GetFileSizeEx(RFile, &FileSize);
	printf("文件大小:%d字节,%dKB,%dMB\n", FileSize.LowPart, FileSize.LowPart / 1024, FileSize.LowPart / 1048576);
	return;
}
//********************************************************************************************
// Function: GetKeyFromUser
//
// Description: Gets a registration key from the user (used for registration and search)
//
//********************************************************************************************
bool GetKeyFromUser(PCWSTR pcwszKeyName, BYTE* KeyData)
{
    int i;
    int hexdigit=0;
    wprintf(L"Enter %s as a string of hex digits, Example: 01 ff 0a b8 80 z\n", pcwszKeyName);
    wprintf(L"The current keysize is %i bytes.  Enter z as the last digit and the remainder of the key will be zero-filled (Most significant byte is first)\n",KEYSIZE);
    for(i=KEYSIZE-1;i>=0;i--)
    {
        if(wscanf_s(L"%2X",&hexdigit) < 1)
            break;
        KeyData[i] = (BYTE)hexdigit;
    }
    for(;i>=0;i--)
        KeyData[i] = 0;
    wprintf(L"Resulting %s:\n", pcwszKeyName);
    for(i=KEYSIZE-1;i>=0;i--)
        wprintf(L"%02x ",KeyData[i]);
    wprintf(L"\n");
    FlushCurrentLine();

    return true;
}
//********************************************************************************************
// Function: GetUserChoice
//
// Description: Presents an interactive menu to the user and returns the user's choice
//
// Input: PCWSTR *choices - An array of strings representing the choices to be presented to 
//                          the users
//
//********************************************************************************************
int GetUserChoice(PCWSTR *choices, int numchoices)
{
   int chr = -1;
   wprintf(L"---------------------------------------------------------\n");
   for(int i=0; i<numchoices; i++)
   {
      wprintf(L"   %i. %s\n",i+1,choices[i]);
   }
   wprintf(L"---------------------------------------------------------\n");
   wprintf(L"Enter a choice (1-%i): ",numchoices);
   wscanf_s(L"%i",&chr);
   FlushCurrentLine();
   if(chr > 0 && chr <= numchoices)
   {
      return chr - 1;
   }
   else
   {
      wprintf(L"Invalid Choice\n");
      return -1;
   }
}
Esempio n. 8
0
int wmain(int argc, wchar_t * argv[])
{
	int i, status = STATUS_SUCCESS;
#ifndef _WINDLL
	wchar_t input[0xff];
	_setmode(_fileno(stdout), _O_U8TEXT);
	_setmode(_fileno(stderr), _O_U8TEXT);
	SetConsoleOutputCP(CP_UTF8);
	SetConsoleTitle(MIMIKATZ L" " MIMIKATZ_VERSION L" " MIMIKATZ_ARCH);
	SetConsoleCtrlHandler(HandlerRoutine, TRUE);
#endif
	kprintf(L"\n"
		L"  .#####.   " MIMIKATZ_FULL L"\n"
		L" .## ^ ##.  \n"
		L" ## / \\ ##  /* * *\n"
		L" ## \\ / ##   Benjamin DELPY `gentilkiwi` ( [email protected] )\n"
		L" '## v ##'   http://blog.gentilkiwi.com/mimikatz             (oe.eo)\n"
		L"  '#####'                                    with %3u modules * * */\n\n", sizeof(mimikatz_modules) / sizeof(KUHL_M *));
	
	mimikatz_initOrClean(TRUE);
	for(i = MIMIKATZ_AUTO_COMMAND_START ; (i < argc) && (status != STATUS_FATAL_APP_EXIT) ; i++)
	{
		kprintf(L"\n" MIMIKATZ L"(" MIMIKATZ_AUTO_COMMAND_STRING L") # %s\n", argv[i]);
		status = mimikatz_dispatchCommand(argv[i]);
	}
#ifndef _WINDLL
	while (status != STATUS_FATAL_APP_EXIT)
	{
		kprintf(L"\n" MIMIKATZ L" # "); fflush(stdin);
		if(wscanf_s(L"%[^\n]s", input, sizeof(input)) == 1)
		{
			kprintf_inputline(L"%s\n", input);
			status = mimikatz_dispatchCommand(input);
		}
	}
#endif
	mimikatz_initOrClean(FALSE);
	return STATUS_SUCCESS;
}
//********************************************************************************************
// Function: UnRegisterKey
//
// Description: Unregisters a previously registered key
//
//********************************************************************************************
bool UnRegisterKey(DRT_CONTEXT* Drt)
{
    int choice = 0;
    wprintf(L"Current Registrations:\n");
    for(UINT i=0; i<Drt->registrations.size(); i++)
    {
        wprintf(L"%i: ",i);
        for(int k=Drt->registrations[i].regInfo.key.cb-1; k>=0; k--)
            wprintf(L" %02x",Drt->registrations[i].regInfo.key.pb[k]);
        wprintf(L"\n");
    }
    wprintf(L"Enter a registration to unregister (or c to cancel):");
    if( (wscanf_s(L"%i",&choice) < 1) || 
        (choice >= (int)Drt->registrations.size()) || 
        (choice < 0) )
    {
        FlushCurrentLine();
        goto Cleanup;
    }
    FlushCurrentLine();

    wprintf(L"Unregistering key: ");
    for(int k=Drt->registrations[choice].regInfo.key.cb; k<=0; k++)
        wprintf(L" %02x",Drt->registrations[choice].regInfo.key.pb[k]);
    wprintf(L"\n");

    DrtUnregisterKey(Drt->registrations[choice].hDrtReg);

    if(Drt->registrations[choice].regInfo.key.pb)
        free(Drt->registrations[choice].regInfo.key.pb);
    if(Drt->registrations[choice].regInfo.appData.pb)
        free(Drt->registrations[choice].regInfo.appData.pb);
    Drt->registrations.erase(Drt->registrations.begin()+choice);

Cleanup:
    return true;
}
//********************************************************************************************
// Function: InitializeDrt
//
// Description: Initializes and brings a DRT instance online
//   1) Brings up an ipv6 transport layer
//   2) Attaches a security provider (according to user's choice)
//   3) Attaches a bootstrap provider (according to user's choice)
//   4) Calls DrtOpen to bring the DRT instance online
//
//********************************************************************************************
bool InitializeDrt(DRT_CONTEXT *Drt)
{
    HRESULT         hr = S_OK;
    DWORD           dwSize = 0;
    PWSTR           pwszCompName = NULL;
    WCHAR           pwszBootstrapHostname[1024] = {0};
    USHORT          usBootstrapPort = 0;

    //
    // Initialize DrtSettings
    //
    Drt->port = 0;
    Drt->settings.pwzDrtInstancePrefix = L"Local_DRT";
    Drt->settings.dwSize = sizeof(DRT_SETTINGS);
    Drt->settings.cbKey = KEYSIZE;
    Drt->settings.ulMaxRoutingAddresses = 4;
    Drt->settings.bProtocolMajorVersion = 0x6;
    Drt->settings.bProtocolMinorVersion = 0x65;
    Drt->settings.eSecurityMode = DRT_SECURE_CONFIDENTIALPAYLOAD;
    Drt->settings.hTransport = NULL;
    Drt->settings.pSecurityProvider = NULL;
    Drt->settings.pBootstrapProvider = NULL;
    Drt->hDrt = NULL;

    //
    // *Transport*
    //

    hr = DrtCreateIpv6UdpTransport(
        DRT_GLOBAL_SCOPE, 
        0,
        300, 
        &Drt->port, 
        &Drt->settings.hTransport
        );
    
    VERIFY_OR_ABORT("DrtCreateTransport",hr);
    
    //
    // *Security Provider*
    //

    if(Drt->SecurityProviderType == 0) //Null Security Provider
    {
        hr = DrtCreateNullSecurityProvider(&Drt->settings.pSecurityProvider);
    }
    else if(Drt->SecurityProviderType == 1) //Derived Key Security Provider
    {
        hr = ReadCertFromFile(L"RootCertificate.cer", &Drt->pRoot, NULL);
        if (FAILED(hr))
        {
            wprintf(L"No RootCertificate.cer file found in the current directory, Creating a new root certificate.\n");
            hr = MakeCert(L"RootCertificate.cer", L"RootCert", NULL, NULL);
            VERIFY_OR_ABORT(L"MakeCert",hr);
            hr = ReadCertFromFile(L"RootCertificate.cer", &Drt->pRoot, NULL);
            VERIFY_OR_ABORT(L"ReadCertFromFile", hr);
        }

        // We now have a root cert, read an existing local cert or create one based on root cert
        hr = ReadCertFromFile(L"LocalCertificate.cer", &Drt->pLocal, NULL);
        if (FAILED(hr))
        {
            wprintf(L"No LocalCertificate.cer file found in the current directory, Creating a new local certificate.\n");
            hr = MakeCert(L"LocalCertificate.cer", L"LocalCert", L"RootCertificate.cer", L"RootCert");
            VERIFY_OR_ABORT(L"MakeCert",hr);
            hr = ReadCertFromFile(L"LocalCertificate.cer", &Drt->pLocal, NULL);
            VERIFY_OR_ABORT(L"ReadCertFromFile", hr);
        }
        hr = DrtCreateDerivedKeySecurityProvider(
            Drt->pRoot,
            Drt->pLocal,
            &Drt->settings.pSecurityProvider
            );
    }
    else if(Drt->SecurityProviderType == 2) //Custom Security Provider
    {
        hr = DrtCreateCustomSecurityProvider(&Drt->settings.pSecurityProvider);
    }
    else
    {
        wprintf(L"Invalid Security Provider passed to InitializeDrt");
        hr = E_FAIL;
    }
    VERIFY_OR_ABORT("DrtCreateSecurityProvider",hr);

    //
    // *Bootstrap Provider*
    //

    if(Drt->BootstrapProviderType == 0) //DNS Bootstrap Provider
    {
        GetComputerNameEx(ComputerNameDnsFullyQualified, NULL, &dwSize );
        pwszCompName = new WCHAR[dwSize+1];
        if(pwszCompName == NULL)
        {
            hr = E_OUTOFMEMORY;
            wprintf(L"Out of memory");
            goto Cleanup;
        }
        ::GetComputerNameEx(ComputerNameDnsFullyQualified, pwszCompName, &dwSize);

        wprintf(L"Enter 'hostname port' for DNS Bootstrap Provider (currently %s %i):\n", pwszCompName, Drt->port);
        if(wscanf_s(L"%s %hu",pwszBootstrapHostname, 1024, &usBootstrapPort) < 2)
        {
            FlushCurrentLine();
            hr = E_INVALIDARG;
            wprintf(L"Invalid hostname:port\n");
            goto Cleanup;
        }
        wprintf(L"DNS Bootstrapping from: %s:%i\n",pwszBootstrapHostname, usBootstrapPort);
        FlushCurrentLine();
     
        hr = DrtCreateDnsBootstrapResolver(
            usBootstrapPort,
            pwszBootstrapHostname,
            &Drt->settings.pBootstrapProvider
            );
    }
    else if (Drt->BootstrapProviderType == 1) //PNRP Bootstrap Provider
    {
        wprintf(L"Enter a PNRP name for PNRP Bootstrap Provider (IE 0.DemoName)\n");
        if(wscanf_s(L"%s",pwszBootstrapHostname, 1024) < 1)
        {
            FlushCurrentLine();
            wprintf(L"Invalid PNRP name\n");
            goto Cleanup;
        }
        wprintf(L"PNRP Bootstrapping from: %s\n",pwszBootstrapHostname);
        FlushCurrentLine();
        hr = DrtCreatePnrpBootstrapResolver(
            TRUE,
            pwszBootstrapHostname,
            L"Global_",
            NULL,
            &Drt->settings.pBootstrapProvider
            );
    }
    else if (Drt->BootstrapProviderType == 2) //Custom Bootstrap Provider
    {
        GetComputerNameEx(ComputerNameDnsFullyQualified, NULL, &dwSize );
        pwszCompName = new WCHAR[dwSize+1];
        ::GetComputerNameEx(ComputerNameDnsFullyQualified, pwszCompName, &dwSize);

        if(pwszCompName == NULL)
        {
            hr = E_OUTOFMEMORY;
            wprintf(L"Out of memory");
            goto Cleanup;
        }

        wprintf(L"Enter 'hostname port' for Custom Bootstrap Provider (currently %s %i\n", pwszCompName, Drt->port);
        if(wscanf_s(L"%s %hu",pwszBootstrapHostname, 1024, &usBootstrapPort) < 2)
        {
            FlushCurrentLine();
            hr = E_INVALIDARG;
            wprintf(L"Invalid hostname:port\n");
            goto Cleanup;
        }
        wprintf(L"Custom Bootstrapping from: %s:%i\n",pwszBootstrapHostname, usBootstrapPort);
        FlushCurrentLine();
     
        hr = DrtCreateCustomBootstrapResolver(
            usBootstrapPort,
            pwszBootstrapHostname,
            &Drt->settings.pBootstrapProvider
            );
    }
    else
    {
        wprintf(L"Invalid Bootstrap Provider passed to InitializeDrt");
        hr = E_FAIL;
    }
    VERIFY_OR_ABORT("DrtCreateBootstrapResolver",hr);

    //
    // *Make sure the Windows Firewall is open*
    //  Also open port 3540 (used by PNRP, if the PNRP bootstrap provider is chosen)
    //

    if(Drt->BootstrapProviderType==1)
        hr = OpenFirewallForDrtSdkSample(TRUE);
    else
        hr = OpenFirewallForDrtSdkSample(FALSE);

    VERIFY_OR_ABORT("OpenFirewallForDrtSdkSample",hr);
    
    //
    // Open the DRT
    //

    Drt->eventHandle = CreateEvent(NULL, FALSE, FALSE, NULL);
    if(NULL == Drt->eventHandle)
    {
        hr = E_OUTOFMEMORY;
        goto Cleanup;
    }

    hr = DrtOpen(&Drt->settings, Drt->eventHandle, NULL, &Drt->hDrt);

    VERIFY_OR_ABORT("DrtOpen", hr);

    //
    // Register a callback to handle DRT Events
    //
    RegisterWaitForSingleObject(&Drt->DrtWaitEvent, Drt->eventHandle, (WAITORTIMERCALLBACK)DrtEventCallback, Drt, INFINITE, WT_EXECUTEDEFAULT);
    
Cleanup:
    if(pwszCompName)
        delete pwszCompName;
    return SUCCEEDED(hr);
}
Esempio n. 11
0
// Search and kill the TeslaCrypt process
bool CTeslaDecrypterApp::SearchAndKillTeslaProc(bool bAskUser, bool bKill, bool bDelete) {
	TCHAR answer[6] = {0};				// User answer if I need to aske
	DWORD dwLastErr = 0;				// Last Win32 error
	BOOL bRetVal = FALSE;				// Returned value
	TCHAR teslaProcPath[MAX_PATH] = {0};			// The TeslaCrypt process full path

	// Get if there is a suspicious TeslaCrypt process running
	DWORD dwTeslaProcId = 0;					// Tesla process ID (if any)
	dwTeslaProcId = SearchForTeslaCryptProcess(teslaProcPath, MAX_PATH);

	if (dwTeslaProcId) {
		cl_wprintf(YELLOW, L"Warning! ");
		wprintf(L"Found TeslaCrypt process running on this system...\r\n");

		if (bAskUser) {
			wprintf(L"This process needs to be terminated before running the decryption.\r\n");
			wprintf(L"Would you like to terminate process #%i? [Y/N] ", dwTeslaProcId);
			
			rewind(stdin);
			wscanf_s(L"%4s", answer, COUNTOF(answer));
		} else 
			answer[0] = (bKill == true ? 'Y' : 'N');

		if (CHR_UPR(answer[0]) == 'Y') {
			HANDLE hProc =
				OpenProcess(PROCESS_TERMINATE, FALSE, dwTeslaProcId);
			if (hProc) {
				bRetVal = TerminateProcess(hProc, 0);
				if (bRetVal) Sleep(800);
				CloseHandle(hProc);
			}
			dwLastErr = GetLastError();
			if (bRetVal)
				wprintf(L"Process #%i Terminated.\r\n", dwTeslaProcId);
		}

		if (!bRetVal) {			// if target process was successfully killed
			cl_wprintf(RED, L"Error! ");
			wprintf(L"Unable to terminate TeslaCrypt process!\r\n"
				L"Bad things can happens....\r\n");
		} else {
			// Delete the found dropper (if needed)
			if (bAskUser) {
				wprintf(L"Would you like to delete the TeslaCrypt dropper? [Y/N] ");
				rewind(stdin);
				wscanf_s(L"%4s", answer, COUNTOF(answer));
			} else 
				answer[0] = (bDelete == true ? 'Y' : 'N');
			
			if (CHR_UPR(answer[0]) == 'Y') {
				// Delete the identified dropper file
				bRetVal = DeleteFile(teslaProcPath);
				if (bRetVal) {
					wprintf(L"TeslaCrypt dropper successfully deleted!\r\n");
					g_pLog->WriteLine(L"SearchAndKillTeslaProc - Successfully deleted \"%s\" TeslaCrypt dropper.",
						teslaProcPath);
				} else {
					wprintf(L"Unable to delete TeslaCrypt dropper.\r\n");
					g_pLog->WriteLine(L"SearchAndKillTeslaProc - Unable to delete \"%s\" file. Returned error: %i.",
						teslaProcPath, (LPVOID)GetLastError());
				}
			}
		} // END if target process was successfully killed
	}
	return (dwTeslaProcId != 0);
}
Esempio n. 12
0
// Normal application startup without any command line
int CTeslaDecrypterApp::NoCmdLineMain() {
	bool bRetVal = false;
	DWORD dwStrLen = 0;
	LPTSTR appDataStr = NULL;					// %APPDATA% full path
	LPTSTR keyDatPath = NULL;					// "key.dat" file standard location
	bool bDoEntirePcDecrypt = false;			// TRUE if I have to decrypt all the workstation files
	TCHAR answer[8] = {0};						// User answer
	TCHAR dirOrFileToDecrypt[MAX_PATH] = {0};	// The file or directory to decrypt

	// Search key.dat file
	keyDatPath = SearchAndImportKeyFile();

	if (!keyDatPath) {
		cl_wprintf(RED, L"\r\nError! ");
		wprintf(L"Unable to recover TeslaCrypt master key!\r\n"
			L"Try to use the command line.\r\n");
		return -1;
	} else {
		delete keyDatPath;			// Don't forget to do this
		keyDatPath = NULL;
	}

	// Search the TeslaCrypt process (if any)
	bRetVal = SearchAndKillTeslaProc(true);

	wprintf(L"Would you like to attempt to decrypt all files encrypted by TeslaCrypt \r\non this computer? [Y/N] ");
	wscanf_s(L"%4s", answer, COUNTOF(answer));
	if (CHR_UPR(answer[0]) == 'Y') bDoEntirePcDecrypt = true;

	if (bDoEntirePcDecrypt) {
		// Decrypt all PC files
		GetDecrypter()->DeleteTeslaCryptGarbage(true);
		bRetVal = GetDecrypter()->DecryptAllPcFiles();
		return bRetVal;
	}
	
	rewind(stdin);
	wprintf(L"Enter directory or filename that you would like to decrypt:\r\n");
	wscanf_s(L"%[^\n]", dirOrFileToDecrypt, COUNTOF(dirOrFileToDecrypt));
	dwStrLen = wcslen(dirOrFileToDecrypt);
	if (dirOrFileToDecrypt[dwStrLen-1] == '\\') dirOrFileToDecrypt[--dwStrLen] = 0;

	if (!FileExists(dirOrFileToDecrypt)) {
		cl_wprintf(RED, L"Error! ");
		wprintf(L"File or directory specified does not exist!\r\n");
		return -1;
		
	}
	DWORD fAttr = GetFileAttributes(dirOrFileToDecrypt);
	if (fAttr & FILE_ATTRIBUTE_DIRECTORY) {
		// The location is a directory
		LPTSTR dirOnlyName = wcsrchr(dirOrFileToDecrypt, '\\');
		if (dirOnlyName) dirOnlyName++;
		else dirOnlyName = dirOrFileToDecrypt;
		wprintf(L"\r\nDecrypting \"%s\" directory... ", dirOnlyName);
		bRetVal = GetDecrypter()->DecryptDirectory(dirOrFileToDecrypt);
		if (bRetVal) {
			cl_wprintf(GREEN, L"Success!\r\n");
			wprintf(L"Encrypted files in the target directory have been decrypted.\r\n"
				L"See the log file for details.\r\n");
		} else {
			cl_wprintf(RED, L"Error!\r\n");
			wprintf(L"Errors while decrypting the files.\r\n"
				L"See log file for details.\r\n");
		}
	} else {
		// The path specify a file
		// Compose the target path
		LPTSTR targetFile = ComposeDestFileName(dirOrFileToDecrypt);
		wprintf(L"\r\nDecrypting \"%s\" file... ", wcsrchr(dirOrFileToDecrypt, '\\') + 1);
		bRetVal = GetDecrypter()->DecryptTeslaFile(dirOrFileToDecrypt, targetFile);
		delete targetFile;			// Don't forget to do this
		if (bRetVal)
			cl_wprintf(GREEN, L"Success!\r\n");
		else
			cl_wprintf(RED, L"Error!\r\n");
	}

	return (bRetVal ? 1 : -1);
}
Esempio n. 13
0
// Gets new location data from the user, and prints the report data.
// The location data includes fields for both a civic address report 
// and a latitude/longitude report.
// The error radius, altitude, and altitude error fields are not
// displayed in the Default Location Control Panel, but they are 
// available from the Location API.
HRESULT EnterLocation(CLocationReport * pLocationReport)
{
    WCHAR address1[ADDRESS_FIELD_LENGTH];
    WCHAR address2[ADDRESS_FIELD_LENGTH]; 
    WCHAR city[ADDRESS_FIELD_LENGTH];
    WCHAR stateprovince[ADDRESS_FIELD_LENGTH];
    WCHAR zipcode[ADDRESS_FIELD_LENGTH];
    WCHAR countryregion[COUNTRYREGION_FIELD_LENGTH]; // ISO-3166 2-digit or 3-digit code
    DOUBLE latitude = 0;
    DOUBLE longitude = 0;
    DOUBLE errorradius = 0;
    DOUBLE altitude = 0;
    DOUBLE altitudeerror = 0;
    int numberfieldsread = 0; // number of fields successfully read by wscanf_s

    // Interface for civic address report
    CComPtr<ICivicAddressReport> spCivicAddressReport; 
    // Interface for latitude/longitude report
    CComPtr<ILatLongReport> spLatLongReport; 

    // prompt user to enter line 1 of the street address.
    wprintf(PROMPT_ADDRESS1);
    SafeGetws(address1, ARRAYSIZE(address1));
    fflush(stdin);
    // Set line 1 of the street address in the new report
    CComBSTR bstrAddress1(address1);
    HRESULT hr = pLocationReport->SetAddressLine1(bstrAddress1);    
    
    if (SUCCEEDED(hr))
    {
        // prompt user to enter line 2 of the street address.
        wprintf(PROMPT_ADDRESS2);
        SafeGetws(address2, ARRAYSIZE(address2));
        fflush(stdin);
        // Set line 2 of the street address in the new report
        CComBSTR bstrAddress2(address2);
        hr = pLocationReport->SetAddressLine2(bstrAddress2);
    }
    if (SUCCEEDED(hr))
    {
        // prompt user to enter the city.
        wprintf(PROMPT_CITY);
        SafeGetws(city, ARRAYSIZE(city));
        fflush(stdin);
        // Set the city in the new report
        CComBSTR bstrCity(city);
        hr = pLocationReport->SetCity(bstrCity);
    }
    if (SUCCEEDED(hr))
    {
        // prompt user to enter the state/province.
        wprintf(PROMPT_STATEPROVINCE);
        SafeGetws(stateprovince, ARRAYSIZE(city));
        fflush(stdin);
        // Set the state/province in the new report
        CComBSTR bstrStateProvince(stateprovince);
        hr = pLocationReport->SetStateProvince(bstrStateProvince);
    }
    if (SUCCEEDED(hr))
    {
        // prompt user to enter the postal code.
        wprintf(PROMPT_POSTALCODE);
        SafeGetws(zipcode, ARRAYSIZE(zipcode));
        fflush(stdin);
        // Set the postal code in the new report
        CComBSTR bstrZipCode(zipcode);
        hr = pLocationReport->SetPostalCode(bstrZipCode);    
    }
    if (SUCCEEDED(hr))
    {
        // prompt user to enter the country code.
        wprintf(PROMPT_COUNTRYREGION);
        SafeGetws(countryregion, ARRAYSIZE(countryregion));
        fflush(stdin);
        // Set the country/region in the new report
        CComBSTR bstrCountryRegion(countryregion);
        hr = pLocationReport->SetCountryRegion(bstrCountryRegion);
    }
    if (SUCCEEDED(hr))
    {
        // prompt the user to enter latitude
        wprintf(PROMPT_LATITUDE);
        numberfieldsread = wscanf_s(L"%lf", &latitude);
        fflush(stdin);
        if (0 == numberfieldsread) 
        {
            wprintf(L"Error reading input. The report field will be set to zero.\n");
        }
        else 
        {
            // Set the latitude
            hr = pLocationReport->SetLatitude(latitude);
        }
    }
    if (SUCCEEDED(hr))
    {
        // prompt the user to enter longitude
        wprintf(PROMPT_LONGITUDE);
        numberfieldsread = wscanf_s(L"%lf", &longitude);
        fflush(stdin);
        if (0 == numberfieldsread) 
        {
            wprintf(L"Error reading input. The report field will be set to zero.\n");
        }
        else 
        {
            // Set the longitude
            hr = pLocationReport->SetLongitude(longitude);
        }
    }
    if (SUCCEEDED(hr))
    {
        // prompt the user to enter the error radius for the latitude/longitude 
        wprintf(PROMPT_ERRORRADIUS);
        numberfieldsread = wscanf_s(L"%lf", &errorradius);
        fflush(stdin);
        if (0 == numberfieldsread) 
        {
            wprintf(L"Error reading input. The report field will be set to a default value.\n");
        }
        else 
        {
            // Set the error radius
            hr = pLocationReport->SetErrorRadius(errorradius);
        }
    }
    if (SUCCEEDED(hr))
    {
        // prompt the user to enter altitude
        wprintf(PROMPT_ALTITUDE);
        numberfieldsread = wscanf_s(L"%lf", &altitude);
        fflush(stdin);
        if (0 == numberfieldsread) 
        {
            wprintf(L"Error reading input. The report field will be set to zero.\n");
        }
        else 
        {
            // Set the altitude
            hr = pLocationReport->SetAltitude(altitude);
        }
    }
    if (SUCCEEDED(hr))
    {
        // prompt the user to enter altitude error
        wprintf(PROMPT_ALTITUDEERROR);
        numberfieldsread = wscanf_s(L"%lf", &altitudeerror);
        fflush(stdin);
        if (0 == numberfieldsread) 
        {
            wprintf(L"Error reading input. The report field will be set to zero.\n");
        }
        else
        {
            // Set the altitude error
            hr = pLocationReport->SetAltitudeError(altitudeerror);
        }
    }
    if (SUCCEEDED(hr))
    {
        // Print the GUID 
        SENSOR_ID SensorID;
        hr = pLocationReport->GetSensorID(&SensorID);
        PrintGUID(SensorID);
    }
    if (SUCCEEDED(hr))
    {
        // Print the timestamp
        SYSTEMTIME systime;
        hr = pLocationReport->GetTimestamp(&systime); 
        PrintTime(systime);
    }
    if (SUCCEEDED(hr))
    {
        hr = pLocationReport->QueryInterface(IID_PPV_ARGS(&spCivicAddressReport));
    }
    if (SUCCEEDED(hr))
    {
        PrintCivicAddress(spCivicAddressReport);
    }
    if (SUCCEEDED(hr))
    {
        hr = pLocationReport->QueryInterface(IID_PPV_ARGS(&spLatLongReport));
    }
    if (SUCCEEDED(hr))
    {
        PrintLatLong(spLatLongReport);
    }
    return hr;
}
Esempio n. 14
0
int Test_scan_wide( void )
/************************/
{
    int         number;
    int         violations = NumViolations;
    wchar_t     buf[64];

    VERIFY( swscanf_s( L"123", L"%d", &number ) == 1 );
    VERIFY( number == 123 );

    VERIFY( swscanf_s( NULL, L"%d", &number ) == WEOF );
    VERIFY( ++violations == NumViolations );

    VERIFY( swscanf_s( L"123", NULL, &number ) == WEOF );
    VERIFY( ++violations == NumViolations );

    VERIFY( swscanf_s( L"123", L"%d", NULL ) == WEOF );
    VERIFY( ++violations == NumViolations );

    VERIFY( swscanf_s( L"123", L"%*d", NULL ) == 0 );

    VERIFY( swscanf_s( L"123", L"%s", NULL ) == WEOF );
    VERIFY( ++violations == NumViolations );

    VERIFY( swscanf_s( L"123", L"%c", NULL ) == WEOF );
    VERIFY( ++violations == NumViolations );

    VERIFY( swscanf_s( L"123", L"%f", NULL ) == WEOF );
    VERIFY( ++violations == NumViolations );

    VERIFY( swscanf_s( L"123", L"%n", NULL ) == WEOF );
    VERIFY( ++violations == NumViolations );

    VERIFY( swscanf_s( L"123", L"%*d%n%n", &number, NULL ) == WEOF );
    VERIFY( ++violations == NumViolations );

    VERIFY( swscanf_s( L" 123", L"%s%n", &buf, sizeof( buf ), &number ) == 1 );
    VERIFY( number == 4 && !wcscmp( L"123", buf ) );

    VERIFY( swscanf_s( L" 123", L"%s%n", &buf, 3 ) == 0 );

    VERIFY( swscanf_s( L"aaa", L"%[a]%n", &buf, 4, &number ) == 1 );
    VERIFY( number == 3 && !wcscmp( L"aaa", buf ) );

    VERIFY( swscanf_s( L"aaaa", L"%[a]", &buf, 4 ) == 0 );

    wmemset( buf, 'Q', 6 );
    VERIFY( swscanf_s( L"aaaaa", L"%5c%n", &buf, 5, &number ) == 1 );
    VERIFY( number == 5 && !wmemcmp( L"aaaaaQ", buf, 6 ) );

    VERIFY( swscanf_s( L"aaa", L"%3c%n", &buf, 2 ) == 0 );


    VERIFY( my_swscanf_s( L"123", L"%d", &number ) == 1 );
    VERIFY( number == 123 );

    VERIFY( my_swscanf_s( NULL, L"%d", &number ) == WEOF );
    VERIFY( ++violations == NumViolations );

    VERIFY( my_swscanf_s( L"123", NULL, &number ) == WEOF );
    VERIFY( ++violations == NumViolations );

    VERIFY( my_swscanf_s( L"123", L"%d", NULL ) == WEOF );
    VERIFY( ++violations == NumViolations );

    VERIFY( my_swscanf_s( L"123", L"%*d", NULL ) == 0 );

    VERIFY( my_swscanf_s( L"123", L"%s", NULL ) == WEOF );
    VERIFY( ++violations == NumViolations );

    VERIFY( my_swscanf_s( L"123", L"%c", NULL ) == WEOF );
    VERIFY( ++violations == NumViolations );

    VERIFY( my_swscanf_s( L"123", L"%f", NULL ) == WEOF );
    VERIFY( ++violations == NumViolations );

    VERIFY( my_swscanf_s( L"123", L"%n", NULL ) == WEOF );
    VERIFY( ++violations == NumViolations );


    VERIFY( wscanf_s( NULL ) == WEOF );
    VERIFY( ++violations == NumViolations );

    VERIFY( wscanf_s( L"%n", NULL ) == WEOF );
    VERIFY( ++violations == NumViolations );


    VERIFY( my_wscanf_s( NULL ) == WEOF );
    VERIFY( ++violations == NumViolations );

    VERIFY( my_wscanf_s( L"%n", NULL ) == WEOF );
    VERIFY( ++violations == NumViolations );


    VERIFY( fwscanf_s( NULL, L"%n", &number ) == WEOF );
    VERIFY( ++violations == NumViolations );

    VERIFY( fwscanf_s( stdin, NULL ) == WEOF );
    VERIFY( ++violations == NumViolations );

    VERIFY( fwscanf_s( stdin, L"%n", NULL ) == WEOF );
    VERIFY( ++violations == NumViolations );


    VERIFY( my_fwscanf_s( NULL, L"%d", &number ) == WEOF );
    VERIFY( ++violations == NumViolations );

    VERIFY( my_fwscanf_s( stdin, NULL ) == WEOF );
    VERIFY( ++violations == NumViolations );

    VERIFY( my_fwscanf_s( stdin, L"%n", NULL ) == WEOF );
    VERIFY( ++violations == NumViolations );

    return( 1 );
}