Oracle Database and .NET (C#) - How to prevent SQL Injections - asp.net

I'll use a select in asp.net page which i.e:
string name=TexBox1.Text;
string pas=TextBox2.Text;
string c="select * from users where name='"+name+"' and password ='"+pas+"'";
İs there any methods to preventing sql injections.

First, you must validate the input data in your code and then use it like parameters..
because if occurs an unhandled exception and you are returning sensitive data like "connection strings" you are giving usefull information like "Column" and "Table"names and that is dangerous.
Second, add a "Data Access Layer" to handle your code not in "Code Behind". You can use "Store Procedures" and call them from your code, using this way you hide the query of the programming logic and only pass parameters to the store preocedure and he do the job and you only return the error in the case that a exception occurs.
This preventions are the basics in a small application but exists many others way to avoid SQL Injections.

Related

Where does the Output go when Print 'Something' in a Trigger?

I'm using SQL Server 2008 R2
If I want to show Print statement from trigger to my .aspx page, Is it possible to return any variable value from trigger ?
Is it possible to use string function i.e. String.Contains() and String.Split() on column value ?
It is sent to the client running the query. More specifically, according to MSDN:
"The message is returned as an informational error to applications using the SQLClient namespace or the ActiveX Data Objects (ADO), OLE DB, and Open Database Connectivity (ODBC) application programming interfaces (APIs). SQLSTATE is set to 01000, the native error is set to 0, and the error message string is set to the character string specified in the PRINT statement. The string is returned to the message handler callback function in DB-Library applications."
In the case of PRINT inside a trigger, it will bubble up to the query that caused the trigger to be called.
If you want to display it through ASP.NET you will need to subscribe to the SqlConnection.InfoMessage event.
Example code:
http://msdn.microsoft.com/en-us/library/a0hee08w.aspx

Other possible ways for SQL injections?

I have an ASP.NET page running in SSL and the checking happens in the code-behind.
I've done the following to prevent sql injection:
Included RegEx to filter out unnecessary/hazardous characters (basically, it now only allows 0-9, a-z, and A-Z).
Using queries which would look something like "SELECT * FROM table WHERE username = #Username...".
I've also added account lockout so you only have a limited tries available.
After the IBM AppScan to test the vulnerabilities, it seems I've only fixed the Blind SQL Injection and not the Authenticated Bypass.
Is there anything that I've missed that's causing me to fail the vulnerability test?
UPDATE:
...
bool bUser = FilterInput(txtUsername.Text);
bool bPass = FilterInput(txtPassword.Text);
// check for restricted characters
if (bUser && bPass)
Response.Redirect("Login.aspx");
...
public static bool FilterInput(string text)
{
// check if string contains only letters and numbers
return (Regex.IsMatch(text, #"^[a-zA-Z0-9]+$"));
}
anything not within the a-zA-Z0-9 characters should throw a 'false' and would cause the page to redirect/refresh the login page.
The DB queries are all using parameterized queries and the login works correctly. no problem about that part.
Drop the first thing that you did and just use SqlCommand.Parameters as explained below:
SQL Injection vs. Lethal Injection / Protection Against SQL Injection
I always use multiple Connection Strings in order to access a database and each of them has different roles: reading, writing, execution. When you do that, you make sure that if the attack is being made successfully on a read action, the attacker cannot do someting other than reading (which is still bad but better than modifying)
Apparently there were 2 DB queries on the code the wasn't updated into parameterized queries.
Parameterized queries were enough to prevent SQL injection so the other steps/features are a bit of an overkill.

The purpose of Include() in ASP.NET MVC + Entity Framework

In the controllers generated by Visual Studio, as well as the sample application (ContosoUniversity), the Index action always has something like
var departments = db.Departments.Include(d => d.Administrator);
What's the difference between that and
var departments = db.Departments;
First I suspected that the first one (with Include) enables the view to retrieve department.Administrator. But the second one (without Include) seems to be able to do that as well.
The Include tells Entity Framework work to eagerly load the Administrator for each Department in the results. In this case, Entity Framework can use a SQL join to grab the data from both tables in a single request.
The code will still work without the Include, but the first time you access a Department's Administrator, EF will need to hit the database to load it (since it wasn't pre-loaded). Loading data on demand (lazily) is a nice feature but it can be a serious performance problem (known as an N+1 problem). Especially if you are accessing the Administrator for each Department (for example, in a loop) - instead of one database call, you will end up with many!
In first case (with Include) when you write department.Administrator servers the object from memory that has been eagerly loaded due to Include method. In the second case, an sql statement will be executed to fetch the Administrator record from the db for each department object.
See the "Lazy, Eager, and Explicit Loading of Related Data" section in this tutorial:
http://www.asp.net/entity-framework/tutorials/reading-related-data-with-the-entity-framework-in-an-asp-net-mvc-application
var departments = db.Departments;
This will retrieves the aggregate domains only if LazyLoadingEnabled is enabled & MultipleActiveResultSets is set to true in connection string.

error handling in asp.net

How can i pass the different types of errors from Data access layer to presentation layer?
suppose if we take the northwind database
scenario
I want to delete the customer, so i selected one customer in ui and clicked the "delete" button.It internally calls the "delete" in data access layer.
The prerequisite for deleting the customer is that the customer doesn't have any orders.So in data access layer we wil check whether that customer has any orders.If the customer has orders how can we pass the message from dal to presentation layer that the customer has orders and we don't delete.
Am i doing right?is there any other ways to deal with this type?
Thanks in advance
The other answers tell you how you should be implementing this particular scenario, however to answer your original question, the answer is to define your own exceptions.
You can have a core DataLayerException as the base for all of you data exceptions (inheriting from ApplicationException or similar) then have sub exceptions based on the scenario, e.g.:
ConnectionClosedException
TImeoutException
etc.
For me personally, it would be better to call a separate "ValidateDeletion" method prior to attempting a delete. This would first check to see if that customer has orders before removing them from the database.
Particulary, if you want to raise different kinds of exception from database... I use to raise an error from SP like this.
if (#invalidCount <> 1)
Begin
Raiserror('[Duplicate] Record Already Posted In System ', 20, 1)
End
Catch the error in the DAL, and analyse the exception type through the exception message (here the keyword for me is the "[Duplicate]") and throw the different kind of exception appropriately.
Of course this will be very cumboresum if you have more than 2/3 types of exceptions.
For me the best way is to raise an event TryToDeleteCustomerWithOrders.
The validation part is also fine, but it's about data, so the data layer should do the whole work. If you put the validation outside, there is chance that you call the deletion function without validation ....

ASP.NET MVC: How to view query executed by SaveChanges (on the ADO.NET Entity Data Model)

When trying to add a few items to the database I'm getting this error:
UpdateException was unhandled by user code
An error occurred while updating the entries. See the InnerException for details.
The InnerException contains this:
{"Column count doesn't match value count at row 1"}
I can't see anything wrong with the objects I'm trying to add, all the required values are filled.
Is there any way of viewing the query that causes the problem?
The method's code, if required:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LaadVerrichtingenIn() {
int[] intArray = Array.ConvertAll<String, int>(Request.Form["selectedObjects"].Split(','), new Converter<String, int>(Convert.ToInt32));
List<Verrichting> gekozenVerrichtingen = new List<Verrichting>();
foreach(int i in intArray){
base._entities.AddToVerrichtingSet(((Dictionary<int, Verrichting>)Session["ingelezenVerrichtingen"])[i]);
gekozenVerrichtingen.Add(((Dictionary<int, Verrichting>)Session["ingelezenVerrichtingen"])[i]);
}
Session["ingelezenVerrichtingen"] = null;
base._entities.SaveChanges(); //Exception occurs here
return View("IngeladenVerrichtingen");
}
base._entities is an ADO.NET Entity Data Model.
Thanks
I'm not sure if there's a 'neater' way to do this with the Entity Framework, but if you're using SQL Server then I'd generally use the SQL Server Profiler to read the queries being executed against the server. If you're using a different database then there may be an equivalent - in any case it would probably be helpful if you let us know.
If you're using MySQL > 5.0.37 it has new query profiler functionality - this should be able to show you the queries being sent.
SQL server profiler will work fine if you're using SQL Server. Within the Entity Framework, you can use the ToTraceString method.
I've just come across the same problem while inserting data using the Entity Framework and MySQL. My hunch is, since I'm using double values, that the decimal separator "," is being misinterpreted as a field separator. I upgraded to Connector version 6.1.0, but still no luck. Maybe this is also going on in your case.
Check out this bug report.
BTW, I found that the following line of code works around the problem:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

Resources