1
0

Implemented the 1.7.6 protocol and authenticator.

Server works both in online and offline modes with 1.7.9.
This commit is contained in:
madmaxoft 2014-04-14 22:52:59 +02:00
parent d505ffc704
commit d12d7b6715
10 changed files with 199 additions and 129 deletions

View File

@ -178,21 +178,32 @@ void cClientHandle::Destroy(void)
void cClientHandle::GenerateOfflineUUID(void)
{
m_UUID = GenerateOfflineUUID(m_Username);
}
AString cClientHandle::GenerateOfflineUUID(const AString & a_Username)
{
// Proper format for a version 3 UUID is:
// xxxxxxxx-xxxx-3xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B
// Generate an md5 checksum, and use it as base for the ID:
MD5 Checksum(m_Username);
m_UUID = Checksum.hexdigest();
m_UUID[12] = '3'; // Version 3 UUID
m_UUID[16] = '8'; // Variant 1 UUID
MD5 Checksum(a_Username);
AString UUID = Checksum.hexdigest();
UUID[12] = '3'; // Version 3 UUID
UUID[16] = '8'; // Variant 1 UUID
// Now the digest doesn't have the UUID slashes, but the client requires them, so add them into the appropriate positions:
m_UUID.insert(8, "-");
m_UUID.insert(13, "-");
m_UUID.insert(18, "-");
m_UUID.insert(23, "-");
UUID.insert(8, "-");
UUID.insert(13, "-");
UUID.insert(18, "-");
UUID.insert(23, "-");
return UUID;
}
@ -223,6 +234,9 @@ void cClientHandle::Authenticate(const AString & a_Name, const AString & a_UUID)
m_Username = a_Name;
m_UUID = a_UUID;
// Send login success (if the protocol supports it):
m_Protocol->SendLoginSuccess();
// Spawn player (only serversided, so data is loaded)
m_Player = new cPlayer(this, GetUsername());

View File

@ -65,10 +65,16 @@ public:
const AString & GetUUID(void) const { return m_UUID; } // tolua_export
void SetUUID(const AString & a_UUID) { m_UUID = a_UUID; }
/** Generates an UUID based on the username stored for this client, and stores it in the m_UUID member.
This is used for the offline (non-auth) mode, when there's no UUID source.
Each username generates a unique and constant UUID, so that when the player reconnects with the same name, their UUID is the same.
Internally calls the GenerateOfflineUUID static function. */
void GenerateOfflineUUID(void);
/** Generates an UUID based on the player name provided.
This is used for the offline (non-auth) mode, when there's no UUID source.
Each username generates a unique and constant UUID, so that when the player reconnects with the same name, their UUID is the same. */
void GenerateOfflineUUID(void);
static AString GenerateOfflineUUID(const AString & a_Username); // tolua_export
void Kick(const AString & a_Reason); // tolua_export
void Authenticate(const AString & a_Name, const AString & a_UUID); // Called by cAuthenticator when the user passes authentication

View File

