1
0

Merge remote-tracking branch 'daniel0916/YggdrasilAuthentication' into Proto176

This commit is contained in:
madmaxoft 2014-04-14 18:53:56 +02:00
commit ffe65b6a18
10 changed files with 362 additions and 296 deletions

View File

@ -1,267 +0,0 @@
#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 "inifile/iniFile.h"
#include <sstream>
#define DEFAULT_AUTH_SERVER "session.minecraft.net"
#define DEFAULT_AUTH_ADDRESS "/game/checkserver.jsp?user=%USERNAME%&serverId=%SERVERID%"
#define MAX_REDIRECTS 10
cAuthenticator::cAuthenticator(void) :
super("cAuthenticator"),
m_Server(DEFAULT_AUTH_SERVER),
m_Address(DEFAULT_AUTH_ADDRESS),
m_ShouldAuthenticate(true)
{
}
cAuthenticator::~cAuthenticator()
{
Stop();
}
void cAuthenticator::ReadINI(cIniFile & IniFile)
{
m_Server = IniFile.GetValueSet("Authentication", "Server", DEFAULT_AUTH_SERVER);
m_Address = IniFile.GetValueSet("Authentication", "Address", DEFAULT_AUTH_ADDRESS);
m_ShouldAuthenticate = IniFile.GetValueSetB("Authentication", "Authenticate", true);
}
void cAuthenticator::Authenticate(int a_ClientID, const AString & a_UserName, const AString & a_ServerHash)
{
if (!m_ShouldAuthenticate)
{
cRoot::Get()->AuthenticateUser(a_ClientID);
return;
}
cCSLock Lock(m_CS);
m_Queue.push_back(cUser(a_ClientID, a_UserName, a_ServerHash));
m_QueueNonempty.Set();
}
void cAuthenticator::Start(cIniFile & IniFile)
{
ReadINI(IniFile);
m_ShouldTerminate = false;
super::Start();
}
void cAuthenticator::Stop(void)
{
m_ShouldTerminate = true;
m_QueueNonempty.Set();
Wait();
}
void cAuthenticator::Execute(void)
{
for (;;)
{
cCSLock Lock(m_CS);
while (!m_ShouldTerminate && (m_Queue.size() == 0))
{
cCSUnlock Unlock(Lock);
m_QueueNonempty.Wait();
}
if (m_ShouldTerminate)
{
return;
}
ASSERT(!m_Queue.empty());
int ClientID = m_Queue.front().m_ClientID;
AString UserName = m_Queue.front().m_Name;
AString ActualAddress = m_Address;
ReplaceString(ActualAddress, "%USERNAME%", UserName);
ReplaceString(ActualAddress, "%SERVERID%", m_Queue.front().m_ServerID);
m_Queue.pop_front();
Lock.Unlock();
if (!AuthFromAddress(m_Server, ActualAddress, UserName))
{
cRoot::Get()->KickUser(ClientID, "Failed to authenticate account!");
}
else
{
cRoot::Get()->AuthenticateUser(ClientID);
}
} // for (-ever)
}
bool cAuthenticator::AuthFromAddress(const AString & a_Server, const AString & a_Address, const AString & a_UserName, int a_Level /* = 1 */)
{
// Returns true if the user authenticated okay, false on error; iLevel is the recursion deptht (bails out if too deep)
cBlockingTCPLink Link;
if (!Link.Connect(a_Server.c_str(), 80))
{
LOGWARNING("%s: cannot connect to auth server \"%s\", kicking user \"%s\"",
__FUNCTION__, a_Server.c_str(), a_UserName.c_str()
);
return false;
}
Link.SendMessage( AString( "GET " + a_Address + " HTTP/1.1\r\n" ).c_str());
Link.SendMessage( AString( "User-Agent: MCServer\r\n" ).c_str());
Link.SendMessage( AString( "Host: " + a_Server + "\r\n" ).c_str());
//Link.SendMessage( AString( "Host: session.minecraft.net\r\n" ).c_str());
Link.SendMessage( AString( "Accept: */*\r\n" ).c_str());
Link.SendMessage( AString( "Connection: close\r\n" ).c_str()); //Close so we don´t have to mess with the Content-Length :)
Link.SendMessage( AString( "\r\n" ).c_str());
AString DataRecvd;
Link.ReceiveData(DataRecvd);
Link.CloseSocket();
std::stringstream ss(DataRecvd);
// Parse the data received:
std::string temp;
ss >> temp;
bool bRedirect = false;
bool bOK = false;
if ((temp.compare("HTTP/1.1") == 0) || (temp.compare("HTTP/1.0") == 0))
{
int code;
ss >> code;
if (code == 302)
{
// redirect blabla
LOGD("%s: Need to redirect, current level %d!", __FUNCTION__, a_Level);
if (a_Level > MAX_REDIRECTS)
{
LOGERROR("cAuthenticator: received too many levels of redirection from auth server \"%s\" for user \"%s\", bailing out and kicking the user", a_Server.c_str(), a_UserName.c_str());
return false;
}
bRedirect = true;
}
else if (code == 200)
{
LOGD("cAuthenticator: Received status 200 OK! :D");
bOK = true;
}
}
else
{
LOGERROR("cAuthenticator: cannot parse auth reply from server \"%s\" for user \"%s\", kicking the user.", a_Server.c_str(), a_UserName.c_str());
return false;
}
if( bRedirect )
{
AString Location;
// Search for "Location:"
bool bFoundLocation = false;
while( !bFoundLocation && ss.good() )
{
char c = 0;
while( c != '\n' )
{
ss.get( c );
}
AString Name;
ss >> Name;
if (Name.compare("Location:") == 0)
{
bFoundLocation = true;
ss >> Location;
}
}
if (!bFoundLocation)
{
LOGERROR("cAuthenticator: received invalid redirection from auth server \"%s\" for user \"%s\", kicking user.", a_Server.c_str(), a_UserName.c_str());
return false;
}
Location = Location.substr(strlen("http://"), std::string::npos); // Strip http://
std::string Server = Location.substr( 0, Location.find( "/" ) ); // Only leave server address
Location = Location.substr( Server.length(), std::string::npos);
return AuthFromAddress(Server, Location, a_UserName, a_Level + 1);
}
if (!bOK)
{
LOGERROR("cAuthenticator: received an error from auth server \"%s\" for user \"%s\", kicking user.", a_Server.c_str(), a_UserName.c_str());
return false;
}
// Header says OK, so receive the rest.
// Go past header, double \n means end of headers
char c = 0;
while (ss.good())
{
while (c != '\n')
{
ss.get(c);
}
ss.get(c);
if( c == '\n' || c == '\r' || ss.peek() == '\r' || ss.peek() == '\n' )
break;
}
if (!ss.good())
{
LOGERROR("cAuthenticator: error while parsing response body from auth server \"%s\" for user \"%s\", kicking user.", a_Server.c_str(), a_UserName.c_str());
return false;
}
std::string Result;
ss >> Result;
LOGD("cAuthenticator: Authentication result was %s", Result.c_str());
if (Result.compare("YES") == 0) //Works well
{
LOGINFO("Authentication result \"YES\", player authentication success!");
return true;
}
LOGINFO("Authentication result was \"%s\", player authentication failure!", Result.c_str());
return false;
}

