Ejemplo n.º 1
0
Protocol* Protocol::decode(const char *bytes, int32_t len, bool decrypt)
{
    int type;
    memcpy(&type, bytes, sizeof(type));
    bytes += sizeof(type);
    len -= 4;
    
    char *temp = new char[len];
    if (decrypt)
    {
        rc4_state state;
        rc4_init(&state, (const u_char *)INKEY.c_str(), INKEY.size());
        rc4_crypt(&state, (const u_char *)bytes, (u_char *)temp, len);
    }
    else
    {
        memcpy(temp, bytes, len);
    }
    std::string plain(temp, len);
    delete[] temp;
    CCLOG("==== Client received:%s ====", plain.c_str());
    Json::Reader reader;
    Json::Value root;
    if (!reader.parse(plain, root))
        return NULL;
    //int type = root["type"].asInt();
    Protocol *p = Protocol::create(type);
    if (p != NULL)
    {
        JsonStream stream(root);
        p->decode(stream);
    }
    return p;
}
Ejemplo n.º 2
0
FRAGMENT(JSObject, simple) {
  JS::Rooted<JSObject*> glob(cx, JS::CurrentGlobalOrNull(cx));
  JS::Rooted<JSObject*> plain(cx, JS_NewPlainObject(cx));
  JS::Rooted<JSObject*> global(cx, JS::CurrentGlobalOrNull(cx));
  JS::Rooted<JSObject*> func(cx, (JSObject*) JS_NewFunction(cx, (JSNative) 1, 0, 0,
                                                              global, "dys"));
  JS::Rooted<JSObject*> anon(cx, (JSObject*) JS_NewFunction(cx, (JSNative) 1, 0, 0, global, 0));
  JS::Rooted<JSFunction*> funcPtr(cx, JS_NewFunction(cx, (JSNative) 1, 0, 0,
                                                      global, "formFollows"));

  JSObject& plainRef = *plain;
  JSFunction& funcRef = *funcPtr;
  JSObject* plainRaw = plain;
  JSObject* funcRaw = func;

  breakpoint();

  (void) glob;
  (void) plain;
  (void) func;
  (void) anon;
  (void) funcPtr;
  (void) &plainRef;
  (void) &funcRef;
  (void) plainRaw;
  (void) funcRaw;
}
Ejemplo n.º 3
0
bool BlockTransformationTest(const CipherFactory &cg, BufferedTransformation &valdata, unsigned int tuples = 0xffff)
{
	HexEncoder output(new FileSink(cout));
	SecByteBlock plain(cg.BlockSize()), cipher(cg.BlockSize()), out(cg.BlockSize()), outplain(cg.BlockSize());
	SecByteBlock key(cg.KeyLength());
	bool pass=true, fail;

	while (valdata.MaxRetrievable() && tuples--)
	{
		valdata.Get(key, cg.KeyLength());
		valdata.Get(plain, cg.BlockSize());
		valdata.Get(cipher, cg.BlockSize());

		apbt transE = cg.NewEncryption(key);
		transE->ProcessBlock(plain, out);
		fail = memcmp(out, cipher, cg.BlockSize()) != 0;

		apbt transD = cg.NewDecryption(key);
		transD->ProcessBlock(out, outplain);
		fail=fail || memcmp(outplain, plain, cg.BlockSize());

		pass = pass && !fail;

		cout << (fail ? "FAILED   " : "passed   ");
		output.Put(key, cg.KeyLength());
		cout << "   ";
		output.Put(outplain, cg.BlockSize());
		cout << "   ";
		output.Put(out, cg.BlockSize());
		cout << endl;
	}
	return pass;
}
Ejemplo n.º 4
0
void addWord(QNFA *lexer, const QString& w, int action, bool cs)
{
	if ( !lexer || !(lexer->type & CxtBeg) || !lexer->out.branch )
		return;
	
	// try using the fastest way if possible
	
	QString pt;
	
	if ( plain(w, &pt) && cs )
	{
		addWord(lexer->tree, pt, action, cs);
		return;
	}
	
	// fallback on (fast) regexp-like NFA-based semi-compiled parsing
	QNFA *nfa, *word, *end;
	
	word = sequence(w.constData(), w.length(), &end, cs);
	word->assertion |= WordStart;
	
	nfa = new QNFA;
	nfa->type = Match;
	nfa->assertion = WordEnd;
	nfa->actionid = action;
	
	end->out.next = nfa;
	
	//lexer->out.branch->append(word);
	addNFA(lexer, word);
}
Ejemplo n.º 5
0
bool RSA_Encryptor<Pad>::SSL_Verify(const byte* message, word32 sz,
                                    const byte* sig)
{
    ByteBlock plain(PK_Lengths(key_.GetModulus()).FixedMaxPlaintextLength());
    SSL_Decrypt(key_, sig, plain.get_buffer());

    if ( (memcmp(plain.get_buffer(), message, sz)) == 0)
        return true;
    return false;
}
Ejemplo n.º 6
0
   void Handler::on_message(connection_ptr con, message_ptr msg)
   {
      if (msg->get_opcode() != websocketpp::frame::opcode::TEXT)
         return;

      Log::debug("client <%s>: <message> %s", plain(con).c_str(),
            msg->get_payload().c_str());

      publish(format_message(msg->get_payload()));
   }
