LoginController.java 22 KB

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