How to save into sql server database without user and password - java

I want to save data in sql server database without username or password. the code example is given bellow. Can anyone explain the cause of not save the data into database?
Thank in advance. Please help me
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://localhost:1433;databaseName=azan";
Connection con = null;
con = DriverManager.getConnection(url);
Statement st = con.createStatement();
String sql = "INSERT INTO huzaifa (username,password) VALUES ('"+username+"','"+password+"')";
st.executeUpdate(sql);
con.close();
}catch (Exception ex)
{
System.out.print(ex);
}//
%>

The only way you can do this is using JNDI Bound Datasource in the server. In general the way it works as follows:
Configure a datasource in the server. The username and password are part of the configuration.
The datasources is bound to to JNDI tree.
The datasource can be looked up into JNDI tree and from there a connection can be obtained.
Once you have the connection, you can fire queries.
Here is an example of how to do this in Tomcat.

I suggest you to move the database operation code in a Servlet rather than doing in JSP.
If you really you want to do in JSP as well then try to avoid Scriplet.
Use JSP Standard Tag Library and JSP Expression Language instead of using Scriplet that is more easy to manage and less error prone. Use SQL Tag Library that provides JSTL SQL tags for accessing databases in JSP.
sample code:
<sql:setDataSource var="dataSource"
driver="com.microsoft.sqlserver.jdbc.SQLServerDriver"
url="jdbc:sqlserver://localhost:1433;databaseName=azan" user=""
password="" />
<sql:update dataSource="${dataSource}"
sql="INSERT INTO huzaifa (username,password) VALUES ( values(?,?)">
<sql:param value="${param.username}" />
<sql:param value="${param.password}" />
</sql:update>

From a SQL Server perspective, if you don't wish to state the username and password in your application connection, you would need to use integrated security which passes the logged in user or user context that is configured in your web server.
I am not a java developer but have located the following specific to what you are trying to do and is hopefully helpful.
http://social.msdn.microsoft.com/Forums/sqlserver/en-US/3d8da2ca-4efb-41d6-bb08-b7193cf49753/jdbc-integrated-security-problem?forum=sqldataaccess

First let me understand your question. You are getting 2 values from the parameter and save it in database. Now you are trying to save the values without the column names?am i right?.
If this is the case, then you just use the INSERT command without column names.
e.g INSERT INTO table_name
VALUES (value1,value2,value3,...);
Or else, If you want to save a value in Database without giving the Authentication Username and Password, Its not possible, I hope..

Related

SQL Injection and possible attacks

Hi I have the following query which is part of a java class. I just want to know what are the possible attacks possible with the SQL Injection. How an attacker can inject queries? What are sample queries in this case that can be used to gain access to the database?
String query = ("SELECT username, password, admin FROM users
WHERE " + "username='" + username + "' AND password='" +
password + "'");
ResultSet rs = st.executeQuery(query);
// Entry in the result set means the query was successful and
//the user is a valid user
if (rs.next()) {
username = rs.getString(1);
isAdmin = rs.getBoolean(3);
I think this is a possible way of attack also by putting username as abc';# since anything after # will be considered as a comment in SQL. What others think about it?
I want to know what the attacker will be entering in the username box and password box of the HTML page to gain access as an administrator. Assuming the job of the above java class is to process the request of the users's input from a HTML page by querying a database.
basically it works like this https://xkcd.com/327/
what I do is assuming, that everything a user inputs is a threat, so I would save everything to variables like usUsername, where "us" means unsafe.
After that I check every "us"-variable for injections, what results in sUsername (s means safe). So when I build a query I can only use s-varaibles and should be safe in most cases.
This idea is totally taken from here: http://www.joelonsoftware.com/articles/Wrong.html
Based on this code you could do ANYTHING you want by manipulating the values of the username or password text sent to the query.
The only constraint is the level of permission of the user account executing the query. If it was a sysadmin, you could delete everything. If it's SQL Server and xp_cmdshell is enabled, you could format the hard drive of the SQL server.
SQL Injection is one of those things where if you can do something you can pretty much do anything.
Look into the Havij tool, that is a security research tool that can demonstrate the power of SQLi.
You can not do that. username and password can be replaced by anything leading to all types of queries. You must use a prepared statement to provide username and password
Entering the following values for password would add a row to the result set containing the values 'admin', 'dummy', 1 for username, password, and admin, respectively:
' AND 1=0 UNION SELECT 'admin', 'dummy', admin FROM users WHERE admin = 1 AND '1'='1
The resulting query would look like:
SELECT username, password, admin FROM users
WHERE username='dummy' AND password='' AND 1=0 UNION SELECT 'admin', 'dummy', admin FROM users WHERE admin = 1 AND '1'='1'
The first SELECT would return no result as 1=0 is false for each record. But the second, injected SELECT would return all records where admin=1 is true and replaces the original values for username and password with admin and dummy, respectively.
You should use prepared statements and pass the values as parameters on execution.

create a user on mysql database through java gui

I am coding an interface which manages a database with all DML and some DDL features. One feature should be, that an admin can add users to the database with specified priviledges.
I know how to grant priviledges in sql i only need it done via a java application.
So is there a way to get this done safely? It probably will work with a simple executeUpdate
String cu = "create user"+userName+" identified by "+pw+";";
Statement stmt;
stmt = con.createStatement();
stmt.executeUpdate(query);
but this opens my ass for injections. Is there a way to get this done safely by a preexisting method ?
Please help me out, mighty stackoverflow community :)
Yes, there is a better way of doing this. Use PrepredStatement instead of Statement.
You need gap and quation ' for password,
String cu = "create user "+userName+" identified by '"+pw+"';";
|
|_put gap here