Ejemplo n.º 7
0
   void Handler::on_close(connection_ptr con)
   {
      ConnectionSet::iterator found = m_connections.find(con);
      if (found == m_connections.end())
         return;

      Log::debug("client <%s>: left", plain(con).c_str());

      m_connections.erase(found);
   }
Ejemplo n.º 8
0
Archivo: Console.cpp Proyecto: ifzz/FDK
int main()
{
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

	void* heap = HeapCreate(0, 0, 0);
	MemoryBuffer compressed(heap);
	MemoryBuffer plain(heap);

	string st;
	for (size_t index = 0; index < 1000; ++index)
	{
		st = st + "test";
	}

	ZipCompress(L"0", const_cast<char*>(st.c_str()), st.length() + 1, compressed);


	ZipDecompress(L"0", compressed.GetData(), compressed.GetSize(), plain);

	const char* output = reinterpret_cast<const char*>(plain.GetData());



	/*
	std::ifstream input("E:\\ticks.zip", std::ios::binary);
	char buffer[256 * 1024] = "";
	input.read(buffer, sizeof(buffer));
	const size_t count = input.gcount();


	HZIP handle = OpenZip(buffer, count, nullptr);

	int index = -1;
	ZIPENTRY zipEntry;
	ZeroMemory(&zipEntry, sizeof(zipEntry));
	ZRESULT status = FindZipItem(handle, L"ticks.txt", false, &index, &zipEntry);

	char* uncompressed = new char[zipEntry.unc_size];
	ZeroMemory(uncompressed, zipEntry.unc_size);


	UnzipItem(handle, index, uncompressed, zipEntry.unc_size);

	std::ofstream output("E:\\ticks2.txt", std::ios::binary);
	output.write(uncompressed, zipEntry.unc_size);


	CloseZip(handle);*/

	return 0;
}
Ejemplo n.º 9
0
ConfigValue* ConfigMapParser::value() throw(PARSEEXCEPTION_THROW)
{
  if(token.type == T::CMT_CBL)
  {
    return map();
  }
  else if(token.type == T::CMT_ABL)
  {
    return list();
  }
  else
  {
    return plain();
  }
}
Ejemplo n.º 10
0
// Initialisation
BOOL
vncProperties::Init(vncServer *server)
{
	// Save the server pointer
	m_server = server;
	
	// Load the settings from the registry
	Load(TRUE);

	// If the password is empty then always show a dialog
	char passwd[MAXPWLEN];
	m_server->GetPassword(passwd);
	{
	    vncPasswd::ToText plain(passwd);
	    if (strlen(plain) == 0)
			if (!m_allowproperties) {
				if(m_server->AuthRequired()) {
					MessageBox(NULL, NO_PASSWD_NO_OVERRIDE_ERR,
								"WinVNC Error",
								MB_OK | MB_ICONSTOP);
					PostQuitMessage(0);
				} else {
					MessageBox(NULL, NO_PASSWD_NO_OVERRIDE_WARN,
								"WinVNC Error",
								MB_OK | MB_ICONEXCLAMATION);
				}
			} else {
				// If null passwords are not allowed, ensure that one is entered!
				if (m_server->AuthRequired()) {
					char username[UNLEN+1];
					if (!vncService::CurrentUser(username, sizeof(username)))
						return FALSE;
					if (strcmp(username, "") == 0) {
						MessageBox(NULL, NO_PASSWD_NO_LOGON_WARN,
									"WinVNC Error",
									MB_OK | MB_ICONEXCLAMATION);
						Show(TRUE, FALSE);
					} else {
						Show(TRUE, TRUE);
					}
				}
			}
	}

	return TRUE;
}
Ejemplo n.º 11
0
//gzip
int test_GzipByMem()
{
	char plainText[]="Plain text here";
	CA2GZIP gzip(plainText,strlen(plainText));
	// do compressing here;
	LPGZIP pgzip=gzip.pgzip; // pgzip is zipped data pointer,
	// you can use it directly
	int len=gzip.Length; // Length is length of zipped
	// data;

	CGZIP2A plain(pgzip,len); // do uncompressing here

	char *pplain=plain.psz; // psz is plain data pointer
	int aLen=plain.Length; // Length is length of unzipped
	// data.
	return 0;
}
Ejemplo n.º 12
0
	/**
	 * 暗号化処理
	 * @param plaintext 平文
	 * @param 鍵
	 * @param initialVector 初期暗号化ブロック列
	 * @return 暗号ブロック連鎖を用いて処理された暗号文
	 */
	static std::vector<unsigned char>
	encrypt(const std::vector<unsigned char>& plaintext,
			const std::vector<unsigned char>& key,
			const std::vector<unsigned char>& initialVector)
	{
		if (plaintext.size() % initialVector.size() ||
			key.size() < initialVector.size())
			throw std::invalid_argument("invalid argument.");

		CipherAlgorithm cipherAlg;
		const size_t blockSize = cipherAlg.getBlockSize();
		cipherAlg.setKey(key);

		std::vector<unsigned char> plain(plaintext);
		std::vector<unsigned char> exclusiveVector(initialVector);
		assert((exclusiveVector.size() % blockSize) == 0);

		std::vector<unsigned char> result(blockSize);
		for (size_t offset = 0;
			 offset < plain.size();
			 offset += blockSize)
		{
			assert(offset + blockSize <= plain.size());
			std::transform(plain.begin() + offset,
						   plain.begin() + offset + blockSize,
						   exclusiveVector.begin(),
						   result.begin(),
						   ExclusiveOr());

			std::vector<unsigned char> cipher =
				cipherAlg.encrypt(result);
			result.swap(cipher);

			assert(result.size() == blockSize);

			std::copy(result.begin(),
					  result.end(),
					  exclusiveVector.begin());
			std::copy(result.begin(),
					  result.end(),
					  plain.begin() + offset);
		}

		return plain;
	}