@ -2,9 +2,10 @@
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "Authenticator.h"
#include "OSSupport/BlockingTCPLink.h"
#include "Root.h"
#include "Server.h"
#include "../OSSupport/BlockingTCPLink.h"
#include "../Root.h"
#include "../Server.h"
#include "../ClientHandle.h"
#include "inifile/iniFile.h"
#include "json/json.h"
@ -32,10 +33,10 @@
cAuthenticator::cAuthenticator(void) :
super("cAuthenticator"),
m_Server(DEFAULT_AUTH_SERVER),
m_Address(DEFAULT_AUTH_ADDRESS),
m_ShouldAuthenticate(true)
super("cAuthenticator"),
m_Server(DEFAULT_AUTH_SERVER),
m_Address(DEFAULT_AUTH_ADDRESS),
m_ShouldAuthenticate(true)
{
}
@ -67,7 +68,7 @@ void cAuthenticator::Authenticate(int a_ClientID, const AString & a_UserName, co
{
if (!m_ShouldAuthenticate)
{
cRoot::Get()->AuthenticateUser(a_ClientID, a_UserName, Printf("%d", a_ClientID));
cRoot::Get()->AuthenticateUser(a_ClientID, a_UserName, cClientHandle::GenerateOfflineUUID(a_UserName));
return;
}
@ -144,9 +145,9 @@ void cAuthenticator::Execute(void)
bool cAuthenticator::AuthWithYggdrasil(AString & a_UserName, const AString & a_ServerId, AString & a_UUID)
{
AString REQUEST;
LOGD("Trying to auth user %s", a_UserName.c_str());
int ret, server_fd = -1;
size_t len = 0;
unsigned char buf[1024];
const char *pers = "cAuthenticator";
@ -162,36 +163,31 @@ bool cAuthenticator::AuthWithYggdrasil(AString & a_UserName, const AString & a_S
entropy_init(&entropy);
if ((ret = ctr_drbg_init(&ctr_drbg, entropy_func, &entropy, (const unsigned char *)pers, strlen(pers))) != 0)
{
LOGERROR("cAuthenticator: ctr_drbg_init returned %d", ret);
LOGWARNING("cAuthenticator: ctr_drbg_init returned %d", ret);
return false;
}
/* Initialize certificates */
#if defined(POLARSSL_CERTS_C)
// TODO: Grab the sessionserver's root CA and any intermediates and hard-code them here, instead of test_ca_list
ret = x509_crt_parse(&cacert, (const unsigned char *)test_ca_list, strlen(test_ca_list));
#else
ret = 1;
LOGWARNING("cAuthenticator: POLARSSL_CERTS_C is not defined.");
#endif
if (ret < 0)
{
LOGERROR("cAuthenticator: x509_crt_parse returned -0x%x", -ret);
LOGWARNING("cAuthenticator: x509_crt_parse returned -0x%x", -ret);
return false;
}
/* Connect */
if ((ret = net_connect(&server_fd, m_Server.c_str(), 443)) != 0)
{
LOGERROR("cAuthenticator: Can't connect to %s: %d", m_Server.c_str(), ret);
LOGWARNING("cAuthenticator: Can't connect to %s: %d", m_Server.c_str(), ret);
return false;
}
/* Setup */
if ((ret = ssl_init(&ssl)) != 0)
{
LOGERROR("cAuthenticator: ssl_init returned %d", ret);
LOGWARNING("cAuthenticator: ssl_init returned %d", ret);
return false;
}
ssl_set_endpoint(&ssl, SSL_IS_CLIENT);
@ -203,9 +199,9 @@ bool cAuthenticator::AuthWithYggdrasil(AString & a_UserName, const AString & a_S
/* Handshake */
while ((ret = ssl_handshake(&ssl)) != 0)
{
if (ret != POLARSSL_ERR_NET_WANT_READ && ret != POLARSSL_ERR_NET_WANT_WRITE)
if ((ret != POLARSSL_ERR_NET_WANT_READ) && (ret != POLARSSL_ERR_NET_WANT_WRITE))
{
LOGERROR("cAuthenticator: ssl_handshake returned -0x%x", -ret);
LOGWARNING("cAuthenticator: ssl_handshake returned -0x%x", -ret);
return false;
}
}
@ -215,54 +211,47 @@ bool cAuthenticator::AuthWithYggdrasil(AString & a_UserName, const AString & a_S
ReplaceString(ActualAddress, "%USERNAME%", a_UserName);
ReplaceString(ActualAddress, "%SERVERID%", a_ServerId);
REQUEST += "GET " + ActualAddress + " HTTP/1.1\r\n";
REQUEST += "Host: " + m_Server + "\r\n";
REQUEST += "User-Agent: MCServer\r\n";
REQUEST += "Connection: close\r\n";
REQUEST += "\r\n";
AString Request;
Request += "GET " + ActualAddress + " HTTP/1.1\r\n";
Request += "Host: " + m_Server + "\r\n";
Request += "User-Agent: MCServer\r\n";
Request += "Connection: close\r\n";
Request += "\r\n";
len = REQUEST.size();
strcpy((char *)buf, REQUEST.c_str());
while ((ret = ssl_write(&ssl, buf, len)) <= 0)
ret = ssl_write(&ssl, (const unsigned char *)Request.c_str(), Request.size());
if (ret <= 0)
{
if (ret != POLARSSL_ERR_NET_WANT_READ && ret != POLARSSL_ERR_NET_WANT_WRITE)
{
LOGERROR("cAuthenticator: ssl_write returned %d", ret);
return false;
}
LOGWARNING("cAuthenticator: ssl_write returned %d", ret);
return false;
}
/* Read the HTTP response */
std::string Builder;
std::string Response;
for (;;)
{
len = sizeof(buf)-1;
memset(buf, 0, sizeof(buf));
ret = ssl_read(&ssl, buf, len);
if (ret > 0)
{
buf[ret] = '\0';
}
ret = ssl_read(&ssl, buf, sizeof(buf));
if (ret == POLARSSL_ERR_NET_WANT_READ || ret == POLARSSL_ERR_NET_WANT_WRITE)
if ((ret == POLARSSL_ERR_NET_WANT_READ) || (ret == POLARSSL_ERR_NET_WANT_WRITE))
{
continue;
}
if (ret == POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY)
{
break;
}
if (ret < 0)
{
LOGERROR("cAuthenticator: ssl_read returned %d", ret);
LOGWARNING("cAuthenticator: ssl_read returned %d", ret);
break;
}
if (ret == 0)
{
LOGERROR("cAuthenticator: EOF");
LOGWARNING("cAuthenticator: EOF");
break;
}
std::string str;
str.append(reinterpret_cast<const char*>(buf));
Builder += str;
Response.append((const char *)buf, ret);
}
ssl_close_notify(&ssl);
@ -272,51 +261,49 @@ bool cAuthenticator::AuthWithYggdrasil(AString & a_UserName, const AString & a_S
entropy_free(&entropy);
memset(&ssl, 0, sizeof(ssl));
std::string prefix("HTTP/1.1 200 OK");
if (Builder.compare(0, prefix.size(), prefix))
return false;
std::stringstream ResponseBuilder;
bool NewLine = false;
bool IsNewLine = false;
for (std::string::const_iterator i = Builder.begin(); i <= Builder.end(); ++i)
// Check the HTTP status line:
AString prefix("HTTP/1.1 200 OK");
AString HexDump;
if (Response.compare(0, prefix.size(), prefix))
{
if (NewLine)
{
ResponseBuilder << *i;
}
else if (!NewLine && *i == '\n')
{
if (IsNewLine)
{
NewLine = true;
}
else
{
IsNewLine = true;
}
}
else if (*i != '\r')
{
IsNewLine = false;
}
LOGINFO("User \"%s\" failed to auth, bad http status line received", a_UserName.c_str());
LOG("Response: \n%s", CreateHexDump(HexDump, Response.data(), Response.size(), 16).c_str());
return false;
}
AString RESPONSE = ResponseBuilder.str();
if (RESPONSE.empty())
// Erase the HTTP headers from the response:
size_t idxHeadersEnd = Response.find("\r\n\r\n");
if (idxHeadersEnd == AString::npos)
{
LOGINFO("User \"%s\" failed to authenticate, bad http response header received", a_UserName.c_str());
LOG("Response: \n%s", CreateHexDump(HexDump, Response.data(), Response.size(), 16).c_str());
return false;
}
Response.erase(0, idxHeadersEnd + 4);
// Parse the Json response:
if (Response.empty())
{
return false;
}
Json::Value root;
Json::Reader reader;
if (!reader.parse(RESPONSE, root, false))
if (!reader.parse(Response, root, false))
{
LOGWARNING("cAuthenticator: Cannot parse Received Data to json!");
return false;
}
a_UserName = root.get("name", "Unknown").asString();
a_UUID = root.get("id", "").asString();
// If the UUID doesn't contain the hashes, insert them at the proper places:
if (a_UUID.size() == 32)
{
a_UUID.insert(8, "-");
a_UUID.insert(13, "-");
a_UUID.insert(18, "-");
a_UUID.insert(23, "-");
}
return true;
}

View File

@ -83,6 +83,7 @@ public:
virtual void SendInventorySlot (char a_WindowID, short a_SlotNum, const cItem & a_Item) = 0;
virtual void SendKeepAlive (int a_PingID) = 0;
virtual void SendLogin (const cPlayer & a_Player, const cWorld & a_World) = 0;
virtual void SendLoginSuccess (void) = 0;
virtual void SendMapColumn (int a_ID, int a_X, int a_Y, const Byte * a_Colors, unsigned int a_Length) = 0;
virtual void SendMapDecorators (int a_ID, const cMapDecoratorList & a_Decorators) = 0;
virtual void SendMapInfo (int a_ID, unsigned int a_Scale) = 0;

View File

@ -594,6 +594,15 @@ void cProtocol125::SendLogin(const cPlayer & a_Player, const cWorld & a_World)
void cProtocol125::SendLoginSuccess(void)
{
// Not supported in this protocol version
}
void cProtocol125::SendMapColumn(int a_ID, int a_X, int a_Y, const Byte * a_Colors, unsigned int a_Length)
{
cCSLock Lock(m_CSPacket);
@ -642,6 +651,17 @@ void cProtocol125::SendMapDecorators(int a_ID, const cMapDecoratorList & a_Decor
void cProtocol125::SendMapInfo(int a_ID, unsigned int a_Scale)
{
// This protocol doesn't support such message
UNUSED(a_ID);
UNUSED(a_Scale);
}
void cProtocol125::SendPickupSpawn(const cPickup & a_Pickup)
{
cCSLock Lock(m_CSPacket);
@ -683,6 +703,16 @@ void cProtocol125::SendParticleEffect(const AString & a_ParticleName, float a_Sr
void cProtocol125::SendPaintingSpawn(const cPainting & a_Painting)
{
// Not implemented in this protocol version
UNUSED(a_Painting);
}
void cProtocol125::SendPlayerListItem(const cPlayer & a_Player, bool a_IsOnline)
{
cCSLock Lock(m_CSPacket);
@ -842,6 +872,18 @@ void cProtocol125::SendExperienceOrb(const cExpOrb & a_ExpOrb)
void cProtocol125::SendScoreboardObjective(const AString & a_Name, const AString & a_DisplayName, Byte a_Mode)
{
// This protocol version doesn't support such message
UNUSED(a_Name);
UNUSED(a_DisplayName);
UNUSED(a_Mode);
}
void cProtocol125::SendSoundEffect(const AString & a_SoundName, int a_SrcX, int a_SrcY, int a_SrcZ, float a_Volume, float a_Pitch)
{
// Not needed in this protocol version

View File

@ -56,19 +56,12 @@ public:
virtual void SendInventorySlot (char a_WindowID, short a_SlotNum, const cItem & a_Item) override;
virtual void SendKeepAlive (int a_PingID) override;
virtual void SendLogin (const cPlayer & a_Player, const cWorld & a_World) override;
virtual void SendLoginSuccess (void) override;
virtual void SendMapColumn (int a_ID, int a_X, int a_Y, const Byte * a_Colors, unsigned int a_Length) override;
virtual void SendMapDecorators (int a_ID, const cMapDecoratorList & a_Decorators) override;
virtual void SendMapInfo (int a_ID, unsigned int a_Scale) override
{
// This protocol doesn't support such message
UNUSED(a_ID);
UNUSED(a_Scale);
}
virtual void SendMapInfo (int a_ID, unsigned int a_Scale) override;
virtual void SendParticleEffect (const AString & a_ParticleName, float a_SrcX, float a_SrcY, float a_SrcZ, float a_OffsetX, float a_OffsetY, float a_OffsetZ, float a_ParticleData, int a_ParticleAmmount) override;
virtual void SendPaintingSpawn (const cPainting & a_Painting) override
{
UNUSED(a_Painting);
};
virtual void SendPaintingSpawn (const cPainting & a_Painting) override;
virtual void SendPickupSpawn (const cPickup & a_Pickup) override;
virtual void SendPlayerAbilities (void) override {} // This protocol doesn't support such message
virtual void SendEntityAnimation (const cEntity & a_Entity, char a_Animation) override;
@ -82,12 +75,7 @@ public:
virtual void SendRespawn (void) override;
virtual void SendExperience (void) override;
virtual void SendExperienceOrb (const cExpOrb & a_ExpOrb) override;
virtual void SendScoreboardObjective (const AString & a_Name, const AString & a_DisplayName, Byte a_Mode) override
{
UNUSED(a_Name);
UNUSED(a_DisplayName);
UNUSED(a_Mode);
} // This protocol doesn't support such message
virtual void SendScoreboardObjective (const AString & a_Name, const AString & a_DisplayName, Byte a_Mode) override;
virtual void SendScoreUpdate (const AString & a_Objective, const AString & a_Player, cObjective::Score a_Score, Byte a_Mode) override {} // This protocol doesn't support such message
virtual void SendDisplayObjective (const AString & a_Objective, cScoreboard::eDisplaySlot a_Display) override {} // This protocol doesn't support such message
virtual void SendSoundEffect (const AString & a_SoundName, int a_SrcX, int a_SrcY, int a_SrcZ, float a_Volume, float a_Pitch) override; // a_Src coords are Block * 8

View File

@ -574,6 +574,21 @@ void cProtocol172::SendLogin(const cPlayer & a_Player, const cWorld & a_World)
void cProtocol172::SendLoginSuccess(void)
{
ASSERT(m_State == 2); // State: login?
cPacketizer Pkt(*this, 0x02); // Login success packet
Pkt.WriteString(m_Client->GetUUID());
Pkt.WriteString(m_Client->GetUsername());
m_State = 3; // State = Game
}
void cProtocol172::SendPaintingSpawn(const cPainting & a_Painting)
{
cPacketizer Pkt(*this, 0x10); // Spawn Painting packet
@ -1556,18 +1571,7 @@ void cProtocol172::HandlePacketLoginEncryptionResponse(cByteBuffer & a_ByteBuffe
}
StartEncryption(DecryptedKey);
/*
// Send login success:
{
cPacketizer Pkt(*this, 0x02); // Login success packet
Pkt.WriteString(m_Client->GetUUID());
Pkt.WriteString(m_Client->GetUsername());
}
m_State = 3; // State = Game
m_Client->HandleLogin(4, m_Client->GetUsername());
*/
}
@ -1599,17 +1603,6 @@ void cProtocol172::HandlePacketLoginStart(cByteBuffer & a_ByteBuffer)
return;
}
// Generate an offline UUID for the player:
m_Client->GenerateOfflineUUID();
// Send login success:
{
cPacketizer Pkt(*this, 0x02); // Login success packet
Pkt.WriteString(m_Client->GetUUID());
Pkt.WriteString(Username);
}
m_State = 3; // State = Game
m_Client->HandleLogin(4, Username);
}
@ -2797,3 +2790,28 @@ void cProtocol176::SendPlayerSpawn(const cPlayer & a_Player)
void cProtocol176::HandlePacketStatusRequest(cByteBuffer & a_ByteBuffer)
{
// Send the response:
AString Response = "{\"version\":{\"name\":\"1.7.6\",\"protocol\":5},\"players\":{";
AppendPrintf(Response, "\"max\":%u,\"online\":%u,\"sample\":[]},",
cRoot::Get()->GetServer()->GetMaxPlayers(),
cRoot::Get()->GetServer()->GetNumPlayers()
);
AppendPrintf(Response, "\"description\":{\"text\":\"%s\"},",
cRoot::Get()->GetServer()->GetDescription().c_str()
);
AppendPrintf(Response, "\"favicon\":\"data:image/png;base64,%s\"",
cRoot::Get()->GetServer()->GetFaviconData().c_str()
);
Response.append("}");
cPacketizer Pkt(*this, 0x00); // Response packet
Pkt.WriteString(Response);
}

View File

@ -87,6 +87,7 @@ public:
virtual void SendInventorySlot (char a_WindowID, short a_SlotNum, const cItem & a_Item) override;
virtual void SendKeepAlive (int a_PingID) override;
virtual void SendLogin (const cPlayer & a_Player, const cWorld & a_World) override;
virtual void SendLoginSuccess (void) override;
virtual void SendMapColumn (int a_ID, int a_X, int a_Y, const Byte * a_Colors, unsigned int a_Length) override;
virtual void SendMapDecorators (int a_ID, const cMapDecoratorList & a_Decorators) override;
virtual void SendMapInfo (int a_ID, unsigned int a_Scale) override;
@ -252,7 +253,7 @@ protected:
// Packet handlers while in the Status state (m_State == 1):
void HandlePacketStatusPing (cByteBuffer & a_ByteBuffer);
void HandlePacketStatusRequest(cByteBuffer & a_ByteBuffer);
virtual void HandlePacketStatusRequest(cByteBuffer & a_ByteBuffer);
// Packet handlers while in the Login state (m_State == 2):
void HandlePacketLoginEncryptionResponse(cByteBuffer & a_ByteBuffer);
@ -318,6 +319,8 @@ public:
// cProtocol172 overrides:
virtual void SendPlayerSpawn(const cPlayer & a_Player) override;
virtual void HandlePacketStatusRequest(cByteBuffer & a_ByteBuffer) override;
} ;

View File

@ -397,6 +397,16 @@ void cProtocolRecognizer::SendLogin(const cPlayer & a_Player, const cWorld & a_W
void cProtocolRecognizer::SendLoginSuccess(void)
{
ASSERT(m_Protocol != NULL);
m_Protocol->SendLoginSuccess();
}
void cProtocolRecognizer::SendMapColumn(int a_ID, int a_X, int a_Y, const Byte * a_Colors, unsigned int a_Length)
{
ASSERT(m_Protocol != NULL);

View File

@ -91,6 +91,7 @@ public:
virtual void SendInventorySlot (char a_WindowID, short a_SlotNum, const cItem & a_Item) override;
virtual void SendKeepAlive (int a_PingID) override;
virtual void SendLogin (const cPlayer & a_Player, const cWorld & a_World) override;
virtual void SendLoginSuccess (void) override;
virtual void SendMapColumn (int a_ID, int a_X, int a_Y, const Byte * a_Colors, unsigned int a_Length) override;
virtual void SendMapDecorators (int a_ID, const cMapDecoratorList & a_Decorators) override;
virtual void SendMapInfo (int a_ID, unsigned int a_Scale) override;