LoginController.java 21 KB

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