LoginController.java 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  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.gameserver.lib.Log;
  34. import com.l2jserver.loginserver.GameServerTable.GameServerInfo;
  35. import com.l2jserver.loginserver.crypt.ScrambledKeyPair;
  36. import com.l2jserver.loginserver.gameserverpackets.ServerStatus;
  37. import com.l2jserver.loginserver.serverpackets.LoginFail.LoginFailReason;
  38. import com.l2jserver.util.Rnd;
  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 boolean isGM(String user)
  423. {
  424. boolean ok = false;
  425. Connection con = null;
  426. PreparedStatement statement = null;
  427. try
  428. {
  429. con = L2DatabaseFactory.getInstance().getConnection();
  430. statement = con.prepareStatement("SELECT accessLevel FROM accounts WHERE login=?");
  431. statement.setString(1, user);
  432. ResultSet rset = statement.executeQuery();
  433. if (rset.next())
  434. {
  435. int accessLevel = rset.getInt(1);
  436. if (accessLevel > 0)
  437. {
  438. ok = true;
  439. }
  440. }
  441. rset.close();
  442. statement.close();
  443. }
  444. catch (Exception e)
  445. {
  446. _log.warning("could not check gm state:" + e);
  447. ok = false;
  448. }
  449. finally
  450. {
  451. try
  452. {
  453. con.close();
  454. }
  455. catch (Exception e)
  456. {
  457. }
  458. }
  459. return ok;
  460. }
  461. /**
  462. * <p>This method returns one of the cached {@link ScrambledKeyPair ScrambledKeyPairs} for communication with Login Clients.</p>
  463. * @return a scrambled keypair
  464. */
  465. public ScrambledKeyPair getScrambledRSAKeyPair()
  466. {
  467. return _keyPairs[Rnd.nextInt(10)];
  468. }
  469. /**
  470. * user name is not case sensitive any more
  471. * @param user
  472. * @param password
  473. * @param address
  474. * @return
  475. */
  476. public boolean loginValid(String user, String password, L2LoginClient client)// throws HackingException
  477. {
  478. boolean ok = false;
  479. InetAddress address = client.getConnection().getInetAddress();
  480. // player disconnected meanwhile
  481. if (address == null)
  482. {
  483. return false;
  484. }
  485. Connection con = null;
  486. try
  487. {
  488. MessageDigest md = MessageDigest.getInstance("SHA");
  489. byte[] raw = password.getBytes("UTF-8");
  490. byte[] hash = md.digest(raw);
  491. byte[] expected = null;
  492. int access = 0;
  493. int lastServer = 1;
  494. con = L2DatabaseFactory.getInstance().getConnection();
  495. PreparedStatement statement = con.prepareStatement("SELECT password, accessLevel, lastServer FROM accounts WHERE login=?");
  496. statement.setString(1, user);
  497. ResultSet rset = statement.executeQuery();
  498. if (rset.next())
  499. {
  500. expected = Base64.decode(rset.getString("password"));
  501. access = rset.getInt("accessLevel");
  502. lastServer = rset.getInt("lastServer");
  503. if (lastServer <= 0)
  504. lastServer = 1; // minServerId is 1 in Interlude
  505. if (Config.DEBUG)
  506. _log.fine("account exists");
  507. }
  508. rset.close();
  509. statement.close();
  510. // if account doesnt exists
  511. if (expected == null)
  512. {
  513. if (Config.AUTO_CREATE_ACCOUNTS)
  514. {
  515. if ((user.length() >= 2) && (user.length() <= 14))
  516. {
  517. statement = con.prepareStatement("INSERT INTO accounts (login,password,lastactive,accessLevel,lastIP) values(?,?,?,?,?)");
  518. statement.setString(1, user);
  519. statement.setString(2, Base64.encodeBytes(hash));
  520. statement.setLong(3, System.currentTimeMillis());
  521. statement.setInt(4, 0);
  522. statement.setString(5, address.getHostAddress());
  523. statement.execute();
  524. statement.close();
  525. if (Config.LOG_LOGIN_CONTROLLER)
  526. Log.add("'" + (user == null ? "null" : user) + "' " + (address == null ? "null" : address.getHostAddress()) + " - OK : AccountCreate", "loginlog");
  527. _log.info("Created new account for " + user);
  528. return true;
  529. }
  530. if (Config.LOG_LOGIN_CONTROLLER)
  531. Log.add("'" + (user == null ? "null" : user) + "' " + (address == null ? "null" : address.getHostAddress()) + " - ERR : ErrCreatingACC", "loginlog");
  532. _log.warning("Invalid username creation/use attempt: " + user);
  533. return false;
  534. }
  535. else
  536. {
  537. if (Config.LOG_LOGIN_CONTROLLER)
  538. Log.add("'" + (user == null ? "null" : user) + "' " + (address == null ? "null" : address.getHostAddress()) + " - ERR : AccountMissing", "loginlog");
  539. _log.warning("Account missing for user " + user);
  540. FailedLoginAttempt failedAttempt = _hackProtection.get(address);
  541. int failedCount;
  542. if (failedAttempt == null)
  543. {
  544. _hackProtection.put(address, new FailedLoginAttempt(address, password));
  545. failedCount = 1;
  546. }
  547. else
  548. {
  549. failedAttempt.increaseCounter();
  550. failedCount = failedAttempt.getCount();
  551. }
  552. if (failedCount >= Config.LOGIN_TRY_BEFORE_BAN)
  553. {
  554. _log.info("Banning '" + address.getHostAddress() + "' for " + Config.LOGIN_BLOCK_AFTER_BAN + " seconds due to "
  555. + failedCount + " invalid user name attempts");
  556. this.addBanForAddress(address, Config.LOGIN_BLOCK_AFTER_BAN * 1000);
  557. }
  558. return false;
  559. }
  560. }
  561. else
  562. {
  563. // is this account banned?
  564. if (access < 0)
  565. {
  566. if (Config.LOG_LOGIN_CONTROLLER)
  567. Log.add("'" + (user == null ? "null" : user) + "' " + (address == null ? "null" : address.getHostAddress()) + " - ERR : AccountBanned", "loginlog");
  568. client.setAccessLevel(access);
  569. return false;
  570. }
  571. // check password hash
  572. ok = true;
  573. for (int i = 0; i < expected.length; i++)
  574. {
  575. if (hash[i] != expected[i])
  576. {
  577. ok = false;
  578. break;
  579. }
  580. }
  581. }
  582. if (ok)
  583. {
  584. client.setAccessLevel(access);
  585. client.setLastServer(lastServer);
  586. statement = con.prepareStatement("UPDATE accounts SET lastactive=?, lastIP=? WHERE login=?");
  587. statement.setLong(1, System.currentTimeMillis());
  588. statement.setString(2, address.getHostAddress());
  589. statement.setString(3, user);
  590. statement.execute();
  591. statement.close();
  592. }
  593. }
  594. catch (Exception e)
  595. {
  596. _log.warning("Could not check password:" + e);
  597. ok = false;
  598. }
  599. finally
  600. {
  601. try
  602. {
  603. con.close();
  604. }
  605. catch (Exception e)
  606. {
  607. }
  608. }
  609. if (!ok)
  610. {
  611. if (Config.LOG_LOGIN_CONTROLLER)
  612. Log.add("'" + (user == null ? "null" : user) + "' " + (address == null ? "null" : address.getHostAddress()) + " - ERR : LoginFailed", "loginlog");
  613. FailedLoginAttempt failedAttempt = _hackProtection.get(address);
  614. int failedCount;
  615. if (failedAttempt == null)
  616. {
  617. _hackProtection.put(address, new FailedLoginAttempt(address, password));
  618. failedCount = 1;
  619. }
  620. else
  621. {
  622. failedAttempt.increaseCounter(password);
  623. failedCount = failedAttempt.getCount();
  624. }
  625. if (failedCount >= Config.LOGIN_TRY_BEFORE_BAN)
  626. {
  627. _log.info("Banning '" + address.getHostAddress() + "' for " + Config.LOGIN_BLOCK_AFTER_BAN + " seconds due to "
  628. + failedCount + " invalid user/pass attempts");
  629. this.addBanForAddress(address, Config.LOGIN_BLOCK_AFTER_BAN * 1000);
  630. }
  631. }
  632. else
  633. {
  634. _hackProtection.remove(address);
  635. if (Config.LOG_LOGIN_CONTROLLER)
  636. Log.add("'" + (user == null ? "null" : user) + "' " + (address == null ? "null" : address.getHostAddress()) + " - OK : LoginOk", "loginlog");
  637. }
  638. return ok;
  639. }
  640. public boolean loginBanned(String user)
  641. {
  642. boolean ok = false;
  643. Connection con = null;
  644. try
  645. {
  646. con = L2DatabaseFactory.getInstance().getConnection();
  647. PreparedStatement statement = con.prepareStatement("SELECT accessLevel FROM accounts WHERE login=?");
  648. statement.setString(1, user);
  649. ResultSet rset = statement.executeQuery();
  650. if (rset.next())
  651. {
  652. int accessLevel = rset.getInt(1);
  653. if (accessLevel < 0)
  654. ok = true;
  655. }
  656. rset.close();
  657. statement.close();
  658. }
  659. catch (Exception e)
  660. {
  661. // digest algo not found ??
  662. // out of bounds should not be possible
  663. _log.warning("could not check ban state:" + e);
  664. ok = false;
  665. }
  666. finally
  667. {
  668. try
  669. {
  670. con.close();
  671. }
  672. catch (Exception e)
  673. {
  674. }
  675. }
  676. return ok;
  677. }
  678. class FailedLoginAttempt
  679. {
  680. //private InetAddress _ipAddress;
  681. private int _count;
  682. private long _lastAttempTime;
  683. private String _lastPassword;
  684. public FailedLoginAttempt(InetAddress address, String lastPassword)
  685. {
  686. //_ipAddress = address;
  687. _count = 1;
  688. _lastAttempTime = System.currentTimeMillis();
  689. _lastPassword = lastPassword;
  690. }
  691. public void increaseCounter(String password)
  692. {
  693. if (!_lastPassword.equals(password))
  694. {
  695. // check if theres a long time since last wrong try
  696. if (System.currentTimeMillis() - _lastAttempTime < 300 * 1000)
  697. {
  698. _count++;
  699. }
  700. else
  701. {
  702. // restart the status
  703. _count = 1;
  704. }
  705. _lastPassword = password;
  706. _lastAttempTime = System.currentTimeMillis();
  707. }
  708. else
  709. //trying the same password is not brute force
  710. {
  711. _lastAttempTime = System.currentTimeMillis();
  712. }
  713. }
  714. public int getCount()
  715. {
  716. return _count;
  717. }
  718. public void increaseCounter()
  719. {
  720. _count++;
  721. }
  722. }
  723. class BanInfo
  724. {
  725. private InetAddress _ipAddress;
  726. // Expiration
  727. private long _expiration;
  728. public BanInfo(InetAddress ipAddress, long expiration)
  729. {
  730. _ipAddress = ipAddress;
  731. _expiration = expiration;
  732. }
  733. public InetAddress getAddress()
  734. {
  735. return _ipAddress;
  736. }
  737. public boolean hasExpired()
  738. {
  739. return System.currentTimeMillis() > _expiration && _expiration > 0;
  740. }
  741. }
  742. class PurgeThread extends Thread
  743. {
  744. @Override
  745. public void run()
  746. {
  747. for (;;)
  748. {
  749. synchronized (_clients)
  750. {
  751. for (Record e = _clients.head(), end = _clients.tail(); (e = e.getNext()) != end;)
  752. {
  753. L2LoginClient client = _clients.valueOf(e);
  754. if (client.getConnectionStartTime() + LOGIN_TIMEOUT >= System.currentTimeMillis())
  755. {
  756. client.close(LoginFailReason.REASON_ACCESS_FAILED);
  757. }
  758. }
  759. }
  760. synchronized (_loginServerClients)
  761. {
  762. for (FastMap.Entry<String, L2LoginClient> e = _loginServerClients.head(), end = _loginServerClients.tail(); (e = e.getNext()) != end;)
  763. {
  764. L2LoginClient client = e.getValue();
  765. if (client.getConnectionStartTime() + LOGIN_TIMEOUT >= System.currentTimeMillis())
  766. {
  767. client.close(LoginFailReason.REASON_ACCESS_FAILED);
  768. }
  769. }
  770. }
  771. try
  772. {
  773. Thread.sleep(2 * LOGIN_TIMEOUT);
  774. }
  775. catch (InterruptedException e)
  776. {
  777. e.printStackTrace();
  778. }
  779. }
  780. }
  781. }
  782. }