Updated Bnet Server.

Port From (https://github.com/TrinityCore/TrinityCore)
This commit is contained in:
hondacrx
2024-02-21 00:05:48 -05:00
parent 7960e7b192
commit 9e3a7df6a7
62 changed files with 2186 additions and 731 deletions
+4 -4
View File
@@ -34,7 +34,7 @@ namespace Game
if (GetId(username) != 0)
return AccountOpResult.NameAlreadyExist;
(byte[] salt, byte[] verifier) = SRP6.MakeRegistrationData(username, password);
(byte[] salt, byte[] verifier) = SRP6.MakeAccountRegistrationData<GruntSRP6>(username, password);
PreparedStatement stmt = LoginDatabase.GetPreparedStatement(LoginStatements.INS_ACCOUNT);
stmt.AddValue(0, username);
@@ -152,7 +152,7 @@ namespace Game
stmt.AddValue(1, accountId);
DB.Login.Execute(stmt);
(byte[] salt, byte[] verifier) = SRP6.MakeRegistrationData(newUsername, newPassword);
(byte[] salt, byte[] verifier) = SRP6.MakeAccountRegistrationData<GruntSRP6>(newUsername, newPassword);
stmt = LoginDatabase.GetPreparedStatement(LoginStatements.UPD_LOGON);
stmt.AddValue(0, salt);
stmt.AddValue(1, verifier);
@@ -178,7 +178,7 @@ namespace Game
return AccountOpResult.PassTooLong;
}
(byte[] salt, byte[] verifier) = SRP6.MakeRegistrationData(username, newPassword);
(byte[] salt, byte[] verifier) = SRP6.MakeAccountRegistrationData<GruntSRP6>(username, newPassword);
PreparedStatement stmt = LoginDatabase.GetPreparedStatement(LoginStatements.UPD_LOGON);
stmt.AddValue(0, salt);
@@ -304,7 +304,7 @@ namespace Game
{
byte[] salt = result.Read<byte[]>(0);
byte[] verifier = result.Read<byte[]>(1);
if (SRP6.CheckLogin(username, password, salt, verifier))
if (new GruntSRP6(username, salt, verifier).CheckCredentials(username, password))
return true;
}
+47 -14
View File
@@ -1,6 +1,7 @@
// Copyright (c) CypherCore <http://github.com/CypherCore> All rights reserved.
// Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE file in the project root for full license information.
using Framework.Cryptography;
using Framework.Database;
using System;
using System.Security.Cryptography;
@@ -10,24 +11,32 @@ namespace Game
{
public sealed class BNetAccountManager : Singleton<BNetAccountManager>
{
static int MAX_BNET_EMAIL_STR = 320;
static int MAX_BNET_PASS_STR = 128;
BNetAccountManager() { }
public AccountOpResult CreateBattlenetAccount(string email, string password, bool withGameAccount, out string gameAccountName)
{
gameAccountName = "";
if (email.IsEmpty() || email.Length > 320)
if (email.IsEmpty() || email.Length > MAX_BNET_EMAIL_STR)
return AccountOpResult.NameTooLong;
if (password.IsEmpty() || password.Length > 16)
if (password.IsEmpty() || password.Length > MAX_BNET_PASS_STR)
return AccountOpResult.PassTooLong;
if (GetId(email) != 0)
return AccountOpResult.NameAlreadyExist;
string srpUsername = GetSrpUsername(email);
var (salt, verifier) = SRP6.MakeBNetRegistrationData<BnetSRP6v2Hash256>(srpUsername, password);
PreparedStatement stmt = LoginDatabase.GetPreparedStatement(LoginStatements.INS_BNET_ACCOUNT);
stmt.AddValue(0, email);
stmt.AddValue(1, CalculateShaPassHash(email.ToUpper(), password.ToUpper()));
stmt.AddValue(1, (sbyte)SrpVersion.v2);
stmt.AddValue(2, salt);
stmt.AddValue(3, verifier);
DB.Login.DirectExecute(stmt);
uint newAccountId = GetId(email);
@@ -36,7 +45,8 @@ namespace Game
if (withGameAccount)
{
gameAccountName = newAccountId + "#1";
Global.AccountMgr.CreateAccount(gameAccountName, password, email, newAccountId, 1);
string gameAccountPassword = password.Substring(0, 16);
Global.AccountMgr.CreateAccount(gameAccountName, gameAccountPassword.ToUpper(), email, newAccountId, 1);
}
return AccountOpResult.Ok;
@@ -48,12 +58,17 @@ namespace Game
if (!GetName(accountId, out username))
return AccountOpResult.NameNotExist;
if (newPassword.Length > 16)
if (newPassword.Length > MAX_BNET_PASS_STR)
return AccountOpResult.PassTooLong;
PreparedStatement stmt = LoginDatabase.GetPreparedStatement(LoginStatements.UPD_BNET_PASSWORD);
stmt.AddValue(0, CalculateShaPassHash(username, newPassword));
stmt.AddValue(1, accountId);
string srpUsername = GetSrpUsername(username);
var (salt, verifier) = SRP6.MakeBNetRegistrationData<BnetSRP6v2Hash256>(srpUsername, newPassword);
PreparedStatement stmt = LoginDatabase.GetPreparedStatement(LoginStatements.UPD_BNET_LOGON);
stmt.AddValue(0, (sbyte)SrpVersion.v2);
stmt.AddValue(1, salt);
stmt.AddValue(2, verifier);
stmt.AddValue(3, accountId);
DB.Login.Execute(stmt);
return AccountOpResult.Ok;
@@ -67,9 +82,23 @@ namespace Game
PreparedStatement stmt = LoginDatabase.GetPreparedStatement(LoginStatements.SEL_BNET_CHECK_PASSWORD);
stmt.AddValue(0, accountId);
stmt.AddValue(1, CalculateShaPassHash(username, password));
SQLResult result = DB.Login.Query(stmt);
if (!result.IsEmpty())
{
var salt = result.Read<byte[]>(1);
var verifier = result.Read<byte[]>(2);
switch ((SrpVersion)result.Read<sbyte>(0))
{
case SrpVersion.v1:
return new BnetSRP6v1Hash256(username, salt, verifier).CheckCredentials(username, password);
case SrpVersion.v2:
return new BnetSRP6v2Hash256(username, salt, verifier).CheckCredentials(username, password);
default:
break;
}
}
return !DB.Login.Query(stmt).IsEmpty();
return false;
}
public AccountOpResult LinkWithGameAccount(string email, string gameAccountName)
@@ -165,11 +194,15 @@ namespace Game
return 0;
}
public string CalculateShaPassHash(string name, string password)
public string GetSrpUsername(string name)
{
SHA256 sha256 = SHA256.Create();
var i = sha256.ComputeHash(Encoding.UTF8.GetBytes(name));
return sha256.ComputeHash(Encoding.UTF8.GetBytes(i.ToHexString() + ":" + password)).ToHexString(true);
return SHA256.HashData(Encoding.UTF8.GetBytes(name)).ToHexString();
}
}
enum SrpVersion
{
v1 = 1, // password length limit 16 characters, case-insensitive, uses SHA256 to generate verifier
v2 = 2 // password length limit 128 characters, case-sensitive, uses PBKDF2 with SHA512 to generate verifier
}
}
+2 -2
View File
@@ -271,7 +271,7 @@ namespace Game.Chat.Commands
[Command("account", RBACPermissions.CommandBanlistAccount, true)]
static bool HandleBanListAccountCommand(CommandHandler handler, [OptionalArg] string filter)
{
PreparedStatement stmt = LoginDatabase.GetPreparedStatement(LoginStatements.DelExpiredIpBans);
PreparedStatement stmt = LoginDatabase.GetPreparedStatement(LoginStatements.DEL_EXPIRED_IP_BANS);
DB.Login.Execute(stmt);
SQLResult result;
@@ -380,7 +380,7 @@ namespace Game.Chat.Commands
[Command("ip", RBACPermissions.CommandBanlistIp, true)]
static bool HandleBanListIPCommand(CommandHandler handler, [OptionalArg] string filter)
{
PreparedStatement stmt = LoginDatabase.GetPreparedStatement(LoginStatements.DelExpiredIpBans);
PreparedStatement stmt = LoginDatabase.GetPreparedStatement(LoginStatements.DEL_EXPIRED_IP_BANS);
DB.Login.Execute(stmt);
SQLResult result;
+2 -1
View File
@@ -16,9 +16,9 @@ using Game.DungeonFinding;
using Game.Entities;
using Game.Garrisons;
using Game.Groups;
using Game.Guilds;
using Game.Loots;
using Game.Maps;
using Game.Networking;
using Game.PvP;
using Game.Scenarios;
using Game.Scripting;
@@ -33,6 +33,7 @@ public static class Global
public static WorldManager WorldMgr { get { return WorldManager.Instance; } }
public static RealmManager RealmMgr { get { return RealmManager.Instance; } }
public static WorldServiceManager ServiceMgr { get { return WorldServiceManager.Instance; } }
public static WorldSocketManager WorldSocketMgr { get { return WorldSocketManager.Instance; } }
//Guild
public static PetitionManager PetitionMgr { get { return PetitionManager.Instance; } }
+10 -37
View File
@@ -29,7 +29,7 @@ namespace Game.Networking
_receiveBuffer = new byte[1024];
}
public void Accept()
public void Start()
{
// wait 1 second for active connections to send negotiation request
for (int counter = 0; counter < 10 && _socket.Available == 0; counter++)
@@ -46,7 +46,7 @@ namespace Game.Networking
}
Send("Authentication Required\r\n");
Send("Email: ");
Send("Username: ");
string userName = ReadString();
if (userName.IsEmpty())
{
@@ -64,7 +64,7 @@ namespace Game.Networking
return;
}
if (!CheckAccessLevelAndPassword(userName, password))
if (!CheckAccessLevel(userName) || Global.AccountMgr.CheckPassword(userName, password))
{
Send("Authentication failed\r\n");
CloseSocket();
@@ -129,56 +129,29 @@ namespace Game.Networking
}
}
bool CheckAccessLevelAndPassword(string email, string password)
bool CheckAccessLevel(string user)
{
//"SELECT a.id, a.username FROM account a LEFT JOIN battlenet_accounts ba ON a.battlenet_account = ba.id WHERE ba.email = ?"
PreparedStatement stmt = LoginDatabase.GetPreparedStatement(LoginStatements.SEL_BNET_GAME_ACCOUNT_LIST);
stmt.AddValue(0, email);
PreparedStatement stmt = LoginDatabase.GetPreparedStatement(LoginStatements.SEL_ACCOUNT_ACCESS);
stmt.AddValue(0, user);
SQLResult result = DB.Login.Query(stmt);
if (result.IsEmpty())
{
Log.outInfo(LogFilter.CommandsRA, $"User {email} does not exist in database");
Log.outInfo(LogFilter.CommandsRA, $"User {user} does not exist in database");
return false;
}
uint accountId = result.Read<uint>(0);
string username = result.Read<string>(1);
stmt = LoginDatabase.GetPreparedStatement(LoginStatements.SEL_ACCOUNT_ACCESS_BY_ID);
stmt.AddValue(0, accountId);
result = DB.Login.Query(stmt);
if (result.IsEmpty())
{
Log.outInfo(LogFilter.CommandsRA, $"User {email} has no privilege to login");
return false;
}
//"SELECT SecurityLevel, RealmID FROM account_access WHERE AccountID = ? and (RealmID = ? OR RealmID = -1) ORDER BY SecurityLevel desc");
if (result.Read<byte>(0) < ConfigMgr.GetDefaultValue("Ra.MinLevel", (byte)AccountTypes.Administrator))
{
Log.outInfo(LogFilter.CommandsRA, $"User {email} has no privilege to login");
Log.outInfo(LogFilter.CommandsRA, $"User {user} has no privilege to login");
return false;
}
else if (result.Read<int>(1) != -1)
{
Log.outInfo(LogFilter.CommandsRA, $"User {email} has to be assigned on all realms (with RealmID = '-1')");
Log.outInfo(LogFilter.CommandsRA, $"User {user} has to be assigned on all realms (with RealmID = '-1')");
return false;
}
stmt = LoginDatabase.GetPreparedStatement(LoginStatements.SEL_CHECK_PASSWORD);
stmt.AddValue(0, accountId);
result = DB.Login.Query(stmt);
if (!result.IsEmpty())
{
var salt = result.Read<byte[]>(0);
var verifier = result.Read<byte[]>(1);
if (SRP6.CheckLogin(username, password, salt, verifier))
return true;
}
Log.outInfo(LogFilter.CommandsRA, $"Wrong password for user: {email}");
return false;
return true;
}
bool ProcessCommand(string command)
+20 -18
View File
@@ -69,11 +69,11 @@ namespace Game.Networking
base.Dispose();
}
public override void Accept()
public override void Start()
{
string ip_address = GetRemoteIpAddress().ToString();
PreparedStatement stmt = LoginDatabase.GetPreparedStatement(LoginStatements.SelIpInfo);
PreparedStatement stmt = LoginDatabase.GetPreparedStatement(LoginStatements.SEL_IP_INFO);
stmt.AddValue(0, ip_address);
stmt.AddValue(1, BitConverter.ToUInt32(GetRemoteIpAddress().Address.GetAddressBytes(), 0));
@@ -489,7 +489,7 @@ namespace Game.Networking
var address = GetRemoteIpAddress();
Sha256 digestKeyHash = new();
digestKeyHash.Process(account.game.SessionKey, account.game.SessionKey.Length);
digestKeyHash.Process(account.game.KeyData, account.game.KeyData.Length);
if (account.game.OS == "Wn64")
digestKeyHash.Finish(buildInfo.Win64AuthSeed);
else if (account.game.OS == "Mc64")
@@ -515,7 +515,7 @@ namespace Game.Networking
}
Sha256 keyData = new();
keyData.Finish(account.game.SessionKey);
keyData.Finish(account.game.KeyData);
HmacSha256 sessionKeyHmac = new(keyData.Digest);
sessionKeyHmac.Process(_serverChallenge, 16);
@@ -652,7 +652,7 @@ namespace Game.Networking
Global.ScriptMgr.OnAccountLogin(account.game.Id);
_worldSession = new WorldSession(account.game.Id, authSession.RealmJoinTicket, account.battleNet.Id, this, account.game.Security, (Expansion)account.game.Expansion,
mutetime, account.game.OS, account.battleNet.Locale, account.game.Recruiter, account.game.IsRectuiter);
mutetime, account.game.OS, account.game.TimezoneOffset, account.battleNet.Locale, account.game.Recruiter, account.game.IsRectuiter);
// Initialize Warden system only if it is enabled by config
//if (wardenActive)
@@ -839,15 +839,15 @@ namespace Game.Networking
{
public AccountInfo(SQLFields fields)
{
// 0 1 2 3 4 5 6 7 8 9 10 11
// SELECT a.id, a.sessionkey, ba.last_ip, ba.locked, ba.lock_country, a.expansion, a.mutetime, ba.locale, a.recruiter, a.os, ba.id, aa.gmLevel,
// 12 13 14
// 0 1 2 3 4 5 6 7 8 9 10 11 12
// SELECT a.id, a.session_key, ba.last_ip, ba.locked, ba.lock_country, a.expansion, a.mutetime, ba.locale, a.recruiter, a.os, a.timezone_offset, ba.id, aa.SecurityLevel,
// 13 14 15
// bab.unbandate > UNIX_TIMESTAMP() OR bab.unbandate = bab.bandate, ab.unbandate > UNIX_TIMESTAMP() OR ab.unbandate = ab.bandate, r.id
// FROM account a LEFT JOIN battlenet_accounts ba ON a.battlenet_account = ba.id LEFT JOIN account_access aa ON a.id = aa.id AND aa.RealmID IN (-1, ?)
// FROM account a LEFT JOIN battlenet_accounts ba ON a.battlenet_account = ba.id LEFT JOIN account_access aa ON a.id = aa.AccountID AND aa.RealmID IN (-1, ?)
// LEFT JOIN battlenet_account_bans bab ON ba.id = bab.id LEFT JOIN account_banned ab ON a.id = ab.id LEFT JOIN account r ON a.id = r.recruiter
// WHERE a.username = ? ORDER BY aa.RealmID DESC LIMIT 1
// WHERE a.username = ? AND LENGTH(a.session_key) = 40 ORDER BY aa.RealmID DESC LIMIT 1
game.Id = fields.Read<uint>(0);
game.SessionKey = fields.Read<byte[]>(1);
game.KeyData = fields.Read<byte[]>(1);
battleNet.LastIP = fields.Read<string>(2);
battleNet.IsLockedToIP = fields.Read<bool>(3);
battleNet.LockCountry = fields.Read<string>(4);
@@ -856,11 +856,12 @@ namespace Game.Networking
battleNet.Locale = (Locale)fields.Read<byte>(7);
game.Recruiter = fields.Read<uint>(8);
game.OS = fields.Read<string>(9);
battleNet.Id = fields.Read<uint>(10);
game.Security = (AccountTypes)fields.Read<byte>(11);
battleNet.IsBanned = fields.Read<uint>(12) != 0;
game.IsBanned = fields.Read<uint>(13) != 0;
game.IsRectuiter = fields.Read<uint>(14) != 0;
game.TimezoneOffset = TimeSpan.FromMinutes(fields.Read<short>(10));
battleNet.Id = fields.Read<uint>(11);
game.Security = (AccountTypes)fields.Read<byte>(12);
battleNet.IsBanned = fields.Read<uint>(13) != 0;
game.IsBanned = fields.Read<uint>(14) != 0;
game.IsRectuiter = fields.Read<uint>(15) != 0;
if (battleNet.Locale >= Locale.Total)
battleNet.Locale = Locale.enUS;
@@ -884,11 +885,12 @@ namespace Game.Networking
public struct Game
{
public uint Id;
public byte[] SessionKey;
public byte[] KeyData;
public byte Expansion;
public long MuteTime;
public string OS;
public uint Recruiter;
public string OS;
public TimeSpan TimezoneOffset;
public bool IsRectuiter;
public AccountTypes Security;
public bool IsBanned;
+9 -1
View File
@@ -10,7 +10,9 @@ namespace Game.Networking
{
public class WorldSocketManager : SocketManager<WorldSocket>
{
public override bool StartNetwork(string bindIp, int port, int threadCount)
public static WorldSocketManager Instance { get; } = new WorldSocketManager();
public override bool StartNetwork(string bindIp, int port, int threadCount = 1)
{
_tcpNoDelay = ConfigMgr.GetDefaultValue("Network.TcpNodelay", true);
@@ -29,6 +31,7 @@ namespace Game.Networking
return false;
}
Acceptor.AsyncAcceptSocket(OnSocketAccept);
_instanceAcceptor.AsyncAcceptSocket(OnSocketOpen);
return true;
@@ -62,6 +65,11 @@ namespace Game.Networking
base.OnSocketOpen(sock);
}
static void OnSocketAccept(Socket sock)
{
Global.WorldSocketMgr.OnSocketOpen(sock);
}
AsyncAcceptor _instanceAcceptor;
int _socketSendBufferSize;
bool _tcpNoDelay;
+6 -2
View File
@@ -25,7 +25,7 @@ namespace Game
{
public partial class WorldSession : IDisposable
{
public WorldSession(uint id, string name, uint battlenetAccountId, WorldSocket sock, AccountTypes sec, Expansion expansion, long mute_time, string os, Locale locale, uint recruiter, bool isARecruiter)
public WorldSession(uint id, string name, uint battlenetAccountId, WorldSocket sock, AccountTypes sec, Expansion expansion, long mute_time, string os, TimeSpan timezoneOffset, Locale locale, uint recruiter, bool isARecruiter)
{
m_muteTime = mute_time;
AntiDOS = new DosProtection(this);
@@ -39,6 +39,7 @@ namespace Game
_os = os;
m_sessionDbcLocale = Global.WorldMgr.GetAvailableDbcLocale(locale);
m_sessionDbLocaleIndex = locale;
_timezoneOffset = timezoneOffset;
recruiterId = recruiter;
isRecruiter = isARecruiter;
expireTime = 60000; // 1 min after socket loss, session is deleted
@@ -897,6 +898,8 @@ namespace Game
public Locale GetSessionDbcLocale() { return m_sessionDbcLocale; }
public Locale GetSessionDbLocaleIndex() { return m_sessionDbLocaleIndex; }
public TimeSpan GetTimezoneOffset() { return _timezoneOffset; }
public uint GetLatency() { return m_latency; }
public void SetLatency(uint latency) { m_latency = latency; }
public void ResetTimeOutTime(bool onlyActive)
@@ -956,6 +959,7 @@ namespace Game
bool m_playerSave;
Locale m_sessionDbcLocale;
Locale m_sessionDbLocaleIndex;
TimeSpan _timezoneOffset;
uint m_latency;
AccountData[] _accountData = new AccountData[(int)AccountDataTypes.Max];
uint[] tutorials = new uint[SharedConst.MaxAccountTutorialValues];
@@ -1141,7 +1145,7 @@ namespace Game
stmt.AddValue(0, battlenetAccountId);
SetQuery(AccountInfoQueryLoad.Mounts, stmt);
stmt = LoginDatabase.GetPreparedStatement(LoginStatements.SelBnetCharacterCountsByAccountId);
stmt = LoginDatabase.GetPreparedStatement(LoginStatements.SEL_BNET_CHARACTER_COUNTS_BY_ACCOUNT_ID);
stmt.AddValue(0, accountId);
SetQuery(AccountInfoQueryLoad.GlobalRealmCharacterCounts, stmt);
+12 -4
View File
@@ -3,11 +3,15 @@
using Bgs.Protocol.GameUtilities.V1;
using Framework.Constants;
using Framework.IO;
using Framework.Web;
using Framework.Serialization;
using Framework.Web.Rest.Realmlist;
using Game.Services;
using Google.Protobuf;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
namespace Game
{
@@ -90,7 +94,11 @@ namespace Game
countEntry.Count = characterCount.Value;
realmCharacterCounts.Counts.Add(countEntry);
}
compressed = Json.Deflate("JSONRealmCharacterCountList", realmCharacterCounts);
var jsonData = Encoding.UTF8.GetBytes("JSONRealmCharacterCountList:" + JsonSerializer.Serialize(realmCharacterCounts) + "\0");
var compressedData = ZLib.Compress(jsonData);
compressed = BitConverter.GetBytes(jsonData.Length).Combine(compressedData);
attribute = new Bgs.Protocol.Attribute();
attribute.Name = "Param_CharacterCountList";
@@ -105,9 +113,9 @@ namespace Game
var realmAddress = Params.LookupByKey("Param_RealmAddress");
if (realmAddress != null)
return Global.RealmMgr.JoinRealm((uint)realmAddress.UintValue, Global.WorldMgr.GetRealm().Build, System.Net.IPAddress.Parse(GetRemoteAddress()), GetRealmListSecret(),
GetSessionDbcLocale(), GetOS(), GetAccountName(), response);
GetSessionDbcLocale(), GetOS(), GetTimezoneOffset(), GetAccountName(), response);
return BattlenetRpcErrorCode.Ok;
}
}
}
}