Ejemplo n.º 13
0
// -----------------------------------------------------------------
// Name : display
// -----------------------------------------------------------------
void InterfaceManager::display()
{
    FREEVEC(m_pTopDisplayList);
    Color plain(1, 1, 1, 1);
    Color alpha(1, 1, 1, 0.65f);

	for (guiFrame* &pFrm : m_pFrameList) {
        if (pFrm != m_pTooltip) {
        	pFrm->displayAt(0, 0, plain, alpha);
        }
    }

	for (TopDisplayObject* &pObj : m_pTopDisplayList) {
		pObj->display();
    }

    if (m_pTooltip != NULL) {
        alpha.a = 0.85f;
        m_pTooltip->displayAt(0, 0, plain, alpha);
    }
}
Ejemplo n.º 14
0
bool ValidateRC2()
{
	cout << "\nRC2 validation suite running...\n\n";

	FileSource valdata("rc2val.dat", true, new HexDecoder);
	HexEncoder output(new FileSink(cout));
	SecByteBlock plain(RC2Encryption::BLOCKSIZE), cipher(RC2Encryption::BLOCKSIZE), out(RC2Encryption::BLOCKSIZE), outplain(RC2Encryption::BLOCKSIZE);
	SecByteBlock key(128);
	bool pass=true, fail;

	while (valdata.MaxRetrievable())
	{
		byte keyLen, effectiveLen;

		valdata.Get(keyLen);
		valdata.Get(effectiveLen);
		valdata.Get(key, keyLen);
		valdata.Get(plain, RC2Encryption::BLOCKSIZE);
		valdata.Get(cipher, RC2Encryption::BLOCKSIZE);

		apbt transE(new RC2Encryption(key, keyLen, effectiveLen));
		transE->ProcessBlock(plain, out);
		fail = memcmp(out, cipher, RC2Encryption::BLOCKSIZE) != 0;

		apbt transD(new RC2Decryption(key, keyLen, effectiveLen));
		transD->ProcessBlock(out, outplain);
		fail=fail || memcmp(outplain, plain, RC2Encryption::BLOCKSIZE);

		pass = pass && !fail;

		cout << (fail ? "FAILED   " : "passed   ");
		output.Put(key, keyLen);
		cout << "   ";
		output.Put(outplain, RC2Encryption::BLOCKSIZE);
		cout << "   ";
		output.Put(out, RC2Encryption::BLOCKSIZE);
		cout << endl;
	}
	return pass;
}
Ejemplo n.º 15
0
bool ValidateRC2()
{
	std::cout << "\nRC2 validation suite running...\n\n";

	FileSource valdata("TestData/rc2val.dat", true, new HexDecoder);
	HexEncoder output(new FileSink(std::cout));
	SecByteBlock plain(RC2Encryption::BLOCKSIZE), cipher(RC2Encryption::BLOCKSIZE), out(RC2Encryption::BLOCKSIZE), outplain(RC2Encryption::BLOCKSIZE);
	SecByteBlock key(128);
	bool pass=true, fail;

	while (valdata.MaxRetrievable())
	{
		byte keyLen, effectiveLen;

		valdata.Get(keyLen);
		valdata.Get(effectiveLen);
		valdata.Get(key, keyLen);
		valdata.Get(plain, RC2Encryption::BLOCKSIZE);
		valdata.Get(cipher, RC2Encryption::BLOCKSIZE);

		auto_ptr<BlockTransformation> transE(new RC2Encryption(key, keyLen, effectiveLen));
		transE->ProcessBlock(plain, out);
		fail = !VerifyBufsEqual(out, cipher, RC2Encryption::BLOCKSIZE);

		auto_ptr<BlockTransformation> transD(new RC2Decryption(key, keyLen, effectiveLen));
		transD->ProcessBlock(out, outplain);
		fail=fail || !VerifyBufsEqual(outplain, plain, RC2Encryption::BLOCKSIZE);

		pass = pass && !fail;

		std::cout << (fail ? "FAILED   " : "passed   ");
		output.Put(key, keyLen);
		std::cout << "   ";
		output.Put(outplain, RC2Encryption::BLOCKSIZE);
		std::cout << "   ";
		output.Put(out, RC2Encryption::BLOCKSIZE);
		std::cout << std::endl;
	}
	return pass;
}
Ejemplo n.º 16
0
static void __init
test_pointer(void)
{
	plain();
	null_pointer();
	invalid_pointer();
	symbol_ptr();
	kernel_ptr();
	struct_resource();
	addr();
	escaped_str();
	hex_string();
	mac();
	ip();
	uuid();
	dentry();
	struct_va_format();
	struct_rtc_time();
	struct_clk();
	bitmap();
	netdev_features();
	flags();
}
Ejemplo n.º 17
0
FRAGMENT(JSObject, simple) {
  AutoSuppressHazardsForTest noanalysis;

  JS::Rooted<JSObject*> glob(cx, JS::CurrentGlobalOrNull(cx));
  JS::Rooted<JSObject*> plain(cx, JS_NewPlainObject(cx));
  JS::Rooted<JSObject*> global(cx, JS::CurrentGlobalOrNull(cx));
  JS::Rooted<JSObject*> func(cx, (JSObject*) JS_NewFunction(cx, (JSNative) 1, 0, 0,
                                                              "dys"));
  JS::Rooted<JSObject*> anon(cx, (JSObject*) JS_NewFunction(cx, (JSNative) 1, 0, 0, nullptr));
  JS::Rooted<JSFunction*> funcPtr(cx, JS_NewFunction(cx, (JSNative) 1, 0, 0,
                                                      "formFollows"));

  JSObject& plainRef = *plain;
  JSFunction& funcRef = *funcPtr;
  JSObject* plainRaw = plain;
  JSObject* funcRaw = func;

  // JS_NewObject will now assert if you feed it a bad class name, so mangle
  // the name after construction.
  char namebuf[20] = "goodname";
  static JSClass cls { namebuf };
  JS::RootedObject badClassName(cx, JS_NewObject(cx, &cls));
  strcpy(namebuf, "\xc7X");

  breakpoint();

  use(glob);
  use(plain);
  use(func);
  use(anon);
  use(funcPtr);
  use(&plainRef);
  use(&funcRef);
  use(plainRaw);
  use(funcRaw);
}
Ejemplo n.º 18
0
void CStateAuthentication::ProcessDataL(const TDesC8& aData)
{
    //free resources
    delete iRequestData;
    iRequestData = NULL;

    if(aData.Size()!=0)
    {
        if(iResponseData == NULL)
        {
            iResponseData = aData.AllocL();
        }
        else
        {
            TInt size = iResponseData->Size();
            iResponseData = iResponseData->ReAllocL(size+aData.Size()); //TODO:check this
            iResponseData->Des().Append(aData);
        }
        return;
    }
    // parse response from server
    if(iResponseData->Find(KApplicationOS)==KErrNotFound)
    {
        //server answered with a redirect
        iObserver.ResponseError(KErrAuth);
        return;
    }
    //retrieve cookie
    HBufC8* cookie = CRestUtils::GetCookieL(*iResponseData);
    TBuf8<32> cookieBuf(*cookie);
    delete cookie;
    iObserver.SetCookie(cookieBuf);

    //extract body from response
    RBuf8 body(CRestUtils::GetBodyL(*iResponseData));
    body.CleanupClosePushL();
    // first 32 bytes are Crypt(Signature,Ks)
    TPtrC8 crypt2 = body.Left(32);
    // retrieve Ks
    RBuf8 Ks(AES::DecryptPkcs5L(crypt2,KIV,iSignKey));
    Ks.CleanupClosePushL();
    // then calculate K=sha1(confKey,Ks,Kd), take only first 16 bytes of sha1
    CSHA1* sha1 = CSHA1::NewL();
    CleanupStack::PushL(sha1);
    sha1->Update(iConfKey);
    sha1->Update(Ks);
    TBuf8<20> keyK;
    keyK.Copy(sha1->Final(iKd));
    CleanupStack::PopAndDestroy(sha1);
    keyK.SetLength(16);
    CleanupStack::PopAndDestroy(&Ks);
    //set K key
    iObserver.SetKey(keyK);

    // last bytes are Crypt(K,Nonce | Response)
    TPtrC8 crypt3 = body.Right(body.Size()-32);
    RBuf8 plain(AES::DecryptPkcs5L(crypt3,KIV,keyK));
    plain.CleanupClosePushL();
    TBufC8<16> nonce(plain.Left(16));
    TBufC8<4> response(plain.Right(4));
    CleanupStack::PopAndDestroy(&plain);
    CleanupStack::PopAndDestroy(&body);
    //verify nonce
    if(iNonce.Compare(nonce)!=0)
    {
        iObserver.ResponseError(KErrAuth);
        return;
    }
    //verify response
    if(response.Compare(KProto_Ok)==0)
    {
        // it's ok, let's go on
        iObserver.ChangeStateL();
        return;
    }
    if(response.Compare(KProto_No)==0)
    {
        iObserver.ResponseError(KErrAuth);
        return;
    }
    if(response.Compare(KProto_CmdUninstall)==0)
    {
        CAbstractState* uninstall = CStateCmdUninstall::NewL(iObserver);
        uninstall->ActivateL(KNullDesC8);
        return;
    }
}
Ejemplo n.º 19
0
 void Handler::on_open(connection_ptr con)
 {
    Log::debug("client <%s>: joined", plain(con).c_str());
    m_connections.insert(con);
    con->send(format_message("hello"));
 }
