2
0

LoginController.java 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  1. /*
  2. * This program is free software: you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation, either version 3 of the License, or (at your option) any later
  5. * version.
  6. *
  7. * This program is distributed in the hope that it will be useful, but WITHOUT
  8. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  10. * details.
  11. *
  12. * You should have received a copy of the GNU General Public License along with
  13. * this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. package com.l2jserver.loginserver;
  16. import java.net.InetAddress;
  17. import java.net.UnknownHostException;
  18. import java.security.GeneralSecurityException;
  19. import java.security.KeyPairGenerator;
  20. import java.security.MessageDigest;
  21. import java.security.interfaces.RSAPrivateKey;
  22. import java.security.spec.RSAKeyGenParameterSpec;
  23. import java.sql.Connection;
  24. import java.sql.PreparedStatement;
  25. import java.sql.ResultSet;
  26. import java.util.Collection;
  27. import java.util.Map;
  28. import java.util.logging.Logger;
  29. import javax.crypto.Cipher;
  30. import com.l2jserver.Base64;
  31. import com.l2jserver.Config;
  32. import com.l2jserver.L2DatabaseFactory;
  33. import com.l2jserver.loginserver.GameServerTable.GameServerInfo;
  34. import com.l2jserver.loginserver.gameserverpackets.ServerStatus;
  35. import com.l2jserver.loginserver.serverpackets.LoginFail.LoginFailReason;
  36. import com.l2jserver.util.Rnd;
  37. import com.l2jserver.util.crypt.ScrambledKeyPair;
  38. import com.l2jserver.util.lib.Log;
  39. import javolution.util.FastMap;
  40. import javolution.util.FastSet;
  41. import javolution.util.FastCollection.Record;
  42. /**
  43. * This class ...
  44. *
  45. * @version $Revision: 1.7.4.3 $ $Date: 2005/03/27 15:30:09 $
  46. */
  47. public class LoginController
  48. {
  49. protected static final Logger _log = Logger.getLogger(LoginController.class.getName());
  50. private static LoginController _instance;
  51. /** Time before kicking the client if he didnt logged yet */
  52. private final static int LOGIN_TIMEOUT = 60 * 1000;
  53. /** Clients that are on the LS but arent assocated with a account yet*/
  54. protected FastSet<L2LoginClient> _clients = new FastSet<L2LoginClient>();
  55. /** Authed Clients on LoginServer*/
  56. protected FastMap<String, L2LoginClient> _loginServerClients = new FastMap<String, L2LoginClient>().setShared(true);
  57. private Map<String, BanInfo> _bannedIps = new FastMap<String, BanInfo>().setShared(true);
  58. private Map<InetAddress, FailedLoginAttempt> _hackProtection;
  59. protected ScrambledKeyPair[] _keyPairs;
  60. protected byte[][] _blowfishKeys;
  61. private static final int BLOWFISH_KEYS = 20;
  62. public static void load() throws GeneralSecurityException
  63. {
  64. synchronized (LoginController.class)
  65. {
  66. if (_instance == null)
  67. {
  68. _instance = new LoginController();
  69. }
  70. else
  71. {
  72. throw new IllegalStateException("LoginController can only be loaded a single time.");
  73. }
  74. }
  75. }
  76. public static LoginController getInstance()
  77. {
  78. return _instance;
  79. }
  80. private LoginController() throws GeneralSecurityException
  81. {
  82. _log.info("Loading LoginController...");
  83. _hackProtection = new FastMap<InetAddress, FailedLoginAttempt>();
  84. _keyPairs = new ScrambledKeyPair[10];
  85. KeyPairGenerator keygen = null;
  86. keygen = KeyPairGenerator.getInstance("RSA");
  87. RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4);
  88. keygen.initialize(spec);
  89. //generate the initial set of keys
  90. for (int i = 0; i < 10; i++)
  91. {
  92. _keyPairs[i] = new ScrambledKeyPair(keygen.generateKeyPair());
  93. }
  94. _log.info("Cached 10 KeyPairs for RSA communication");
  95. testCipher((RSAPrivateKey) _keyPairs[0]._pair.getPrivate());
  96. // Store keys for blowfish communication
  97. generateBlowFishKeys();
  98. }
  99. /**
  100. * This is mostly to force the initialization of the Crypto Implementation, avoiding it being done on runtime when its first needed.<BR>
  101. * In short it avoids the worst-case execution time on runtime by doing it on loading.
  102. * @param key Any private RSA Key just for testing purposes.
  103. * @throws GeneralSecurityException if a underlying exception was thrown by the Cipher
  104. */
  105. private void testCipher(RSAPrivateKey key) throws GeneralSecurityException
  106. {
  107. // avoid worst-case execution, KenM
  108. Cipher rsaCipher = Cipher.getInstance("RSA/ECB/nopadding");
  109. rsaCipher.init(Cipher.DECRYPT_MODE, key);
  110. }
  111. private void generateBlowFishKeys()
  112. {
  113. _blowfishKeys = new byte[BLOWFISH_KEYS][16];
  114. for (int i = 0; i < BLOWFISH_KEYS; i++)
  115. {
  116. for (int j = 0; j < _blowfishKeys[i].length; j++)
  117. {
  118. _blowfishKeys[i][j] = (byte) (Rnd.nextInt(255) + 1);
  119. }
  120. }
  121. _log.info("Stored " + _blowfishKeys.length + " keys for Blowfish communication");
  122. }
  123. /**
  124. * @return Returns a random key
  125. */
  126. public byte[] getBlowfishKey()
  127. {
  128. return _blowfishKeys[(int) (Math.random() * BLOWFISH_KEYS)];
  129. }
  130. public void addLoginClient(L2LoginClient client)
  131. {
  132. synchronized (_clients)
  133. {
  134. _clients.add(client);
  135. }
  136. }
  137. public void removeLoginClient(L2LoginClient client)
  138. {
  139. synchronized (_clients)
  140. {
  141. _clients.remove(client);
  142. }
  143. }
  144. public SessionKey assignSessionKeyToClient(String account, L2LoginClient client)
  145. {
  146. SessionKey key;
  147. key = new SessionKey(Rnd.nextInt(), Rnd.nextInt(), Rnd.nextInt(), Rnd.nextInt());
  148. _loginServerClients.put(account, client);
  149. return key;
  150. }
  151. public void removeAuthedLoginClient(String account)
  152. {
  153. _loginServerClients.remove(account);
  154. }
  155. public boolean isAccountInLoginServer(String account)
  156. {
  157. return _loginServerClients.containsKey(account);
  158. }
  159. public L2LoginClient getAuthedClient(String account)
  160. {
  161. return _loginServerClients.get(account);
  162. }
  163. public static enum AuthLoginResult
  164. {
  165. INVALID_PASSWORD,
  166. ACCOUNT_BANNED,
  167. ALREADY_ON_LS,
  168. ALREADY_ON_GS,
  169. AUTH_SUCCESS
  170. }
  171. public AuthLoginResult tryAuthLogin(String account, String password, L2LoginClient client) throws HackingException
  172. {
  173. AuthLoginResult ret = AuthLoginResult.INVALID_PASSWORD;
  174. // check auth
  175. if (loginValid(account, password, client))
  176. {
  177. // login was successful, verify presence on Gameservers
  178. ret = AuthLoginResult.ALREADY_ON_GS;
  179. if (!isAccountInAnyGameServer(account))
  180. {
  181. // account isnt on any GS verify LS itself
  182. ret = AuthLoginResult.ALREADY_ON_LS;
  183. // dont allow 2 simultaneous login
  184. synchronized (_loginServerClients)
  185. {
  186. if (!_loginServerClients.containsKey(account))
  187. {
  188. _loginServerClients.put(account, client);
  189. ret = AuthLoginResult.AUTH_SUCCESS;
  190. // remove him from the non-authed list
  191. removeLoginClient(client);
  192. }
  193. }
  194. }
  195. }
  196. else
  197. {
  198. if (client.getAccessLevel() < 0)
  199. {
  200. ret = AuthLoginResult.ACCOUNT_BANNED;
  201. }
  202. }
  203. return ret;
  204. }
  205. /**
  206. * Adds the address to the ban list of the login server, with the given duration.
  207. *
  208. * @param address The Address to be banned.
  209. * @param expiration Timestamp in miliseconds when this ban expires
  210. * @throws UnknownHostException if the address is invalid.
  211. */
  212. public void addBanForAddress(String address, long expiration) throws UnknownHostException
  213. {
  214. InetAddress netAddress = InetAddress.getByName(address);
  215. if (!_bannedIps.containsKey(netAddress.getHostAddress()))
  216. _bannedIps.put(netAddress.getHostAddress(), new BanInfo(netAddress, expiration));
  217. }
  218. /**
  219. * Adds the address to the ban list of the login server, with the given duration.
  220. *
  221. * @param address The Address to be banned.
  222. * @param duration is miliseconds
  223. */
  224. public void addBanForAddress(InetAddress address, long duration)
  225. {
  226. if (!_bannedIps.containsKey(address.getHostAddress()))
  227. _bannedIps.put(address.getHostAddress(), new BanInfo(address, System.currentTimeMillis() + duration));
  228. }
  229. public boolean isBannedAddress(InetAddress address)
  230. {
  231. String[] parts = address.getHostAddress().split("\\.");
  232. BanInfo bi = _bannedIps.get(address.getHostAddress());
  233. if (bi == null)
  234. bi = _bannedIps.get(parts[0] + "." + parts[1] + "." + parts[2] + ".0");
  235. if (bi == null)
  236. bi = _bannedIps.get(parts[0] + "." + parts[1] + ".0.0");
  237. if (bi == null)
  238. bi = _bannedIps.get(parts[0] + ".0.0.0");
  239. if (bi != null)
  240. {
  241. if (bi.hasExpired())
  242. {
  243. _bannedIps.remove(address.getHostAddress());
  244. return false;
  245. }
  246. else
  247. {
  248. return true;
  249. }
  250. }
  251. return false;
  252. }
  253. public Map<String, BanInfo> getBannedIps()
  254. {
  255. return _bannedIps;
  256. }
  257. /**
  258. * Remove the specified address from the ban list
  259. * @param address The address to be removed from the ban list
  260. * @return true if the ban was removed, false if there was no ban for this ip
  261. */
  262. public boolean removeBanForAddress(InetAddress address)
  263. {
  264. return _bannedIps.remove(address.getHostAddress()) != null;
  265. }
  266. /**
  267. * Remove the specified address from the ban list
  268. * @param address The address to be removed from the ban list
  269. * @return true if the ban was removed, false if there was no ban for this ip or the address was invalid.
  270. */
  271. public boolean removeBanForAddress(String address)
  272. {
  273. try
  274. {
  275. return this.removeBanForAddress(InetAddress.getByName(address));
  276. }
  277. catch (UnknownHostException e)
  278. {
  279. return false;
  280. }
  281. }
  282. public SessionKey getKeyForAccount(String account)
  283. {
  284. L2LoginClient client = _loginServerClients.get(account);
  285. if (client != null)
  286. {
  287. return client.getSessionKey();
  288. }
  289. return null;
  290. }
  291. public int getOnlinePlayerCount(int serverId)
  292. {
  293. GameServerInfo gsi = GameServerTable.getInstance().getRegisteredGameServerById(serverId);
  294. if (gsi != null && gsi.isAuthed())
  295. {
  296. return gsi.getCurrentPlayerCount();
  297. }
  298. return 0;
  299. }
  300. public boolean isAccountInAnyGameServer(String account)
  301. {
  302. Collection<GameServerInfo> serverList = GameServerTable.getInstance().getRegisteredGameServers().values();
  303. for (GameServerInfo gsi : serverList)
  304. {
  305. GameServerThread gst = gsi.getGameServerThread();
  306. if (gst != null && gst.hasAccountOnGameServer(account))
  307. {
  308. return true;
  309. }
  310. }
  311. return false;
  312. }
  313. public GameServerInfo getAccountOnGameServer(String account)
  314. {
  315. Collection<GameServerInfo> serverList = GameServerTable.getInstance().getRegisteredGameServers().values();
  316. for (GameServerInfo gsi : serverList)
  317. {
  318. GameServerThread gst = gsi.getGameServerThread();
  319. if (gst != null && gst.hasAccountOnGameServer(account))
  320. {
  321. return gsi;
  322. }
  323. }
  324. return null;
  325. }
  326. public int getTotalOnlinePlayerCount()
  327. {
  328. int total = 0;
  329. Collection<GameServerInfo> serverList = GameServerTable.getInstance().getRegisteredGameServers().values();
  330. for (GameServerInfo gsi : serverList)
  331. {
  332. if (gsi.isAuthed())
  333. {
  334. total += gsi.getCurrentPlayerCount();
  335. }
  336. }
  337. return total;
  338. }
  339. public int getMaxAllowedOnlinePlayers(int id)
  340. {
  341. GameServerInfo gsi = GameServerTable.getInstance().getRegisteredGameServerById(id);
  342. if (gsi != null)
  343. {
  344. return gsi.getMaxPlayers();
  345. }
  346. return 0;
  347. }
  348. /**
  349. *
  350. * @return
  351. */
  352. public boolean isLoginPossible(L2LoginClient client, int serverId)
  353. {
  354. GameServerInfo gsi = GameServerTable.getInstance().getRegisteredGameServerById(serverId);
  355. int access = client.getAccessLevel();
  356. if (gsi != null && gsi.isAuthed())
  357. {
  358. boolean loginOk = (gsi.getCurrentPlayerCount() < gsi.getMaxPlayers() && gsi.getStatus() != ServerStatus.STATUS_GM_ONLY)
  359. || access > 0;
  360. if (loginOk && client.getLastServer() != serverId)
  361. {
  362. Connection con = null;
  363. PreparedStatement statement = null;
  364. try
  365. {
  366. con = L2DatabaseFactory.getInstance().getConnection();
  367. String stmt = "UPDATE accounts SET lastServer = ? WHERE login = ?";
  368. statement = con.prepareStatement(stmt);
  369. statement.setInt(1, serverId);
  370. statement.setString(2, client.getAccount());
  371. statement.executeUpdate();
  372. statement.close();
  373. }
  374. catch (Exception e)
  375. {
  376. _log.warning("Could not set lastServer: " + e);
  377. }
  378. finally
  379. {
  380. try
  381. {
  382. con.close();
  383. }
  384. catch (Exception e)
  385. {
  386. }
  387. }
  388. }
  389. return loginOk;
  390. }
  391. return false;
  392. }
  393. public void setAccountAccessLevel(String account, int banLevel)
  394. {
  395. Connection con = null;
  396. PreparedStatement statement = null;
  397. try
  398. {
  399. con = L2DatabaseFactory.getInstance().getConnection();
  400. String stmt = "UPDATE accounts SET accessLevel=? WHERE login=?";
  401. statement = con.prepareStatement(stmt);
  402. statement.setInt(1, banLevel);
  403. statement.setString(2, account);
  404. statement.executeUpdate();
  405. statement.close();
  406. }
  407. catch (Exception e)
  408. {
  409. _log.warning("Could not set accessLevel: " + e);
  410. }
  411. finally
  412. {
  413. try
  414. {
  415. con.close();
  416. }
  417. catch (Exception e)
  418. {
  419. }
  420. }
  421. }
  422. public void setAccountLastTracert(String account, String pcIp,
  423. String hop1, String hop2, String hop3, String hop4)
  424. {
  425. Connection con = null;
  426. PreparedStatement statement = null;
  427. try
  428. {
  429. con = L2DatabaseFactory.getInstance().getConnection();
  430. String stmt = "UPDATE accounts SET pcIp=?, hop1=?, hop2=?, hop3=?, hop4=? WHERE login=?";
  431. statement = con.prepareStatement(stmt);
  432. statement.setString(1, pcIp);
  433. statement.setString(2, hop1);
  434. statement.setString(3, hop2);
  435. statement.setString(4, hop3);
  436. statement.setString(5, hop4);
  437. statement.setString(6, account);
  438. statement.executeUpdate();
  439. statement.close();
  440. }
  441. catch (Exception e)
  442. {
  443. _log.warning("Could not set last tracert: " + e);
  444. }
  445. finally
  446. {
  447. try
  448. {
  449. con.close();
  450. }
  451. catch (Exception e)
  452. {
  453. }
  454. }
  455. }
  456. public boolean isGM(String user)
  457. {
  458. boolean ok = false;
  459. Connection con = null;
  460. PreparedStatement statement = null;
  461. try
  462. {
  463. con = L2DatabaseFactory.getInstance().getConnection();
  464. statement = con.prepareStatement("SELECT accessLevel FROM accounts WHERE login=?");
  465. statement.setString(1, user);
  466. ResultSet rset = statement.executeQuery();
  467. if (rset.next())
  468. {
  469. int accessLevel = rset.getInt(1);
  470. if (accessLevel > 0)
  471. {
  472. ok = true;
  473. }
  474. }
  475. rset.close();
  476. statement.close();
  477. }
  478. catch (Exception e)
  479. {
  480. _log.warning("could not check gm state:" + e);
  481. ok = false;
  482. }
  483. finally
  484. {
  485. try
  486. {
  487. con.close();
  488. }
  489. catch (Exception e)
  490. {
  491. }
  492. }
  493. return ok;
  494. }
  495. /**
  496. * <p>This method returns one of the cached {@link ScrambledKeyPair ScrambledKeyPairs} for communication with Login Clients.</p>
  497. * @return a scrambled keypair
  498. */
  499. public ScrambledKeyPair getScrambledRSAKeyPair()
  500. {
  501. return _keyPairs[Rnd.nextInt(10)];
  502. }
  503. /**
  504. * user name is not case sensitive any more
  505. * @param user
  506. * @param password
  507. * @param address
  508. * @return
  509. */
  510. public boolean loginValid(String user, String password, L2LoginClient client)// throws HackingException
  511. {
  512. boolean ok = false;
  513. InetAddress address = client.getConnection().getInetAddress();
  514. // player disconnected meanwhile
  515. if (address == null)
  516. {
  517. return false;
  518. }
  519. Connection con = null;
  520. try
  521. {
  522. MessageDigest md = MessageDigest.getInstance("SHA");
  523. byte[] raw = password.getBytes("UTF-8");
  524. byte[] hash = md.digest(raw);
  525. byte[] expected = null;
  526. int access = 0;
  527. int lastServer = 1;
  528. String userIP = null;
  529. con = L2DatabaseFactory.getInstance().getConnection();
  530. PreparedStatement statement = con.prepareStatement("SELECT password, accessLevel, lastServer, userIP FROM accounts WHERE login=?");
  531. statement.setString(1, user);
  532. ResultSet rset = statement.executeQuery();
  533. if (rset.next())
  534. {
  535. expected = Base64.decode(rset.getString("password"));
  536. access = rset.getInt("accessLevel");
  537. lastServer = rset.getInt("lastServer");
  538. userIP = rset.getString("userIP");
  539. if (lastServer <= 0)
  540. lastServer = 1; // minServerId is 1 in Interlude
  541. if (Config.DEBUG)
  542. _log.fine("account exists");
  543. }
  544. rset.close();
  545. statement.close();
  546. // if account doesnt exists
  547. if (expected == null)
  548. {
  549. if (Config.AUTO_CREATE_ACCOUNTS)
  550. {
  551. if ((user.length() >= 2) && (user.length() <= 14))
  552. {
  553. statement = con.prepareStatement("INSERT INTO accounts (login,password,lastactive,accessLevel,lastIP) values(?,?,?,?,?)");
  554. statement.setString(1, user);
  555. statement.setString(2, Base64.encodeBytes(hash));
  556. statement.setLong(3, System.currentTimeMillis());
  557. statement.setInt(4, 0);
  558. statement.setString(5, address.getHostAddress());
  559. statement.execute();
  560. statement.close();
  561. if (Config.LOG_LOGIN_CONTROLLER)
  562. Log.add("'" + (user == null ? "null" : user) + "' " + (address == null ? "null" : address.getHostAddress()) + " - OK : AccountCreate", "loginlog");
  563. _log.info("Created new account for " + user);
  564. return true;
  565. }
  566. if (Config.LOG_LOGIN_CONTROLLER)
  567. Log.add("'" + (user == null ? "null" : user) + "' " + (address == null ? "null" : address.getHostAddress()) + " - ERR : ErrCreatingACC", "loginlog");
  568. _log.warning("Invalid username creation/use attempt: " + user);
  569. return false;
  570. }
  571. else
  572. {
  573. if (Config.LOG_LOGIN_CONTROLLER)
  574. Log.add("'" + (user == null ? "null" : user) + "' " + (address == null ? "null" : address.getHostAddress()) + " - ERR : AccountMissing", "loginlog");
  575. _log.warning("Account missing for user " + user);
  576. FailedLoginAttempt failedAttempt = _hackProtection.get(address);
  577. int failedCount;
  578. if (failedAttempt == null)
  579. {
  580. _hackProtection.put(address, new FailedLoginAttempt(address, password));
  581. failedCount = 1;
  582. }
  583. else
  584. {
  585. failedAttempt.increaseCounter();
  586. failedCount = failedAttempt.getCount();
  587. }
  588. if (failedCount >= Config.LOGIN_TRY_BEFORE_BAN)
  589. {
  590. _log.info("Banning '" + address.getHostAddress() + "' for " + Config.LOGIN_BLOCK_AFTER_BAN + " seconds due to "
  591. + failedCount + " invalid user name attempts");
  592. this.addBanForAddress(address, Config.LOGIN_BLOCK_AFTER_BAN * 1000);
  593. }
  594. return false;
  595. }
  596. }
  597. else
  598. {
  599. // is this account banned?
  600. if (access < 0)
  601. {
  602. if (Config.LOG_LOGIN_CONTROLLER)
  603. Log.add("'" + (user == null ? "null" : user) + "' " + (address == null ? "null" : address.getHostAddress()) + " - ERR : AccountBanned", "loginlog");
  604. client.setAccessLevel(access);
  605. return false;
  606. }
  607. // Check IP
  608. if ( address != null && userIP != null && !address.getHostAddress().equalsIgnoreCase(userIP))
  609. {
  610. if (Config.LOG_LOGIN_CONTROLLER)
  611. Log.add("'" + (user == null ? "null" : user) + "' " + (address == null ? "null" : address.getHostAddress()) + "/" + userIP + " - ERR : INCORRECT IP", "loginlog");
  612. return false;
  613. }
  614. // check password hash
  615. ok = true;
  616. for (int i = 0; i < expected.length; i++)
  617. {
  618. if (hash[i] != expected[i])
  619. {
  620. ok = false;
  621. break;
  622. }
  623. }
  624. }
  625. if (ok)
  626. {
  627. client.setAccessLevel(access);
  628. client.setLastServer(lastServer);
  629. statement = con.prepareStatement("UPDATE accounts SET lastactive=?, lastIP=? WHERE login=?");
  630. statement.setLong(1, System.currentTimeMillis());
  631. statement.setString(2, address.getHostAddress());
  632. statement.setString(3, user);
  633. statement.execute();
  634. statement.close();
  635. }
  636. }
  637. catch (Exception e)
  638. {
  639. _log.warning("Could not check password:" + e);
  640. ok = false;
  641. }
  642. finally
  643. {
  644. try
  645. {
  646. con.close();
  647. }
  648. catch (Exception e)
  649. {
  650. }
  651. }
  652. if (!ok)
  653. {
  654. if (Config.LOG_LOGIN_CONTROLLER)
  655. Log.add("'" + (user == null ? "null" : user) + "' " + (address == null ? "null" : address.getHostAddress()) + " - ERR : LoginFailed", "loginlog");
  656. FailedLoginAttempt failedAttempt = _hackProtection.get(address);
  657. int failedCount;
  658. if (failedAttempt == null)
  659. {
  660. _hackProtection.put(address, new FailedLoginAttempt(address, password));
  661. failedCount = 1;
  662. }
  663. else
  664. {
  665. failedAttempt.increaseCounter(password);
  666. failedCount = failedAttempt.getCount();
  667. }
  668. if (failedCount >= Config.LOGIN_TRY_BEFORE_BAN)
  669. {
  670. _log.info("Banning '" + address.getHostAddress() + "' for " + Config.LOGIN_BLOCK_AFTER_BAN + " seconds due to "
  671. + failedCount + " invalid user/pass attempts");
  672. this.addBanForAddress(address, Config.LOGIN_BLOCK_AFTER_BAN * 1000);
  673. }
  674. }
  675. else
  676. {
  677. _hackProtection.remove(address);
  678. if (Config.LOG_LOGIN_CONTROLLER)
  679. Log.add("'" + (user == null ? "null" : user) + "' " + (address == null ? "null" : address.getHostAddress()) + " - OK : LoginOk", "loginlog");
  680. }
  681. return ok;
  682. }
  683. public boolean loginBanned(String user)
  684. {
  685. boolean ok = false;
  686. Connection con = null;
  687. try
  688. {
  689. con = L2DatabaseFactory.getInstance().getConnection();
  690. PreparedStatement statement = con.prepareStatement("SELECT accessLevel FROM accounts WHERE login=?");
  691. statement.setString(1, user);
  692. ResultSet rset = statement.executeQuery();
  693. if (rset.next())
  694. {
  695. int accessLevel = rset.getInt(1);
  696. if (accessLevel < 0)
  697. ok = true;
  698. }
  699. rset.close();
  700. statement.close();
  701. }
  702. catch (Exception e)
  703. {
  704. // digest algo not found ??
  705. // out of bounds should not be possible
  706. _log.warning("could not check ban state:" + e);
  707. ok = false;
  708. }
  709. finally
  710. {
  711. try
  712. {
  713. con.close();
  714. }
  715. catch (Exception e)
  716. {
  717. }
  718. }
  719. return ok;
  720. }
  721. class FailedLoginAttempt
  722. {
  723. //private InetAddress _ipAddress;
  724. private int _count;
  725. private long _lastAttempTime;
  726. private String _lastPassword;
  727. public FailedLoginAttempt(InetAddress address, String lastPassword)
  728. {
  729. //_ipAddress = address;
  730. _count = 1;
  731. _lastAttempTime = System.currentTimeMillis();
  732. _lastPassword = lastPassword;
  733. }
  734. public void increaseCounter(String password)
  735. {
  736. if (!_lastPassword.equals(password))
  737. {
  738. // check if theres a long time since last wrong try
  739. if (System.currentTimeMillis() - _lastAttempTime < 300 * 1000)
  740. {
  741. _count++;
  742. }
  743. else
  744. {
  745. // restart the status
  746. _count = 1;
  747. }
  748. _lastPassword = password;
  749. _lastAttempTime = System.currentTimeMillis();
  750. }
  751. else
  752. //trying the same password is not brute force
  753. {
  754. _lastAttempTime = System.currentTimeMillis();
  755. }
  756. }
  757. public int getCount()
  758. {
  759. return _count;
  760. }
  761. public void increaseCounter()
  762. {
  763. _count++;
  764. }
  765. }
  766. class BanInfo
  767. {
  768. private InetAddress _ipAddress;
  769. // Expiration
  770. private long _expiration;
  771. public BanInfo(InetAddress ipAddress, long expiration)
  772. {
  773. _ipAddress = ipAddress;
  774. _expiration = expiration;
  775. }
  776. public InetAddress getAddress()
  777. {
  778. return _ipAddress;
  779. }
  780. public boolean hasExpired()
  781. {
  782. return System.currentTimeMillis() > _expiration && _expiration > 0;
  783. }
  784. }
  785. class PurgeThread extends Thread
  786. {
  787. @Override
  788. public void run()
  789. {
  790. for (;;)
  791. {
  792. synchronized (_clients)
  793. {
  794. for (Record e = _clients.head(), end = _clients.tail(); (e = e.getNext()) != end;)
  795. {
  796. L2LoginClient client = _clients.valueOf(e);
  797. if (client.getConnectionStartTime() + LOGIN_TIMEOUT >= System.currentTimeMillis())
  798. {
  799. client.close(LoginFailReason.REASON_ACCESS_FAILED);
  800. }
  801. }
  802. }
  803. synchronized (_loginServerClients)
  804. {
  805. for (FastMap.Entry<String, L2LoginClient> e = _loginServerClients.head(), end = _loginServerClients.tail(); (e = e.getNext()) != end;)
  806. {
  807. L2LoginClient client = e.getValue();
  808. if (client.getConnectionStartTime() + LOGIN_TIMEOUT >= System.currentTimeMillis())
  809. {
  810. client.close(LoginFailReason.REASON_ACCESS_FAILED);
  811. }
  812. }
  813. }
  814. try
  815. {
  816. Thread.sleep(2 * LOGIN_TIMEOUT);
  817. }
  818. catch (InterruptedException e)
  819. {
  820. e.printStackTrace();
  821. }
  822. }
  823. }
  824. }
  825. }