View File

@ -24,7 +24,7 @@
#include "Root.h"
#include "Authenticator.h"
#include "Protocol/Authenticator.h"
#include "MersenneTwister.h"
#include "Protocol/ProtocolRecognizer.h"
@ -188,7 +188,7 @@ void cClientHandle::Kick(const AString & a_Reason)
void cClientHandle::Authenticate(void)
void cClientHandle::Authenticate(const AString & a_Name, const AString & a_UUID)
{
if (m_State != csAuthenticating)
{
@ -197,6 +197,9 @@ void cClientHandle::Authenticate(void)
ASSERT( m_Player == NULL );
m_Username = a_Name;
m_UUID = a_UUID;
// Spawn player (only serversided, so data is loaded)
m_Player = new cPlayer(this, GetUsername());

View File

@ -62,8 +62,11 @@ public:
cPlayer* GetPlayer() { return m_Player; } // tolua_export
const AString & GetUUID(void) const { return m_UUID; } // tolua_export
void setUUID(const AString & a_UUID) { m_UUID = a_UUID; }
void Kick(const AString & a_Reason); // tolua_export
void Authenticate(void); // Called by cAuthenticator when the user passes authentication
void Authenticate(const AString & a_Name, const AString & a_UUID); // Called by cAuthenticator when the user passes authentication
void StreamChunks(void);
@ -326,6 +329,7 @@ private:
static int s_ClientCount;
int m_UniqueID;
AString m_UUID;
/** Set to true when the chunk where the player is is sent to the client. Used for spawning the player */
bool m_HasSentPlayerChunk;

View File

@ -0,0 +1,326 @@
#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 "inifile/iniFile.h"
#include "json/json.h"
#include "polarssl/config.h"
#include "polarssl/net.h"
#include "polarssl/ssl.h"
#include "polarssl/entropy.h"
#include "polarssl/ctr_drbg.h"
#include "polarssl/error.h"
#include "polarssl/certs.h"
#include <sstream>
#include <iomanip>
#define DEFAULT_AUTH_SERVER "sessionserver.mojang.com"
#define DEFAULT_AUTH_ADDRESS "/session/minecraft/hasJoined?username=%USERNAME%&serverId=%SERVERID%"
cAuthenticator::cAuthenticator(void) :
super("cAuthenticator"),
m_Server(DEFAULT_AUTH_SERVER),
m_Address(DEFAULT_AUTH_ADDRESS),
m_ShouldAuthenticate(true)
{
}
cAuthenticator::~cAuthenticator()
{
Stop();
}
void cAuthenticator::ReadINI(cIniFile & IniFile)
{
m_Server = IniFile.GetValueSet("Authentication", "Server", DEFAULT_AUTH_SERVER);
m_Address = IniFile.GetValueSet("Authentication", "Address", DEFAULT_AUTH_ADDRESS);
m_ShouldAuthenticate = IniFile.GetValueSetB("Authentication", "Authenticate", true);
}
void cAuthenticator::Authenticate(int a_ClientID, const AString & a_UserName, const AString & a_ServerHash)
{
if (!m_ShouldAuthenticate)
{
cRoot::Get()->AuthenticateUser(a_ClientID, a_UserName, Printf("%d", a_ClientID));
return;
}
cCSLock LOCK(m_CS);
m_Queue.push_back(cUser(a_ClientID, a_UserName, a_ServerHash));
m_QueueNonempty.Set();
}
void cAuthenticator::Start(cIniFile & IniFile)
{
ReadINI(IniFile);
m_ShouldTerminate = false;
super::Start();
}
void cAuthenticator::Stop(void)
{
m_ShouldTerminate = true;
m_QueueNonempty.Set();
Wait();
}
void cAuthenticator::Execute(void)
{
for (;;)
{
cCSLock Lock(m_CS);
while (!m_ShouldTerminate && (m_Queue.size() == 0))
{
cCSUnlock Unlock(Lock);
m_QueueNonempty.Wait();
}
if (m_ShouldTerminate)
{
return;
}
ASSERT(!m_Queue.empty());
int ClientID = m_Queue.front().m_ClientID;
AString UserName = m_Queue.front().m_Name;
AString ServerID = m_Queue.front().m_ServerID;
m_Queue.pop_front();
Lock.Unlock();
AString NewUserName = UserName;
AString UUID;
if (AuthWithYggdrasil(NewUserName, ServerID, UUID))
{
LOGINFO("User %s authenticated with UUID '%s'", NewUserName.c_str(), UUID.c_str());
cRoot::Get()->AuthenticateUser(ClientID, NewUserName, UUID);
}
else
{
cRoot::Get()->KickUser(ClientID, "Failed to authenticate account!");
}
} // for (-ever)
}
bool cAuthenticator::AuthWithYggdrasil(AString & a_UserName, const AString & a_ServerId, AString & a_UUID)
{
AString REQUEST;
int ret, server_fd = -1;
size_t len = 0;
unsigned char buf[1024];
const char *pers = "cAuthenticator";
entropy_context entropy;
ctr_drbg_context ctr_drbg;
ssl_context ssl;
x509_crt cacert;
/* Initialize the RNG and the session data */
memset(&ssl, 0, sizeof(ssl_context));
x509_crt_init(&cacert);
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);
return false;
}
/* Initialize certificates */
#if defined(POLARSSL_CERTS_C)
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);
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);
return false;
}
/* Setup */
if ((ret = ssl_init(&ssl)) != 0)
{
LOGERROR("cAuthenticator: ssl_init returned %d", ret);
return false;
}
ssl_set_endpoint(&ssl, SSL_IS_CLIENT);
ssl_set_authmode(&ssl, SSL_VERIFY_OPTIONAL);
ssl_set_ca_chain(&ssl, &cacert, NULL, "PolarSSL Server 1");
ssl_set_rng(&ssl, ctr_drbg_random, &ctr_drbg);
ssl_set_bio(&ssl, net_recv, &server_fd, net_send, &server_fd);
/* Handshake */
while ((ret = ssl_handshake(&ssl)) != 0)
{
if (ret != POLARSSL_ERR_NET_WANT_READ && ret != POLARSSL_ERR_NET_WANT_WRITE)
{
LOGERROR("cAuthenticator: ssl_handshake returned -0x%x", -ret);
return false;
}
}
/* Write the GET request */
AString ActualAddress = m_Address;
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";
len = REQUEST.size();
strcpy((char *)buf, REQUEST.c_str());
while ((ret = ssl_write(&ssl, buf, len)) <= 0)
{
if (ret != POLARSSL_ERR_NET_WANT_READ && ret != POLARSSL_ERR_NET_WANT_WRITE)
{
LOGERROR("cAuthenticator: ssl_write returned %d", ret);
return false;
}
}
/* Read the HTTP response */
std::string Builder;
for (;;)
{
len = sizeof(buf)-1;
memset(buf, 0, sizeof(buf));
ret = ssl_read(&ssl, buf, len);
if (ret > 0)
{
buf[ret] = '\0';
}
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);
break;
}
if (ret == 0)
{
LOGERROR("cAuthenticator: EOF");
break;
}
std::string str;
str.append(reinterpret_cast<const char*>(buf));
Builder += str;
}
ssl_close_notify(&ssl);
x509_crt_free(&cacert);
net_close(server_fd);
ssl_free(&ssl);
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)
{
if (NewLine)
{
ResponseBuilder << *i;
}
else if (!NewLine && *i == '\n')
{
if (IsNewLine)
{
NewLine = true;
}
else
{
IsNewLine = true;
}
}
else if (*i != '\r')
{
IsNewLine = false;
}
}
AString RESPONSE = ResponseBuilder.str();
if (RESPONSE.empty())
return false;
Json::Value root;
Json::Reader reader;
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();
return true;
}

