Ejemplo n.º 1
0
extern "C" __declspec(dllexport) void __cdecl Encrypt(char *cData)
{
	RSA *rsa = RSA::getInstance();

	rsa->SetKey(tibia_rsa_key);
	rsa->encrypt(cData);
}
Ejemplo n.º 2
0
/*
This method performs all the alice actions. 
*/
BigInt Requester(BigInt message, BigInt signersPubKey, BigInt modulus)
{
    //Initializing all the variables required
    BigInt blindingFactor, encBlindingFactor, blindingFactorInverse, signedMessageWithBlindingFactor, encMessageWithBlindingFactor, messageWithSign,originalMessage;
    
    //RSA which will have signers publicKey and modulus
    RSA requesterRSA;
    requesterRSA.setN(modulus);
    requesterRSA.setPublicKey(signersPubKey);
    
    //Generating a random blindfactor
    blindingFactor = int(((double)std::rand()/RAND_MAX)*RAND_LIMIT32);
    //Blind factor modulus inverse is calculated
    blindingFactorInverse = modInverse(blindingFactor, modulus);
    
    
    
    //Encrypting the blinding factor with signers public key
    encBlindingFactor = requesterRSA.encrypt(blindingFactor);
    //appending original message to the encrypted blindfactor
    encMessageWithBlindingFactor = encBlindingFactor*message;
    encMessageWithBlindingFactor = encMessageWithBlindingFactor%modulus;
    
    //sending the encyrpted blindfactor and origin message to signer as product and get back the signed message with blinding factor
    signedMessageWithBlindingFactor = Signer(encMessageWithBlindingFactor);
    
    std::cout<<"Alice's(Sender's) Random Message generated:  " << message.toHexString() <<std::endl;
    std::cout<<"Encrypted Message sent to Bob with blindfactor and original message:" << encMessageWithBlindingFactor.toHexString() <<std::endl;
    
    //removing the blindfactor
    messageWithSign = (signedMessageWithBlindingFactor*blindingFactorInverse) % modulus;
    std::cout<<"Signed Message recieved from Bob with blindfactor and original message:" << signedMessageWithBlindingFactor.toHexString() <<std::endl;
    return messageWithSign;
}  
Ejemplo n.º 3
0
BigInt sendtoAlice(BigInt pk,BigInt mod){
RSA Aliceobj;
Aliceobj.setN(mod);
Aliceobj.setPublicKey(pk);
randomno=int(((double)rand()/RAND_MAX)*LIMIT_RAND);//generate the random number
message=int(((double)rand()/RAND_MAX)*LIMIT_RAND);//generate the message
std::cout<<"\ninitialmessage="<<message.toHexString()<<std::endl;
BigInt encrandom=Aliceobj.encrypt(randomno);//encrypt the number in Bob's public key
BigInt mulmsg=encrandom*message;
mulmsg=mulmsg%mod;
return mulmsg;
}
Ejemplo n.º 4
0
void KClient::rsaAndDes(RSA rsa)
{
    unsigned long long tempn,tempe,temp;

    this->kcsSock.RecvMsg(this->sMsgBuf); //Recieve RSA n key
    //cout<<"After recieve RSA"<<endl;
    this->kpProto.ReadBuf(this->sMsgBuf);
    this->enMode=this->kpProto.enMode; //Set encrypt mode
    if(this->kpProto.m_cmd==RSAKEY)
    {
        cout<<"keybufn="<<this->kpProto.keybufn<<endl;
        cout<<"keybufe="<<this->kpProto.keybufe<<endl;
    }
    int i;
    tempn=0;
    for(i=0;i<strlen(this->kpProto.keybufn);i++)
    {
            tempn=tempn*10+(this->kpProto.keybufn[i]-'0');
    }
    tempe=0;
    for(i=0;i<strlen(this->kpProto.keybufe);i++)
    {
            tempe=tempe*10+(this->kpProto.keybufe[i]-'0');
    }
    rsa.setN(tempn);
    rsa.setE(tempe);

    time_t t=time(NULL);
    char *key=ctime(&t);
    strncpy(this->desKey, key, strlen(key));
    this->desKey[strlen(key)]='\0';
    int k=0;
    for(i=0;i<strlen(this->desKey);i++)
    {
        temp=rsa.encry(this->desKey[i]);
        char result2[24]="\0";
        sprintf(result2,"%lld",temp);
        for(int j=0;j<strlen(result2);j++)
        {
                this->kpProto.encryptDesKey[k++]=result2[j];
        }
        this->kpProto.encryptDesKey[k++]='a';
    }
    this->kpProto.encryptDesKey[k-1]='\0';
    this->kpProto.m_cmd=DESKEY;
    this->kpProto.WriteBuf(this->sMsgBuf);
    this->kcsSock.SendMsg(this->sMsgBuf);
    cout<<"des key="<<this->desKey<<endl;
    cout<<"rsa encrpt des key="<<this->kpProto.encryptDesKey<<endl;

}
Ejemplo n.º 5
0
void sendtoAlice2(BigInt msg,BigInt pk,BigInt mod){
RSA verifyobj;//verification object
verifyobj.setN(mod);
verifyobj.setPublicKey(pk);
BigInt randomInv=modInverse(randomno,mod);
BigInt mulmsg=msg*randomInv;
std::cout<<"signedmessage="<<mulmsg.toHexString()<<std::endl;
BigInt signedmsg=mulmsg%mod;//the actual signature of the message
BigInt finalmessage=verifyobj.encrypt(signedmsg);
std::cout<<"finalmessage="<<finalmessage.toHexString()<<std::endl;
//check if matches with original message after decrypting 
if(finalmessage==message){
std::cout<<"Initial and final messages are matching , hence verified\n\n"<<std::endl;

}
}
Ejemplo n.º 6
0
int main(int argc, char*argv[]){      /*********************************************************
 * A Simple Driver
 * *******************************************************
 */
     unsigned long int *a;
     unsigned long int arr[4];
     a=&arr[0];

       RSA myRSA;
	BigInt message, cipher, deciphered;

       message = int(((double)std::rand()/RAND_MAX)*RAND_LIMIT32);
       message.toULong(a,4);
       cipher = myRSA.encrypt(message);
       deciphered = myRSA.decrypt(cipher);
       std::cout<<*a<<std::endl;
  //  std::cout<<"message "<<message.toString();
std::cout<<"message: "<<message.toHexString()<<"\tcipher: "<<cipher.toHexString()<<"\tdeciphered: "<<deciphered.toHexString()<<std::endl;

}
Ejemplo n.º 7
0
int main()
{
    mpz_t pN;
    mpz_init(pN);
    mpz_t puC;
    mpz_init(puC);
    mpz_t prU;
    mpz_init(prU);

    gmp_randstate_t state;
    gmp_randinit_default(state);

    mpz_t seed;
    mpz_init(seed);

    RSA KeyGenerator;

    KeyGenerator.randInit(seed,"ahahah");
    gmp_randseed(state,seed);

    std::cout << "état : " <<state <<std::endl;

    KeyGenerator.getKeys(pN, puC, prU, state);

    std::cout << "public keys : " <<pN <<std::endl<<puC<<std::endl;
    std::cout << "private keys : " <<pN <<std::endl<<prU<<std::endl;

    gmp_randclear(state);

    Message Chaine("s");
    mpz_t code;
    mpz_init(code);
    std::string text1 = Chaine.encryptRSA(puC,pN);

    //std::cout << "voici le texte crypté:"<<std::endl<<text1<<std::endl;

    std::string text2 = Chaine.decryptRSA(prU, pN);
    //std::cout << "voici le texte décrypté:"<<std::endl<<text2<<std::endl;

    return 0;
}
int main(int argc, char*argv[]){
       BigInt  cipher, deciphered,message;
        unsigned long int *a;
        unsigned long int arr[10];
        a=&arr[0];
        BigInt pubkey, privatekey;
        BigInt gnm;
		
		//message=1000;
       message = int(((double)(std::rand())/RAND_MAX)*RAND_LIMIT32);
        
        for(int i=1;i<=10;i++)
     {
      sleep(1);
      std::cout<<std::endl<<"RSA "<<i<<std::endl;     
      RSA newrsa;    // default , no args, program generates its own p and q
      std::cout<<"Public Key ";
      pubkey= newrsa.getPublicKey();
      pubkey.toULong(a,4);
       std::cout<<*a<<std::endl;
       privatekey=newrsa.getPrivateKey();
       privatekey.toULong(a,4);
       std::cout<<"Private Key : "<<*a<<std::endl;
       gnm = newrsa.getModulus();
       std::cout<<"N  is "<<gnm.toHexString()<<std::endl;
        
       cipher = newrsa.encrypt(message);
       deciphered = newrsa.decrypt(cipher);

       std::cout<<"message: "<<message.toHexString()<<"\tcipher: "<<cipher.toHexString()<<"\tdeciphered: "<<deciphered.toHexString()<<std::endl<<std::endl;     
     }
     
     
}
Ejemplo n.º 9
0
void RSA::atacar() {
    long long pAtacado, qAtacado;
    this->generarListaDePrimos();
    list<int>::iterator it1 = primos.begin();
    list<int>::iterator it2 = primos.begin();
    it2++;
    bool fin = false;
    while ((!fin) && (it1!= primos.end())) {
        while (it2!= primos.end() && (!fin)) {
            long long supuestoN= *it1*(*it2);
            if (supuestoN==this->n) {
                pAtacado=*it1;
                qAtacado=*it2;
                fin=true;
            }
            else it2++;
        }
        if (!fin) {
            it1++;
            it2=it1;
            it2++;
        }
    }
    cout << "Vulnerado!!!" << endl;
    cout << "El p es= " << pAtacado << endl;
    cout << "El q es= " << qAtacado << endl;
    RSA* unRSA = new RSA();
    for (int i=0; i<6; i++) {
        unRSA->fila1.push_back(0);
        unRSA->fila2.push_back(0);
    }
    unRSA->setP(pAtacado);
    unRSA->setQ(qAtacado);
    unRSA->calcularN();
    cout << "N= " << this->n << endl;
    unRSA->calcularPhi();
    unRSA->setD(this->d);
    cout << "D: "<< this->d <<endl;
    unRSA->calcularEATAQUE();
    cout << "E= " << this->e  << endl;
    delete unRSA;
    cout << "Con estos datos puede crearse el archivo clavePrivada.txt y vulnerarse la seguridad" << endl;
}
Ejemplo n.º 10
0
void ProtocolAdmin::parsePacket(NetworkMessage& msg)
{
	if (g_game.getGameState() == GAME_STATE_SHUTDOWN) {
		getConnection()->closeConnection();
		return;
	}

	uint8_t recvbyte = msg.GetByte();

	OutputMessagePool* outputPool = OutputMessagePool::getInstance();

	OutputMessage_ptr output = outputPool->getOutputMessage(this, false);

	if (!output) {
		return;
	}

	switch (m_state) {
		case ENCRYPTION_NO_SET: {
			if (g_adminConfig->requireEncryption()) {
				if ((time(NULL) - m_startTime) > 30000) {
					getConnection()->closeConnection();
					addLogLine(this, LOGTYPE_WARNING, 1, "encryption timeout");
					return;
				}

				if (recvbyte != AP_MSG_ENCRYPTION && recvbyte != AP_MSG_KEY_EXCHANGE) {
					output->AddByte(AP_MSG_ERROR);
					output->AddString("encryption needed");
					outputPool->send(output);
					getConnection()->closeConnection();
					addLogLine(this, LOGTYPE_WARNING, 1, "wrong command while ENCRYPTION_NO_SET");
					return;
				}

				break;
			} else {
				m_state = NO_LOGGED_IN;
			}
		}

		case NO_LOGGED_IN: {
			if (g_adminConfig->requireLogin()) {
				if ((time(NULL) - m_startTime) > 30000) {
					//login timeout
					getConnection()->closeConnection();
					addLogLine(this, LOGTYPE_WARNING, 1, "login timeout");
					return;
				}

				if (m_loginTries > 3) {
					output->AddByte(AP_MSG_ERROR);
					output->AddString("too many login tries");
					outputPool->send(output);
					getConnection()->closeConnection();
					addLogLine(this, LOGTYPE_WARNING, 1, "too many login tries");
					return;
				}

				if (recvbyte != AP_MSG_LOGIN) {
					output->AddByte(AP_MSG_ERROR);
					output->AddString("you are not logged in");
					outputPool->send(output);
					getConnection()->closeConnection();
					addLogLine(this, LOGTYPE_WARNING, 1, "wrong command while NO_LOGGED_IN");
					return;
				}

				break;
			} else {
				m_state = LOGGED_IN;
			}
		}

		case LOGGED_IN: {
			//can execute commands
			break;
		}

		default: {
			getConnection()->closeConnection();
			return;
		}
	}

	m_lastCommand = time(NULL);

	switch (recvbyte) {
		case AP_MSG_LOGIN: {
			if (m_state == NO_LOGGED_IN && g_adminConfig->requireLogin()) {
				std::string password = msg.GetString();

				if (g_adminConfig->passwordMatch(password)) {
					m_state = LOGGED_IN;
					output->AddByte(AP_MSG_LOGIN_OK);
					addLogLine(this, LOGTYPE_EVENT, 1, "login ok");
				} else {
					m_loginTries++;
					output->AddByte(AP_MSG_LOGIN_FAILED);
					output->AddString("wrong password");
					addLogLine(this, LOGTYPE_WARNING, 1, "login failed.(" + password + ")");
				}
			} else {
				output->AddByte(AP_MSG_LOGIN_FAILED);
				output->AddString("can not login");
				addLogLine(this, LOGTYPE_WARNING, 1, "wrong state at login");
			}

			break;
		}

		case AP_MSG_ENCRYPTION: {
			if (m_state == ENCRYPTION_NO_SET && g_adminConfig->requireEncryption()) {
				uint8_t keyType = msg.GetByte();

				if (keyType == ENCRYPTION_RSA1024XTEA) {
					RSA* rsa = g_adminConfig->getRSAKey(ENCRYPTION_RSA1024XTEA);

					if (!rsa) {
						output->AddByte(AP_MSG_ENCRYPTION_FAILED);
						addLogLine(this, LOGTYPE_WARNING, 1, "no valid server key type");
						break;
					}

					if (RSA_decrypt(rsa, msg)) {
						m_state = NO_LOGGED_IN;
						uint32_t k[4];
						k[0] = msg.GetU32();
						k[1] = msg.GetU32();
						k[2] = msg.GetU32();
						k[3] = msg.GetU32();

						//use for in/out the new key we have
						enableXTEAEncryption();
						setXTEAKey(k);

						output->AddByte(AP_MSG_ENCRYPTION_OK);
						addLogLine(this, LOGTYPE_EVENT, 1, "encryption ok");
					} else {
						output->AddByte(AP_MSG_ENCRYPTION_FAILED);
						output->AddString("wrong encrypted packet");
						addLogLine(this, LOGTYPE_WARNING, 1, "wrong encrypted packet");
					}
				} else {
					output->AddByte(AP_MSG_ENCRYPTION_FAILED);
					output->AddString("no valid key type");
					addLogLine(this, LOGTYPE_WARNING, 1, "no valid client key type");
				}
			} else {
				output->AddByte(AP_MSG_ENCRYPTION_FAILED);
				output->AddString("can not set encryption");
				addLogLine(this, LOGTYPE_EVENT, 1, "can not set encryption");
			}

			break;
		}

		case AP_MSG_KEY_EXCHANGE: {
			if (m_state == ENCRYPTION_NO_SET && g_adminConfig->requireEncryption()) {
				uint8_t keyType = msg.GetByte();

				if (keyType == ENCRYPTION_RSA1024XTEA) {
					RSA* rsa = g_adminConfig->getRSAKey(ENCRYPTION_RSA1024XTEA);

					if (!rsa) {
						output->AddByte(AP_MSG_KEY_EXCHANGE_FAILED);
						addLogLine(this, LOGTYPE_WARNING, 1, "no valid server key type");
						break;
					}

					output->AddByte(AP_MSG_KEY_EXCHANGE_OK);
					output->AddByte(ENCRYPTION_RSA1024XTEA);
					char RSAPublicKey[128];
					rsa->getPublicKey(RSAPublicKey);
					output->AddBytes(RSAPublicKey, 128);
				} else {
					output->AddByte(AP_MSG_KEY_EXCHANGE_FAILED);
					addLogLine(this, LOGTYPE_WARNING, 1, "no valid client key type");
				}
			} else {
				output->AddByte(AP_MSG_KEY_EXCHANGE_FAILED);
				output->AddString("can not get public key");
				addLogLine(this, LOGTYPE_WARNING, 1, "can not get public key");
			}

			break;
		}

		case AP_MSG_COMMAND: {
			if (m_state != LOGGED_IN) {
				addLogLine(this, LOGTYPE_ERROR, 1, "recvbyte == AP_MSG_COMMAND && m_state != LOGGED_IN !!!");
				// We should never reach this point
				break;
			}

			uint8_t command = msg.GetByte();

			switch (command) {
				case CMD_BROADCAST: {
					const std::string message = msg.GetString();
					addLogLine(this, LOGTYPE_EVENT, 1, "broadcast: " + message);
					g_dispatcher.addTask(createTask(boost::bind(&Game::broadcastMessage, &g_game, message, MSG_STATUS_WARNING)));
					output->AddByte(AP_MSG_COMMAND_OK);
					break;
				}

				case CMD_CLOSE_SERVER: {
					g_dispatcher.addTask(createTask(boost::bind(&ProtocolAdmin::adminCommandCloseServer, this)));
					break;
				}

				case CMD_PAY_HOUSES: {
					g_dispatcher.addTask(createTask(boost::bind(&ProtocolAdmin::adminCommandPayHouses, this)));
					break;
				}

				case CMD_OPEN_SERVER: {
					g_dispatcher.addTask(createTask(boost::bind(&ProtocolAdmin::adminCommandOpenServer, this)));
					break;
				}

				case CMD_SHUTDOWN_SERVER: {
					g_dispatcher.addTask(createTask(boost::bind(&ProtocolAdmin::adminCommandShutdownServer, this)));
					getConnection()->closeConnection();
					return;
				}

				case CMD_KICK: {
					const std::string name = msg.GetString();
					g_dispatcher.addTask(createTask(boost::bind(&ProtocolAdmin::adminCommandKickPlayer, this, name)));
					break;
				}

				case CMD_SETOWNER: {
					const std::string param = msg.GetString();
					g_dispatcher.addTask(createTask(boost::bind(&ProtocolAdmin::adminCommandSetOwner, this, param)));
					break;
				}

				default: {
					output->AddByte(AP_MSG_COMMAND_FAILED);
					output->AddString("not known server command");
					addLogLine(this, LOGTYPE_WARNING, 1, "not known server command");
					break;
				}
			}

			break;
		}

		case AP_MSG_PING: {
			output->AddByte(AP_MSG_PING_OK);
			break;
		}

		default: {
			output->AddByte(AP_MSG_ERROR);
			output->AddString("not known command byte");
			addLogLine(this, LOGTYPE_WARNING, 1, "not known command byte");
			break;
		}
	}

	if (output->getMessageLength() > 0) {
		outputPool->send(output);
	}
}
Ejemplo n.º 11
0
void mainLoader(int, char*[], ServiceManager* services)
{
    //dispatcher thread
    g_game.setGameState(GAME_STATE_STARTUP);

    srand(static_cast<unsigned int>(OTSYS_TIME()));
#ifdef _WIN32
    SetConsoleTitle(STATUS_SERVER_NAME);
#endif
    std::cout << "The " << STATUS_SERVER_NAME << " Version: (" << STATUS_SERVER_VERSION << "." << MINOR_VERSION << " . " << REVISION_VERSION << ") - Codename: ( " << SOFTWARE_CODENAME << " )" << std::endl;
    std::cout << "Compiled with: " << BOOST_COMPILER << std::endl;
    std::cout << "Compiled on " << __DATE__ << ' ' << __TIME__ << " for platform ";

#if defined(__amd64__) || defined(_M_X64)
    std::cout << "x64" << std::endl;
#elif defined(__i386__) || defined(_M_IX86) || defined(_X86_)
    std::cout << "x86" << std::endl;
#elif defined(__arm__)
    std::cout << "ARM" << std::endl;
#else
    std::cout << "unknown" << std::endl;
#endif
    std::cout << std::endl;

    std::cout << "A server developed by " << STATUS_SERVER_DEVELOPERS << "." << std::endl;
    std::cout << "Visit our forum for updates, support, and resources: " << GIT_REPO <<"." << std::endl;
    std::cout << std::endl;

    // read global config
    std::cout << ">> Loading config" << std::endl;
    if (!g_config.load()) {
        startupErrorMessage("Unable to load config.lua!");
        return;
    }

#ifdef _WIN32
    const std::string& defaultPriority = g_config.getString(ConfigManager::DEFAULT_PRIORITY);
    if (strcasecmp(defaultPriority.c_str(), "high") == 0) {
        SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
    } else if (strcasecmp(defaultPriority.c_str(), "above-normal") == 0) {
        SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
    }
#endif

    //set RSA key
    const char* p("14299623962416399520070177382898895550795403345466153217470516082934737582776038882967213386204600674145392845853859217990626450972452084065728686565928113");
    const char* q("7630979195970404721891201847792002125535401292779123937207447574596692788513647179235335529307251350570728407373705564708871762033017096809910315212884101");
    g_RSA.setKey(p, q);

    std::cout << ">> Establishing database connection..." << std::flush;

    Database* db = Database::getInstance();
    if (!db->connect()) {
        startupErrorMessage("Failed to connect to database.");
        return;
    }

    std::cout << " MySQL " << Database::getClientVersion() << std::endl;

    // run database manager
    std::cout << ">> Running database manager" << std::endl;

    if (!DatabaseManager::isDatabaseSetup()) {
        startupErrorMessage("The database you have specified in config.lua is empty, please import the schema.sql to your database.");
        return;
    }
    g_databaseTasks.start();

    DatabaseManager::updateDatabase();

    if (g_config.getBoolean(ConfigManager::OPTIMIZE_DATABASE) && !DatabaseManager::optimizeTables()) {
        std::cout << "> No tables were optimized." << std::endl;
    }

    //load vocations
    std::cout << ">> Loading vocations" << std::endl;
    if (!g_vocations.loadFromXml()) {
        startupErrorMessage("Unable to load vocations!");
        return;
    }

    // load item data
    std::cout << ">> Loading items" << std::endl;
    if (Item::items.loadFromOtb("data/items/items.otb") != ERROR_NONE) {
        startupErrorMessage("Unable to load items (OTB)!");
        return;
    }

    if (!Item::items.loadFromXml()) {
        startupErrorMessage("Unable to load items (XML)!");
        return;
    }

    std::cout << ">> Loading script systems" << std::endl;
    if (!ScriptingManager::getInstance()->loadScriptSystems()) {
        startupErrorMessage("Failed to load script systems");
        return;
    }

    std::cout << ">> Loading monsters" << std::endl;
    if (!g_monsters.loadFromXml()) {
        startupErrorMessage("Unable to load monsters!");
        return;
    }

    std::cout << ">> Loading outfits" << std::endl;
    Outfits* outfits = Outfits::getInstance();
    if (!outfits->loadFromXml()) {
        startupErrorMessage("Unable to load outfits!");
        return;
    }

    std::cout << ">> Checking world type... " << std::flush;
    std::string worldType = asLowerCaseString(g_config.getString(ConfigManager::WORLD_TYPE));
    if (worldType == "pvp") {
        g_game.setWorldType(WORLD_TYPE_PVP);
    } else if (worldType == "no-pvp") {
        g_game.setWorldType(WORLD_TYPE_NO_PVP);
    } else if (worldType == "pvp-enforced") {
        g_game.setWorldType(WORLD_TYPE_PVP_ENFORCED);
    } else {
        std::cout << std::endl;

        std::ostringstream ss;
        ss << "> ERROR: Unknown world type: " << g_config.getString(ConfigManager::WORLD_TYPE) << ", valid world types are: pvp, no-pvp and pvp-enforced.";
        startupErrorMessage(ss.str());
        return;
    }
    std::cout << asUpperCaseString(worldType) << std::endl;

    std::cout << ">> Loading map" << std::endl;
    if (!g_game.loadMainMap(g_config.getString(ConfigManager::MAP_NAME))) {
        startupErrorMessage("Failed to load map");
        return;
    }

    std::cout << ">> Initializing gamestate" << std::endl;
    g_game.setGameState(GAME_STATE_INIT);

    // Game client protocols
    services->add<ProtocolGame>(g_config.getNumber(ConfigManager::GAME_PORT));
    services->add<ProtocolLogin>(g_config.getNumber(ConfigManager::LOGIN_PORT));

    // OT protocols
    services->add<ProtocolStatus>(g_config.getNumber(ConfigManager::STATUS_PORT));

    // Legacy login protocol
    services->add<ProtocolOld>(g_config.getNumber(ConfigManager::LOGIN_PORT));

    RentPeriod_t rentPeriod;
    std::string strRentPeriod = asLowerCaseString(g_config.getString(ConfigManager::HOUSE_RENT_PERIOD));

    if (strRentPeriod == "yearly") {
        rentPeriod = RENTPERIOD_YEARLY;
    } else if (strRentPeriod == "weekly") {
        rentPeriod = RENTPERIOD_WEEKLY;
    } else if (strRentPeriod == "monthly") {
        rentPeriod = RENTPERIOD_MONTHLY;
    } else if (strRentPeriod == "daily") {
        rentPeriod = RENTPERIOD_DAILY;
    } else {
        rentPeriod = RENTPERIOD_NEVER;
    }

    g_game.map.houses.payHouses(rentPeriod);

    IOMarket::checkExpiredOffers();
    IOMarket::getInstance()->updateStatistics();

    std::cout << ">> Loaded all modules, server starting up..." << std::endl;

#ifndef _WIN32
    if (getuid() == 0 || geteuid() == 0) {
        std::cout << "> Warning: " << STATUS_SERVER_NAME << " has been executed as root user, please consider running it as a normal user." << std::endl;
    }
#endif

    g_game.start(services);
    g_game.setGameState(GAME_STATE_NORMAL);
    g_loaderSignal.notify_all();
}
Ejemplo n.º 12
0
void mainLoader(int, char*[], ServiceManager* services)
{

	srand(static_cast<unsigned int>(OTSYS_TIME()));
#ifdef _WIN32
	SetConsoleTitle(STATUS_SERVER_NAME);
#endif
	std::cout << STATUS_SERVER_NAME << " - Version " << STATUS_SERVER_VERSION << std::endl;
	std::cout << "Compiled with " << BOOST_COMPILER << std::endl;
	std::cout << "Compiled on " << __DATE__ << ' ' << __TIME__ << " for platform ";

#if defined(__amd64__) || defined(_M_X64)
	std::cout << "x64" << std::endl;
#elif defined(__i386__) || defined(_M_IX86) || defined(_X86_)
	std::cout << "x86" << std::endl;
#elif defined(__arm__)
	std::cout << "ARM" << std::endl;
#else
	std::cout << "unknown" << std::endl;
#endif
	std::cout << std::endl;

	std::cout << "A server developed by " << STATUS_SERVER_DEVELOPERS << std::endl;
	std::cout << "Visit our forum for updates, support, and resources: http://otland.net/." << std::endl;
	std::cout << std::endl;

	// read global config
	std::cout << ">> Loading config" << std::endl;
	if (!g_config.load()) {
		startupErrorMessage("Unable to load config.lua!");
		return;
	}

	std::cout << ">> Loading gameserver config..." << std::endl;

	if (!g_gameserver.load()) {
		startupErrorMessage("Unable to load gameservers!");
		return;
	}

#ifdef _WIN32
	const std::string& defaultPriority = g_config.getString(ConfigManager::DEFAULT_PRIORITY);
	if (strcasecmp(defaultPriority.c_str(), "high") == 0) {
		SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
	} else if (strcasecmp(defaultPriority.c_str(), "above-normal") == 0) {
		SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
	}
#endif

	//set RSA key
	const char* p("14299623962416399520070177382898895550795403345466153217470516082934737582776038882967213386204600674145392845853859217990626450972452084065728686565928113");
	const char* q("7630979195970404721891201847792002125535401292779123937207447574596692788513647179235335529307251350570728407373705564708871762033017096809910315212884101");
	g_RSA.setKey(p, q);

	std::cout << ">> Establishing database connection..." << std::flush;

	Database* db = Database::getInstance();
	if (!db->connect()) {
		startupErrorMessage("Failed to connect to database.");
		return;
	}

	std::cout << " MySQL " << Database::getClientVersion() << std::endl;

	// run database manager
	std::cout << ">> Running database manager" << std::endl;

	if (!DatabaseManager::isDatabaseSetup()) {
		startupErrorMessage("The database you have specified in config.lua is empty, please import the schema.sql to your database.");
		return;
	}
	g_databaseTasks.start();

	if (g_config.getBoolean(ConfigManager::OPTIMIZE_DATABASE) && !DatabaseManager::optimizeTables()) {
		std::cout << "> No tables were optimized." << std::endl;
	}

	services->add<ProtocolLogin>(g_config.getNumber(ConfigManager::LOGIN_PORT));
	services->add<ProtocolOld>(g_config.getNumber(ConfigManager::LOGIN_PORT));

	std::cout << ">> Loaded all modules, server starting up..." << std::endl;

#ifndef _WIN32
	if (getuid() == 0 || geteuid() == 0) {
		std::cout << "> Warning: " << STATUS_SERVER_NAME << " has been executed as root user, please consider running it as a normal user." << std::endl;
	}
#endif

	g_loaderSignal.notify_all();
}
Ejemplo n.º 13
0
/**
testing.
*/
int mainCryptopp(const char* encryptPath, const char* decryptPath)
{
    printf("/***************************************************************************\n");
    printf("C++ crypto, wrap cryptopp interface, reference to www.cryptopp.com\n");
    printf("[email protected] 2006-5-25\n");
    printf("***************************************************************************/\n");

    // base64 testing.
    {
        printf("\n=======================base64=====================\n");
        // input data.
        const char * indata = "bsmith is a good guy.";
        int inlen = (int)strlen(indata);
        printf("inlen=%d\n", inlen);
        printf("indata(hex)=");
        dump(indata, inlen);
        
        // encoding ...
        int maxoutlen = Base64::getCipherLen(inlen);
        printf("maxoutlen=%d\n", maxoutlen);
        char * outdata = new char[maxoutlen];
        int outlen = Base64::encode(indata, inlen, outdata);
        printf("outlen=%d\n", outlen);
        printf("outdata(hex)=");
        dump(outdata, outlen);
        // encoded base64 string.
        char * outstr = new char[outlen+1];
        memcpy(outstr, outdata, outlen);
        outstr[outlen] = 0x00;
        printf("outstr=%s\n", outstr);

        // decoding ...
        int maxinlen = Base64::getPlainLen(outlen);
        printf("maxinlen=%d\n", maxinlen);
        char * orgdata = new char[maxinlen];
        int orglen = Base64::decode(outdata, outlen, orgdata);
        printf("orglen=%d\n", orglen);
        printf("orgdata(hex)=");
        dump(orgdata, orglen);

        delete[] outdata;
        delete[] outstr;
        delete[] orgdata;
    }

    // base16 testing.
    {
        printf("\n=======================base16=====================\n");
        // input data.
        const char * indata = "bsmith is a good guy.";
        int inlen = (int)strlen(indata);
        printf("inlen=%d\n", inlen);
        printf("indata(hex)=");
        dump(indata, inlen);
        
        // encoding ...
        int maxoutlen = Base16::getCipherLen(inlen);
        printf("maxoutlen=%d\n", maxoutlen);
        char * outdata = new char[maxoutlen];
        int outlen = Base16::encode(indata, inlen, outdata);
        printf("outlen=%d\n", outlen);
        printf("outdata(hex)=");
        dump(outdata, outlen);
        // encoded base16 string.
        char * outstr = new char[outlen+1];
        memcpy(outstr, outdata, outlen);
        outstr[outlen] = 0x00;
        printf("outstr=%s\n", outstr);

        // decoding ...
        int maxinlen = Base16::getPlainLen(outlen);
        printf("maxinlen=%d\n", maxinlen);
        char * orgdata = new char[maxinlen];
        int orglen = Base16::decode(outdata, outlen, orgdata);
        printf("orglen=%d\n", orglen);
        printf("orgdata(hex)=");
        dump(orgdata, orglen);

        delete[] outdata;
        delete[] outstr;
        delete[] orgdata;
    }

    // RSA testing.
    {
        printf("\n=======================RSA PKCS #1=====================\n");
        // key
        // N factor in RSA, aslo called modulus.
        const char * N = "90755611487566208138950675092879865387596685014726501531250157258482495478524769456222913843665634824684037468817980814231054856125127115894189385717148934026931120932481402379431731629550862846041784305274651476086892165805223719552575599962253392248079811268061946102234935422772131475340988882825043233323";
        // e factor in RSA, aslo called public exponent.
        const char * e = "65537";
        // d factor in RSA, aslo called private exponent
        const char * d = "17790520481266507102264359414044396762660094486842415203197747383916331528947124726552875080482359744765793816651732601742929364124685415229452844016482477236658413327331659722342187036963943428678684677279032263501011143882814728160215380051287503219732737197808611144507720521201393129692996926599975297921";

        // input data.
        const char * indata = "bsmith is a good guy.";
        int inlen = (int)strlen(indata);
        printf("inlen=%d\n", inlen);
        printf("indata(hex)=");
        dump(indata, inlen);

        // init RSA public key encryptor.
        RSA enc;
        enc.initPublicKey(N, e);

        // encrypt.
        int maxoutlen = enc.getCipherLen(inlen);
        printf("maxoutlen=%d\n", maxoutlen);
        char * outdata = new char[maxoutlen];
        int outlen = enc.encrypt(indata, inlen, outdata);
        printf("outlen=%d\n", outlen);
        printf("outdata(hex)=");
        dump(outdata, outlen);

        // init private for RSA decryptor.
        RSA dec;
        dec.initPrivateKey(N, e, d);

        // decrypt.
        int maxinlen = dec.getPlainLen(outlen);
        printf("maxinlen=%d\n", maxinlen);
        char * orgdata = new char[maxinlen];
        int orglen = dec.decrypt(outdata, outlen, orgdata);
        printf("orglen=%d\n", orglen);
        printf("orgdata(hex)=");
        dump(orgdata, orglen);

        delete[] outdata;
        delete[] orgdata;
    }

    // AES/CBC/PKCS5Padding testing.
    {
        printf("\n=======================AES/CBC/PKCS5Padding=====================\n");
        // key
        const char * key = "0123456789abcdef";
        // iv
        const char * iv = "fedcba9876543210";

        // init AES.
        AES aes;
        aes.init(key, 16, iv);

        // input data.
        // const char * indata = "bsmith is a good guy.";
        // const char * indata = "bsmith.";
        const char * indata = "I am a good guy.";
        int inlen = (int)strlen(indata);
        printf("inlen=%d\n", inlen);
        printf("indata(hex)=");
        dump(indata, inlen);

        // encrypt.
        int maxoutlen = aes.getCipherLen(inlen);
        printf("maxoutlen=%d\n", maxoutlen);
        char * outdata = new char[maxoutlen];
        int outlen = 0;
        {
            outlen = aes.encrypt(indata, inlen, outdata);
            printf("outlen=%d\n", outlen);
            printf("outdata(hex)=");
            dump(outdata, outlen);
        }
        {
            outlen = aes.encrypt(indata, inlen, outdata);
            printf("outlen=%d\n", outlen);
            printf("outdata(hex)=");
            dump(outdata, outlen);
        }

        // decrypt.
        int maxinlen = aes.getPlainLen(outlen);
        printf("maxinlen=%d\n", maxinlen);
        char * orgdata = new char[maxinlen];
        {
            
            int orglen = aes.decrypt(outdata, outlen, orgdata);
            printf("orglen=%d\n", orglen);
            printf("orgdata(hex)=");
            dump(orgdata, orglen);
        }
        {
            int orglen = aes.decrypt(outdata, outlen, orgdata);
            printf("orglen=%d\n", orglen);
            printf("orgdata(hex)=");
            dump(orgdata, orglen);
        }

        delete[] outdata;
        delete[] orgdata;

    }

    // SHA1 testing.
    {
        printf("\n=======================SHA1=====================\n");

        SHA1 sha1;

        // input data.
        const char * indata = "bsmith is a good guy.";
        int inlen = (int)strlen(indata);
        printf("inlen=%d\n", inlen);
        printf("indata(hex)=");
        dump(indata, inlen);
        
        // one time digest.
        {
            char * outdata = new char[sha1.getCipherLen(inlen)];
            int outlen = sha1.digest(indata, inlen, outdata);
            printf("outlen=%d\n", outlen);
            printf("outdata(hex)=");
            dump(outdata, outlen);

            delete[] outdata;
        }

        // serval times
        {
            char * outdata = new char[sha1.getCipherLen(inlen)];
            sha1.update(indata, 5);
            sha1.update(indata+5, inlen-5);
            int outlen = sha1.final(outdata);
            printf("outlen=%d\n", outlen);
            printf("outdata(hex)=");
            dump(outdata, outlen);

            delete[] outdata;
        }

        // one time digest.
        {
            char * outdata = new char[sha1.getCipherLen(inlen)];
            int outlen = sha1.digest(indata, inlen, outdata);
            printf("outlen=%d\n", outlen);
            printf("outdata(hex)=");
            dump(outdata, outlen);

            delete[] outdata;
        }

        // serval times
        {
            char * outdata = new char[sha1.getCipherLen(inlen)];
            sha1.update(indata, 5);
            sha1.update(indata+5, inlen-5);
            int outlen = sha1.final(outdata);
            printf("outlen=%d\n", outlen);
            printf("outdata(hex)=");
            dump(outdata, outlen);

            delete[] outdata;
        }
    }

    // RSA-SHA1 Sign testing.
    {
        printf("\n=======================RSA-SHA1 Sign=====================\n");

        // key
        // N factor in RSA, aslo called modulus.
        const char * N = "90755611487566208138950675092879865387596685014726501531250157258482495478524769456222913843665634824684037468817980814231054856125127115894189385717148934026931120932481402379431731629550862846041784305274651476086892165805223719552575599962253392248079811268061946102234935422772131475340988882825043233323";
        // e factor in RSA, aslo called public exponent.
        const char * e = "65537";
        // d factor in RSA, aslo called private exponent
        const char * d = "17790520481266507102264359414044396762660094486842415203197747383916331528947124726552875080482359744765793816651732601742929364124685415229452844016482477236658413327331659722342187036963943428678684677279032263501011143882814728160215380051287503219732737197808611144507720521201393129692996926599975297921";

        // input data.
        const char * indata = "bsmith is a good guy.";
        int inlen = (int)strlen(indata);
        printf("inlen=%d\n", inlen);
        printf("indata(hex)=");
        dump(indata, inlen);

        Sign sign;
        // private key for signer.
        sign.initPrivateKey(N, e, d);

        // sign.
        int maxoutlen = sign.getCipherLen(inlen);
        printf("maxoutlen=%d\n", maxoutlen);
        char * outdata = new char[maxoutlen];
        int outlen = sign.sign(indata, inlen, outdata);
        printf("outlen=%d\n", outlen);
        printf("outdata(hex)=");
        dump(outdata, outlen);

        // public key for verifier.
        sign.initPublicKey(N, e);

        // verify.
        {
            bool res = sign.verify(indata, inlen, outdata, outlen);
            printf("result <?> true : %s\n", res?"true":"false");
        }
        
        // another data.
        const char * indata1 = "bsmith is not a good guy.";
        int inlen1 = (int)strlen(indata1);
        {
            bool res = sign.verify(indata1, inlen1, outdata, outlen);
            printf("result <?> false : %s\n", res?"true":"false");
        }

        delete[] outdata;
    }

    //printf("press any key to exit!");
    //getchar();
    
    {
        //my test
        unsigned long decryptSize = 0;
        char* decryptBuffer = (char*)getFileData(decryptPath, &decryptSize);
        
        unsigned long encryptSize = 0;
        char* encryptBuffer = (char*)getFileData(encryptPath, &encryptSize);
        
        printf("decryptBuffer(hex)=");
        dump(decryptBuffer, decryptSize);
        
        // key
        const char * key = "0123456789abcdef";
        // iv
        const char * iv = "fedcba9876543210";
        
        // init AES.
        AES aes;
        aes.init(key, 16, iv);
        {
            // decrypt.
            int maxinlen = aes.getPlainLen(encryptSize);
            char * orgdata = new char[maxinlen];
            {
                int orglen = aes.decrypt(encryptBuffer, encryptSize, orgdata);
                printf("decryptWithCrypto++(hex)=");
                dump(orgdata, orglen);
            }
            delete [] orgdata;
        }
        
        printf("encryptBuffer(hex)=");
        dump(encryptBuffer, encryptSize);
        
        {
            // encrypt.
            int maxoutlen = aes.getCipherLen(decryptSize);
            char * outdata = new char[maxoutlen];
            int outlen = 0;
            {
                outlen = aes.encrypt(decryptBuffer, decryptSize, outdata);
                printf("encryptWithCrypto++(hex)=");
                dump(outdata, outlen);
            }
            delete [] outdata;
        }
        
        delete [] decryptBuffer;
        delete [] encryptBuffer;
        
        
    }

    return 0;
}
Ejemplo n.º 14
0
int main(int argc, char*argv[])
{
	RSA* _RSA_obj[10];
	BigInt _message, _encrypt, _decrypt;
	int _primeNumber[] = { 40343,40351,40357,40361,40387,40423,40427,40429,40433,40459,40471,40483,40487,40493,40499,40507,40519,40529,40531};
	int _nonPrimeNumber[] = {36782,36792,36792,36802,36822,36832,36842,36852,36872,36872,37692,37692,37692,37722,37742,37712,37782,37792,37812,37814};


cout << "1)------------------Encryption and Decryption using RSA----------------------"<<"\n";

//------------No arguments RSA --------------------------------------------
	   cout << "a) 10 instances of RSA routine(argument-less) encryption-decryption"<<"\n";
	for (int i = 0; i < 10; i++)
	{
		_RSA_obj[i] = new RSA();
		usleep(21000);
		_message = int(((double) rand() / RAND_MAX)*RAND_GEN32);
		_encrypt = _RSA_obj[i]->encrypt(_message);
		_decrypt = _RSA_obj[i]->decrypt(_encrypt);

    cout << "Message: " << _message.toHexString() << "\t\tEncrypted: " << _encrypt.toHexString() << "\t\tDecrypted: " << _decrypt.toHexString()<<"\n";
	}
	cout<<"\n";
//------------1 prime number RSA --------------------------------------------
	   cout << "b) 5 RSA instances(1 prime number(>30,000) as argument) encryption-decryption "<<"\n";
	for (int i = 0; i < 5; i++)
	{
		_RSA_obj[i] = new RSA(_primeNumber[i]);
		usleep(450000);
		_message = int(((double) rand() / RAND_MAX)*RAND_GEN32);
		_encrypt = _RSA_obj[i]->encrypt(_message);
		_decrypt = _RSA_obj[i]->decrypt(_encrypt);

    cout << "Message: " << _message.toHexString() << "\t\tEncrypted: " << _encrypt.toHexString() << "\t\tDecrypted: " << _decrypt.toHexString()<<"\n";
	}
	cout<<"\n";
//------------2 prime numbers RSA --------------------------------------------
   cout << "c) 5 RSA instances(2 prime numbers(>30,000) as arguments) encryption-decryption "<<"\n";
	 for (int i = 0; i < 5; i++)
 	{
 		_RSA_obj[i] = new RSA(_primeNumber[i], _primeNumber[10-i]);
 		usleep(450000);
 		_message = int(((double) rand() / RAND_MAX)*RAND_GEN32);
 		_encrypt = _RSA_obj[i]->encrypt(_message);
	_decrypt = _RSA_obj[i]->decrypt(_encrypt);
 		 cout << "Message: " << _message.toHexString() << "\tEncrypted: " << _encrypt.toHexString() << "\tDecrypted: " << _decrypt.toHexString()<<"\n";
 	}
	cout<<"\n";

//--------------2 non prime numbers RSA-------------------------------------
cout << "d) 5 RSA instances(2 non prime numbers(>30,000) as arguments) encryption-decryption "<<"\n";
for (int i = 0; i < 10; i++)
{
 _RSA_obj[i] = new RSA(_nonPrimeNumber[i], _nonPrimeNumber[10-i]);
 usleep(50000);
 _message = int(((double) rand() / RAND_MAX)*RAND_GEN32);
 _encrypt = _RSA_obj[i]->encrypt(_message);
 _decrypt = _RSA_obj[i]->decrypt(_encrypt);
	cout << "Message: " << _message.toHexString() << "\tEncrypted: " << _encrypt.toHexString() << "\tDecrypted: " << _decrypt.toHexString()<<"\n";
}
cout<<"\n";

//--------------challenge response scheme---------------------------------------
cout << "2)--------------------Challenge response scheme--------------------" <<  "\n";
RSA obj1, obj2;

BigInt rsaPK = obj1.getPublicKey();
BigInt rsaN = obj1.getModulus();

obj2.setPublicKey(rsaPK);
obj2.setN(rsaN);

//random message
_message = int(((double) rand() / RAND_MAX)*RAND_GEN32);

BigInt encrypt = obj2.encrypt(_message);
BigInt decrypt = obj1.decrypt(encrypt);

cout << "Plain Text:" << _message.toHexString() << "\tDecrypted Text:" << decrypt.toHexString() <<  "\n";
if (_message.operator==(decrypt))
	cout << "Challenge response scheme is Successful" <<  "\n";
else
	cout << "Challenge response scheme is Unsuccessful" <<  "\n";
cout <<  "\n";


//--------------Blind signature---------------------------------------

cout << "3)------------------Blind signature---------------------" <<  "\n";
RSA obj;
BigInt bobN = obj.getModulus();
BigInt bobPK = obj.getPublicKey();

// Generate random number and its inverse
double AliceRandomNo = double(((double) rand() / RAND_MAX)*RAND_GEN32);
BigInt rnd(AliceRandomNo);
BigInt AliceRandomNoInverse = RSAUtil::modInverse(rnd, bobN);

//random message
_message = int(((double) rand() / RAND_MAX)*RAND_GEN32);

BigInt encryptRandom = RSAUtil::modPow(rnd, bobPK, bobN);

BigInt messageToRSAobj = encryptRandom.operator*(_message).operator%(bobN);

BigInt messageFromRSAobj = getDecryptedMessageFromRSA_obj(messageToRSAobj, obj);

BigInt sign = messageFromRSAobj.operator*(AliceRandomNoInverse).operator%(bobN);

BigInt flag = RSAUtil::modPow(sign, bobPK, bobN);

cout << "message: " << _message.toHexString() << "\tsignature: " << sign.toHexString() << "\tdecrypted: " << flag.toHexString() <<  "\n";

cout << "\nBlind signature: ";
if(_message.operator==(flag))
	cout << "Blind signature Successful" <<"\n";
else
	cout << "Blind signature Unsuccessful" << "\n";

//--------------------------------------end of main--------------------
cout<<"\n";
return 0;
}
Ejemplo n.º 15
0
void mainLoader(int, char*[], ServiceManager* services)
{
	//dispatcher thread
	g_game.setGameState(GAME_STATE_STARTUP);

	srand(static_cast<unsigned int>(OTSYS_TIME()));
#ifdef _WIN32
	SetConsoleTitle(STATUS_SERVER_NAME);
#endif
	std::cout << STATUS_SERVER_NAME << " - Versao " << STATUS_SERVER_VERSION << std::endl;
	std::cout << "Compilado com " << BOOST_COMPILER << std::endl;
	std::cout << "Compilado em " << __DATE__ << ' ' << __TIME__ << " para plataforma ";

#if defined(__amd64__) || defined(_M_X64)
	std::cout << "x64" << std::endl;
#elif defined(__i386__) || defined(_M_IX86) || defined(_X86_)
	std::cout << "x86" << std::endl;
#elif defined(__arm__)
	std::cout << "ARM" << std::endl;
#else
	std::cout << "desconhecida" << std::endl;
#endif
	std::cout << std::endl;

	std::cout << "Este servidor foi desenvolvido por " << STATUS_SERVER_DEVELOPERS << std::endl;
	std::cout << "Visite nosso forum para updates, suporte e pedidos: http://xtibia.com/." << std::endl;
	std::cout << "Um oferecimento OTPanel, OTserv Cloud em 60s." << std::endl;
	std::cout << std::endl;

	// read global config
	std::cout << ">> Carregando configuracoes" << std::endl;
	if (!g_config.load()) {
		startupErrorMessage("Falha ao carregar o config.lua!");
		return;
	}

#ifdef _WIN32
	const std::string& defaultPriority = g_config.getString(ConfigManager::DEFAULT_PRIORITY);
	if (strcasecmp(defaultPriority.c_str(), "high") == 0) {
		SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
	} else if (strcasecmp(defaultPriority.c_str(), "above-normal") == 0) {
		SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
	}
#endif

	//set RSA key
	const char* p("14299623962416399520070177382898895550795403345466153217470516082934737582776038882967213386204600674145392845853859217990626450972452084065728686565928113");
	const char* q("7630979195970404721891201847792002125535401292779123937207447574596692788513647179235335529307251350570728407373705564708871762033017096809910315212884101");
	g_RSA.setKey(p, q);

	std::cout << ">> Estabilizando conexao com o banco de dados..." << std::flush;

	Database* db = Database::getInstance();
	if (!db->connect()) {
		startupErrorMessage("Falha ao conectar-se com o banco de dados.");
		return;
	}

	std::cout << " MySQL " << Database::getClientVersion() << std::endl;

	// run database manager
	std::cout << ">> Carregando banco de dados" << std::endl;

	if (!DatabaseManager::isDatabaseSetup()) {
		startupErrorMessage("O banco de dados que especificou no config.lua esta vazio, por favor importar o schema.sql para seu banco de dados.");
		return;
	}
	g_databaseTasks.start();

	DatabaseManager::updateDatabase();

	if (g_config.getBoolean(ConfigManager::OPTIMIZE_DATABASE) && !DatabaseManager::optimizeTables()) {
		std::cout << "> Nenhuma tabela foi otimizada." << std::endl;
	}

	//load vocations
	std::cout << ">> Carregando vocacoes" << std::endl;
	if (!g_vocations.loadFromXml()) {
		startupErrorMessage("Impossivel carregar vocacoes!");
		return;
	}

	// load item data
	std::cout << ">> Carregando items" << std::endl;
	if (Item::items.loadFromOtb("data/items/items.otb") != ERROR_NONE) {
		startupErrorMessage("Impossivel carregar items (OTB)!");
		return;
	}

	if (!Item::items.loadFromXml()) {
		startupErrorMessage("Impossivel carregar (XML)!");
		return;
	}

	std::cout << ">> Carregando sistemas de scripts" << std::endl;
	if (!ScriptingManager::getInstance()->loadScriptSystems()) {
		startupErrorMessage("Impossivel carregar sistemas de scripts");
		return;
	}

	std::cout << ">> Carregando criaturas" << std::endl;
	if (!g_monsters.loadFromXml()) {
		startupErrorMessage("Impossivel carregar criaturas!");
		return;
	}

	std::cout << ">> Carregando outfits" << std::endl;
	Outfits* outfits = Outfits::getInstance();
	if (!outfits->loadFromXml()) {
		startupErrorMessage("Impossivel carregar outfits!");
		return;
	}

	std::cout << ">> Checando tipo do servidor... " << std::flush;
	std::string worldType = asLowerCaseString(g_config.getString(ConfigManager::WORLD_TYPE));
	if (worldType == "pvp") {
		g_game.setWorldType(WORLD_TYPE_PVP);
	} else if (worldType == "no-pvp") {
		g_game.setWorldType(WORLD_TYPE_NO_PVP);
	} else if (worldType == "pvp-enforced") {
		g_game.setWorldType(WORLD_TYPE_PVP_ENFORCED);
	} else {
		std::cout << std::endl;

		std::ostringstream ss;
		ss << "> ERRO: Tipo do servidor desconhecido: " << g_config.getString(ConfigManager::WORLD_TYPE) << ", os tipos validos sao: pvp, no-pvp and pvp-enforced.";
		startupErrorMessage(ss.str());
		return;
	}
	std::cout << asUpperCaseString(worldType) << std::endl;

	std::cout << ">> Carregando mapa" << std::endl;
	if (!g_game.loadMainMap(g_config.getString(ConfigManager::MAP_NAME))) {
		startupErrorMessage("Impossivel carregar o mapa");
		return;
	}

	std::cout << ">> Inicializando o servidor" << std::endl;
	g_game.setGameState(GAME_STATE_INIT);

	// Game client protocols
	services->add<ProtocolGame>(g_config.getNumber(ConfigManager::GAME_PORT));
	services->add<ProtocolLogin>(g_config.getNumber(ConfigManager::LOGIN_PORT));

	// OT protocols
	services->add<ProtocolStatus>(g_config.getNumber(ConfigManager::STATUS_PORT));

	// Legacy login protocol
	services->add<ProtocolOld>(g_config.getNumber(ConfigManager::LOGIN_PORT));

	RentPeriod_t rentPeriod;
	std::string strRentPeriod = asLowerCaseString(g_config.getString(ConfigManager::HOUSE_RENT_PERIOD));

	if (strRentPeriod == "yearly") {
		rentPeriod = RENTPERIOD_YEARLY;
	} else if (strRentPeriod == "weekly") {
		rentPeriod = RENTPERIOD_WEEKLY;
	} else if (strRentPeriod == "monthly") {
		rentPeriod = RENTPERIOD_MONTHLY;
	} else if (strRentPeriod == "daily") {
		rentPeriod = RENTPERIOD_DAILY;
	} else {
		rentPeriod = RENTPERIOD_NEVER;
	}

	g_game.map.houses.payHouses(rentPeriod);

	IOMarket::checkExpiredOffers();
	IOMarket::getInstance()->updateStatistics();

	std::cout << ">> Todos os modulos carregados, servidor iniciando..." << std::endl;

#ifndef _WIN32
	if (getuid() == 0 || geteuid() == 0) {
		std::cout << "> Aviso: O servidor foi executado com usuario root, por favor considere executa-lo como um usuario normal." << std::endl;
	}
#endif

	g_game.start(services);
	g_game.setGameState(GAME_STATE_NORMAL);
	g_loaderSignal.notify_all();
}
Ejemplo n.º 16
0
int main(int argc, char*argv[]){    
  
	/*
	TASK 1: Perform encryption and Decryption each using the RSA routines provided here. They don’t necessarily have to be part of the same code
	*/
	int count = 10;
	int i=0;
	std::string result;
	BigInt randMessage[10];
	
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	std::cout<<"TASK 1a: Create 10 instances of the RSA class without giving arguments, generate random message or assign messages, and perform encryption through each of the 10 classes. "<<std::endl;
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	//initializing at once as everytime RSA is called srand is called internally and reseting the random function
	for(i=0;i<count;i++)
	{
	   randMessage[i] = int(((double)std::rand()/RAND_MAX)*RAND_LIMIT32);
	}
	for(i=0;i<count;i++)
	{
	  RSA myRSA;
	  BigInt message, cipher, deciphered;
	  message = randMessage[i];
	
	  //encrypting
	  cipher = myRSA.encrypt(message);
	  //decrypting
	  deciphered = myRSA.decrypt(cipher);
	  
	  //Checking if the decrypted value is equal to original value 
	  if(message == deciphered)
	  {
	    result = "success";
	  }
	  else
	  {
	    result = "failed";
	  }
	  std::cout<<"Instance:"<<i<<"\tmessage: "<<message.toHexString()<<"\tcipher: "<<cipher.toHexString()<<"\tdeciphered: "<<deciphered.toHexString()<<"\tverification-result:"<<result<<std::endl;
	}
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	std::cout<<"TASK 1b: Create 5 instances of the RSA class by passing a large prime number [p](> 30,000), and perform encryption decryption. "<<std::endl;
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	
	count =  5;
	//Initializing some primes and non-primes to be used by following tasks.
	unsigned long int setOfLargePrimes[] = {103919, 103951, 103963, 103967,103969, 104677 ,104681 ,104683 ,104693 ,104701 ,104707 ,104711 ,104717 ,104723 ,104729};
	unsigned long int setOfNonPrimes[] = {40000, 31000, 42000, 45000, 50000, 48000,60000,80000,70000,90000,99000};
	
	
	//iterating 5 time for question 1b
	for(i=0;i<count;i++)
	{
	  //giving one primenumber as input to the RSA
	  RSA rsaInstance(setOfLargePrimes[i]);
	  BigInt message, cipher, deciphered;
	  message = randMessage[i];
	 
	  //decrypting and encrypting 
	  cipher = rsaInstance.encrypt(message);
	  deciphered = rsaInstance.decrypt(cipher);
	  
	  //Checking if the decrypted value is equal to original value 
	  if(message == deciphered)
	  {
	    result = "success";
	  }
	  else
	  {
	    result = "failed";
	  }
	  
	  std::cout<<"Instance:"<<i<<"\tmessage: "<<message.toHexString()<<"\tcipher: "<<cipher.toHexString()<<"\tdeciphered: "<<deciphered.toHexString()<<"\tverification-result:"<<result<<std::endl;
	
	}
	
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	std::cout<<"TASK 1c: Create 5 instances of the RSA class by passing 2 large prime numbers [p,q] (> 30,000) and perform encryption decryption "<<std::endl;
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	
	for(i=0;i<count;i++)
	{
	  //Intializing RSA with two primenumbers
	  RSA rsaInstance(setOfLargePrimes[2*i], setOfLargePrimes[2*i+1]);
	  BigInt message, cipher, deciphered;
	  
	  message = randMessage[i];
	  
	  //encrypting and decrypting
	  cipher = rsaInstance.encrypt(message);
	  deciphered = rsaInstance.decrypt(cipher);
	 
	  //Checking if the decrypted value is equal to original value 
	  if(message == deciphered)
	  {
	    result = "success";
	  }
	  else
	  {
	    result = "failed";
	  }
	  
	  std::cout<<"Instance:"<<i<<"\tmessage: "<<message.toHexString()<<"\tcipher: "<<cipher.toHexString()<<"\tdeciphered: "<<deciphered.toHexString()<<"\tverification-result:"<<result<<std::endl;
	
	}
	
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	std::cout<<"TASK 1d: Create 10 instances of the RSA class by passing 2 large non prime numbers (> 30,000) and perform encryption decryption. In most of the cases the message should not get decrypted correctly.  "<<std::endl;
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	
	for(i=0;i<10;i++)
	{
	  //Creating RSA with non primes. 
	  RSA rsaInstance(setOfNonPrimes[i], setOfNonPrimes[i+1]);
	  BigInt message, cipher, deciphered;
	  
	  message = randMessage[i];
	   //encrypting and decrypting
	  cipher = rsaInstance.encrypt(message);
	  deciphered = rsaInstance.decrypt(cipher);
	 
	  //Checking if the decrypted value is equal to original value 
	  if(message == deciphered)
	  {
	    result = "success";
	  }
	  else
	  {
	    result = "failed";
	  }
	  
	  std::cout<<"Instance:"<<i<<"\tmessage: "<<message.toHexString()<<"\tcipher: "<<cipher.toHexString()<<"\tdeciphered: "<<deciphered.toHexString()<<"\tverification-result:"<<result<<std::endl;
	
	}
	
	/*
	TASK 2: Challenge Response: Scheme 0
	*/
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	std::cout<<" TASK 2: Challenge Response Scheme 0 "<<std::endl;
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	
	{
	  RSA RSA1, RSA2;
	  
	  //Assigning RSA1 public key and Modulus to RSA2 
	  BigInt publicKey = RSA1.getPublicKey();
	  BigInt modulus = RSA1.getModulus();
	  RSA2.setPublicKey(publicKey);
	  RSA2.setN(modulus);
	  
	  //generating random message
	  BigInt message, cipher, deciphered;
	  message = int(((double)std::rand()/RAND_MAX)*RAND_LIMIT32);
	  
	  
	  //encrypting with RSA2 i.e RSA1's public key
	  cipher = RSA2.encrypt(message);
	  //decrypting with RSA1 i.e RSA1's private key
	  deciphered = RSA1.decrypt(cipher);
	  
	 //Checking if the decrypted value is equal to original value 
	  if(message == deciphered)
	  {
	    result = "success";
	  }
	  else
	  {
	    result = "failed";
	  }
	  
	  std::cout<<"Instance:"<<i<<"\tmessage: "<<message.toHexString()<<"\tcipher: "<<cipher.toHexString()<<"\tdeciphered: "<<deciphered.toHexString()<<"\tverification-result:"<<result<<std::endl;
	
	}
	
	/*
	TASK 3: Blind Signature
	*/
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	std::cout<<" TASK 3: Blind Signature  "<<std::endl;
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	
	{
	  //Random message requester want to send with signers signature
	  BigInt message = int(((double)std::rand()/RAND_MAX)*RAND_LIMIT32);
	  
	  //Passing signers public key to the requester so that he can generate the blind factor
	  BigInt signedMessage =  Requester(message, signersRSA.getPublicKey(), signersRSA.getModulus());
	  BigInt deciphered = signersRSA.encrypt(signedMessage);
	  
	  std::cout<<"Signed Message without blindfactor:" << signedMessage.toHexString() <<std::endl;
	  
	  std::cout<<" Message Decrypted:" << deciphered.toHexString() <<std::endl;
	  
	  //Checking if the decrypted value is equal to original value 
	  if(message == deciphered)
	  {
	    std::cout<<"Blind Signature successfully implemented"<<std::endl;
	  }
	  else
	  {
	    std::cout<<"Blind Signature implementation failed"<<std::endl;
	  }
	  
	 
	}
	

}
Ejemplo n.º 17
0
void mainLoader(int argc, char* argv[], ServiceManager* services)
{
	//dispatcher thread
	g_game.setGameState(GAME_STATE_STARTUP);

	srand((unsigned int)OTSYS_TIME());
#ifdef _WIN32
	SetConsoleTitle(STATUS_SERVER_NAME);
#endif
	std::cout << STATUS_SERVER_NAME << " - Version " << STATUS_SERVER_VERSION << std::endl;
	std::cout << "Compilied on " << __DATE__ << ' ' << __TIME__ << " for arch ";

#if defined(__amd64__) || defined(_M_X64)
	std::cout << "x64" << std::endl;
#elif defined(__i386__) || defined(_M_IX86) || defined(_X86_)
	std::cout << "x86" << std::endl;
#elif defined(__arm__)
	std::cout << "ARM" << std::endl;
#elif defined(__mips__)
	std::cout << "MIPS" << std::endl;
#else
	std::cout << "unk" << std::endl;
#endif
	std::cout << std::endl;

	std::cout << "A server developed by " << STATUS_SERVER_DEVELOPERS << std::endl;
	std::cout << "Visit our forum for updates, support, and resources: http://otland.net/." << std::endl;
	std::cout << std::endl;

	// read global config
	std::cout << ">> Loading config" << std::endl;
	if (!g_config.load()) {
		startupErrorMessage("Unable to load config.lua!");
		return;
	}

#ifdef _WIN32
	std::string defaultPriority = asLowerCaseString(g_config.getString(ConfigManager::DEFAULT_PRIORITY));
	if (defaultPriority == "realtime") {
		SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
	} else if (defaultPriority == "high") {
		SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
	} else if (defaultPriority == "higher") {
		SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
	}

	std::ostringstream mutexName;
	mutexName << "forgottenserver_" << g_config.getNumber(ConfigManager::LOGIN_PORT);
	CreateMutex(nullptr, FALSE, mutexName.str().c_str());
	if (GetLastError() == ERROR_ALREADY_EXISTS) {
		startupErrorMessage("Another instance of The Forgotten Server is already running with the same login port, please shut it down first or change ports for this one.");
		return;
	}
#endif

	//set RSA key
	const char* p("14299623962416399520070177382898895550795403345466153217470516082934737582776038882967213386204600674145392845853859217990626450972452084065728686565928113");
	const char* q("7630979195970404721891201847792002125535401292779123937207447574596692788513647179235335529307251350570728407373705564708871762033017096809910315212884101");
	g_RSA.setKey(p, q);

	std::cout << ">> Establishing database connection..." << std::flush;

	Database* db = Database::getInstance();
	if (!db->connect()) {
		startupErrorMessage("Failed to connect to database.");
		return;
	}

	std::cout << " MySQL " << Database::getClientVersion() << std::endl;

	// run database manager
	std::cout << ">> Running database manager" << std::endl;

	if (!DatabaseManager::isDatabaseSetup()) {
		startupErrorMessage("The database you have specified in config.lua is empty, please import the schema.sql to your database.");
		return;
	}

	DatabaseManager::updateDatabase();
	DatabaseManager::checkEncryption();

	if (g_config.getBoolean(ConfigManager::OPTIMIZE_DATABASE) && !DatabaseManager::optimizeTables()) {
		std::cout << "> No tables were optimized." << std::endl;
	}

	//load vocations
	std::cout << ">> Loading vocations" << std::endl;
	if (!g_vocations.loadFromXml()) {
		startupErrorMessage("Unable to load vocations!");
		return;
	}

	//load commands
	std::cout << ">> Loading commands" << std::endl;
	if (!g_commands.loadFromXml()) {
		startupErrorMessage("Unable to load commands!");
		return;
	}

	// load item data
	std::cout << ">> Loading items" << std::endl;
	if (Item::items.loadFromOtb("data/items/items.otb")) {
		startupErrorMessage("Unable to load items (OTB)!");
		return;
	}

	if (!Item::items.loadFromXml()) {
		startupErrorMessage("Unable to load items (XML)!");
		return;
	}

	std::cout << ">> Loading script systems" << std::endl;
	if (!ScriptingManager::getInstance()->loadScriptSystems()) {
		startupErrorMessage("Failed to load script systems");
		return;
	}

	std::cout << ">> Loading monsters" << std::endl;
	if (!g_monsters.loadFromXml()) {
		startupErrorMessage("Unable to load monsters!");
		return;
	}

	std::cout << ">> Loading outfits" << std::endl;
	Outfits* outfits = Outfits::getInstance();
	if (!outfits->loadFromXml()) {
		startupErrorMessage("Unable to load outfits!");
		return;
	}

	g_adminConfig = new AdminProtocolConfig();
	std::cout << ">> Loading admin protocol config" << std::endl;
	if (!g_adminConfig->loadXMLConfig()) {
		startupErrorMessage("Unable to load admin protocol config!");
		return;
	}

	std::cout << ">> Loading experience stages" << std::endl;
	if (!g_game.loadExperienceStages()) {
		startupErrorMessage("Unable to load experience stages!");
		return;
	}

	std::string passwordType = asLowerCaseString(g_config.getString(ConfigManager::PASSWORDTYPE));
	if (passwordType == "sha1") {
		g_config.setNumber(ConfigManager::PASSWORD_TYPE, PASSWORD_TYPE_SHA1);
		std::cout << ">> Using SHA1 passwords" << std::endl;
	} else {
		g_config.setNumber(ConfigManager::PASSWORD_TYPE, PASSWORD_TYPE_PLAIN);
		std::cout << ">> Using plaintext passwords" << std::endl;
	}

	std::cout << ">> Checking world type... " << std::flush;
	std::string worldType = asLowerCaseString(g_config.getString(ConfigManager::WORLD_TYPE));
	if (worldType == "pvp") {
		g_game.setWorldType(WORLD_TYPE_PVP);
	} else if (worldType == "no-pvp") {
		g_game.setWorldType(WORLD_TYPE_NO_PVP);
	} else if (worldType == "pvp-enforced") {
		g_game.setWorldType(WORLD_TYPE_PVP_ENFORCED);
	} else {
		std::cout << std::endl;

		std::ostringstream ss;
		ss << "> ERROR: Unknown world type: " << g_config.getString(ConfigManager::WORLD_TYPE) << ", valid world types are: pvp, no-pvp and pvp-enforced.";
		startupErrorMessage(ss.str());
		return;
	}
	std::cout << asUpperCaseString(worldType) << std::endl;

	std::cout << ">> Loading map" << std::endl;

	if (!g_game.loadMainMap(g_config.getString(ConfigManager::MAP_NAME))) {
		startupErrorMessage("Failed to load map");
		return;
	}

	std::cout << ">> Initializing gamestate" << std::endl;
	g_game.setGameState(GAME_STATE_INIT);

	// Tibia protocols
	services->add<ProtocolGame>(g_config.getNumber(ConfigManager::GAME_PORT));
	services->add<ProtocolLogin>(g_config.getNumber(ConfigManager::LOGIN_PORT));

	// OT protocols
	services->add<ProtocolAdmin>(g_config.getNumber(ConfigManager::ADMIN_PORT));
	services->add<ProtocolStatus>(g_config.getNumber(ConfigManager::STATUS_PORT));

	// Legacy protocols
	services->add<ProtocolOldLogin>(g_config.getNumber(ConfigManager::LOGIN_PORT));
	services->add<ProtocolOldGame>(g_config.getNumber(ConfigManager::LOGIN_PORT));

	int32_t autoSaveEachMinutes = g_config.getNumber(ConfigManager::AUTO_SAVE_EACH_MINUTES);
	if (autoSaveEachMinutes > 0) {
		g_scheduler->addEvent(createSchedulerTask(autoSaveEachMinutes * 1000 * 60, std::bind(&Game::autoSave, &g_game)));
	}

	if (g_config.getBoolean(ConfigManager::SERVERSAVE_ENABLED)) {
		int32_t serverSaveHour = g_config.getNumber(ConfigManager::SERVERSAVE_H);
		if (serverSaveHour >= 0 && serverSaveHour <= 24) {
			time_t timeNow = time(nullptr);
			tm* timeinfo = localtime(&timeNow);

			if (serverSaveHour == 0) {
				serverSaveHour = 23;
			} else {
				serverSaveHour--;
			}

			timeinfo->tm_hour = serverSaveHour;
			timeinfo->tm_min = 55;
			timeinfo->tm_sec = 0;

			double difference = difftime(mktime(timeinfo), timeNow);
			if (difference < 0) {
				difference += 86400;
			}
			g_scheduler->addEvent(createSchedulerTask(difference * 1000, std::bind(&Game::prepareServerSave, &g_game)));
		}
	}

	Houses::getInstance().payHouses();
	IOLoginData::updateHouseOwners();
	g_game.checkExpiredMarketOffers();
	IOMarket::getInstance()->updateStatistics();

	std::cout << ">> Loaded all modules, server starting up..." << std::endl;

#if !defined(WIN32) && !defined(__ROOT_PERMISSION__)
	if (getuid() == 0 || geteuid() == 0) {
		std::cout << "> WARNING: " << STATUS_SERVER_NAME << " has been executed as root user, it is recommended to execute is as a normal user." << std::endl;
	}
#endif

	g_game.start(services);
	g_game.setGameState(GAME_STATE_NORMAL);
	g_loaderSignal.notify_all();
}
Ejemplo n.º 18
0
void mainLoader(int argc, char* argv[], ServiceManager* services)
{
    //dispatcher thread
    g_game.setGameState(GAME_STATE_STARTUP);

    srand((unsigned int)OTSYS_TIME());
#ifdef WIN32
    SetConsoleTitle(STATUS_SERVER_NAME);
#endif
    std::cout << STATUS_SERVER_NAME << " - Version " << STATUS_SERVER_VERSION << std::endl;
    std::cout << "Compilied on " << __DATE__ << " " << __TIME__ << " for arch ";

#if defined(__amd64__) || defined(_M_X64)
    std::cout << "x64" << std::endl;
#elif defined(__i386__) || defined(_M_IX86) || defined(_X86_)
    std::cout << "x86" << std::endl;
#else
    std::cout << "unk" << std::endl;
#endif

    std::cout << std::endl;

    std::cout << "A server developed by " << STATUS_SERVER_DEVELOPERS << std::endl;
    std::cout << "Visit our forum for updates, support, and resources: http://otland.net/." << std::endl;
    std::cout << std::endl;

    // read global config
    std::cout << ">> Loading config" << std::endl;

    if (!g_config.loadFile("config.lua")) {
        startupErrorMessage("Unable to load config.lua!");
        return;
    }

#ifdef WIN32
    std::string defaultPriority = asLowerCaseString(g_config.getString(ConfigManager::DEFAULT_PRIORITY));
    if (defaultPriority == "realtime") {
        SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
    } else if (defaultPriority == "high") {
        SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
    } else if (defaultPriority == "higher") {
        SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
    }

    std::ostringstream mutexName;
    mutexName << "forgottenserver_" << g_config.getNumber(ConfigManager::LOGIN_PORT);
    CreateMutex(NULL, FALSE, mutexName.str().c_str());
    if (GetLastError() == ERROR_ALREADY_EXISTS) {
        startupErrorMessage("Another instance of The Forgotten Server is already running with the same login port, please shut it down first or change ports for this one.");
        return;
    }
#endif

    //set RSA key
    const char* p("14299623962416399520070177382898895550795403345466153217470516082934737582776038882967213386204600674145392845853859217990626450972452084065728686565928113");
    const char* q("7630979195970404721891201847792002125535401292779123937207447574596692788513647179235335529307251350570728407373705564708871762033017096809910315212884101");
    const char* d("46730330223584118622160180015036832148732986808519344675210555262940258739805766860224610646919605860206328024326703361630109888417839241959507572247284807035235569619173792292786907845791904955103601652822519121908367187885509270025388641700821735345222087940578381210879116823013776808975766851829020659073");
    g_RSA.setKey(p, q, d);

    std::cout << ">> Establishing database connection..." << std::flush;

    Database* db = Database::getInstance();
    if (!db->connect()) {
        startupErrorMessage("Failed to connect to database.");
        return;
    }

    std::cout << " MySQL " << db->getClientVersion() << std::endl;

    // run database manager
    std::cout << ">> Running database manager" << std::endl;

    DatabaseManager* dbManager = DatabaseManager::getInstance();
    if (!dbManager->isDatabaseSetup()) {
        startupErrorMessage("The database you have specified in config.lua is empty, please import the schema to the database.");
        return;
    }

    for (uint32_t version = dbManager->updateDatabase(); version != 0; version = dbManager->updateDatabase()) {
        std::cout << "> Database has been updated to version " << version << "." << std::endl;
    }

    dbManager->checkTriggers();
    dbManager->checkEncryption();

    if (g_config.getBoolean(ConfigManager::OPTIMIZE_DATABASE) && !dbManager->optimizeTables()) {
        std::cout << "> No tables were optimized." << std::endl;
    }

    //load vocations
    std::cout << ">> Loading vocations" << std::endl;

    if (!g_vocations.loadFromXml()) {
        startupErrorMessage("Unable to load vocations!");
        return;
    }

    //load commands
    std::cout << ">> Loading commands" << std::endl;

    if (!commands.loadFromXml()) {
        startupErrorMessage("Unable to load commands!");
        return;
    }

    // load item data
    std::cout << ">> Loading items" << std::endl;

    if (Item::items.loadFromOtb("data/items/items.otb")) {
        startupErrorMessage("Unable to load items (OTB)!");
        return;
    }

    if (!Item::items.loadFromXml()) {
        startupErrorMessage("Unable to load items (XML)!");
        return;
    }

    std::cout << ">> Loading script systems" << std::endl;

    if (!ScriptingManager::getInstance()->loadScriptSystems()) {
        startupErrorMessage("Failed to load script systems");
        return;
    }

    std::cout << ">> Loading monsters" << std::endl;

    if (!g_monsters.loadFromXml()) {
        startupErrorMessage("Unable to load monsters!");
        return;
    }

    std::cout << ">> Loading outfits" << std::endl;
    Outfits* outfits = Outfits::getInstance();
    if (!outfits->loadFromXml()) {
        startupErrorMessage("Unable to load outfits!");
        return;
    }

    g_adminConfig = new AdminProtocolConfig();
    std::cout << ">> Loading admin protocol config" << std::endl;

    if (!g_adminConfig->loadXMLConfig()) {
        startupErrorMessage("Unable to load admin protocol config!");
        return;
    }

    std::cout << ">> Loading experience stages" << std::endl;

    if (!g_game.loadExperienceStages()) {
        startupErrorMessage("Unable to load experience stages!");
        return;
    }

    std::string passwordType = asLowerCaseString(g_config.getString(ConfigManager::PASSWORDTYPE));

    if (passwordType == "md5") {
        g_config.setNumber(ConfigManager::PASSWORD_TYPE, PASSWORD_TYPE_MD5);
        std::cout << ">> Using MD5 passwords" << std::endl;
    } else if (passwordType == "sha1") {
        g_config.setNumber(ConfigManager::PASSWORD_TYPE, PASSWORD_TYPE_SHA1);
        std::cout << ">> Using SHA1 passwords" << std::endl;
    } else {
        g_config.setNumber(ConfigManager::PASSWORD_TYPE, PASSWORD_TYPE_PLAIN);
        std::cout << ">> Using plaintext passwords" << std::endl;
    }

    std::cout << ">> Checking world type... " << std::flush;
    std::string worldType = asLowerCaseString(g_config.getString(ConfigManager::WORLD_TYPE));
    if (worldType == "pvp") {
        g_game.setWorldType(WORLD_TYPE_PVP);
    } else if (worldType == "no-pvp") {
        g_game.setWorldType(WORLD_TYPE_NO_PVP);
    } else if (worldType == "pvp-enforced") {
        g_game.setWorldType(WORLD_TYPE_PVP_ENFORCED);
    } else {
        std::cout << std::endl;

        std::ostringstream ss;
        ss << "> ERROR: Unknown world type: " << g_config.getString(ConfigManager::WORLD_TYPE) << ", valid world types are: pvp, no-pvp and pvp-enforced.";
        startupErrorMessage(ss.str());
        return;
    }
    std::cout << asUpperCaseString(worldType) << std::endl;

    std::cout << ">> Loading map" << std::endl;

    if (!g_game.loadMap(g_config.getString(ConfigManager::MAP_NAME))) {
        startupErrorMessage("Failed to load map");
        return;
    }

    std::cout << ">> Initializing gamestate" << std::endl;
    g_game.setGameState(GAME_STATE_INIT);

    // Tibia protocols
    services->add<ProtocolGame>(g_config.getNumber(ConfigManager::GAME_PORT));
    services->add<ProtocolLogin>(g_config.getNumber(ConfigManager::LOGIN_PORT));

    // OT protocols
    services->add<ProtocolAdmin>(g_config.getNumber(ConfigManager::ADMIN_PORT));
    services->add<ProtocolStatus>(g_config.getNumber(ConfigManager::STATUS_PORT));

    // Legacy protocols
    services->add<ProtocolOldLogin>(g_config.getNumber(ConfigManager::LOGIN_PORT));
    services->add<ProtocolOldGame>(g_config.getNumber(ConfigManager::LOGIN_PORT));

    int32_t autoSaveEachMinutes = g_config.getNumber(ConfigManager::AUTO_SAVE_EACH_MINUTES);
    if (autoSaveEachMinutes > 0) {
        g_scheduler.addEvent(createSchedulerTask(autoSaveEachMinutes * 1000 * 60, boost::bind(&Game::autoSave, &g_game)));
    }

    if (g_config.getBoolean(ConfigManager::SERVERSAVE_ENABLED)) {
        int32_t serverSaveHour = g_config.getNumber(ConfigManager::SERVERSAVE_H);
        if (serverSaveHour >= 0 && serverSaveHour <= 24) {
            time_t timeNow = time(NULL);
            tm* timeinfo = localtime(&timeNow);

            if (serverSaveHour == 0) {
                serverSaveHour = 23;
            } else {
                serverSaveHour--;
            }

            timeinfo->tm_hour = serverSaveHour;
            timeinfo->tm_min = 55;
            timeinfo->tm_sec = 0;
            time_t difference = (time_t)difftime(mktime(timeinfo), timeNow);

            if (difference < 0) {
                difference += 86400;
            }

            g_scheduler.addEvent(createSchedulerTask(difference * 1000, boost::bind(&Game::prepareServerSave, &g_game)));
        }
    }

    Houses::getInstance().payHouses();
    IOLoginData::getInstance()->updateHouseOwners();
    g_npcs.reload();

    if (g_config.getBoolean(ConfigManager::MARKET_ENABLED)) {
        g_game.checkExpiredMarketOffers();
        IOMarket::getInstance()->updateStatistics();
    }

    std::cout << ">> Loaded all modules, server starting up..." << std::endl;

    std::pair<uint32_t, uint32_t> IpNetMask;
    IpNetMask.first = inet_addr("127.0.0.1");
    IpNetMask.second = 0xFFFFFFFF;
    serverIPs.push_back(IpNetMask);

    char szHostName[128];
    if (gethostname(szHostName, 128) == 0) {
        hostent* he = gethostbyname(szHostName);
        if (he) {
            unsigned char** addr = (unsigned char**)he->h_addr_list;
            while (addr[0] != NULL) {
                IpNetMask.first = *(uint32_t*)(*addr);
                IpNetMask.second = 0xFFFFFFFF;
                serverIPs.push_back(IpNetMask);
                addr++;
            }
        }
    }

    std::string ip = g_config.getString(ConfigManager::IP);

    uint32_t resolvedIp = inet_addr(ip.c_str());
    if (resolvedIp == INADDR_NONE) {
        struct hostent* he = gethostbyname(ip.c_str());
        if (!he) {
            std::ostringstream ss;
            ss << "ERROR: Cannot resolve " << ip << "!" << std::endl;
            startupErrorMessage(ss.str());
            return;
        }
        resolvedIp = *(uint32_t*)he->h_addr;
    }

    IpNetMask.first = resolvedIp;
    IpNetMask.second = 0;
    serverIPs.push_back(IpNetMask);

#if !defined(WIN32) && !defined(__ROOT_PERMISSION__)
    if (getuid() == 0 || geteuid() == 0) {
        std::cout << "> WARNING: " << STATUS_SERVER_NAME << " has been executed as root user, it is recommended to execute is as a normal user." << std::endl;
    }
#endif

    g_game.start(services);
    g_game.setGameState(GAME_STATE_NORMAL);
    g_loaderSignal.notify_all();
}
Ejemplo n.º 19
0
int main() {


    int pprimes[18] = { 30839, 30841, 30851, 30853, 30859, 30869, 30871, 30881, 30893, 30911, 30931, 30937, 30941
            , 30949, 30971, 30977, 30983, 31013 };


    string str = "1";


    //Create 10 instances of the RSA class without giving arguments, generate random message or assign messages,
    // and perform encryption through each of the 10 classes.
    for (int i=0; i < 10; i++) {

        RSA* rsa = new RSA();
        str = str + "0";
        bitset<96> mssg (str);

        BigInt* msg = new BigInt(mssg);

        BigInt encrypted = rsa->encrypt(*msg);

        BigInt decrypted = rsa->decrypt(encrypted);

        string decmsg = decrypted.toString();

        cout << "part a message was:" << decmsg << endl;

        delete rsa;
    }

    //Create 5 instances of the RSA class by passing a large prime number [p](> 30,000), and perform encryption decryption
    for (int j=0; j < 5; j++) {

        RSA* rsa = new RSA(pprimes[j]);
        str = str + "1";

        bitset<96> mssg (str);

        BigInt* msg = new BigInt(mssg);

        BigInt encrypted = rsa->encrypt(*msg);

        BigInt decrypted = rsa->decrypt(encrypted);

        string decmsg = decrypted.toString();

        cout << "part b (1 prime) message was:" << decmsg << endl;

        delete rsa;
    }

    //Create 5 instances of the RSA class by passing 2 large prime numbers [p,q] (> 30,000) and perform encryption decryption
    for (int j=0; j < 5; j++) {

        RSA* rsa = new RSA(pprimes[j], pprimes[j+1]);
        str = str + "0";

        bitset<96> mssg (str);

        BigInt* msg = new BigInt(mssg);

        BigInt encrypted = rsa->encrypt(*msg);

        BigInt decrypted = rsa->decrypt(encrypted);

        string decmsg = decrypted.toString();

        cout << "part c (2 primes) message was:" << decmsg << endl;

        delete rsa;
    }

    //Create 10 instances of the RSA class by passing 2 large non prime numbers (> 30,000) and perform encryption decryption.
    // In most of the cases the message should not get decrypted correctly.
    for (int j=0; j < 10; j++) {
        //add one to the prime number to make it non-prime
        RSA* rsa = new RSA(pprimes[j] + 1, pprimes[j+1] + 1);
        str = str + "1";

        bitset<96> mssg (str);

        BigInt* msg = new BigInt(mssg);

        BigInt encrypted = rsa->encrypt(*msg);

        BigInt decrypted = rsa->decrypt(encrypted);

        string decmsg = decrypted.toString();

        cout << "part d (nonprimes) message was:" << decmsg << endl;

        delete rsa;
    }


    RSA* RSA1 = new RSA();
    RSA* RSA2 = new RSA();
    BigInt pub1 = RSA1->getPublicKey();
    BigInt n = RSA1->getModulus();
    BigInt* randmsg = new BigInt(rand());

    cout << "\n PART 2 " << endl;

    cout << "\nrandom message before encryption: " << randmsg->toString() << endl;

    RSA2->setPublicKey(pub1);
    RSA2->setN(n);

    BigInt encr = RSA2->encrypt(*randmsg);

    BigInt decr = RSA1->decrypt(encr);

    cout << "random message after encryption: " << decr.toString() << endl;

    //PART 3

    cout << "\n PART 3" << endl;

    //a. Alice obtains the public key and Modulus N of the person (Bob) who is to sign the message
    RSA* bob = new RSA();
    RSA* alice = new RSA();

    BigInt bpubkey = bob->getPublicKey();
    BigInt bmod = bob->getModulus();

    alice->setN(bmod);
    alice->setPublicKey(bpubkey);


    //b. Obtain a random number and its inverse with respect to the Modulus [Not phi] of Bob
    BigInt* randnum = new BigInt(rand());
    BigInt inverse = randnum->operator%(bob->getModulus());

    //c. Alice obtains/generates a message to be signed.
    BigInt* rmssg = new BigInt(rand());
    cout << "\nrandom message before encryption: " << rmssg->toString() << endl;

    //d. Alice encrypts the random number with the public key.
    BigInt emessg = alice->encrypt(*rmssg);

    //e. Alice multiplies this value by the message
    BigInt newval = emessg.operator*(*rmssg);

    //f. Alice then takes a modulus over N
    BigInt newmod = newval.operator%(alice->getModulus());

    //g. Alice sends it to Bob
    //h. Bob simply decrypts the received value with the private key

    BigInt bobdecrypt = bob->decrypt(newmod);

    //i. Bob sends it back to Alice
    //j. Alice then multiplied the received value with the inverse and takes a modulus over N.

    BigInt alicemult = bobdecrypt.operator*(inverse);
    BigInt alicemod = alicemult.operator%(alice->getModulus());

    //k. The value obtained above is the signed message. To obtain the original message from it, again encrypt it with Bob’s Public Key.
    BigInt original = alice->encrypt(alicemod);
    cout << "\n Alice decrypted message:  " << original.toString() << endl;

    return 0;
}
Ejemplo n.º 20
0
BigInt getDecryptedMessageFromRSA_obj(BigInt m, RSA RSA_obj)
{
	return RSA_obj.decrypt(m);
}
Ejemplo n.º 21
0
BigInt	Signer(BigInt messageWithBlindFactor)
{
   return signersRSA.decrypt(messageWithBlindFactor);
}
Ejemplo n.º 22
0
void ProtocolAdmin::parsePacket(NetworkMessage& msg)
{
	if(g_game.getGameState() == GAMESTATE_SHUTDOWN)
	{
		getConnection()->close();
		return;
	}

	uint8_t recvbyte = msg.get<char>();
	OutputMessage_ptr output = OutputMessagePool::getInstance()->getOutputMessage(this, false);
	if(!output)
		return;

	TRACK_MESSAGE(output);
	switch(m_state)
	{
		case ENCRYPTION_NO_SET:
		{
			if(Admin::getInstance()->isEncypted())
			{
				if((time(NULL) - m_startTime) > 30000)
				{
					getConnection()->close();
					addLogLine(LOGTYPE_EVENT, "encryption timeout");
					return;
				}

				if(recvbyte != AP_MSG_ENCRYPTION && recvbyte != AP_MSG_KEY_EXCHANGE)
				{
					output->put<char>(AP_MSG_ERROR);
					output->putString("encryption needed");
					OutputMessagePool::getInstance()->send(output);

					getConnection()->close();
					addLogLine(LOGTYPE_EVENT, "wrong command while ENCRYPTION_NO_SET");
					return;
				}
			}
			else
				m_state = NO_LOGGED_IN;

			break;
		}

		case NO_LOGGED_IN:
		{
			if(g_config.getBool(ConfigManager::ADMIN_REQUIRE_LOGIN))
			{
				if((time(NULL) - m_startTime) > 30000)
				{
					//login timeout
					getConnection()->close();
					addLogLine(LOGTYPE_EVENT, "login timeout");
					return;
				}

				if(m_loginTries > 3)
				{
					output->put<char>(AP_MSG_ERROR);
					output->putString("too many login tries");
					OutputMessagePool::getInstance()->send(output);

					getConnection()->close();
					addLogLine(LOGTYPE_EVENT, "too many login tries");
					return;
				}

				if(recvbyte != AP_MSG_LOGIN)
				{
					output->put<char>(AP_MSG_ERROR);
					output->putString("you are not logged in");
					OutputMessagePool::getInstance()->send(output);

					getConnection()->close();
					addLogLine(LOGTYPE_EVENT, "wrong command while NO_LOGGED_IN");
					return;
				}
			}
			else
				m_state = LOGGED_IN;

			break;
		}

		case LOGGED_IN:
			break;

		default:
		{
			getConnection()->close();
			addLogLine(LOGTYPE_EVENT, "no valid connection state!!!");
			return;
		}
	}

	m_lastCommand = time(NULL);
	switch(recvbyte)
	{
		case AP_MSG_LOGIN:
		{
			if(m_state == NO_LOGGED_IN && g_config.getBool(ConfigManager::ADMIN_REQUIRE_LOGIN))
			{
				std::string pass = msg.getString(), word = g_config.getString(ConfigManager::ADMIN_PASSWORD);
				_encrypt(word, false);
				if(pass == word)
				{
					m_state = LOGGED_IN;
					output->put<char>(AP_MSG_LOGIN_OK);
					addLogLine(LOGTYPE_EVENT, "login ok");
				}
				else
				{
					m_loginTries++;
					output->put<char>(AP_MSG_LOGIN_FAILED);
					output->putString("wrong password");
					addLogLine(LOGTYPE_EVENT, "login failed.("+ pass + ")");
				}
			}
			else
			{
				output->put<char>(AP_MSG_LOGIN_FAILED);
				output->putString("cannot login");
				addLogLine(LOGTYPE_EVENT, "wrong state at login");
			}

			break;
		}

		case AP_MSG_ENCRYPTION:
		{
			if(m_state == ENCRYPTION_NO_SET && Admin::getInstance()->isEncypted())
			{
				uint8_t keyType = msg.get<char>();
				switch(keyType)
				{
					case ENCRYPTION_RSA1024XTEA:
					{
						RSA* rsa = Admin::getInstance()->getRSAKey(ENCRYPTION_RSA1024XTEA);
						if(!rsa)
						{
							output->put<char>(AP_MSG_ENCRYPTION_FAILED);
							addLogLine(LOGTYPE_EVENT, "no valid server key type");
							break;
						}

						if(RSA_decrypt(rsa, msg))
						{
							m_state = NO_LOGGED_IN;
							uint32_t k[4]= {msg.get<uint32_t>(), msg.get<uint32_t>(), msg.get<uint32_t>(), msg.get<uint32_t>()};

							//use for in/out the new key we have
							enableXTEAEncryption();
							setXTEAKey(k);

							output->put<char>(AP_MSG_ENCRYPTION_OK);
							addLogLine(LOGTYPE_EVENT, "encryption ok");
						}
						else
						{
							output->put<char>(AP_MSG_ENCRYPTION_FAILED);
							output->putString("wrong encrypted packet");
							addLogLine(LOGTYPE_EVENT, "wrong encrypted packet");
						}

						break;
					}

					default:
					{
						output->put<char>(AP_MSG_ENCRYPTION_FAILED);
						output->putString("no valid key type");

						addLogLine(LOGTYPE_EVENT, "no valid client key type");
						break;
					}
				}
			}
			else
			{
				output->put<char>(AP_MSG_ENCRYPTION_FAILED);
				output->putString("cannot set encryption");
				addLogLine(LOGTYPE_EVENT, "cannot set encryption");
			}

			break;
		}

		case AP_MSG_KEY_EXCHANGE:
		{
			if(m_state == ENCRYPTION_NO_SET && Admin::getInstance()->isEncypted())
			{
				uint8_t keyType = msg.get<char>();
				switch(keyType)
				{
					case ENCRYPTION_RSA1024XTEA:
					{
						RSA* rsa = Admin::getInstance()->getRSAKey(ENCRYPTION_RSA1024XTEA);
						if(!rsa)
						{
							output->put<char>(AP_MSG_KEY_EXCHANGE_FAILED);
							addLogLine(LOGTYPE_EVENT, "no valid server key type");
							break;
						}

						output->put<char>(AP_MSG_KEY_EXCHANGE_OK);
						output->put<char>(ENCRYPTION_RSA1024XTEA);

						char RSAPublicKey[128];
						rsa->getPublicKey(RSAPublicKey);

						output->put<char>s(RSAPublicKey, 128);
						break;
					}

					default:
					{
						output->put<char>(AP_MSG_KEY_EXCHANGE_FAILED);
						addLogLine(LOGTYPE_EVENT, "no valid client key type");
						break;
					}
				}
			}
			else
			{
				output->put<char>(AP_MSG_KEY_EXCHANGE_FAILED);
				output->putString("cannot get public key");
				addLogLine(LOGTYPE_EVENT, "cannot get public key");
			}

			break;
		}

		case AP_MSG_COMMAND:
		{
			if(m_state != LOGGED_IN)
			{
				addLogLine(LOGTYPE_EVENT, "recvbyte == AP_MSG_COMMAND && m_state != LOGGED_IN !!!");
				break;
			}

			uint8_t command = msg.get<char>();
			switch(command)
			{
				case CMD_SAVE_SERVER:
				case CMD_SHALLOW_SAVE_SERVER:
				{
					uint8_t flags = (uint8_t)SAVE_PLAYERS | (uint8_t)SAVE_MAP | (uint8_t)SAVE_STATE;
					if(command == CMD_SHALLOW_SAVE_SERVER)
						flags |= SAVE_PLAYERS_SHALLOW;

					addLogLine(LOGTYPE_EVENT, "saving server");
					Dispatcher::getInstance().addTask(createTask(boost::bind(&Game::saveGameState, &g_game, flags)));

					output->put<char>(AP_MSG_COMMAND_OK);
					break;
				}

				case CMD_CLOSE_SERVER:
				{
					addLogLine(LOGTYPE_EVENT, "closing server");
					Dispatcher::getInstance().addTask(createTask(boost::bind(
						&Game::setGameState, &g_game, GAMESTATE_CLOSED)));

					output->put<char>(AP_MSG_COMMAND_OK);
					break;
				}

				case CMD_OPEN_SERVER:
				{
					addLogLine(LOGTYPE_EVENT, "opening server");
					g_game.setGameState(GAMESTATE_NORMAL);

					output->put<char>(AP_MSG_COMMAND_OK);
					break;
				}

				case CMD_SHUTDOWN_SERVER:
				{
					addLogLine(LOGTYPE_EVENT, "shutting down server");
					Dispatcher::getInstance().addTask(createTask(boost::bind(
						&Game::setGameState, &g_game, GAMESTATE_SHUTDOWN)));

					output->put<char>(AP_MSG_COMMAND_OK);
					break;
				}

				case CMD_PAY_HOUSES:
				{
					Dispatcher::getInstance().addTask(createTask(boost::bind(
						&ProtocolAdmin::adminCommandPayHouses, this)));
					break;
				}

				case CMD_RELOAD_SCRIPTS:
				{
					const int8_t reload = msg.get<char>();
					Dispatcher::getInstance().addTask(createTask(boost::bind(
						&ProtocolAdmin::adminCommandReload, this, reload)));
					break;
				}

				case CMD_KICK:
				{
					const std::string param = msg.getString();
					Dispatcher::getInstance().addTask(createTask(boost::bind(
						&ProtocolAdmin::adminCommandKickPlayer, this, param)));
					break;
				}

				case CMD_SEND_MAIL:
				{
					const std::string xmlData = msg.getString();
					Dispatcher::getInstance().addTask(createTask(boost::bind(
						&ProtocolAdmin::adminCommandSendMail, this, xmlData)));
					break;
				}

				case CMD_BROADCAST:
				{
					const std::string param = msg.getString();
					addLogLine(LOGTYPE_EVENT, "broadcasting: " + param);
					Dispatcher::getInstance().addTask(createTask(boost::bind(
						&Game::broadcastMessage, &g_game, param, MSG_STATUS_WARNING)));

					output->put<char>(AP_MSG_COMMAND_OK);
					break;
				}

				default:
				{
					output->put<char>(AP_MSG_COMMAND_FAILED);
					output->putString("not known server command");
					addLogLine(LOGTYPE_EVENT, "not known server command");
				}
			}
			break;
		}

		case AP_MSG_PING:
			output->put<char>(AP_MSG_PING_OK);
			break;

		case AP_MSG_KEEP_ALIVE:
			break;

		default:
		{
			output->put<char>(AP_MSG_ERROR);
			output->putString("not known command byte");

			addLogLine(LOGTYPE_EVENT, "not known command byte");
			break;
		}
	}

	if(output->size() > 0)
		OutputMessagePool::getInstance()->send(output);
}
Ejemplo n.º 23
0
int main(){
/* Implementation of task1*/

std::cout<<"\n\n************Task1***********"<<std::endl;
srand(time(NULL));
/* Subtask1 */
std::cout<<"\n************Subtask1************"<<std::endl;
RSA objRSA[10];
//char * messages[]={"One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"};
int msg=int(((double)rand()/RAND_MAX)*LIMIT_RAND);  //generation of random message
BigInt result(0);
for(int i=0;i<10;i++){
        printf("\nEncrypting the message %d \n", msg);
        result=objRSA[i].encrypt(msg);                //Encryption of message
        std::cout<<"Encryption result : "<<result.toHexString()<<std::endl;
}
/* Subtask 2 */
std::cout<<"\n***********Subtask2**************"<<std::endl;
RSA * objRSA_onearg[5]={NULL};
std::cout<<"\nEncrypting the message "<<msg<<std::endl;
int primep[10]={0};
generate_prime(primep,10);//prime number generation
for(int i=0;i<5;i++){
objRSA_onearg[i] = new RSA (primep[i]);
result = objRSA_onearg[i]->encrypt(msg); // encrypt message
std::cout<<"\nEncryption result using the prime p as "<<primep[i]<<" is "<<result.toHexString()<<std::endl;
result = objRSA_onearg[i]->decrypt(result);//decrypt message
std::cout<<"Decryption result : "<<result.toHexString()<<std::endl;
}

/* Subtask 3 */
std::cout<<"\n***********Subtask3**************"<<std::endl;
RSA * objRSA_twoarg[5]={NULL};
std::cout<<"\nEncrypting the message "<<msg<<std::endl;
for(int i=0;i<5;i++){
objRSA_onearg[i] = new RSA (primep[i],primep[5+i]);
result = objRSA_onearg[i]->encrypt(msg);//encrypting the message
std::cout<<"\nEncryption result using the prime p and q as  "<<primep[i]<<" "<<primep[5+i]<<" is "<<result.toHexString()<<std::endl;
result = objRSA_onearg[i]->decrypt(result);//decrypting the message
std::cout<<"Decryption result : " << result.toHexString()<<std::endl;
}
/* Subtask 4 */
std::cout<<"\n***********Subtask4**************"<<std::endl;
RSA * objRSA_twononprimearg[5]={NULL};
int nprime[10]={0};
generate_nonprime(nprime,10);//generate non prime numbers
std::cout<<"\nEncrypting the message "<<msg<<std::endl;
for(int i=0;i<5;i++){
objRSA_onearg[i] = new RSA (nprime[i],nprime[5+i]);
result = objRSA_onearg[i]->encrypt(msg);//encrypting the message
std::cout<<"\nEncryption result using the non prime p and q as  "<<nprime[i]<<" "<<nprime[5+i]<<" is "<<result.toHexString()<<std::endl;
result = objRSA_onearg[i]->decrypt(result);//decrypt message
std::cout<<"Decryption result : "<<result.toHexString()<<std::endl;
if(result==objRSA_onearg[i]->encrypt(msg)){//check if encrypted and decrypted messages are same
std::cout<<"This case is an out of ordinary case "<<std::endl;
}
}
/*Implementation of task3*/
/*********Task2********/
std::cout<<"\n\n***************Task2*********"<<std::endl;
RSA RSAObj1;
RSA RSAObj2;
unsigned long result_long[2];
int size_result_array=2;
result=RSAObj1.getPublicKey();
RSAObj2.setPublicKey(result);
RSAObj2.setN(RSAObj1.getModulus());
//int rno=rand();
BigInt rno=int(((double)rand()/RAND_MAX)*LIMIT_RAND);//random message 
 std::cout<<"\noriginal message="<<rno.toHexString()<<std::endl;
result=RSAObj2.encrypt(rno);
std::cout<<"encrypted message="<<result.toHexString()<<std::endl;
result=RSAObj1.decrypt(result);
std::cout<<"decrypted message="<<result.toHexString()<<std::endl;
//converttoint(result,result_long,size_result_array);
if(result==rno){//check if values match
 std::cout<<"Original message and decrypted messages match , hence verified "<<std::endl;
}

/*Implementation of task3*/
/************Task3********/
std::cout<<"\n\n*****************Task3***************"<<std::endl;

RSA Bobobj;
BigInt pk= Bobobj.getPublicKey();
BigInt mod= Bobobj.getModulus();
//Bob sends public key and modN to Alice
BigInt msgAlice=sendtoAlice(pk,mod);
//Bob decrypts the message received from Alice 
BigInt decmessage= Bobobj.decrypt(msgAlice);
//send the decrypted message to Alice again
sendtoAlice2(decmessage,pk,mod);
}
Ejemplo n.º 24
0
void mainLoader(int, char*[], ServiceManager* services)
{

	srand(static_cast<unsigned int>(OTSYS_TIME()));
#ifdef _WIN32
	SetConsoleTitle(STATUS_SERVER_NAME);
#endif
	std::cout << STATUS_SERVER_NAME << " - Version " << STATUS_SERVER_VERSION << std::endl;
	std::cout << "Compiled with " << BOOST_COMPILER << std::endl;
	std::cout << "Compiled on " << __DATE__ << ' ' << __TIME__ << " for platform ";

#if defined(__amd64__) || defined(_M_X64)
	std::cout << "x64" << std::endl;
#elif defined(__i386__) || defined(_M_IX86) || defined(_X86_)
	std::cout << "x86" << std::endl;
#elif defined(__arm__)
	std::cout << "ARM" << std::endl;
#else
	std::cout << "unknown" << std::endl;
#endif
	std::cout << std::endl;

	std::cout << "A server developed by " << STATUS_SERVER_DEVELOPERS << std::endl;
	std::cout << std::endl;

	// read global config
	std::cout << ">> Loading config" << std::endl;
	if (!g_config.load()) {
		startupErrorMessage("Unable to load config.lua!");
		return;
	}

	std::cout << ">> Loading gameserver config..." << std::endl;

	if (!g_gameserver.load()) {
		startupErrorMessage("Unable to load gameservers!");
		return;
	}

#ifdef _WIN32
	const std::string& defaultPriority = g_config.getString(ConfigManager::DEFAULT_PRIORITY);
	if (strcasecmp(defaultPriority.c_str(), "high") == 0) {
		SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
	} else if (strcasecmp(defaultPriority.c_str(), "above-normal") == 0) {
		SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS);
	}
