OregonCore  revision fb2a440-git
Your Favourite TBC server
AuthSocket.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of the OregonCore Project. See AUTHORS file for Copyright information
3  *
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License as published by the
6  * Free Software Foundation; either version 2 of the License, or (at your
7  * option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12  * more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program. If not, see <http://www.gnu.org/licenses/>.
16  */
17 
18 #include "Common.h"
19 #include "Database/DatabaseEnv.h"
20 #include "Config/Config.h"
21 #include "Log.h"
22 #include "RealmList.h"
23 #include "AuthSocket.h"
24 #include "AuthCodes.h"
25 #include "PatchHandler.h"
26 
27 #include <openssl/md5.h>
28 //#include "Util.h" -- for commented utf8ToUpperOnlyLatin
29 
30 #include <ace/OS_NS_unistd.h>
31 #include <ace/OS_NS_fcntl.h>
32 #include <ace/OS_NS_sys_stat.h>
33 
35 
36 // GCC have alternative #pragma pack(N) syntax and old gcc version not support pack(push,N), also any gcc version not support it at some paltform
37 #if defined( __GNUC__ )
38 #pragma pack(1)
39 #else
40 #pragma pack(push,1)
41 #endif
42 
43 typedef struct AUTH_LOGON_CHALLENGE_C
44 {
54  uint8 os[4];
59  uint8 I[1];
61 
62 //typedef sAuthLogonChallenge_C sAuthReconnectChallenge_C;
63 /*
64 typedef struct
65 {
66  uint8 cmd;
67  uint8 error;
68  uint8 unk2;
69  uint8 B[32];
70  uint8 g_len;
71  uint8 g[1];
72  uint8 N_len;
73  uint8 N[32];
74  uint8 s[32];
75  uint8 unk3[16];
76 } sAuthLogonChallenge_S;
77 */
78 
79 typedef struct AUTH_LOGON_PROOF_C
80 {
82  uint8 A[32];
83  uint8 M1[20];
84  uint8 crc_hash[20];
86  uint8 securityFlags; // 0x00-0x04
88 /*
89 typedef struct
90 {
91  uint16 unk1;
92  uint32 unk2;
93  uint8 unk3[4];
94  uint16 unk4[20];
95 } sAuthLogonProofKey_C;
96 */
97 typedef struct AUTH_LOGON_PROOF_S
98 {
101  uint8 M2[20];
106 
108 {
111  uint8 M2[20];
112  //uint32 unk1;
114  //uint16 unk3;
116 
118 {
120  uint8 R1[16];
121  uint8 R2[20];
122  uint8 R3[20];
125 
126 typedef struct XFER_INIT
127 {
128  uint8 cmd; // XFER_INITIATE
129  uint8 fileNameLen; // strlen(fileName);
130  uint8 fileName[5]; // fileName[fileNameLen]
131  uint64 file_size; // file size (bytes)
132  uint8 md5[MD5_DIGEST_LENGTH]; // MD5
133 } XFER_INIT;
134 
135 typedef struct AuthHandler
136 {
139  bool (AuthSocket::*handler)(void);
140 } AuthHandler;
141 
142 // GCC have alternative #pragma pack() syntax and old gcc version not support pack(pop), also any gcc version not support it at some paltform
143 #if defined( __GNUC__ )
144 #pragma pack()
145 #else
146 #pragma pack(pop)
147 #endif
148 
150 {
159 };
160 
161 #define AUTH_TOTAL_COMMANDS sizeof(table)/sizeof(AuthHandler)
162 
163 // Constructor - set the N and g values for SRP6
165 {
166  N.SetHexStr("894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7");
167  g.SetDword(7);
168  _status = STATUS_CHALLENGE;
169 
170  _accountSecurityLevel = SEC_PLAYER;
171 
172  _build = 0;
173  patch_ = ACE_INVALID_HANDLE;
174 }
175 
176 // Close patch file descriptor before leaving
178 {
179  if (patch_ != ACE_INVALID_HANDLE)
180  ACE_OS::close(patch_);
181 }
182 
183 // Accept the connection and set the s random value for SRP6
185 {
186  sLog.outBasic("'%s' Accepting connection", getRemoteAddress().c_str());
187 }
188 
189 // Read the packet from the client
191 {
192  #define MAX_AUTH_LOGON_CHALLENGES_IN_A_ROW 3
193  uint32 challengesInARow = 0;
194 
195  uint8 _cmd;
196  while (1)
197  {
198  if(!recv_soft((char*)&_cmd, 1))
199  return;
200 
201  if (_cmd == CMD_AUTH_LOGON_CHALLENGE)
202  {
203  ++challengesInARow;
204  if (challengesInARow == MAX_AUTH_LOGON_CHALLENGES_IN_A_ROW)
205  {
206  sLog.outError("Got %u CMD_AUTH_LOGON_CHALLENGE in a row from '%s', possible ongoing DoS", challengesInARow, getRemoteAddress().c_str());
207  close_connection();
208  return;
209  }
210  }
211 
212  size_t i;
213 
214  // Circle through known commands and call the correct command handler
215  for (i = 0; i < AUTH_TOTAL_COMMANDS; ++i)
216  {
217  if ((uint8)table[i].cmd == _cmd && table[i].status == _status)
218  {
219  DEBUG_LOG("[Auth] got data for cmd %u recv length %u",
220  (uint32)_cmd, (uint32)recv_len());
221 
222  if (!(*this.*table[i].handler)())
223  {
224  DEBUG_LOG("Command handler failed for cmd %u recv length %u",
225  (uint32)_cmd, (uint32)recv_len());
226 
227  return;
228  }
229  break;
230  }
231  }
232 
233  // Report unknown packets in the error log
234  if (i == AUTH_TOTAL_COMMANDS)
235  {
236  sLog.outError("[Auth] got unknown packet from '%s'. Kicking.", getRemoteAddress().c_str());
237  ACE_OS::close(patch_); // kick
238  patch_ = ACE_INVALID_HANDLE;
239  return;
240  }
241  }
242 }
243 
244 // Make the SRP6 calculation from hash in dB
245 void AuthSocket::_SetVSFields(const std::string& rI)
246 {
247  s.SetRand(s_BYTE_SIZE * 8);
248 
249  BigNumber I;
250  I.SetHexStr(rI.c_str());
251 
252  // In case of leading zeros in the rI hash, restore them
253  uint8 mDigest[SHA_DIGEST_LENGTH];
254  memset(mDigest, 0, SHA_DIGEST_LENGTH);
255  if (I.GetNumBytes() <= SHA_DIGEST_LENGTH)
256  memcpy(mDigest, I.AsByteArray(), I.GetNumBytes());
257 
258  std::reverse(mDigest, mDigest + SHA_DIGEST_LENGTH);
259 
260  Sha1Hash sha;
261  sha.UpdateData(s.AsByteArray(), s.GetNumBytes());
262  sha.UpdateData(mDigest, SHA_DIGEST_LENGTH);
263  sha.Finalize();
264  BigNumber x;
265  x.SetBinary(sha.GetDigest(), sha.GetLength());
266  v = g.ModExp(x, N);
267  // No SQL injection (username escaped)
268  const char* v_hex, *s_hex;
269  v_hex = v.AsHexStr();
270  s_hex = s.AsHexStr();
271  LoginDatabase.PExecute("UPDATE account SET v = '%s', s = '%s' WHERE username = '%s'", v_hex, s_hex, _safelogin.c_str() );
272  OPENSSL_free((void*)v_hex);
273  OPENSSL_free((void*)s_hex);
274 }
275 
277 {
278  switch (_build)
279  {
280  case 5875: // 1.12.1
281  case 6005: // 1.12.2
282  {
284  memcpy(proof.M2, sha.GetDigest(), 20);
285  proof.cmd = CMD_AUTH_LOGON_PROOF;
286  proof.error = 0;
287  proof.unk2 = 0x00;
288 
289  send((char*)&proof, sizeof(proof));
290  break;
291  }
292  case 8606: // 2.4.3
293  case 10505: // 3.2.2a
294  case 11159: // 3.3.0a
295  case 11403: // 3.3.2
296  case 11723: // 3.3.3a
297  case 12340: // 3.3.5a
298  default: // or later
299  {
300  sAuthLogonProof_S proof;
301  memcpy(proof.M2, sha.GetDigest(), 20);
302  proof.cmd = CMD_AUTH_LOGON_PROOF;
303  proof.error = 0;
304  proof.unk1 = 0x00800000;
305  proof.unk2 = 0x00;
306  proof.unk3 = 0x00;
307 
308  send((char*)&proof, sizeof(proof));
309  break;
310  }
311  }
312 }
313 
314 // Logon Challenge command handler
316 {
317  DEBUG_LOG("Entering _HandleLogonChallenge");
318  if (recv_len() < sizeof(sAuthLogonChallenge_C))
319  return false;
320 
321  // Read the first 4 bytes (header) to get the length of the remaining of the packet
322  std::vector<uint8> buf;
323  buf.resize(4);
324 
325  recv((char*)&buf[0], 4);
326 
327  EndianConvert(*((uint16*)(&buf[0])));
328  uint16 remaining = ((sAuthLogonChallenge_C*)&buf[0])->size;
329  DEBUG_LOG("[AuthChallenge] got header, body is %#04x bytes", remaining);
330 
331  if ((remaining < sizeof(sAuthLogonChallenge_C) - buf.size()) || (recv_len() < remaining))
332  return false;
333 
334  _status = STATUS_CLOSED;
335 
336  // No big fear of memory outage (size is int16, i.e. < 65536)
337  buf.resize(remaining + buf.size() + 1);
338  buf[buf.size() - 1] = 0;
340 
341  // Read the remaining of the packet
342  recv((char*)&buf[4], remaining);
343  DEBUG_LOG("[AuthChallenge] got full packet, %#04x bytes", ch->size);
344  DEBUG_LOG("[AuthChallenge] name(%d): '%s'", ch->I_len, ch->I);
345 
346  // BigEndian code, nop in little endian case
347  // size already converted
348  EndianConvert(ch->gamename[0]);
349  EndianConvert(ch->build);
350  EndianConvert(ch->platform[0]);
351  EndianConvert(ch->os[0]);
352  EndianConvert(ch->country[0]);
354  EndianConvert(ch->ip);
355 
356  ByteBuffer pkt;
357 
358  _login = (const char*)ch->I;
359  _build = ch->build;
360 
361  _os = (const char*)ch->os;
362 
363  if (_os.size() > 4)
364  return false;
365 
366  // Restore string order as its byte order is reversed
367  std::reverse(_os.begin(), _os.end());
368 
369  // Escape the user login to avoid further SQL injection
370  // Memory will be freed on AuthSocket object destruction
371  _safelogin = _login;
372  LoginDatabase.escape_string(_safelogin);
373 
375  pkt << (uint8) 0x00;
376 
377  // Verify that this IP is not in the ip_banned table
378  // No SQL injection possible (paste the IP address as passed by the socket)
379  std::string address = getRemoteAddress();
380  LoginDatabase.escape_string(address);
381  QueryResult_AutoPtr result = LoginDatabase.PQuery("SELECT unbandate FROM ip_banned WHERE "
382  // permanent still banned
383  "(unbandate = bandate OR unbandate > UNIX_TIMESTAMP()) AND ip = '%s'", address.c_str());
384  if (result)
385  {
386  pkt << (uint8)WOW_FAIL_BANNED;
387  sLog.outBasic("'%s' [AuthChallenge] Banned ip tries to login!", getRemoteAddress().c_str());
388 
389  }
390  else
391  {
392  // Get the account details from the account table
393  // No SQL injection (escaped user name)
394 
395  result =
396  LoginDatabase.PQuery("SELECT a.sha_pass_hash,a.id,a.locked,a.last_ip,aa.gmlevel,a.v,a.s "
397  "FROM account a "
398  "LEFT JOIN account_access aa "
399  "ON (a.id = aa.id) "
400  "WHERE a.username = '%s'", _safelogin.c_str ());
401  if (result)
402  {
403  // If the IP is 'locked', check that the player comes indeed from the correct IP address
404  bool locked = false;
405  if ((*result)[2].GetUInt8() == 1) // if ip is locked
406  {
407  DEBUG_LOG("[AuthChallenge] Account '%s' is locked to IP - '%s'", _login.c_str(), (*result)[3].GetString());
408  DEBUG_LOG("[AuthChallenge] Player address is '%s'", getRemoteAddress().c_str());
409  if ( strcmp((*result)[3].GetString(), getRemoteAddress().c_str()) )
410  {
411  DEBUG_LOG("[AuthChallenge] Account IP differs");
413  locked = true;
414  }
415  else
416  DEBUG_LOG("[AuthChallenge] Account IP matches");
417  }
418  else
419  DEBUG_LOG("[AuthChallenge] Account '%s' is not locked to ip", _login.c_str());
420 
421  if (!locked)
422  {
423  // If the account is banned, reject the logon attempt
424  QueryResult_AutoPtr banresult = LoginDatabase.PQuery("SELECT bandate,unbandate FROM account_banned WHERE "
425  "id = %u AND active = 1 AND (unbandate > UNIX_TIMESTAMP() OR unbandate = bandate)", (*result)[1].GetUInt32());
426  if (banresult)
427  {
428  if ((*banresult)[0].GetUInt64() == (*banresult)[1].GetUInt64())
429  {
430  pkt << (uint8) WOW_FAIL_BANNED;
431  sLog.outBasic("[AuthChallenge] Banned account %s tries to login!", _login.c_str ());
432  }
433  else
434  {
435  pkt << (uint8) WOW_FAIL_SUSPENDED;
436  sLog.outBasic("[AuthChallenge] Temporarily banned account %s tries to login!", _login.c_str ());
437  }
438  }
439  else
440  {
441  // Get the password from the account table, upper it, and make the SRP6 calculation
442  std::string rI = (*result)[0].GetCppString();
443 
444  // Don't calculate (v, s) if there are already some in the database
445  std::string databaseV = (*result)[5].GetCppString();
446  std::string databaseS = (*result)[6].GetCppString();
447 
448  DEBUG_LOG("database authentication values: v='%s' s='%s'", databaseV.c_str(), databaseS.c_str());
449 
450  // multiply with 2, bytes are stored as hexstring
451  if (databaseV.size() != s_BYTE_SIZE * 2 || databaseS.size() != s_BYTE_SIZE * 2)
452  _SetVSFields(rI);
453  else
454  {
455  s.SetHexStr(databaseS.c_str());
456  v.SetHexStr(databaseV.c_str());
457  }
458 
459  b.SetRand(19 * 8);
460  BigNumber gmod = g.ModExp(b, N);
461  B = ((v * 3) + gmod) % N;
462 
463  ASSERT(gmod.GetNumBytes() <= 32);
464 
465  BigNumber unk3;
466  unk3.SetRand(16 * 8);
467 
468  // Fill the response packet with the result
469  pkt << uint8(WOW_SUCCESS);
470 
471  // B may be calculated < 32B so we force minimal length to 32B
472  pkt.append(B.AsByteArray(32), 32); // 32 bytes
473  pkt << uint8(1);
474  pkt.append(g.AsByteArray(), 1);
475  pkt << uint8(32);
476  pkt.append(N.AsByteArray(32), 32);
477  pkt.append(s.AsByteArray(), s.GetNumBytes());// 32 bytes
478  pkt.append(unk3.AsByteArray(16), 16);
479  uint8 securityFlags = 0;
480  pkt << uint8(securityFlags); // security flags (0x0...0x04)
481 
482  if (securityFlags & 0x01) // PIN input
483  {
484  pkt << uint32(0);
485  pkt << uint64(0) << uint64(0); // 16 bytes hash?
486  }
487 
488  if (securityFlags & 0x02) // Matrix input
489  {
490  pkt << uint8(0);
491  pkt << uint8(0);
492  pkt << uint8(0);
493  pkt << uint8(0);
494  pkt << uint64(0);
495  }
496 
497  if (securityFlags & 0x04) // Security token input
498  pkt << uint8(1);
499 
500  uint8 secLevel = (*result)[4].GetUInt8();
501  _accountSecurityLevel = secLevel <= SEC_ADMINISTRATOR ? AccountTypes(secLevel) : SEC_ADMINISTRATOR;
502 
503  _localizationName.resize(4);
504  for (int i = 0; i < 4; ++i)
505  _localizationName[i] = ch->country[4 - i - 1];
506 
507  sLog.outBasic("[AuthChallenge] account %s is using '%c%c%c%c' locale (%u)", _login.c_str (), ch->country[3], ch->country[2], ch->country[1], ch->country[0], GetLocaleByName(_localizationName));
508 
509  _status = STATUS_LOGON_PROOF;
510  }
511  }
512  }
513  else // no account
515  }
516  send((char const*)pkt.contents(), pkt.size());
517  return true;
518 }
519 
520 // Logon Proof command handler
522 {
523  DEBUG_LOG("Entering _HandleLogonProof");
524  // Read the packet
526  if (!recv((char*)&lp, sizeof(sAuthLogonProof_C)))
527  return false;
528 
529  // Check if the client has one of the expected version numbers
530  bool valid_version = FindBuildInfo(_build) != NULL;
531 
532  // If the client has no valid version
533  if (!valid_version)
534  {
535  if (this->patch_ != ACE_INVALID_HANDLE)
536  return false;
537 
538  // Check if we have the apropriate patch on the disk
539  // file looks like: 65535enGB.mpq
540  char tmp[64];
541 
542  snprintf(tmp, 24, "./patches/%d%s.mpq", _build, _localizationName.c_str());
543 
544  char filename[PATH_MAX];
545  if (ACE_OS::realpath(tmp, filename) != NULL)
546  patch_ = ACE_OS::open(filename, GENERIC_READ | FILE_FLAG_SEQUENTIAL_SCAN);
547 
548  if (patch_ == ACE_INVALID_HANDLE)
549  {
550  // no patch found
551  ByteBuffer pkt;
553  pkt << (uint8) 0x00;
555  DEBUG_LOG("[AuthChallenge] %u is not a valid client version!", _build);
556  DEBUG_LOG("[AuthChallenge] Patch %s not found", tmp);
557  send((char const*)pkt.contents(), pkt.size());
558  return true;
559  }
560 
561  XFER_INIT xferh;
562 
563  ACE_OFF_T file_size = ACE_OS::filesize(this->patch_);
564 
565  if (file_size == -1)
566  {
567  close_connection();
568  return false;
569  }
570 
571  if (!PatchCache::instance()->GetHash(tmp, (uint8*)&xferh.md5))
572  {
573  // calculate patch md5, happens if patch was added while realmd was running
575  PatchCache::instance()->GetHash(tmp, (uint8*)&xferh.md5);
576  }
577 
579  send((const char*)data, sizeof(data));
580 
581  memcpy(&xferh, "0\x05Patch", 7);
582  xferh.cmd = CMD_XFER_INITIATE;
583  xferh.file_size = file_size;
584 
585  send((const char*)&xferh, sizeof(xferh));
586  return true;
587  }
588 
589  // Continue the SRP6 calculation based on data received from the client
590  BigNumber A;
591 
592  A.SetBinary(lp.A, 32);
593 
594  // SRP safeguard: abort if A==0 or A % N == 0
595  if (A.isZero() || (A % N).isZero())
596  return false;
597 
598  Sha1Hash sha;
599  sha.UpdateBigNumbers(&A, &B, NULL);
600  sha.Finalize();
601  BigNumber u;
602  u.SetBinary(sha.GetDigest(), 20);
603  BigNumber S = (A * (v.ModExp(u, N))).ModExp(b, N);
604 
605  uint8 t[32];
606  uint8 t1[16];
607  uint8 vK[40];
608  memcpy(t, S.AsByteArray(32), 32);
609  for (int i = 0; i < 16; ++i)
610  t1[i] = t[i * 2];
611  sha.Initialize();
612  sha.UpdateData(t1, 16);
613  sha.Finalize();
614  for (int i = 0; i < 20; ++i)
615  vK[i * 2] = sha.GetDigest()[i];
616  for (int i = 0; i < 16; ++i)
617  t1[i] = t[i * 2 + 1];
618  sha.Initialize();
619  sha.UpdateData(t1, 16);
620  sha.Finalize();
621  for (int i = 0; i < 20; ++i)
622  vK[i * 2 + 1] = sha.GetDigest()[i];
623  K.SetBinary(vK, 40);
624 
625  uint8 hash[20];
626 
627  sha.Initialize();
628  sha.UpdateBigNumbers(&N, NULL);
629  sha.Finalize();
630  memcpy(hash, sha.GetDigest(), 20);
631  sha.Initialize();
632  sha.UpdateBigNumbers(&g, NULL);
633  sha.Finalize();
634  for (int i = 0; i < 20; ++i)
635  hash[i] ^= sha.GetDigest()[i];
636  BigNumber t3;
637  t3.SetBinary(hash, 20);
638 
639  sha.Initialize();
640  sha.UpdateData(_login);
641  sha.Finalize();
642  uint8 t4[SHA_DIGEST_LENGTH];
643  memcpy(t4, sha.GetDigest(), SHA_DIGEST_LENGTH);
644 
645  sha.Initialize();
646  sha.UpdateBigNumbers(&t3, NULL);
647  sha.UpdateData(t4, SHA_DIGEST_LENGTH);
648  sha.UpdateBigNumbers(&s, &A, &B, &K, NULL);
649  sha.Finalize();
650  BigNumber M;
651  M.SetBinary(sha.GetDigest(), 20);
652 
653  // Check if SRP6 results match (password is correct), else send an error
654  if (!memcmp(M.AsByteArray(), lp.M1, 20))
655  {
656  sLog.outBasic("User '%s' successfully authenticated", _login.c_str());
657 
658  // Update the sessionkey, last_ip, last login time and reset number of failed logins in the account table for this account
659  // No SQL injection (escaped user name) and IP address as received by socket
660  const char* K_hex = K.AsHexStr();
661  LoginDatabase.PExecute("UPDATE account SET sessionkey = '%s', last_ip = '%s', last_login = NOW(), locale = '%u', os = '%s', failed_logins = 0 WHERE username = '%s'", K_hex, getRemoteAddress().c_str(), GetLocaleByName(_localizationName), _os.c_str(), _safelogin.c_str() );
662  OPENSSL_free((void*)K_hex);
663 
664  // Finish SRP6 and send the final result to the client
665  sha.Initialize();
666  sha.UpdateBigNumbers(&A, &M, &K, NULL);
667  sha.Finalize();
668 
669  SendProof(sha);
670 
671  // Set _status to authed
672  _status = STATUS_AUTHED;
673  }
674  else
675  {
676  if (_build > 6005) // > 1.12.2
677  {
678  char data[4] = { CMD_AUTH_LOGON_PROOF, WOW_FAIL_UNKNOWN_ACCOUNT, 3, 0};
679  send(data, sizeof(data));
680  }
681  else
682  {
683  // 1.x not react incorrectly at 4-byte message use 3 as real error
685  send(data, sizeof(data));
686  }
687  sLog.outBasic("[AuthChallenge] account %s tried to login with wrong password!", _login.c_str ());
688 
689  uint32 MaxWrongPassCount = sConfig.GetIntDefault("WrongPass.MaxCount", 0);
690  if (MaxWrongPassCount > 0)
691  {
692  // Increment number of failed logins by one and if it reaches the limit temporarily ban that account or IP
693  LoginDatabase.PExecute("UPDATE account SET failed_logins = failed_logins + 1 WHERE username = '%s'", _safelogin.c_str());
694 
695  if (QueryResult_AutoPtr loginfail = LoginDatabase.PQuery("SELECT id, failed_logins FROM account WHERE username = '%s'", _safelogin.c_str()))
696  {
697  Field* fields = loginfail->Fetch();
698  uint32 failed_logins = fields[1].GetUInt32();
699 
700  if ( failed_logins >= MaxWrongPassCount )
701  {
702  uint32 WrongPassBanTime = sConfig.GetIntDefault("WrongPass.BanTime", 600);
703  bool WrongPassBanType = sConfig.GetBoolDefault("WrongPass.BanType", false);
704 
705  if (WrongPassBanType)
706  {
707  uint32 acc_id = fields[0].GetUInt32();
708  LoginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()+'%u','Oregon realmd','Failed login autoban',1)",
709  acc_id, WrongPassBanTime);
710  sLog.outBasic("[AuthChallenge] account %s got banned for '%u' seconds because it failed to authenticate '%u' times",
711  _login.c_str(), WrongPassBanTime, failed_logins);
712  }
713  else
714  {
715  std::string current_ip = getRemoteAddress();
716  LoginDatabase.escape_string(current_ip);
717  LoginDatabase.PExecute("INSERT INTO ip_banned VALUES ('%s',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()+'%u','Oregon realmd','Failed login autoban')",
718  current_ip.c_str(), WrongPassBanTime);
719  sLog.outBasic("[AuthChallenge] IP %s got banned for '%u' seconds because account %s failed to authenticate '%u' times",
720  current_ip.c_str(), WrongPassBanTime, _login.c_str(), failed_logins);
721  }
722  }
723  }
724  }
725  }
726  return true;
727 }
728 
729 // Reconnect Challenge command handler
731 {
732  DEBUG_LOG("Entering _HandleReconnectChallenge");
733  if (recv_len() < sizeof(sAuthLogonChallenge_C))
734  return false;
735 
736  // Read the first 4 bytes (header) to get the length of the remaining of the packet
737  std::vector<uint8> buf;
738  buf.resize(4);
739 
740  recv((char*)&buf[0], 4);
741 
742  EndianConvert(*((uint16*)(&buf[0])));
743  uint16 remaining = ((sAuthLogonChallenge_C*)&buf[0])->size;
744  DEBUG_LOG("[ReconnectChallenge] got header, body is %#04x bytes", remaining);
745 
746  if ((remaining < sizeof(sAuthLogonChallenge_C) - buf.size()) || (recv_len() < remaining))
747  return false;
748 
749  _status = STATUS_CLOSED;
750 
751  // No big fear of memory outage (size is int16, i.e. < 65536)
752  buf.resize(remaining + buf.size() + 1);
753  buf[buf.size() - 1] = 0;
755 
756  // Read the remaining of the packet
757  recv((char*)&buf[4], remaining);
758  DEBUG_LOG("[ReconnectChallenge] got full packet, %#04x bytes", ch->size);
759  DEBUG_LOG("[ReconnectChallenge] name(%d): '%s'", ch->I_len, ch->I);
760 
761  _login = (const char*)ch->I;
762 
763  _safelogin = _login;
764  LoginDatabase.escape_string(_safelogin);
765 
766  EndianConvert(ch->build);
767  _build = ch->build;
768 
769  _os = (const char*)ch->os;
770 
771  if (_os.size() > 4)
772  return false;
773 
774  // Restore string order as its byte order is reversed
775  std::reverse(_os.begin(), _os.end());
776 
777  QueryResult_AutoPtr result = LoginDatabase.PQuery ("SELECT sessionkey FROM account WHERE username = '%s'", _safelogin.c_str ());
778 
779  // Stop if the account is not found
780  if (!result)
781  {
782  sLog.outError("[ERROR] user %s tried to login and we cannot find his session key in the database.", _login.c_str());
783  close_connection();
784  return false;
785  }
786 
787  Field* fields = result->Fetch ();
788  K.SetHexStr (fields[0].GetString ());
789 
790  _status = STATUS_RECON_PROOF;
791 
792  // Sending response
793  ByteBuffer pkt;
795  pkt << (uint8) 0x00;
796  _reconnectProof.SetRand(16 * 8);
797  pkt.append(_reconnectProof.AsByteArray(16), 16); // 16 bytes random
798  pkt << (uint64) 0x00 << (uint64) 0x00; // 16 bytes zeros
799  send((char const*)pkt.contents(), pkt.size());
800  return true;
801 }
802 
803 // Reconnect Proof command handler
805 {
806  DEBUG_LOG("Entering _HandleReconnectProof");
807  // Read the packet
809  if (!recv((char*)&lp, sizeof(sAuthReconnectProof_C)))
810  return false;
811 
812  _status = STATUS_CLOSED;
813 
814  if (_login.empty() || !_reconnectProof.GetNumBytes() || !K.GetNumBytes())
815  return false;
816 
817  BigNumber t1;
818  t1.SetBinary(lp.R1, 16);
819 
820  Sha1Hash sha;
821  sha.Initialize();
822  sha.UpdateData(_login);
823  sha.UpdateBigNumbers(&t1, &_reconnectProof, &K, NULL);
824  sha.Finalize();
825 
826  if (!memcmp(sha.GetDigest(), lp.R2, SHA_DIGEST_LENGTH))
827  {
828  // Sending response
829  ByteBuffer pkt;
831  pkt << (uint8) 0x00;
832  pkt << (uint16) 0x00; // 2 bytes zeros
833  send((char const*)pkt.contents(), pkt.size());
834 
835  // Set _status to authed
836  _status = STATUS_AUTHED;
837 
838  return true;
839  }
840  else
841  {
842  sLog.outError("[ERROR] user %s tried to login, but session invalid.", _login.c_str());
843  close_connection();
844  return false;
845  }
846 }
847 
848 // Realm List command handler
850 {
851  DEBUG_LOG("Entering _HandleRealmList");
852  if (recv_len() < 5)
853  return false;
854 
855  recv_skip(5);
856 
857  // Get the user id (else close the connection)
858  // No SQL injection (escaped user name)
859 
860  QueryResult_AutoPtr result = LoginDatabase.PQuery("SELECT id,sha_pass_hash FROM account WHERE username = '%s'", _safelogin.c_str());
861  if (!result)
862  {
863  sLog.outError("[ERROR] user %s tried to login and we cannot find him in the database.", _login.c_str());
864  close_connection();
865  return false;
866  }
867 
868  uint32 id = (*result)[0].GetUInt32();
869  std::string rI = (*result)[1].GetCppString();
870 
871  // Update realm list if need
872  sRealmList->UpdateIfNeed();
873 
874  // Circle through realms in the RealmList and construct the return packet (including # of user characters in each realm)
875  ByteBuffer pkt;
876  LoadRealmlist(pkt, id);
877 
878  ByteBuffer hdr;
879  hdr << (uint8) CMD_REALM_LIST;
880  hdr << (uint16)pkt.size();
881  hdr.append(pkt);
882 
883  send((char const*)hdr.contents(), hdr.size());
884 
885  return true;
886 }
887 
889 {
890  switch (_build)
891  {
892  case 5875: // 1.12.1
893  case 6005: // 1.12.2
894  {
895  pkt << uint32(0);
896  pkt << uint8(sRealmList->size());
897 
898  for (RealmList::RealmMap::const_iterator i = sRealmList->begin(); i != sRealmList->end(); ++i)
899  {
900  uint8 AmountOfCharacters;
901 
902  // No SQL injection. id of realm is controlled by the database.
903  QueryResult_AutoPtr result = LoginDatabase.PQuery( "SELECT numchars FROM realmcharacters WHERE realmid = '%d' AND acctid='%u'", i->second.m_ID, acctid);
904  if ( result )
905  {
906  Field* fields = result->Fetch();
907  AmountOfCharacters = fields[0].GetUInt8();
908  }
909  else
910  AmountOfCharacters = 0;
911 
912  bool ok_build = std::find(i->second.realmbuilds.begin(), i->second.realmbuilds.end(), _build) != i->second.realmbuilds.end();
913 
914  RealmBuildInfo const* buildInfo = ok_build ? FindBuildInfo(_build) : NULL;
915  if (!buildInfo)
916  buildInfo = &i->second.realmBuildInfo;
917 
918  RealmFlags realmflags = i->second.realmflags;
919 
920  // 1.x clients not support explicitly REALM_FLAG_SPECIFYBUILD, so manually form similar name as show in more recent clients
921  std::string name = i->first;
922  if (realmflags & REALM_FLAG_SPECIFYBUILD)
923  {
924  char buf[20];
925  snprintf(buf, 20, " (%d,%d,%d)", buildInfo->major_version, buildInfo->minor_version, buildInfo->bugfix_version);
926  name += buf;
927  }
928 
929  // Show offline state for unsupported client builds and locked realms (1.x clients not support locked state show)
930  if (!ok_build || (i->second.allowedSecurityLevel >= _accountSecurityLevel))
931  realmflags = RealmFlags(realmflags | REALM_FLAG_OFFLINE);
932 
933  pkt << uint32(i->second.icon); // realm type
934  pkt << uint8(realmflags); // realmflags
935  pkt << name; // name
936  pkt << i->second.address; // address
937  pkt << float(i->second.populationLevel);
938  pkt << uint8(AmountOfCharacters);
939  pkt << uint8(i->second.timezone); // realm category
940  pkt << uint8(0x00); // unk, may be realm number/id?
941  }
942 
943  pkt << uint8(0x00);
944  pkt << uint8(0x02);
945  break;
946  }
947 
948  case 8606: // 2.4.3
949  case 10505: // 3.2.2a
950  case 11159: // 3.3.0a
951  case 11403: // 3.3.2
952  case 11723: // 3.3.3a
953  case 12340: // 3.3.5a
954  default: // and later
955  {
956  pkt << uint32(0);
957  pkt << uint16(sRealmList->size());
958 
959  for (RealmList::RealmMap::const_iterator i = sRealmList->begin(); i != sRealmList->end(); ++i)
960  {
961  uint8 AmountOfCharacters;
962 
963  // No SQL injection. id of realm is controlled by the database.
964  QueryResult_AutoPtr result = LoginDatabase.PQuery("SELECT numchars FROM realmcharacters WHERE realmid = '%d' AND acctid='%u'", i->second.m_ID, acctid);
965  if ( result )
966  {
967  Field* fields = result->Fetch();
968  AmountOfCharacters = fields[0].GetUInt8();
969  }
970  else
971  AmountOfCharacters = 0;
972 
973  bool ok_build = std::find(i->second.realmbuilds.begin(), i->second.realmbuilds.end(), _build) != i->second.realmbuilds.end();
974 
975  RealmBuildInfo const* buildInfo = ok_build ? FindBuildInfo(_build) : NULL;
976  if (!buildInfo)
977  buildInfo = &i->second.realmBuildInfo;
978 
979  uint8 lock = (i->second.allowedSecurityLevel > _accountSecurityLevel) ? 1 : 0;
980 
981  RealmFlags realmFlags = i->second.realmflags;
982 
983  // Show offline state for unsupported client builds
984  if (!ok_build)
985  realmFlags = RealmFlags(realmFlags | REALM_FLAG_OFFLINE);
986 
987  if (!buildInfo)
988  realmFlags = RealmFlags(realmFlags & ~REALM_FLAG_SPECIFYBUILD);
989 
990  pkt << uint8(i->second.icon); // realm type (this is second column in Cfg_Configs.dbc)
991  pkt << uint8(lock); // flags, if 0x01, then realm locked
992  pkt << uint8(realmFlags); // see enum RealmFlags
993  pkt << i->first; // name
994  pkt << i->second.address; // address
995  pkt << float(i->second.populationLevel);
996  pkt << uint8(AmountOfCharacters);
997  pkt << uint8(i->second.timezone); // realm category (Cfg_Categories.dbc)
998  pkt << uint8(0x2C); // unk, may be realm number/id?
999 
1000  if (buildInfo && realmFlags & REALM_FLAG_SPECIFYBUILD)
1001  {
1002  pkt << uint8(buildInfo->major_version);
1003  pkt << uint8(buildInfo->minor_version);
1004  pkt << uint8(buildInfo->bugfix_version);
1005  pkt << uint16(_build);
1006  }
1007  }
1008 
1009  pkt << uint16(0x0010);
1010  break;
1011  }
1012  }
1013 }
1014 
1015 // Resume patch transfer
1017 {
1018  DEBUG_LOG("Entering _HandleXferResume");
1019 
1020  if (recv_len() < 9)
1021  return false;
1022 
1023  recv_skip(1);
1024 
1025  uint64 start_pos;
1026  recv((char*)&start_pos, 8);
1027 
1028  if (patch_ == ACE_INVALID_HANDLE)
1029  {
1030  close_connection();
1031  return false;
1032  }
1033 
1034  ACE_OFF_T file_size = ACE_OS::filesize(patch_);
1035 
1036  if (file_size == -1 || start_pos >= (uint64)file_size)
1037  {
1038  close_connection();
1039  return false;
1040  }
1041 
1042  if (ACE_OS::lseek(patch_, start_pos, SEEK_SET) == -1)
1043  {
1044  close_connection();
1045  return false;
1046  }
1047 
1048  InitPatch();
1049 
1050  return true;
1051 }
1052 
1053 // Cancel patch transfer
1055 {
1056  DEBUG_LOG("Entering _HandleXferCancel");
1057 
1058  recv_skip(1);
1059  close_connection();
1060 
1061  return true;
1062 }
1063 
1064 // Accept patch transfer
1066 {
1067  DEBUG_LOG("Entering _HandleXferAccept");
1068 
1069  recv_skip(1);
1070 
1071  InitPatch();
1072 
1073  return true;
1074 }
1075 
1077 {
1078  PatchHandler* handler = new PatchHandler(ACE_OS::dup(get_handle()), patch_);
1079 
1080  patch_ = ACE_INVALID_HANDLE;
1081 
1082  if (handler->open() == -1)
1083  {
1084  handler->close();
1085  close_connection();
1086  }
1087 }
1088 
void LoadPatchMD5(const char *)
Player authenticated.
Definition: Opcodes.h:1100
#define sConfig
Definition: Config.h:52
#define MAX_AUTH_LOGON_CHALLENGES_IN_A_ROW
void SendProof(Sha1Hash sha)
Definition: AuthSocket.cpp:276
You have applied a lock to your account. You can change your locked status by calling your account lo...
Definition: AuthCodes.h:70
#define snprintf
Definition: Common.h:129
const uint8 * contents() const
Definition: ByteBuffer.h:331
The information you have entered is not valid. Please check the spelling of the account name and pass...
Definition: AuthCodes.h:58
uint8 * AsByteArray(int minSize=0, bool reverse=true)
Definition: BigNumber.cpp:166
uint8 md5[MD5_DIGEST_LENGTH]
Definition: AuthSocket.cpp:132
void SetRand(int numbits)
Definition: BigNumber.cpp:71
int open(void *=0)
Downloading.
Definition: AuthCodes.h:64
int GetNumBytes(void)
Definition: BigNumber.cpp:151
QueryResult_AutoPtr PQuery(const char *format,...) ATTR_PRINTF(2
Definition: Database.cpp:400
AccountTypes
Definition: Common.h:188
This <game> account has been temporarily suspended. Please go to <site>/banned.html for further infor...
Definition: AuthCodes.h:66
bool _HandleXferResume()
RealmBuildInfo const * FindBuildInfo(uint16 _build)
Definition: RealmList.cpp:43
Definition: Field.h:24
bool _HandleLogonProof()
Definition: AuthSocket.cpp:521
void EndianConvert(T &val)
Definition: ByteConverter.h:48
struct AuthHandler AuthHandler
#define sLog
Log class singleton.
Definition: Log.h:187
unsigned long escape_string(char *to, const char *from, unsigned long length)
Definition: Database.cpp:212
struct XFER_INIT XFER_INIT
BigNumber ModExp(const BigNumber &bn1, const BigNumber &bn2)
Definition: BigNumber.cpp:139
LocaleConstant GetLocaleByName(const std::string &name)
Definition: Common.cpp:33
bool isZero() const
Definition: BigNumber.cpp:161
uint8 * GetDigest(void)
Definition: Sha1.h:41
struct AUTH_LOGON_CHALLENGE_C sAuthLogonChallenge_C
uint64 file_size
Definition: AuthSocket.cpp:131
int minor_version
Definition: RealmList.h:29
void SetBinary(const uint8 *bytes, int len)
Definition: BigNumber.cpp:59
ACE_UINT8 uint8
Definition: Define.h:73
void Finalize()
Definition: Sha1.cpp:61
void InitPatch()
bool _HandleLogonChallenge()
Definition: AuthSocket.cpp:315
void SetHexStr(const char *str)
Definition: BigNumber.cpp:66
void LoadRealmlist(ByteBuffer &pkt, uint32 acctid)
Definition: AuthSocket.cpp:888
static PatchCache * instance()
size_t size() const
Definition: ByteBuffer.h:336
const AuthHandler table[]
Definition: AuthSocket.cpp:149
void UpdateBigNumbers(BigNumber *bn0,...)
Definition: Sha1.cpp:41
void Initialize()
Definition: Sha1.cpp:56
#define DEBUG_LOG(...)
Definition: Log.h:194
struct AUTH_LOGON_PROOF_S_BUILD_6005 sAuthLogonProof_S_BUILD_6005
eAuthCmd cmd
Definition: AuthSocket.cpp:137
bool PExecute(const char *format,...) ATTR_PRINTF(2
Definition: Database.cpp:441
struct AUTH_RECONNECT_PROOF_C sAuthReconnectProof_C
struct AUTH_LOGON_PROOF_S sAuthLogonProof_S
void OnAccept()
Definition: AuthSocket.cpp:184
bool _HandleXferCancel()
ACE_UINT64 uint64
Definition: Define.h:70
int major_version
Definition: RealmList.h:28
void append(const std::string &str)
Definition: ByteBuffer.h:358
eAuthCmd
Definition: AuthCodes.h:21
This <game> account has been closed and is no longer available for use. Please go to <site>/banned...
Definition: AuthCodes.h:57
ACE_Refcounted_Auto_Ptr< QueryResult, ACE_Null_Mutex > QueryResult_AutoPtr
Definition: QueryResult.h:113
bool _HandleXferAccept()
int bugfix_version
Definition: RealmList.h:30
uint8 fileNameLen
Definition: AuthSocket.cpp:129
bool _HandleReconnectProof()
Definition: AuthSocket.cpp:804
#define sRealmList
Definition: RealmList.h:92
void UpdateData(const uint8 *dta, int len)
Definition: Sha1.cpp:31
#define ASSERT
Definition: Errors.h:29
uint32 status
Definition: AuthSocket.cpp:138
Unable to validate game version. This may be caused by file corruption or interference of another pro...
Definition: AuthCodes.h:63
DatabaseType LoginDatabase
Accessor to the realm/login database.
Definition: Main.cpp:55
void OnRead()
Definition: AuthSocket.cpp:190
struct AUTH_LOGON_PROOF_C sAuthLogonProof_C
ACE_UINT16 uint16
Definition: Define.h:72
ACE_UINT32 uint32
Definition: Define.h:71
int GetLength(void)
Definition: Sha1.h:45
RealmFlags
Definition: Common.h:198
#define AUTH_TOTAL_COMMANDS
Definition: AuthSocket.cpp:161
bool _HandleRealmList()
Definition: AuthSocket.cpp:849
Definition: Sha1.h:26
bool GetHash(const char *pat, ACE_UINT8 mymd5[MD5_DIGEST_LENGTH])
void _SetVSFields(const std::string &rI)
Definition: AuthSocket.cpp:245
bool _HandleReconnectChallenge()
Definition: AuthSocket.cpp:730