LoginController.java 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  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. import javolution.util.FastSet;
  42. import javolution.util.FastCollection.Record;
  43. /**
  44. * This class ...
  45. *
  46. * @version $Revision: 1.7.4.3 $ $Date: 2005/03/27 15:30:09 $
  47. */
  48. public class LoginController
  49. {
  50. protected static final Logger _log = Logger.getLogger(LoginController.class.getName());
  51. private static LoginController _instance;
  52. /** Time before kicking the client if he didnt logged yet */
  53. private final static int LOGIN_TIMEOUT = 60 * 1000;
  54. /** Clients that are on the LS but arent assocated with a account yet*/
  55. protected FastSet<L2LoginClient> _clients = new FastSet<L2LoginClient>();
  56. /** Authed Clients on LoginServer*/
  57. protected FastMap<String, L2LoginClient> _loginServerClients = new FastMap<String, L2LoginClient>().shared();
  58. private Map<String, BanInfo> _bannedIps = new FastMap<String, BanInfo>().shared();
  59. private Map<InetAddress, FailedLoginAttempt> _hackProtection;
  60. protected ScrambledKeyPair[] _keyPairs;
  61. protected byte[][] _blowfishKeys;
  62. private static final int BLOWFISH_KEYS = 20;
  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. }
  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 void addLoginClient(L2LoginClient client)
  132. {
  133. synchronized (_clients)
  134. {
  135. _clients.add(client);
  136. }
  137. }
  138. public void removeLoginClient(L2LoginClient client)
  139. {
  140. synchronized (_clients)
  141. {
  142. _clients.remove(client);
  143. }
  144. }
  145. public SessionKey assignSessionKeyToClient(String account, L2LoginClient client)
  146. {
  147. SessionKey key;
  148. key = new SessionKey(Rnd.nextInt(), Rnd.nextInt(), Rnd.nextInt(), Rnd.nextInt());
  149. _loginServerClients.put(account, client);
  150. return key;
  151. }
  152. public void removeAuthedLoginClient(String account)
  153. {
  154. _loginServerClients.remove(account);
  155. }
  156. public boolean isAccountInLoginServer(String account)
  157. {
  158. return _loginServerClients.containsKey(account);
  159. }
  160. public L2LoginClient getAuthedClient(String account)
  161. {
  162. return _loginServerClients.get(account);
  163. }
  164. public static enum AuthLoginResult
  165. {
  166. INVALID_PASSWORD,
  167. ACCOUNT_BANNED,
  168. ALREADY_ON_LS,
  169. ALREADY_ON_GS,
  170. AUTH_SUCCESS
  171. }
  172. public AuthLoginResult tryAuthLogin(String account, String password, L2LoginClient client) throws HackingException
  173. {
  174. AuthLoginResult ret = AuthLoginResult.INVALID_PASSWORD;
  175. // check auth
  176. if (loginValid(account, password, client))
  177. {
  178. // login was successful, verify presence on Gameservers
  179. ret = AuthLoginResult.ALREADY_ON_GS;
  180. if (!isAccountInAnyGameServer(account))
  181. {
  182. // account isnt on any GS verify LS itself
  183. ret = AuthLoginResult.ALREADY_ON_LS;
  184. // dont allow 2 simultaneous login
  185. synchronized (_loginServerClients)
  186. {
  187. if (!_loginServerClients.containsKey(account))
  188. {
  189. _loginServerClients.put(account, client);
  190. ret = AuthLoginResult.AUTH_SUCCESS;
  191. // remove him from the non-authed list
  192. removeLoginClient(client);
  193. }
  194. }
  195. }
  196. }
  197. else
  198. {
  199. if (client.getAccessLevel() < 0)
  200. {
  201. ret = AuthLoginResult.ACCOUNT_BANNED;
  202. }
  203. }
  204. return ret;
  205. }
  206. /**
  207. * Adds the address to the ban list of the login server, with the given duration.
  208. *
  209. * @param address The Address to be banned.
  210. * @param expiration Timestamp in miliseconds when this ban expires
  211. * @throws UnknownHostException if the address is invalid.
  212. */
  213. public void addBanForAddress(String address, long expiration) throws UnknownHostException
  214. {
  215. InetAddress netAddress = InetAddress.getByName(address);
  216. if (!_bannedIps.containsKey(netAddress.getHostAddress()))
  217. _bannedIps.put(netAddress.getHostAddress(), new BanInfo(netAddress, expiration));
  218. }
  219. /**
  220. * Adds the address to the ban list of the login server, with the given duration.
  221. *
  222. * @param address The Address to be banned.
  223. * @param duration is miliseconds
  224. */
  225. public void addBanForAddress(InetAddress address, long duration)
  226. {
  227. if (!_bannedIps.containsKey(address.getHostAddress()))
  228. _bannedIps.put(address.getHostAddress(), new BanInfo(address, System.currentTimeMillis() + duration));
  229. }
  230. public boolean isBannedAddress(InetAddress address)
  231. {
  232. String[] parts = address.getHostAddress().split("\\.");
  233. BanInfo bi = _bannedIps.get(address.getHostAddress());
  234. if (bi == null)
  235. bi = _bannedIps.get(parts[0] + "." + parts[1] + "." + parts[2] + ".0");
  236. if (bi == null)
  237. bi = _bannedIps.get(parts[0] + "." + parts[1] + ".0.0");
  238. if (bi == null)
  239. bi = _bannedIps.get(parts[0] + ".0.0.0");
  240. if (bi != null)
  241. {
  242. if (bi.hasExpired())
  243. {
  244. _bannedIps.remove(address.getHostAddress());
  245. return false;
  246. }
  247. else
  248. {
  249. return true;
  250. }
  251. }
  252. return false;
  253. }
  254. public Map<String, BanInfo> getBannedIps()
  255. {
  256. return _bannedIps;
  257. }
  258. /**
  259. * Remove the specified address from the ban list
  260. * @param address The address to be removed from the ban list
  261. * @return true if the ban was removed, false if there was no ban for this ip
  262. */
  263. public boolean removeBanForAddress(InetAddress address)
  264. {
  265. return _bannedIps.remove(address.getHostAddress()) != null;
  266. }
  267. /**
  268. * Remove the specified address from the ban list
  269. * @param address The address to be removed from the ban list
  270. * @return true if the ban was removed, false if there was no ban for this ip or the address was invalid.
  271. */
  272. public boolean removeBanForAddress(String address)
  273. {
  274. try
  275. {
  276. return this.removeBanForAddress(InetAddress.getByName(address));
  277. }
  278. catch (UnknownHostException e)
  279. {
  280. return false;
  281. }
  282. }
  283. public SessionKey getKeyForAccount(String account)
  284. {
  285. L2LoginClient client = _loginServerClients.get(account);
  286. if (client != null)
  287. {
  288. return client.getSessionKey();
  289. }
  290. return null;
  291. }
  292. public int getOnlinePlayerCount(int serverId)
  293. {
  294. GameServerInfo gsi = GameServerTable.getInstance().getRegisteredGameServerById(serverId);
  295. if (gsi != null && gsi.isAuthed())
  296. {
  297. return gsi.getCurrentPlayerCount();
  298. }
  299. return 0;
  300. }
  301. public boolean isAccountInAnyGameServer(String account)
  302. {
  303. Collection<GameServerInfo> serverList = GameServerTable.getInstance().getRegisteredGameServers().values();
  304. for (GameServerInfo gsi : serverList)
  305. {
  306. GameServerThread gst = gsi.getGameServerThread();
  307. if (gst != null && gst.hasAccountOnGameServer(account))
  308. {
  309. return true;
  310. }
  311. }
  312. return false;
  313. }
  314. public GameServerInfo getAccountOnGameServer(String account)
  315. {
  316. Collection<GameServerInfo> serverList = GameServerTable.getInstance().getRegisteredGameServers().values();
  317. for (GameServerInfo gsi : serverList)
  318. {
  319. GameServerThread gst = gsi.getGameServerThread();
  320. if (gst != null && gst.hasAccountOnGameServer(account))
  321. {
  322. return gsi;
  323. }
  324. }
  325. return null;
  326. }
  327. public int getTotalOnlinePlayerCount()
  328. {
  329. int total = 0;
  330. Collection<GameServerInfo> serverList = GameServerTable.getInstance().getRegisteredGameServers().values();
  331. for (GameServerInfo gsi : serverList)
  332. {
  333. if (gsi.isAuthed())
  334. {
  335. total += gsi.getCurrentPlayerCount();
  336. }
  337. }
  338. return total;
  339. }
  340. public int getMaxAllowedOnlinePlayers(int id)
  341. {
  342. GameServerInfo gsi = GameServerTable.getInstance().getRegisteredGameServerById(id);
  343. if (gsi != null)
  344. {
  345. return gsi.getMaxPlayers();
  346. }
  347. return 0;
  348. }
  349. /**
  350. *
  351. * @return
  352. */
  353. public boolean isLoginPossible(L2LoginClient client, int serverId)
  354. {
  355. GameServerInfo gsi = GameServerTable.getInstance().getRegisteredGameServerById(serverId);
  356. int access = client.getAccessLevel();
  357. if (gsi != null && gsi.isAuthed())
  358. {
  359. boolean loginOk = (gsi.getCurrentPlayerCount() < gsi.getMaxPlayers() && gsi.getStatus() != ServerStatus.STATUS_GM_ONLY)
  360. || access > 0;
  361. if (loginOk && client.getLastServer() != serverId)
  362. {
  363. Connection con = null;
  364. PreparedStatement statement = null;
  365. try
  366. {
  367. con = L2DatabaseFactory.getInstance().getConnection();
  368. String stmt = "UPDATE accounts SET lastServer = ? WHERE login = ?";
  369. statement = con.prepareStatement(stmt);
  370. statement.setInt(1, serverId);
  371. statement.setString(2, client.getAccount());
  372. statement.executeUpdate();
  373. statement.close();
  374. }
  375. catch (Exception e)
  376. {
  377. _log.log(Level.WARNING, "Could not set lastServer: " + e.getMessage(), e);
  378. }
  379. finally
  380. {
  381. try
  382. {
  383. con.close();
  384. }
  385. catch (Exception e)
  386. {
  387. }
  388. }
  389. }
  390. return loginOk;
  391. }
  392. return false;
  393. }
  394. public void setAccountAccessLevel(String account, int banLevel)
  395. {
  396. Connection con = null;
  397. PreparedStatement statement = null;
  398. try
  399. {
  400. con = L2DatabaseFactory.getInstance().getConnection();
  401. String stmt = "UPDATE accounts SET accessLevel=? WHERE login=?";
  402. statement = con.prepareStatement(stmt);
  403. statement.setInt(1, banLevel);
  404. statement.setString(2, account);
  405. statement.executeUpdate();
  406. statement.close();
  407. }
  408. catch (Exception e)
  409. {
  410. _log.log(Level.WARNING, "Could not set accessLevel: " + e.getMessage(), e);
  411. }
  412. finally
  413. {
  414. try
  415. {
  416. con.close();
  417. }
  418. catch (Exception e)
  419. {
  420. }
  421. }
  422. }
  423. public void setAccountLastTracert(String account, String pcIp,
  424. String hop1, String hop2, String hop3, String hop4)
  425. {
  426. Connection con = null;
  427. PreparedStatement statement = null;
  428. try
  429. {
  430. con = L2DatabaseFactory.getInstance().getConnection();
  431. String stmt = "UPDATE accounts SET pcIp=?, hop1=?, hop2=?, hop3=?, hop4=? WHERE login=?";
  432. statement = con.prepareStatement(stmt);
  433. statement.setString(1, pcIp);
  434. statement.setString(2, hop1);
  435. statement.setString(3, hop2);
  436. statement.setString(4, hop3);
  437. statement.setString(5, hop4);
  438. statement.setString(6, account);
  439. statement.executeUpdate();
  440. statement.close();
  441. }
  442. catch (Exception e)
  443. {
  444. _log.log(Level.WARNING, "Could not set last tracert: " + e.getMessage(), e);
  445. }
  446. finally
  447. {
  448. try
  449. {
  450. con.close();
  451. }
  452. catch (Exception e)
  453. {
  454. }
  455. }
  456. }
  457. public boolean isGM(String user)
  458. {
  459. boolean ok = false;
  460. Connection con = null;
  461. PreparedStatement statement = null;
  462. try
  463. {
  464. con = L2DatabaseFactory.getInstance().getConnection();
  465. statement = con.prepareStatement("SELECT accessLevel FROM accounts WHERE login=?");
  466. statement.setString(1, user);
  467. ResultSet rset = statement.executeQuery();
  468. if (rset.next())
  469. {
  470. int accessLevel = rset.getInt(1);
  471. if (accessLevel > 0)
  472. {
  473. ok = true;
  474. }
  475. }
  476. rset.close();
  477. statement.close();
  478. }
  479. catch (Exception e)
  480. {
  481. _log.log(Level.WARNING, "Could not check gm state:" + e.getMessage(), e);
  482. ok = false;
  483. }
  484. finally
  485. {
  486. try
  487. {
  488. con.close();
  489. }
  490. catch (Exception e)
  491. {
  492. }
  493. }
  494. return ok;
  495. }
  496. /**
  497. * <p>This method returns one of the cached {@link ScrambledKeyPair ScrambledKeyPairs} for communication with Login Clients.</p>
  498. * @return a scrambled keypair
  499. */
  500. public ScrambledKeyPair getScrambledRSAKeyPair()
  501. {
  502. return _keyPairs[Rnd.nextInt(10)];
  503. }
  504. /**
  505. * user name is not case sensitive any more
  506. * @param user
  507. * @param password
  508. * @param address
  509. * @return
  510. */
  511. public boolean loginValid(String user, String password, L2LoginClient client)// throws HackingException
  512. {
  513. boolean ok = false;
  514. InetAddress address = client.getConnection().getInetAddress();
  515. // player disconnected meanwhile
  516. if (address == null || user == null)
  517. {
  518. return false;
  519. }
  520. Connection con = null;
  521. try
  522. {
  523. MessageDigest md = MessageDigest.getInstance("SHA");
  524. byte[] raw = password.getBytes("UTF-8");
  525. byte[] hash = md.digest(raw);
  526. byte[] expected = null;
  527. int access = 0;
  528. int lastServer = 1;
  529. String userIP = null;
  530. con = L2DatabaseFactory.getInstance().getConnection();
  531. PreparedStatement statement = con.prepareStatement("SELECT password, accessLevel, lastServer, userIP FROM accounts WHERE login=?");
  532. statement.setString(1, user);
  533. ResultSet rset = statement.executeQuery();
  534. if (rset.next())
  535. {
  536. expected = Base64.decode(rset.getString("password"));
  537. access = rset.getInt("accessLevel");
  538. lastServer = rset.getInt("lastServer");
  539. userIP = rset.getString("userIP");
  540. if (lastServer <= 0)
  541. lastServer = 1; // minServerId is 1 in Interlude
  542. if (Config.DEBUG)
  543. _log.fine("account exists");
  544. }
  545. rset.close();
  546. statement.close();
  547. // if account doesnt exists
  548. if (expected == null)
  549. {
  550. if (Config.AUTO_CREATE_ACCOUNTS)
  551. {
  552. if ((user.length() >= 2) && (user.length() <= 14))
  553. {
  554. statement = con.prepareStatement("INSERT INTO accounts (login,password,lastactive,accessLevel,lastIP) values(?,?,?,?,?)");
  555. statement.setString(1, user);
  556. statement.setString(2, Base64.encodeBytes(hash));
  557. statement.setLong(3, System.currentTimeMillis());
  558. statement.setInt(4, 0);
  559. statement.setString(5, address.getHostAddress());
  560. statement.execute();
  561. statement.close();
  562. if (Config.LOG_LOGIN_CONTROLLER)
  563. Log.add("'" + user + "' " + address.getHostAddress() + " - OK : AccountCreate", "loginlog");
  564. _log.info("Created new account for " + user);
  565. return true;
  566. }
  567. if (Config.LOG_LOGIN_CONTROLLER)
  568. Log.add("'" + user + "' " + address.getHostAddress() + " - ERR : ErrCreatingACC", "loginlog");
  569. _log.warning("Invalid username creation/use attempt: " + user);
  570. return false;
  571. }
  572. else
  573. {
  574. if (Config.LOG_LOGIN_CONTROLLER)
  575. Log.add("'" + user + "' " + address.getHostAddress() + " - ERR : AccountMissing", "loginlog");
  576. _log.warning("Account missing for user " + user);
  577. FailedLoginAttempt failedAttempt = _hackProtection.get(address);
  578. int failedCount;
  579. if (failedAttempt == null)
  580. {
  581. _hackProtection.put(address, new FailedLoginAttempt(address, password));
  582. failedCount = 1;
  583. }
  584. else
  585. {
  586. failedAttempt.increaseCounter();
  587. failedCount = failedAttempt.getCount();
  588. }
  589. if (failedCount >= Config.LOGIN_TRY_BEFORE_BAN)
  590. {
  591. _log.info("Banning '" + address.getHostAddress() + "' for " + Config.LOGIN_BLOCK_AFTER_BAN + " seconds due to "
  592. + failedCount + " invalid user name attempts");
  593. this.addBanForAddress(address, Config.LOGIN_BLOCK_AFTER_BAN * 1000);
  594. }
  595. return false;
  596. }
  597. }
  598. else
  599. {
  600. // is this account banned?
  601. if (access < 0)
  602. {
  603. if (Config.LOG_LOGIN_CONTROLLER)
  604. Log.add("'" + user + "' " + address.getHostAddress() + " - ERR : AccountBanned", "loginlog");
  605. client.setAccessLevel(access);
  606. return false;
  607. }
  608. // Check IP
  609. if (userIP != null && !address.getHostAddress().equalsIgnoreCase(userIP))
  610. {
  611. if (Config.LOG_LOGIN_CONTROLLER)
  612. Log.add("'" + user + "' " + address.getHostAddress() + "/" + userIP + " - ERR : INCORRECT IP", "loginlog");
  613. return false;
  614. }
  615. // check password hash
  616. ok = true;
  617. for (int i = 0; i < expected.length; i++)
  618. {
  619. if (hash[i] != expected[i])
  620. {
  621. ok = false;
  622. break;
  623. }
  624. }
  625. }
  626. if (ok)
  627. {
  628. client.setAccessLevel(access);
  629. client.setLastServer(lastServer);
  630. statement = con.prepareStatement("UPDATE accounts SET lastactive=?, lastIP=? WHERE login=?");
  631. statement.setLong(1, System.currentTimeMillis());
  632. statement.setString(2, address.getHostAddress());
  633. statement.setString(3, user);
  634. statement.execute();
  635. statement.close();
  636. }
  637. }
  638. catch (Exception e)
  639. {
  640. _log.log(Level.WARNING, "Could not check password:" + e.getMessage(), e);
  641. ok = false;
  642. }
  643. finally
  644. {
  645. try
  646. {
  647. con.close();
  648. }
  649. catch (Exception e)
  650. {
  651. }
  652. }
  653. if (!ok)
  654. {
  655. if (Config.LOG_LOGIN_CONTROLLER)
  656. Log.add("'" + user + "' " + address.getHostAddress() + " - ERR : LoginFailed", "loginlog");
  657. FailedLoginAttempt failedAttempt = _hackProtection.get(address);
  658. int failedCount;
  659. if (failedAttempt == null)
  660. {
  661. _hackProtection.put(address, new FailedLoginAttempt(address, password));
  662. failedCount = 1;
  663. }
  664. else
  665. {
  666. failedAttempt.increaseCounter(password);
  667. failedCount = failedAttempt.getCount();
  668. }
  669. if (failedCount >= Config.LOGIN_TRY_BEFORE_BAN)
  670. {
  671. _log.info("Banning '" + address.getHostAddress() + "' for " + Config.LOGIN_BLOCK_AFTER_BAN + " seconds due to "
  672. + failedCount + " invalid user/pass attempts");
  673. this.addBanForAddress(address, Config.LOGIN_BLOCK_AFTER_BAN * 1000);
  674. }
  675. }
  676. else
  677. {
  678. _hackProtection.remove(address);
  679. if (Config.LOG_LOGIN_CONTROLLER)
  680. Log.add("'" + user + "' " + address.getHostAddress() + " - OK : LoginOk", "loginlog");
  681. }
  682. return ok;
  683. }
  684. public boolean loginBanned(String user)
  685. {
  686. boolean ok = false;
  687. Connection con = null;
  688. try
  689. {
  690. con = L2DatabaseFactory.getInstance().getConnection();
  691. PreparedStatement statement = con.prepareStatement("SELECT accessLevel FROM accounts WHERE login=?");
  692. statement.setString(1, user);
  693. ResultSet rset = statement.executeQuery();
  694. if (rset.next())
  695. {
  696. int accessLevel = rset.getInt(1);
  697. if (accessLevel < 0)
  698. ok = true;
  699. }
  700. rset.close();
  701. statement.close();
  702. }
  703. catch (Exception e)
  704. {
  705. // digest algo not found ??
  706. // out of bounds should not be possible
  707. _log.log(Level.WARNING, "Could not check ban state:" + e.getMessage(), e);
  708. ok = false;
  709. }
  710. finally
  711. {
  712. try
  713. {
  714. con.close();
  715. }
  716. catch (Exception e)
  717. {
  718. }
  719. }
  720. return ok;
  721. }
  722. class FailedLoginAttempt
  723. {
  724. //private InetAddress _ipAddress;
  725. private int _count;
  726. private long _lastAttempTime;
  727. private String _lastPassword;
  728. public FailedLoginAttempt(InetAddress address, String lastPassword)
  729. {
  730. //_ipAddress = address;
  731. _count = 1;
  732. _lastAttempTime = System.currentTimeMillis();
  733. _lastPassword = lastPassword;
  734. }
  735. public void increaseCounter(String password)
  736. {
  737. if (!_lastPassword.equals(password))
  738. {
  739. // check if theres a long time since last wrong try
  740. if (System.currentTimeMillis() - _lastAttempTime < 300 * 1000)
  741. {
  742. _count++;
  743. }
  744. else
  745. {
  746. // restart the status
  747. _count = 1;
  748. }
  749. _lastPassword = password;
  750. _lastAttempTime = System.currentTimeMillis();
  751. }
  752. else
  753. //trying the same password is not brute force
  754. {
  755. _lastAttempTime = System.currentTimeMillis();
  756. }
  757. }
  758. public int getCount()
  759. {
  760. return _count;
  761. }
  762. public void increaseCounter()
  763. {
  764. _count++;
  765. }
  766. }
  767. class BanInfo
  768. {
  769. private InetAddress _ipAddress;
  770. // Expiration
  771. private long _expiration;
  772. public BanInfo(InetAddress ipAddress, long expiration)
  773. {
  774. _ipAddress = ipAddress;
  775. _expiration = expiration;
  776. }
  777. public InetAddress getAddress()
  778. {
  779. return _ipAddress;
  780. }
  781. public boolean hasExpired()
  782. {
  783. return System.currentTimeMillis() > _expiration && _expiration > 0;
  784. }
  785. }
  786. class PurgeThread extends Thread
  787. {
  788. @Override
  789. public void run()
  790. {
  791. for (;;)
  792. {
  793. synchronized (_clients)
  794. {
  795. for (Record e = _clients.head(), end = _clients.tail(); (e = e.getNext()) != end;)
  796. {
  797. L2LoginClient client = _clients.valueOf(e);
  798. if (client.getConnectionStartTime() + LOGIN_TIMEOUT >= System.currentTimeMillis())
  799. {
  800. client.close(LoginFailReason.REASON_ACCESS_FAILED);
  801. }
  802. }
  803. }
  804. synchronized (_loginServerClients)
  805. {
  806. for (FastMap.Entry<String, L2LoginClient> e = _loginServerClients.head(), end = _loginServerClients.tail(); (e = e.getNext()) != end;)
  807. {
  808. L2LoginClient client = e.getValue();
  809. if (client.getConnectionStartTime() + LOGIN_TIMEOUT >= System.currentTimeMillis())
  810. {
  811. client.close(LoginFailReason.REASON_ACCESS_FAILED);
  812. }
  813. }
  814. }
  815. try
  816. {
  817. Thread.sleep(2 * LOGIN_TIMEOUT);
  818. }
  819. catch (InterruptedException e)
  820. {
  821. e.printStackTrace();
  822. }
  823. }
  824. }
  825. }
  826. }