2
0

LoginController.java 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  1. /*
  2. * This program is free software: you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation, either version 3 of the License, or (at your option) any later
  5. * version.
  6. *
  7. * This program is distributed in the hope that it will be useful, but WITHOUT
  8. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  10. * details.
  11. *
  12. * You should have received a copy of the GNU General Public License along with
  13. * this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. package com.l2jserver.loginserver;
  16. import java.net.InetAddress;
  17. import java.net.UnknownHostException;
  18. import java.security.GeneralSecurityException;
  19. import java.security.KeyPairGenerator;
  20. import java.security.MessageDigest;
  21. import java.security.interfaces.RSAPrivateKey;
  22. import java.security.spec.RSAKeyGenParameterSpec;
  23. import java.sql.Connection;
  24. import java.sql.PreparedStatement;
  25. import java.sql.ResultSet;
  26. import java.util.Collection;
  27. import java.util.Map;
  28. import java.util.logging.Level;
  29. import java.util.logging.Logger;
  30. import javax.crypto.Cipher;
  31. import javolution.util.FastMap;
  32. import com.l2jserver.Base64;
  33. import com.l2jserver.Config;
  34. import com.l2jserver.L2DatabaseFactory;
  35. import com.l2jserver.loginserver.GameServerTable.GameServerInfo;
  36. import com.l2jserver.loginserver.gameserverpackets.ServerStatus;
  37. import com.l2jserver.loginserver.serverpackets.LoginFail.LoginFailReason;
  38. import com.l2jserver.util.Rnd;
  39. import com.l2jserver.util.crypt.ScrambledKeyPair;
  40. import com.l2jserver.util.lib.Log;
  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. if (_loginServerClients.putIfAbsent(account, client) == null)
  173. {
  174. ret = AuthLoginResult.AUTH_SUCCESS;
  175. }
  176. }
  177. }
  178. else
  179. {
  180. if (client.getAccessLevel() < 0)
  181. {
  182. ret = AuthLoginResult.ACCOUNT_BANNED;
  183. }
  184. }
  185. return ret;
  186. }
  187. /**
  188. * Adds the address to the ban list of the login server, with the given duration.
  189. *
  190. * @param address The Address to be banned.
  191. * @param expiration Timestamp in miliseconds when this ban expires
  192. * @throws UnknownHostException if the address is invalid.
  193. */
  194. public void addBanForAddress(String address, long expiration) throws UnknownHostException
  195. {
  196. InetAddress netAddress = InetAddress.getByName(address);
  197. if (!_bannedIps.containsKey(netAddress.getHostAddress()))
  198. _bannedIps.put(netAddress.getHostAddress(), new BanInfo(netAddress, expiration));
  199. }
  200. /**
  201. * Adds the address to the ban list of the login server, with the given duration.
  202. *
  203. * @param address The Address to be banned.
  204. * @param duration is miliseconds
  205. */
  206. public void addBanForAddress(InetAddress address, long duration)
  207. {
  208. if (!_bannedIps.containsKey(address.getHostAddress()))
  209. _bannedIps.put(address.getHostAddress(), new BanInfo(address, System.currentTimeMillis() + duration));
  210. }
  211. public boolean isBannedAddress(InetAddress address)
  212. {
  213. String[] parts = address.getHostAddress().split("\\.");
  214. BanInfo bi = _bannedIps.get(address.getHostAddress());
  215. if (bi == null)
  216. bi = _bannedIps.get(parts[0] + "." + parts[1] + "." + parts[2] + ".0");
  217. if (bi == null)
  218. bi = _bannedIps.get(parts[0] + "." + parts[1] + ".0.0");
  219. if (bi == null)
  220. bi = _bannedIps.get(parts[0] + ".0.0.0");
  221. if (bi != null)
  222. {
  223. if (bi.hasExpired())
  224. {
  225. _bannedIps.remove(address.getHostAddress());
  226. return false;
  227. }
  228. else
  229. {
  230. return true;
  231. }
  232. }
  233. return false;
  234. }
  235. public Map<String, BanInfo> getBannedIps()
  236. {
  237. return _bannedIps;
  238. }
  239. /**
  240. * Remove the specified address from the ban list
  241. * @param address The address to be removed from the ban list
  242. * @return true if the ban was removed, false if there was no ban for this ip
  243. */
  244. public boolean removeBanForAddress(InetAddress address)
  245. {
  246. return _bannedIps.remove(address.getHostAddress()) != null;
  247. }
  248. /**
  249. * Remove the specified address from the ban list
  250. * @param address The address to be removed from the ban list
  251. * @return true if the ban was removed, false if there was no ban for this ip or the address was invalid.
  252. */
  253. public boolean removeBanForAddress(String address)
  254. {
  255. try
  256. {
  257. return this.removeBanForAddress(InetAddress.getByName(address));
  258. }
  259. catch (UnknownHostException e)
  260. {
  261. return false;
  262. }
  263. }
  264. public SessionKey getKeyForAccount(String account)
  265. {
  266. L2LoginClient client = _loginServerClients.get(account);
  267. if (client != null)
  268. {
  269. return client.getSessionKey();
  270. }
  271. return null;
  272. }
  273. public int getOnlinePlayerCount(int serverId)
  274. {
  275. GameServerInfo gsi = GameServerTable.getInstance().getRegisteredGameServerById(serverId);
  276. if (gsi != null && gsi.isAuthed())
  277. {
  278. return gsi.getCurrentPlayerCount();
  279. }
  280. return 0;
  281. }
  282. public boolean isAccountInAnyGameServer(String account)
  283. {
  284. Collection<GameServerInfo> serverList = GameServerTable.getInstance().getRegisteredGameServers().values();
  285. for (GameServerInfo gsi : serverList)
  286. {
  287. GameServerThread gst = gsi.getGameServerThread();
  288. if (gst != null && gst.hasAccountOnGameServer(account))
  289. {
  290. return true;
  291. }
  292. }
  293. return false;
  294. }
  295. public GameServerInfo getAccountOnGameServer(String account)
  296. {
  297. Collection<GameServerInfo> serverList = GameServerTable.getInstance().getRegisteredGameServers().values();
  298. for (GameServerInfo gsi : serverList)
  299. {
  300. GameServerThread gst = gsi.getGameServerThread();
  301. if (gst != null && gst.hasAccountOnGameServer(account))
  302. {
  303. return gsi;
  304. }
  305. }
  306. return null;
  307. }
  308. public int getTotalOnlinePlayerCount()
  309. {
  310. int total = 0;
  311. Collection<GameServerInfo> serverList = GameServerTable.getInstance().getRegisteredGameServers().values();
  312. for (GameServerInfo gsi : serverList)
  313. {
  314. if (gsi.isAuthed())
  315. {
  316. total += gsi.getCurrentPlayerCount();
  317. }
  318. }
  319. return total;
  320. }
  321. public void getCharactersOnAccount(String account)
  322. {
  323. Collection<GameServerInfo> serverList = GameServerTable.getInstance().getRegisteredGameServers().values();
  324. for (GameServerInfo gsi : serverList)
  325. {
  326. if (gsi.isAuthed())
  327. gsi.getGameServerThread().requestCharacters(account);
  328. }
  329. }
  330. public int getMaxAllowedOnlinePlayers(int id)
  331. {
  332. GameServerInfo gsi = GameServerTable.getInstance().getRegisteredGameServerById(id);
  333. if (gsi != null)
  334. {
  335. return gsi.getMaxPlayers();
  336. }
  337. return 0;
  338. }
  339. /**
  340. *
  341. * @return
  342. */
  343. public boolean isLoginPossible(L2LoginClient client, int serverId)
  344. {
  345. GameServerInfo gsi = GameServerTable.getInstance().getRegisteredGameServerById(serverId);
  346. int access = client.getAccessLevel();
  347. if (gsi != null && gsi.isAuthed())
  348. {
  349. boolean loginOk = (gsi.getCurrentPlayerCount() < gsi.getMaxPlayers() && gsi.getStatus() != ServerStatus.STATUS_GM_ONLY)
  350. || access > 0;
  351. if (loginOk && client.getLastServer() != serverId)
  352. {
  353. Connection con = null;
  354. PreparedStatement statement = null;
  355. try
  356. {
  357. con = L2DatabaseFactory.getInstance().getConnection();
  358. String stmt = "UPDATE accounts SET lastServer = ? WHERE login = ?";
  359. statement = con.prepareStatement(stmt);
  360. statement.setInt(1, serverId);
  361. statement.setString(2, client.getAccount());
  362. statement.executeUpdate();
  363. statement.close();
  364. }
  365. catch (Exception e)
  366. {
  367. _log.log(Level.WARNING, "Could not set lastServer: " + e.getMessage(), e);
  368. }
  369. finally
  370. {
  371. L2DatabaseFactory.close(con);
  372. }
  373. }
  374. return loginOk;
  375. }
  376. return false;
  377. }
  378. public void setAccountAccessLevel(String account, int banLevel)
  379. {
  380. Connection con = null;
  381. PreparedStatement statement = null;
  382. try
  383. {
  384. con = L2DatabaseFactory.getInstance().getConnection();
  385. String stmt = "UPDATE accounts SET accessLevel=? WHERE login=?";
  386. statement = con.prepareStatement(stmt);
  387. statement.setInt(1, banLevel);
  388. statement.setString(2, account);
  389. statement.executeUpdate();
  390. statement.close();
  391. }
  392. catch (Exception e)
  393. {
  394. _log.log(Level.WARNING, "Could not set accessLevel: " + e.getMessage(), e);
  395. }
  396. finally
  397. {
  398. try
  399. {
  400. L2DatabaseFactory.close(con);
  401. }
  402. catch (Exception e)
  403. {
  404. }
  405. }
  406. }
  407. public void setAccountLastTracert(String account, String pcIp,
  408. String hop1, String hop2, String hop3, String hop4)
  409. {
  410. Connection con = null;
  411. PreparedStatement statement = null;
  412. try
  413. {
  414. con = L2DatabaseFactory.getInstance().getConnection();
  415. String stmt = "UPDATE accounts SET pcIp=?, hop1=?, hop2=?, hop3=?, hop4=? WHERE login=?";
  416. statement = con.prepareStatement(stmt);
  417. statement.setString(1, pcIp);
  418. statement.setString(2, hop1);
  419. statement.setString(3, hop2);
  420. statement.setString(4, hop3);
  421. statement.setString(5, hop4);
  422. statement.setString(6, account);
  423. statement.executeUpdate();
  424. statement.close();
  425. }
  426. catch (Exception e)
  427. {
  428. _log.log(Level.WARNING, "Could not set last tracert: " + e.getMessage(), e);
  429. }
  430. finally
  431. {
  432. try
  433. {
  434. L2DatabaseFactory.close(con);
  435. }
  436. catch (Exception e)
  437. {
  438. }
  439. }
  440. }
  441. public void setCharactersOnServer(String account, int charsNum, long[] timeToDel, int serverId)
  442. {
  443. L2LoginClient client = _loginServerClients.get(account);
  444. if (charsNum > 0)
  445. client.setCharsOnServ(serverId, charsNum);
  446. if (timeToDel.length > 0)
  447. client.serCharsWaitingDelOnServ(serverId, timeToDel);
  448. }
  449. public boolean isGM(String user)
  450. {
  451. boolean ok = false;
  452. Connection con = null;
  453. PreparedStatement statement = null;
  454. try
  455. {
  456. con = L2DatabaseFactory.getInstance().getConnection();
  457. statement = con.prepareStatement("SELECT accessLevel FROM accounts WHERE login=?");
  458. statement.setString(1, user);
  459. ResultSet rset = statement.executeQuery();
  460. if (rset.next())
  461. {
  462. int accessLevel = rset.getInt(1);
  463. if (accessLevel > 0)
  464. {
  465. ok = true;
  466. }
  467. }
  468. rset.close();
  469. statement.close();
  470. }
  471. catch (Exception e)
  472. {
  473. _log.log(Level.WARNING, "Could not check gm state:" + e.getMessage(), e);
  474. ok = false;
  475. }
  476. finally
  477. {
  478. try
  479. {
  480. L2DatabaseFactory.close(con);
  481. }
  482. catch (Exception e)
  483. {
  484. }
  485. }
  486. return ok;
  487. }
  488. /**
  489. * <p>This method returns one of the cached {@link ScrambledKeyPair ScrambledKeyPairs} for communication with Login Clients.</p>
  490. * @return a scrambled keypair
  491. */
  492. public ScrambledKeyPair getScrambledRSAKeyPair()
  493. {
  494. return _keyPairs[Rnd.nextInt(10)];
  495. }
  496. /**
  497. * user name is not case sensitive any more
  498. * @param user
  499. * @param password
  500. * @param address
  501. * @return
  502. */
  503. public boolean loginValid(String user, String password, L2LoginClient client)// throws HackingException
  504. {
  505. boolean ok = false;
  506. InetAddress address = client.getConnection().getInetAddress();
  507. // player disconnected meanwhile
  508. if (address == null || user == null)
  509. {
  510. return false;
  511. }
  512. Connection con = null;
  513. try
  514. {
  515. MessageDigest md = MessageDigest.getInstance("SHA");
  516. byte[] raw = password.getBytes("UTF-8");
  517. byte[] hash = md.digest(raw);
  518. byte[] expected = null;
  519. int access = 0;
  520. int lastServer = 1;
  521. String userIP = null;
  522. con = L2DatabaseFactory.getInstance().getConnection();
  523. PreparedStatement statement = con.prepareStatement("SELECT password, accessLevel, lastServer, userIP FROM accounts WHERE login=?");
  524. statement.setString(1, user);
  525. ResultSet rset = statement.executeQuery();
  526. if (rset.next())
  527. {
  528. expected = Base64.decode(rset.getString("password"));
  529. access = rset.getInt("accessLevel");
  530. lastServer = rset.getInt("lastServer");
  531. userIP = rset.getString("userIP");
  532. if (lastServer <= 0)
  533. lastServer = 1; // minServerId is 1 in Interlude
  534. if (Config.DEBUG)
  535. _log.fine("account exists");
  536. }
  537. rset.close();
  538. statement.close();
  539. // if account doesnt exists
  540. if (expected == null)
  541. {
  542. if (Config.AUTO_CREATE_ACCOUNTS)
  543. {
  544. if ((user.length() >= 2) && (user.length() <= 14))
  545. {
  546. statement = con.prepareStatement("INSERT INTO accounts (login,password,lastactive,accessLevel,lastIP) values(?,?,?,?,?)");
  547. statement.setString(1, user);
  548. statement.setString(2, Base64.encodeBytes(hash));
  549. statement.setLong(3, System.currentTimeMillis());
  550. statement.setInt(4, 0);
  551. statement.setString(5, address.getHostAddress());
  552. statement.execute();
  553. statement.close();
  554. if (Config.LOG_LOGIN_CONTROLLER)
  555. Log.add("'" + user + "' " + address.getHostAddress() + " - OK : AccountCreate", "loginlog");
  556. _log.info("Created new account for " + user);
  557. return true;
  558. }
  559. if (Config.LOG_LOGIN_CONTROLLER)
  560. Log.add("'" + user + "' " + address.getHostAddress() + " - ERR : ErrCreatingACC", "loginlog");
  561. _log.warning("Invalid username creation/use attempt: " + user);
  562. return false;
  563. }
  564. else
  565. {
  566. if (Config.LOG_LOGIN_CONTROLLER)
  567. Log.add("'" + user + "' " + address.getHostAddress() + " - ERR : AccountMissing", "loginlog");
  568. _log.warning("Account missing for user " + user);
  569. FailedLoginAttempt failedAttempt = _hackProtection.get(address);
  570. int failedCount;
  571. if (failedAttempt == null)
  572. {
  573. _hackProtection.put(address, new FailedLoginAttempt(address, password));
  574. failedCount = 1;
  575. }
  576. else
  577. {
  578. failedAttempt.increaseCounter();
  579. failedCount = failedAttempt.getCount();
  580. }
  581. if (failedCount >= Config.LOGIN_TRY_BEFORE_BAN)
  582. {
  583. _log.info("Banning '" + address.getHostAddress() + "' for " + Config.LOGIN_BLOCK_AFTER_BAN + " seconds due to "
  584. + failedCount + " invalid user name attempts");
  585. this.addBanForAddress(address, Config.LOGIN_BLOCK_AFTER_BAN * 1000);
  586. }
  587. return false;
  588. }
  589. }
  590. else
  591. {
  592. // is this account banned?
  593. if (access < 0)
  594. {
  595. if (Config.LOG_LOGIN_CONTROLLER)
  596. Log.add("'" + user + "' " + address.getHostAddress() + " - ERR : AccountBanned", "loginlog");
  597. client.setAccessLevel(access);
  598. return false;
  599. }
  600. // Check IP
  601. if (userIP != null)
  602. {
  603. if(!isValidIPAddress(userIP))
  604. {
  605. // Address is not valid so it's a domain name, get IP
  606. try
  607. {
  608. InetAddress addr = InetAddress.getByName(userIP);
  609. userIP = addr.getHostAddress();
  610. }
  611. catch(Exception e)
  612. {
  613. return false;
  614. }
  615. }
  616. if(!address.getHostAddress().equalsIgnoreCase(userIP))
  617. {
  618. if (Config.LOG_LOGIN_CONTROLLER)
  619. Log.add("'" + user + "' " + address.getHostAddress() + "/" + userIP + " - ERR : INCORRECT IP", "loginlog");
  620. return false;
  621. }
  622. }
  623. // check password hash
  624. ok = true;
  625. for (int i = 0; i < expected.length; i++)
  626. {
  627. if (hash[i] != expected[i])
  628. {
  629. ok = false;
  630. break;
  631. }
  632. }
  633. }
  634. if (ok)
  635. {
  636. client.setAccessLevel(access);
  637. client.setLastServer(lastServer);
  638. statement = con.prepareStatement("UPDATE accounts SET lastactive=?, lastIP=? WHERE login=?");
  639. statement.setLong(1, System.currentTimeMillis());
  640. statement.setString(2, address.getHostAddress());
  641. statement.setString(3, user);
  642. statement.execute();
  643. statement.close();
  644. }
  645. }
  646. catch (Exception e)
  647. {
  648. _log.log(Level.WARNING, "Could not check password:" + e.getMessage(), e);
  649. ok = false;
  650. }
  651. finally
  652. {
  653. L2DatabaseFactory.close(con);
  654. }
  655. if (!ok)
  656. {
  657. if (Config.LOG_LOGIN_CONTROLLER)
  658. Log.add("'" + user + "' " + address.getHostAddress() + " - ERR : LoginFailed", "loginlog");
  659. FailedLoginAttempt failedAttempt = _hackProtection.get(address);
  660. int failedCount;
  661. if (failedAttempt == null)
  662. {
  663. _hackProtection.put(address, new FailedLoginAttempt(address, password));
  664. failedCount = 1;
  665. }
  666. else
  667. {
  668. failedAttempt.increaseCounter(password);
  669. failedCount = failedAttempt.getCount();
  670. }
  671. if (failedCount >= Config.LOGIN_TRY_BEFORE_BAN)
  672. {
  673. _log.info("Banning '" + address.getHostAddress() + "' for " + Config.LOGIN_BLOCK_AFTER_BAN + " seconds due to "
  674. + failedCount + " invalid user/pass attempts");
  675. this.addBanForAddress(address, Config.LOGIN_BLOCK_AFTER_BAN * 1000);
  676. }
  677. }
  678. else
  679. {
  680. _hackProtection.remove(address);
  681. if (Config.LOG_LOGIN_CONTROLLER)
  682. Log.add("'" + user + "' " + address.getHostAddress() + " - OK : LoginOk", "loginlog");
  683. }
  684. return ok;
  685. }
  686. public boolean loginBanned(String user)
  687. {
  688. boolean ok = false;
  689. Connection con = null;
  690. try
  691. {
  692. con = L2DatabaseFactory.getInstance().getConnection();
  693. PreparedStatement statement = con.prepareStatement("SELECT accessLevel FROM accounts WHERE login=?");
  694. statement.setString(1, user);
  695. ResultSet rset = statement.executeQuery();
  696. if (rset.next())
  697. {
  698. int accessLevel = rset.getInt(1);
  699. if (accessLevel < 0)
  700. ok = true;
  701. }
  702. rset.close();
  703. statement.close();
  704. }
  705. catch (Exception e)
  706. {
  707. // digest algo not found ??
  708. // out of bounds should not be possible
  709. _log.log(Level.WARNING, "Could not check ban state:" + e.getMessage(), e);
  710. ok = false;
  711. }
  712. finally
  713. {
  714. try
  715. {
  716. L2DatabaseFactory.close(con);
  717. }
  718. catch (Exception e)
  719. {
  720. }
  721. }
  722. return ok;
  723. }
  724. public boolean isValidIPAddress(String ipAddress)
  725. {
  726. String[] parts = ipAddress.split("\\.");
  727. if (parts.length != 4)
  728. return false;
  729. for (String s : parts)
  730. {
  731. int i = Integer.parseInt(s);
  732. if ((i < 0) || (i > 255))
  733. return false;
  734. }
  735. return true;
  736. }
  737. class FailedLoginAttempt
  738. {
  739. //private InetAddress _ipAddress;
  740. private int _count;
  741. private long _lastAttempTime;
  742. private String _lastPassword;
  743. public FailedLoginAttempt(InetAddress address, String lastPassword)
  744. {
  745. //_ipAddress = address;
  746. _count = 1;
  747. _lastAttempTime = System.currentTimeMillis();
  748. _lastPassword = lastPassword;
  749. }
  750. public void increaseCounter(String password)
  751. {
  752. if (!_lastPassword.equals(password))
  753. {
  754. // check if theres a long time since last wrong try
  755. if (System.currentTimeMillis() - _lastAttempTime < 300 * 1000)
  756. {
  757. _count++;
  758. }
  759. else
  760. {
  761. // restart the status
  762. _count = 1;
  763. }
  764. _lastPassword = password;
  765. _lastAttempTime = System.currentTimeMillis();
  766. }
  767. else
  768. //trying the same password is not brute force
  769. {
  770. _lastAttempTime = System.currentTimeMillis();
  771. }
  772. }
  773. public int getCount()
  774. {
  775. return _count;
  776. }
  777. public void increaseCounter()
  778. {
  779. _count++;
  780. }
  781. }
  782. class BanInfo
  783. {
  784. private InetAddress _ipAddress;
  785. // Expiration
  786. private long _expiration;
  787. public BanInfo(InetAddress ipAddress, long expiration)
  788. {
  789. _ipAddress = ipAddress;
  790. _expiration = expiration;
  791. }
  792. public InetAddress getAddress()
  793. {
  794. return _ipAddress;
  795. }
  796. public boolean hasExpired()
  797. {
  798. return System.currentTimeMillis() > _expiration && _expiration > 0;
  799. }
  800. }
  801. class PurgeThread extends Thread
  802. {
  803. public PurgeThread()
  804. {
  805. setName("PurgeThread");
  806. }
  807. @Override
  808. public void run()
  809. {
  810. while (!isInterrupted())
  811. {
  812. for (L2LoginClient client : _loginServerClients.values())
  813. {
  814. if (client == null)
  815. continue;
  816. if ((client.getConnectionStartTime() + LOGIN_TIMEOUT) < System.currentTimeMillis())
  817. {
  818. client.close(LoginFailReason.REASON_ACCESS_FAILED);
  819. }
  820. }
  821. try
  822. {
  823. Thread.sleep(LOGIN_TIMEOUT / 2);
  824. }
  825. catch (InterruptedException e)
  826. {
  827. return;
  828. }
  829. }
  830. }
  831. }
  832. }