View File

@ -14,7 +14,7 @@
#ifndef CAUTHENTICATOR_H_INCLUDED
#define CAUTHENTICATOR_H_INCLUDED
#include "OSSupport/IsThread.h"
#include "../OSSupport/IsThread.h"
@ -31,23 +31,23 @@ class cAuthenticator :
public cIsThread
{
typedef cIsThread super;
public:
cAuthenticator(void);
~cAuthenticator();
/// (Re-)read server and address from INI:
/** (Re-)read server and address from INI: */
void ReadINI(cIniFile & IniFile);
/// Queues a request for authenticating a user. If the auth fails, the user is kicked
/** Queues a request for authenticating a user. If the auth fails, the user will be kicked */
void Authenticate(int a_ClientID, const AString & a_UserName, const AString & a_ServerHash);
/// Starts the authenticator thread. The thread may be started and stopped repeatedly
/** Starts the authenticator thread. The thread may be started and stopped repeatedly */
void Start(cIniFile & IniFile);
/// Stops the authenticator thread. The thread may be started and stopped repeatedly
/** Stops the authenticator thread. The thread may be started and stopped repeatedly */
void Stop(void);
private:
class cUser
@ -56,30 +56,30 @@ private:
int m_ClientID;
AString m_Name;
AString m_ServerID;
cUser(int a_ClientID, const AString & a_Name, const AString & a_ServerID) :
m_ClientID(a_ClientID),
m_Name(a_Name),
m_ServerID(a_ServerID)
{
}
} ;
};
typedef std::deque<cUser> cUserList;
cCriticalSection m_CS;
cUserList m_Queue;
cEvent m_QueueNonempty;
AString m_Server;
AString m_Address;
bool m_ShouldAuthenticate;
// cIsThread override:
/** cIsThread override: */
virtual void Execute(void) override;
// Returns true if the user authenticated okay, false on error; iLevel is the recursion deptht (bails out if too deep)
bool AuthFromAddress(const AString & a_Server, const AString & a_Address, const AString & a_UserName, int a_Level = 1);
/** Returns true if the user authenticated okay, false on error; iLevel is the recursion deptht (bails out if too deep) */
bool AuthWithYggdrasil(AString & a_UserName, const AString & a_ServerId, AString & a_UUID);
};

