LoginController.java 23 KB

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