Easiest way to access a xml form variable from java snippet in jsp page?

Basically, I have an xml form that redirects the user to another webpage. I need the form to also pass in a field that the user enters.
This form redirects the user to a jsp page and I'm using a java scriptlet in the page to create a sql database, but I can't figure out a way to access the user's input in that java scriplet.
Here is the java sciptlet:
<jsp:scriptlet><![CDATA[
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, "root", "");
stmt = con.createStatement();
stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS new_presidents_db;");
stmt.executeUpdate("use new_presidents_db");
stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS new_presidents_db;");
stmt.executeUpdate("DROP TABLE IF EXISTS presidents_table;");
stmt.executeUpdate("CREATE TABLE presidents_table (id INT, presidents_name varchar(50), PRIMARY KEY (id));");
stmt.executeUpdate("INSERT INTO presidents_table (id, presidents_name) VALUES ('1', 'George Washington')");
stmt.executeUpdate("INSERT INTO presidents_table (id, presidents_name) VALUES ('2', 'John Adams')");
stmt.executeUpdate("INSERT INTO presidents_table (id, presidents_name) VALUES ('3', 'Thomas Jefferson')");
ResultSet result = stmt.executeQuery("SELECT * FROM presidents_table;");
String resultString=null;
Integer i = 1;
while(result.next() && i < 3)
{
resultString=result.getString(i);
out.println(resultString);
i++;
}
con.close();
]]></jsp:scriptlet>
What I'd like is to include in the sql select statement, something like, SELECT * FROM presidents_table WHERE id = "user input variable here";
But I have no idea how to access that variable from the form.
I'm somewhat familiar with java but jsp and forms are completely new to me. Anybody know the best way to get this variable from the xml form?
First: DO NOT open database connection in your JSP. Do that in some model class and use servlet for communication between JSP and that model class. Basically, use MVC design pattern.
Second: Use String id = request.getParameter("id"); (in servlet of course) (if your component for input is for example: <input type="text" name="id">) to get user input.
Also, have a look at this PreparedStatement example to avoid SQL injection attacks.
Regards.

How to get UserName from java.sql.Connection?

I have a data source for SQLServer created in Weblogic with username 'sa'.
In code I am using following to get user name.
Context ctx = new InitialContext(prop);
Object obj = ctx.lookup("sqlserver1");
System.out.println("Data Source Found….");
DataSource ds = (DataSource) obj;
Connection conn = ds.getConnection();
DatabaseMetaData mtdt = conn.getMetaData();
// Get UserName
System.out.println("User name: " + mtdt.getUserName());
But above code always returns 'dbo' as the username. I expected the username to be 'sa'. If the DB is Oracle it works fine. Is there a generic way for me to get user name for all different types of database.
The correct method should be DatabaseMetaData.getUserName(), but as you demonstrate not all databases implement that correctly. Another way would be to use the JDBC function escape USER() eg (eg SELECT {fn USER()} FROM DUAL), but not all drivers implement all JDBC escapes, and it could just be that this returns the same as the DatabaseMetaData. You could also try the SQL standard defined CURRENT_USER (or USER) in a query, but there you have two problems: 1) some databases require you to select from a table (eg DUAL in Oracle, some don't) and 2) not all databases implement all parts of the SQL standards, so the CURRENT_USER or USER context variable might be absent.
But as you have the DataSource object, you could try to get the user property from the datasource (it is defined in table 9.1 of the JDBC 4.1 specification, although the property names described there are not all required).
So for example:
Method getter = new PropertyDescriptor("user", ds.getClass()).getReadMethod();
String value = (String) getter.invoke(ds);
This assume that 1) the DataSource ds has a getUser() and 2) that it is actually set (for example with SQL Server integrated security the datasource doesn't need to know about a user).
FWIW, Java 1.7 provides the Connection.getSchema() method. I don't know how widely 1.7 has been adopted at this point however, so this might just be something to keep in mind for future reference.

Using Java (HTMLUnit) to Scrape a Web Page then Write Results to a mySQL Database

I've been able to use Java and HTMLUnit to scrape a web page, however I'm unsure how I can get this to write the resulting data to a MySQL database on a remote hosted server. I also need this to happen at regular intervals (perhaps once a day) if possible, without having to manually run the program.
Is this possible and can I have any guidance, thorough or not, on how to do this?
Thanks!
Get your page's HTML into some String variable
String scrapedHtml = "";
Create a table in mysql with a text field
create table html_store (
id int primary key autoincrement,
content text not null
);
Use JDBC code to connect to the database and inset the data. Set the connectionURL and other parameters correctly
Connection conn = DriverManager.getConnection(connectionURL, user, password);
PreparedStatement pstmt =
conn.prepareStatement("insert into html_store (content) values (?)");
pstmt.setString(1, scrapedHtml);
pstmt.executeUpdate();
pstmt.close();
conn.close();

Categories

Resources