View File

@ -1559,7 +1559,7 @@ void cProtocol172::HandlePacketLoginEncryptionResponse(cByteBuffer & a_ByteBuffe
// Send login success:
{
cPacketizer Pkt(*this, 0x02); // Login success packet
Pkt.WriteString(Printf("%d", m_Client->GetUniqueID())); // TODO: proper UUID
Pkt.WriteString(m_Client->GetUUID());
Pkt.WriteString(m_Client->GetUsername());
}

View File

@ -499,9 +499,9 @@ void cRoot::KickUser(int a_ClientID, const AString & a_Reason)
void cRoot::AuthenticateUser(int a_ClientID)
void cRoot::AuthenticateUser(int a_ClientID, const AString & a_Name, const AString & a_UUID)
{
m_Server->AuthenticateUser(a_ClientID);
m_Server->AuthenticateUser(a_ClientID, a_Name, a_UUID);
}

View File

@ -1,7 +1,7 @@
#pragma once
#include "Authenticator.h"
#include "Protocol/Authenticator.h"
#include "HTTPServer/HTTPServer.h"
#include "Defines.h"
@ -89,7 +89,7 @@ public:
void KickUser(int a_ClientID, const AString & a_Reason);
/// Called by cAuthenticator to auth the specified user
void AuthenticateUser(int a_ClientID);
void AuthenticateUser(int a_ClientID, const AString & a_Name, const AString & a_UUID);
/// Executes commands queued in the command queue
void TickCommands(void);

View File

@ -615,14 +615,14 @@ void cServer::KickUser(int a_ClientID, const AString & a_Reason)
void cServer::AuthenticateUser(int a_ClientID)
void cServer::AuthenticateUser(int a_ClientID, const AString & a_Name, const AString & a_UUID)
{
cCSLock Lock(m_CSClients);
for (ClientList::iterator itr = m_Clients.begin(); itr != m_Clients.end(); ++itr)
{
if ((*itr)->GetUniqueID() == a_ClientID)
{
(*itr)->Authenticate();
(*itr)->Authenticate(a_Name, a_UUID);
return;
}
} // for itr - m_Clients[]

View File

@ -83,7 +83,7 @@ public: // tolua_export
void Shutdown(void);
void KickUser(int a_ClientID, const AString & a_Reason);
void AuthenticateUser(int a_ClientID); // Called by cAuthenticator to auth the specified user
void AuthenticateUser(int a_ClientID, const AString & a_Name, const AString & a_UUID); // Called by cAuthenticator to auth the specified user
const AString & GetServerID(void) const { return m_ServerID; } // tolua_export