2
0

LoginController.java 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  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) throws HackingException
  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. * @return
  307. */
  308. public boolean isLoginPossible(L2LoginClient client, int serverId)
  309. {
  310. GameServerInfo gsi = GameServerTable.getInstance().getRegisteredGameServerById(serverId);
  311. int access = client.getAccessLevel();
  312. if (gsi != null && gsi.isAuthed())
  313. {
  314. boolean loginOk = (gsi.getCurrentPlayerCount() < gsi.getMaxPlayers() && gsi.getStatus() != ServerStatus.STATUS_GM_ONLY)
  315. || access > 0;
  316. if (loginOk && client.getLastServer() != serverId)
  317. {
  318. Connection con = null;
  319. PreparedStatement statement = null;
  320. try
  321. {
  322. con = L2DatabaseFactory.getInstance().getConnection();
  323. String stmt = "UPDATE accounts SET lastServer = ? WHERE login = ?";
  324. statement = con.prepareStatement(stmt);
  325. statement.setInt(1, serverId);
  326. statement.setString(2, client.getAccount());
  327. statement.executeUpdate();
  328. statement.close();
  329. }
  330. catch (Exception e)
  331. {
  332. _log.log(Level.WARNING, "Could not set lastServer: " + e.getMessage(), e);
  333. }
  334. finally
  335. {
  336. L2DatabaseFactory.close(con);
  337. }
  338. }
  339. return loginOk;
  340. }
  341. return false;
  342. }
  343. public void setAccountAccessLevel(String account, int banLevel)
  344. {
  345. Connection con = null;
  346. PreparedStatement statement = null;
  347. try
  348. {
  349. con = L2DatabaseFactory.getInstance().getConnection();
  350. String stmt = "UPDATE accounts SET accessLevel=? WHERE login=?";
  351. 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. try
  364. {
  365. L2DatabaseFactory.close(con);
  366. }
  367. catch (Exception e)
  368. {
  369. }
  370. }
  371. }
  372. public void setAccountLastTracert(String account, String pcIp,
  373. String hop1, String hop2, String hop3, String hop4)
  374. {
  375. Connection con = null;
  376. PreparedStatement statement = null;
  377. try
  378. {
  379. con = L2DatabaseFactory.getInstance().getConnection();
  380. String stmt = "UPDATE accounts SET pcIp=?, hop1=?, hop2=?, hop3=?, hop4=? WHERE login=?";
  381. statement = con.prepareStatement(stmt);
  382. statement.setString(1, pcIp);
  383. statement.setString(2, hop1);
  384. statement.setString(3, hop2);
  385. statement.setString(4, hop3);
  386. statement.setString(5, hop4);
  387. statement.setString(6, account);
  388. statement.executeUpdate();
  389. statement.close();
  390. }
  391. catch (Exception e)
  392. {
  393. _log.log(Level.WARNING, "Could not set last tracert: " + e.getMessage(), e);
  394. }
  395. finally
  396. {
  397. try
  398. {
  399. L2DatabaseFactory.close(con);
  400. }
  401. catch (Exception e)
  402. {
  403. }
  404. }
  405. }
  406. public void setCharactersOnServer(String account, int charsNum, long[] timeToDel, int serverId)
  407. {
  408. L2LoginClient client = _loginServerClients.get(account);
  409. if (client == null)
  410. return;
  411. if (charsNum > 0)
  412. client.setCharsOnServ(serverId, charsNum);
  413. if (timeToDel.length > 0)
  414. client.serCharsWaitingDelOnServ(serverId, timeToDel);
  415. }
  416. /**
  417. * <p>This method returns one of the cached {@link ScrambledKeyPair ScrambledKeyPairs} for communication with Login Clients.</p>
  418. * @return a scrambled keypair
  419. */
  420. public ScrambledKeyPair getScrambledRSAKeyPair()
  421. {
  422. return _keyPairs[Rnd.nextInt(10)];
  423. }
  424. /**
  425. * user name is not case sensitive any more
  426. * @param user
  427. * @param password
  428. * @param address
  429. * @return
  430. */
  431. public boolean loginValid(String user, String password, L2LoginClient client)// throws HackingException
  432. {
  433. boolean ok = false;
  434. InetAddress address = client.getConnection().getInetAddress();
  435. // player disconnected meanwhile
  436. if (address == null || user == null)
  437. {
  438. return false;
  439. }
  440. Connection con = null;
  441. try
  442. {
  443. MessageDigest md = MessageDigest.getInstance("SHA");
  444. byte[] raw = password.getBytes("UTF-8");
  445. byte[] hash = md.digest(raw);
  446. byte[] expected = null;
  447. int access = 0;
  448. int lastServer = 1;
  449. String userIP = null;
  450. con = L2DatabaseFactory.getInstance().getConnection();
  451. PreparedStatement statement = con.prepareStatement(USER_INFO_SELECT);
  452. statement.setString(1, Long.toString(System.currentTimeMillis()));
  453. statement.setString(2, user);
  454. ResultSet rset = statement.executeQuery();
  455. if (rset.next())
  456. {
  457. expected = Base64.decode(rset.getString("password"));
  458. access = rset.getInt("accessLevel");
  459. lastServer = rset.getInt("lastServer");
  460. userIP = rset.getString("userIP");
  461. if (lastServer <= 0)
  462. lastServer = 1; // minServerId is 1 in Interlude
  463. if (Config.DEBUG)
  464. _log.fine("account exists");
  465. }
  466. rset.close();
  467. statement.close();
  468. // if account doesnt exists
  469. if (expected == null)
  470. {
  471. if (Config.AUTO_CREATE_ACCOUNTS)
  472. {
  473. if ((user.length() >= 2) && (user.length() <= 14))
  474. {
  475. statement = con.prepareStatement("INSERT INTO accounts (login,password,lastactive,accessLevel,lastIP) values(?,?,?,?,?)");
  476. statement.setString(1, user);
  477. statement.setString(2, Base64.encodeBytes(hash));
  478. statement.setLong(3, System.currentTimeMillis());
  479. statement.setInt(4, 0);
  480. statement.setString(5, address.getHostAddress());
  481. statement.execute();
  482. statement.close();
  483. if (Config.LOG_LOGIN_CONTROLLER)
  484. Log.add("'" + user + "' " + address.getHostAddress() + " - OK : AccountCreate", "loginlog");
  485. _log.info("Created new account for " + user);
  486. return true;
  487. }
  488. if (Config.LOG_LOGIN_CONTROLLER)
  489. Log.add("'" + user + "' " + address.getHostAddress() + " - ERR : ErrCreatingACC", "loginlog");
  490. _log.warning("Invalid username creation/use attempt: " + user);
  491. }
  492. else
  493. {
  494. if (Config.LOG_LOGIN_CONTROLLER)
  495. Log.add("'" + user + "' " + address.getHostAddress() + " - ERR : AccountMissing", "loginlog");
  496. _log.warning("Account missing for user " + user);
  497. FailedLoginAttempt failedAttempt = _hackProtection.get(address);
  498. int failedCount;
  499. if (failedAttempt == null)
  500. {
  501. _hackProtection.put(address, new FailedLoginAttempt(address, password));
  502. failedCount = 1;
  503. }
  504. else
  505. {
  506. failedAttempt.increaseCounter();
  507. failedCount = failedAttempt.getCount();
  508. }
  509. if (failedCount >= Config.LOGIN_TRY_BEFORE_BAN)
  510. {
  511. _log.info("Banning '" + address.getHostAddress() + "' for " + Config.LOGIN_BLOCK_AFTER_BAN + " seconds due to "
  512. + failedCount + " invalid user name attempts");
  513. this.addBanForAddress(address, Config.LOGIN_BLOCK_AFTER_BAN * 1000);
  514. }
  515. }
  516. return false;
  517. }
  518. // is this account banned?
  519. if (access < 0)
  520. {
  521. if (Config.LOG_LOGIN_CONTROLLER)
  522. Log.add("'" + user + "' " + address.getHostAddress() + " - ERR : AccountBanned", "loginlog");
  523. client.setAccessLevel(access);
  524. return false;
  525. }
  526. // Check IP
  527. if (userIP != null)
  528. {
  529. if(!isValidIPAddress(userIP))
  530. {
  531. // Address is not valid so it's a domain name, get IP
  532. try
  533. {
  534. InetAddress addr = InetAddress.getByName(userIP);
  535. userIP = addr.getHostAddress();
  536. }
  537. catch(Exception e)
  538. {
  539. return false;
  540. }
  541. }
  542. if(!address.getHostAddress().equalsIgnoreCase(userIP))
  543. {
  544. if (Config.LOG_LOGIN_CONTROLLER)
  545. Log.add("'" + user + "' " + address.getHostAddress() + "/" + userIP + " - ERR : INCORRECT IP", "loginlog");
  546. return false;
  547. }
  548. }
  549. // check password hash
  550. ok = true;
  551. for (int i = 0; i < expected.length; i++)
  552. {
  553. if (hash[i] != expected[i])
  554. {
  555. ok = false;
  556. break;
  557. }
  558. }
  559. if (ok)
  560. {
  561. client.setAccessLevel(access);
  562. client.setLastServer(lastServer);
  563. statement = con.prepareStatement("UPDATE accounts SET lastactive=?, lastIP=? WHERE login=?");
  564. statement.setLong(1, System.currentTimeMillis());
  565. statement.setString(2, address.getHostAddress());
  566. statement.setString(3, user);
  567. statement.execute();
  568. statement.close();
  569. }
  570. }
  571. catch (Exception e)
  572. {
  573. _log.log(Level.WARNING, "Could not check password:" + e.getMessage(), e);
  574. ok = false;
  575. }
  576. finally
  577. {
  578. L2DatabaseFactory.close(con);
  579. }
  580. if (!ok)
  581. {
  582. if (Config.LOG_LOGIN_CONTROLLER)
  583. Log.add("'" + user + "' " + address.getHostAddress() + " - ERR : LoginFailed", "loginlog");
  584. FailedLoginAttempt failedAttempt = _hackProtection.get(address);
  585. int failedCount;
  586. if (failedAttempt == null)
  587. {
  588. _hackProtection.put(address, new FailedLoginAttempt(address, password));
  589. failedCount = 1;
  590. }
  591. else
  592. {
  593. failedAttempt.increaseCounter(password);
  594. failedCount = failedAttempt.getCount();
  595. }
  596. if (failedCount >= Config.LOGIN_TRY_BEFORE_BAN)
  597. {
  598. _log.info("Banning '" + address.getHostAddress() + "' for " + Config.LOGIN_BLOCK_AFTER_BAN + " seconds due to "
  599. + failedCount + " invalid user/pass attempts");
  600. this.addBanForAddress(address, Config.LOGIN_BLOCK_AFTER_BAN * 1000);
  601. }
  602. }
  603. else
  604. {
  605. _hackProtection.remove(address);
  606. if (Config.LOG_LOGIN_CONTROLLER)
  607. Log.add("'" + user + "' " + address.getHostAddress() + " - OK : LoginOk", "loginlog");
  608. }
  609. return ok;
  610. }
  611. public boolean isValidIPAddress(String ipAddress)
  612. {
  613. String[] parts = ipAddress.split("\\.");
  614. if (parts.length != 4)
  615. return false;
  616. for (String s : parts)
  617. {
  618. int i = Integer.parseInt(s);
  619. if ((i < 0) || (i > 255))
  620. return false;
  621. }
  622. return true;
  623. }
  624. class FailedLoginAttempt
  625. {
  626. //private InetAddress _ipAddress;
  627. private int _count;
  628. private long _lastAttempTime;
  629. private String _lastPassword;
  630. public FailedLoginAttempt(InetAddress address, String lastPassword)
  631. {
  632. //_ipAddress = address;
  633. _count = 1;
  634. _lastAttempTime = System.currentTimeMillis();
  635. _lastPassword = lastPassword;
  636. }
  637. public void increaseCounter(String password)
  638. {
  639. if (!_lastPassword.equals(password))
  640. {
  641. // check if theres a long time since last wrong try
  642. if (System.currentTimeMillis() - _lastAttempTime < 300 * 1000)
  643. {
  644. _count++;
  645. }
  646. else
  647. {
  648. // restart the status
  649. _count = 1;
  650. }
  651. _lastPassword = password;
  652. _lastAttempTime = System.currentTimeMillis();
  653. }
  654. else
  655. //trying the same password is not brute force
  656. {
  657. _lastAttempTime = System.currentTimeMillis();
  658. }
  659. }
  660. public int getCount()
  661. {
  662. return _count;
  663. }
  664. public void increaseCounter()
  665. {
  666. _count++;
  667. }
  668. }
  669. class BanInfo
  670. {
  671. private final InetAddress _ipAddress;
  672. // Expiration
  673. private final long _expiration;
  674. public BanInfo(InetAddress ipAddress, long expiration)
  675. {
  676. _ipAddress = ipAddress;
  677. _expiration = expiration;
  678. }
  679. public InetAddress getAddress()
  680. {
  681. return _ipAddress;
  682. }
  683. public boolean hasExpired()
  684. {
  685. return System.currentTimeMillis() > _expiration && _expiration > 0;
  686. }
  687. }
  688. class PurgeThread extends Thread
  689. {
  690. public PurgeThread()
  691. {
  692. setName("PurgeThread");
  693. }
  694. @Override
  695. public void run()
  696. {
  697. while (!isInterrupted())
  698. {
  699. for (L2LoginClient client : _loginServerClients.values())
  700. {
  701. if (client == null)
  702. continue;
  703. if ((client.getConnectionStartTime() + LOGIN_TIMEOUT) < System.currentTimeMillis())
  704. {
  705. client.close(LoginFailReason.REASON_ACCESS_FAILED);
  706. }
  707. }
  708. try
  709. {
  710. Thread.sleep(LOGIN_TIMEOUT / 2);
  711. }
  712. catch (InterruptedException e)
  713. {
  714. return;
  715. }
  716. }
  717. }
  718. }
  719. }