Ejemplo n.º 20
0
BOOL
vncClientThread::InitAuthenticate()
{
	// Retrieve the local password
	char password[MAXPWLEN];
	m_server->GetPassword(password);
	vncPasswd::ToText plain(password);

	// Verify the peer host name against the AuthHosts string
	vncServer::AcceptQueryReject verified;
	if (m_auth) {
		verified = vncServer::aqrAccept;
	} else {
		verified = m_server->VerifyHost(m_socket->GetPeerName());
	}
	
	// If necessary, query the connection with a timed dialog
	if (verified == vncServer::aqrQuery) {
		vncAcceptDialog *acceptDlg = new vncAcceptDialog(m_server->QueryTimeout(), m_socket->GetPeerName());
		if ((acceptDlg == 0) || (!(acceptDlg->DoDialog())))
			verified = vncServer::aqrReject;
	}
	if (verified == vncServer::aqrReject) {
		CARD32 auth_val = Swap32IfLE(rfbConnFailed);
		char *errmsg = "Your connection has been rejected.";
		CARD32 errlen = Swap32IfLE(strlen(errmsg));
		if (!m_socket->SendExact((char *)&auth_val, sizeof(auth_val)))
			return FALSE;
		if (!m_socket->SendExact((char *)&errlen, sizeof(errlen)))
			return FALSE;
		m_socket->SendExact(errmsg, strlen(errmsg));
		return FALSE;
	}

	// By default we disallow passwordless workstations!
	if ((strlen(plain) == 0) && m_server->AuthRequired())
	{
		vnclog.Print(LL_CONNERR, VNCLOG("no password specified for server - client rejected\n"));

		// Send an error message to the client
		CARD32 auth_val = Swap32IfLE(rfbConnFailed);
		char *errmsg =
			"This server does not have a valid password enabled.  "
			"Until a password is set, incoming connections cannot be accepted.";
		CARD32 errlen = Swap32IfLE(strlen(errmsg));

		if (!m_socket->SendExact((char *)&auth_val, sizeof(auth_val)))
			return FALSE;
		if (!m_socket->SendExact((char *)&errlen, sizeof(errlen)))
			return FALSE;
		m_socket->SendExact(errmsg, strlen(errmsg));

		return FALSE;
	}

	// By default we filter out local loop connections, because they're pointless
	if (!m_server->LoopbackOk())
	{
		char *localname = strdup(m_socket->GetSockName());
		char *remotename = strdup(m_socket->GetPeerName());

		// Check that the local & remote names are different!
		if ((localname != NULL) && (remotename != NULL))
		{
			BOOL ok = strcmp(localname, remotename) != 0;

			if (localname != NULL)
				free(localname);

			if (remotename != NULL)
				free(remotename);

			if (!ok)
			{
				vnclog.Print(LL_CONNERR, VNCLOG("loopback connection attempted - client rejected\n"));
				
				// Send an error message to the client
				CARD32 auth_val = Swap32IfLE(rfbConnFailed);
				char *errmsg = "Local loop-back connections are disabled.";
				CARD32 errlen = Swap32IfLE(strlen(errmsg));

				if (!m_socket->SendExact((char *)&auth_val, sizeof(auth_val)))
					return FALSE;
				if (!m_socket->SendExact((char *)&errlen, sizeof(errlen)))
					return FALSE;
				m_socket->SendExact(errmsg, strlen(errmsg));

				return FALSE;
			}
		}
	}

	// Authenticate the connection, if required
	if (m_auth || (strlen(plain) == 0))
	{
		// Send no-auth-required message
		CARD32 auth_val = Swap32IfLE(rfbNoAuth);
		if (!m_socket->SendExact((char *)&auth_val, sizeof(auth_val)))
			return FALSE;
	}
	else
	{
		// Send auth-required message
		CARD32 auth_val = Swap32IfLE(rfbVncAuth);
		if (!m_socket->SendExact((char *)&auth_val, sizeof(auth_val)))
			return FALSE;

		BOOL auth_ok = TRUE;
		{
			// Now create a 16-byte challenge
			char challenge[16];
			vncRandomBytes((BYTE *)&challenge);

			// Send the challenge to the client
			if (!m_socket->SendExact(challenge, sizeof(challenge)))
				return FALSE;

			// Read the response
			char response[16];
			if (!m_socket->ReadExact(response, sizeof(response)))\
				return FALSE;

			// Encrypt the challenge bytes
			vncEncryptBytes((BYTE *)&challenge, plain);

			// Compare them to the response
			for (int i=0; i<sizeof(challenge); i++)
			{
				if (challenge[i] != response[i])
				{
					auth_ok = FALSE;
					break;
				}
			}
		}

		// Did the authentication work?
		CARD32 authmsg;
		if (!auth_ok)
		{
			vnclog.Print(LL_CONNERR, VNCLOG("authentication failed\n"));

			authmsg = Swap32IfLE(rfbVncAuthFailed);
			m_socket->SendExact((char *)&authmsg, sizeof(authmsg));
			return FALSE;
		}
		else
		{
			// Tell the client we're ok
			authmsg = Swap32IfLE(rfbVncAuthOK);
			if (!m_socket->SendExact((char *)&authmsg, sizeof(authmsg)))
				return FALSE;
		}
	}

	// Read the client's initialisation message
	rfbClientInitMsg client_ini;
	if (!m_socket->ReadExact((char *)&client_ini, sz_rfbClientInitMsg))
		return FALSE;

	// If the client wishes to have exclusive access then remove other clients
	if (!client_ini.shared && !m_shared)
	{
		// Which client takes priority, existing or incoming?
		if (m_server->ConnectPriority() < 1)
		{
			// Incoming
			vnclog.Print(LL_INTINFO, VNCLOG("non-shared connection - disconnecting old clients\n"));
			m_server->KillAuthClients();
		} else if (m_server->ConnectPriority() > 1)
		{
			// Existing
			if (m_server->AuthClientCount() > 0)
			{
				vnclog.Print(LL_CLIENTS, VNCLOG("connections already exist - client rejected\n"));
				return FALSE;
			}
		}
	}

	// Tell the server that this client is ok
	return m_server->Authenticated(m_client->GetClientId());
}
Ejemplo n.º 21
0
// Dialog box handling functions
void
vncProperties::Show(BOOL show, BOOL usersettings)
{
	if (show)
	{
		if (!m_allowproperties)
		{
			// If the user isn't allowed to override the settings then tell them
			MessageBox(NULL, NO_OVERRIDE_ERR, "WinVNC Error", MB_OK | MB_ICONEXCLAMATION);
			return;
		}

		// Verify that we know who is logged on
		if (usersettings) {
			char username[UNLEN+1];
			if (!vncService::CurrentUser(username, sizeof(username)))
				return;
			if (strcmp(username, "") == 0) {
				MessageBox(NULL, NO_CURRENT_USER_ERR, "WinVNC Error", MB_OK | MB_ICONEXCLAMATION);
				return;
			}
		} else {
			// We're trying to edit the default local settings - verify that we can
			HKEY hkLocal, hkDefault;
			BOOL canEditDefaultPrefs = 1;
			DWORD dw;
			if (RegCreateKeyEx(HKEY_LOCAL_MACHINE,
				WINVNC_REGISTRY_KEY,
				0, REG_NONE, REG_OPTION_NON_VOLATILE,
				KEY_READ, NULL, &hkLocal, &dw) != ERROR_SUCCESS)
				canEditDefaultPrefs = 0;
			else if (RegCreateKeyEx(hkLocal,
				"Default",
				0, REG_NONE, REG_OPTION_NON_VOLATILE,
				KEY_WRITE | KEY_READ, NULL, &hkDefault, &dw) != ERROR_SUCCESS)
				canEditDefaultPrefs = 0;
			if (hkLocal) RegCloseKey(hkLocal);
			if (hkDefault) RegCloseKey(hkDefault);

			if (!canEditDefaultPrefs) {
				MessageBox(NULL, CANNOT_EDIT_DEFAULT_PREFS, "WinVNC Error", MB_OK | MB_ICONEXCLAMATION);
				return;
			}
		}

		// Now, if the dialog is not already displayed, show it!
		if (!m_dlgvisible)
		{
			if (usersettings)
				vnclog.Print(LL_INTINFO, VNCLOG("show per-user Properties\n"));
			else
				vnclog.Print(LL_INTINFO, VNCLOG("show default system Properties\n"));

			// Load in the settings relevant to the user or system
			Load(usersettings);

			for (;;)
			{
				m_returncode_valid = FALSE;

				// Do the dialog box
				int result = DialogBoxParam(hAppInstance,
				    MAKEINTRESOURCE(IDD_PROPERTIES), 
				    NULL,
				    (DLGPROC) DialogProc,
				    (LONG) this);

				if (!m_returncode_valid)
				    result = IDCANCEL;

				vnclog.Print(LL_INTINFO, VNCLOG("dialog result = %d\n"), result);

				if (result == -1)
				{
					// Dialog box failed, so quit
					PostQuitMessage(0);
					return;
				}

				// We're allowed to exit if the password is not empty
				char passwd[MAXPWLEN];
				m_server->GetPassword(passwd);
				{
				    vncPasswd::ToText plain(passwd);
				    if ((strlen(plain) != 0) || !m_server->AuthRequired())
					break;
				}

				vnclog.Print(LL_INTERR, VNCLOG("warning - empty password\n"));

				// The password is empty, so if OK was used then redisplay the box,
				// otherwise, if CANCEL was used, close down WinVNC
				if (result == IDCANCEL)
				{
				    vnclog.Print(LL_INTERR, VNCLOG("no password - QUITTING\n"));
				    PostQuitMessage(0);
				    return;
				}

				// If we reached here then OK was used & there is no password!
				int result2 = MessageBox(NULL, NO_PASSWORD_WARN,
				    "WinVNC Warning", MB_OK | MB_ICONEXCLAMATION);

				omni_thread::sleep(4);
			}

			// Load in all the settings
			Load(TRUE);
		}
	}
}