#endif

	//set RSA key
	
	//cipsoft
	const char* p("12017580013707233233987537782574702577133548287527131234152948150506251412291888866940292054989907714155267326586216043845592229084368540020196135619327879");
	const char* q("11898921368616868351880508246112101394478760265769325412746398405473436969889506919017477758618276066588858607419440134394668095105156501566867770737187273");
	
	//opentibia
	/*
	const char* p("14299623962416399520070177382898895550795403345466153217470516082934737582776038882967213386204600674145392845853859217990626450972452084065728686565928113");
	const char* q("7630979195970404721891201847792002125535401292779123937207447574596692788513647179235335529307251350570728407373705564708871762033017096809910315212884101");
	*/

	g_RSA.setKey(p, q);

	std::cout << ">> Establishing database connection..." << std::flush;

	Database* db = Database::getInstance();
	if (!db->connect()) {
		startupErrorMessage("Failed to connect to database.");
		return;
	}

	std::cout << " MySQL " << Database::getClientVersion() << std::endl;

	// run database manager
	std::cout << ">> Running database manager" << std::endl;

	if (!DatabaseManager::isDatabaseSetup()) {
		startupErrorMessage("The database you have specified in config.lua is empty, please import the schema.sql to your database.");
		return;
	}

	g_databaseTasks.start();

	if (g_config.getBoolean(ConfigManager::OPTIMIZE_DATABASE) && !DatabaseManager::optimizeTables()) {
		std::cout << "> No tables were optimized." << std::endl;
	}

	// Game client protocols
	services->add<ProtocolOld>(g_config.getNumber(ConfigManager::LOGIN_PORT));
	// OT protocols
	services->add<ProtocolStatus>(g_config.getNumber(ConfigManager::STATUS_PORT));

	//check each 1 minute for player amount and record
	ProtocolStatus::getPlayerRecordAndPlayerAmount();

	std::cout << ">> Loaded all modules, server starting up..." << std::endl;

#ifndef _WIN32
	if (getuid() == 0 || geteuid() == 0) {
		std::cout << "> Warning: " << STATUS_SERVER_NAME << " has been executed as root user, please consider running it as a normal user." << std::endl;
	}
#endif

	g_loaderSignal.notify_all();
}