LoginController.java 23 KB

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