问题
Is there any method to avoid SQL injection and other security failure in JavaFX desktop application? If yes, how can I do it?
回答1:
SQL Injection attacks are related to malicious statements deliberately sent by the end user to the database, while JavaFX is the front-end from a user's point of view.
That said, let's assume you have a login screen to input user and password. Could you prevent the user to type one of the following sentences instead of their real user name?
DROP TABLE Users; --or
DELETE FROM Users WHERE 1=1;
You could validate the text looking for certain keywords like DROP, INSERT, UPDATE or DELETE. But is it worth? Maybe it does, depending on how probably is the users will try to go ahead with this kind of attacks.
However the best way to mitigate and frustrate SQL injection begins from the connection itself. Tipically you'll want to connect to the database with users that have the less necessary privileges to operate. A common practice is to create a dedicate user to do the login for example, with read-only access to the Users table and maybe INSERT and UPDATE granted to a Sessions table (if you are interested in keep a sessions log of course):
CREATE USER 'login_user'@'%' IDENTIFIED BY 'password';
GRANT USAGE ON MyDataBase.* TO 'login_user'@'%';
GRANT SELECT ON Users TO 'login_user'@'%';
GRANT INSERT, UPDATE ON Sessions TO 'login_user'@'%';
Note: the snippet is based on MySQL but the same concept applies to other RDBMS as well.
In this scenario, if the end user succeeds in sending one of the above sentences to the database, the db user which was established the connection wont' have enough privileges to perform none of those sentences and will cause an SQL exception. The same applies to other entities as well, just provide a db user with the less privileges to operate with sensistive data.
In addition, JDBC provides PreparedStatement interface which is intended to avoid SQL injection by using placeholders to build the statements. For example:
String sql = "SELECT * FROM Users WHERE username = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, userName);
The userName parameter will be wrapped into literals before sent the statement to the database so if the user types one of the above malicious sentences they won't have any effect. Plus, if you want to execute more than one sentence you have to use addBatch() and executeBatch() which is under developer's control, making it even safer.
来源:https://stackoverflow.com/questions/28109969/how-to-avoid-sql-injection-and-other-security-failure-in-javafx-desktop-applicat